Monday, September 2, 2013

Subscriber block Observable

Rx observable waits for each subscribe to process in single threaded fashion. So Blocking happens

            var obs = System.Reactive.Linq.Observable.Range(0, 200, System.Reactive.Concurrency.Scheduler.TaskPool).Publish();
            obs.Timestamp().Select(i => i).
            Subscribe(i => { Console.WriteLine("sub1 block " + i); Thread.Sleep(3000); });

            obs.Timestamp().Select(i => i).
Subscribe(i => { Console.WriteLine("sub2  " + i); });
            obs.Connect();

            Console.ReadLine();  

Saturday, June 15, 2013

Calculating Max number of Pages used to host Handle Table Enties by Executive


Here are information related to System Internal in general
http://live.sysinternals.com/

http://technet.microsoft.com/en-us/sysinternals/bb963901.aspx

http://blogs.technet.com/b/markrussinovich/archive/2009/09/29/3283844.aspx

The JPG shows the actual calculation:


Thursday, June 13, 2013

Set up Monitoring Desktop Heap as Performance Alert

Find Heap Size at registion location LM\System\CurrentControlSet\Control\SessionManager\SubSystem\Windows\

%SystemRoot%\system32\csrss.exe ObjectDirectory=\Windows SharedSection=1024,3072,512 ....

1024k = Common Size, Do not change
3072k = Interactive Size/Desktop, Do not change
512k = Non-Intereactive Size, can change but very careful

Buffer size is 48M and everything must fit into it.

So each DeskTop Heap can support (49152-3072)/512 =(48M-3M)/512K=95 processes.

Set up Alert:
Control Panel-> Admin->Perf->Perf Log and Alert->New Alert Settings->Add Counter
->System Perf Object->Processes Counter->Add->DropDown="Alert when Value over" 95,
->Action Tab->Check "Log an entry in Event Log"->Ok, Start Alert.

Monday, May 27, 2013

Subjects in Science worthy of life time commitment

(1) Build a bio Transistor.
(2) Quantum bit based computer to simulate Bio System evolution and behavior

C# code to stress Memory (Copy from MSDN)

this code is very usefull to bump up resource usage and run your code for exposing bugs
class Test
{
   static void Main() {
      unsafe {
         byte* buffer = (byte*)Memory.Alloc(256);
         try {
            for (int i = 0; i < 256; i++) buffer[i] = (byte)i;
            byte[] array = new byte[256];
            fixed (byte* p = array) Memory.Copy(buffer, p, 256);
         }
         finally {
            Memory.Free(buffer);
         }
         for (int i = 0; i < 256; i++) Console.WriteLine(array[i]);
      }
   }
}
 
 
 
using System;
using System.Runtime.InteropServices;
public unsafe class Memory
{
   // Handle for the process heap. This handle is used in all calls to the
   // HeapXXX APIs in the methods below.
   static int ph = GetProcessHeap();
   // Private instance constructor to prevent instantiation.
   private Memory() {}
   // Allocates a memory block of the given size. The allocated memory is
   // automatically initialized to zero.
   public static void* Alloc(int size) {
      void* result = HeapAlloc(ph, HEAP_ZERO_MEMORY, size);
      if (result == null) throw new OutOfMemoryException();
      return result;
   }
   // Copies count bytes from src to dst. The source and destination
   // blocks are permitted to overlap.
   public static void Copy(void* src, void* dst, int count) {
      byte* ps = (byte*)src;
      byte* pd = (byte*)dst;
      if (ps > pd) {
         for (; count != 0; count--) *pd++ = *ps++;
      }
      else if (ps < pd) {
         for (ps += count, pd += count; count != 0; count--) *--pd = *--ps;
      }
   }
   // Frees a memory block.
   public static void Free(void* block) {
      if (!HeapFree(ph, 0, block)) throw new InvalidOperationException();
   }
   // Re-allocates a memory block. If the reallocation request is for a
   // larger size, the additional region of memory is automatically
   // initialized to zero.
   public static void* ReAlloc(void* block, int size) {
      void* result = HeapReAlloc(ph, HEAP_ZERO_MEMORY, block, size);
      if (result == null) throw new OutOfMemoryException();
      return result;
   }
   // Returns the size of a memory block.
   public static int SizeOf(void* block) {
      int result = HeapSize(ph, 0, block);
      if (result == -1) throw new InvalidOperationException();
      return result;
   }
   // Heap API flags
   const int HEAP_ZERO_MEMORY = 0x00000008;
   // Heap API functions
   [DllImport("kernel32")]
   static extern int GetProcessHeap();
   [DllImport("kernel32")]
   static extern void* HeapAlloc(int hHeap, int flags, int size);
   [DllImport("kernel32")]
   static extern bool HeapFree(int hHeap, int flags, void* block);
   [DllImport("kernel32")]
   static extern void* HeapReAlloc(int hHeap, int flags,
      void* block, int size);
   [DllImport("kernel32")]
   static extern int HeapSize(int hHeap, int flags, void* block);
}

Wednesday, April 10, 2013

Detect WPF Window out of bound for multiple monitor

            Point p =new Point(left, top);
            bool outOfBoundHorizontal = p.X < SystemParameters.VirtualScreenLeft || p.X > SystemParameters.VirtualScreenLeft + SystemParameters.VirtualScreenWidth;
            bool outOfBoundVertical = p.Y < SystemParameters.VirtualScreenTop || p.Y > SystemParameters.VirtualScreenTop + SystemParameters.VirtualScreenHeight;

Note that VirtualScreenHeight/Width considered Multiple Monitor with various Display Positioning, It can start at negative  and to position 1/3, use 1/0/3.0*(SystemParameters.VirtualScreenLeft + SystemParameters.VirtualScreenWidth), not just width.

TO reposition find Primary Monitor
           if (outOfBoundHorizontal || outOfBoundVertical)
            {
                var primaryMonitor = Screen.AllScreens.FirstOrDefault(s => s.Primary);
                if (primaryMonitor == null)
                {
                  wnd.Left = 0;
                  wnd.Top = 0; 
                }
                else
                {
                    // Fit into Primary Monitor if possible. Note Primary Monitor start @ (0,0)
                    wnd.Left = primaryMonitor.Bounds.Left + Math.Max(primaryMonitor.Bounds.Width- wnd.Width, 0);
                    wnd.Top = primaryMonitor.Bounds.Height + Math.Max(primaryMonitor.Bounds.Height - wnd.Height, 0);                   
                }
            }

Update--- the above code does not work property due to measurement issues , flip monitor, Landscape/Portrait, L shapes.
1 point = 1/72 inch, 1 px = 1/96 inch. The size could use either px or point per Graphics.PageUnit

Rectangle hitTestRec= new System.Drawing.Rectange(left,top, new size(2,2))

var hitTestMonitor= System.Windows.Form.Screen.AllScreens.FirstOrDefault(s => s.Bounds.Contains(hitTestRect));
bool outOfBound = hitTestMonitor ==null;

Sunday, September 9, 2012

Hit Test Toolbar to find button


Toolbar is an ItemsControl and does not have click event handler to indicate which button is clicked. Here Hit Testing is used to figure that out:

Note that we need to use Preview to Tunneling Event Handler

       void tbr_PreviewMouseDown(object sender, MouseButtonEventArgs e)
        {
            ToolBar tbr = sender as ToolBar;
           
            Point pt=e.GetPosition(tbr);
            object btnClicked=null;
            UIElement element = tbr.InputHitTest(pt) as UIElement;
            while (element != null)
            {
                if (element == tbr) return;
                 btnClicked = tbr.ItemContainerGenerator.ItemFromContainer(element);
                 if (!btnClicked.Equals(DependencyProperty.UnsetValue)) break;
                element = (UIElement)VisualTreeHelper.GetParent(element);
            }
           
            if (btnClicked != null)
                Console.WriteLine((btnClicked as Button).Content);
            else
                Console.WriteLine("no item found");
        }