Sunday, August 30, 2015

Prism 5.0 based WPF/MVVM Real-time streaming stack


V
|
|  (auto wire VM using VMLocatot)
VM
|
|  (IoC Services)
Services
|       \   (IExecutionCommand)
|        \
|       Network API ( Tibco, 29West, BB, etc.)
|            /
|           /  (IProdsumer:: Add/Take)
Model -----Producer-Consumer BlockingCollection


(1) VM will host data and Command properties
(2) Actual Processing code will be in Services
(3) Services: IExecutionCommand, IUICommand, IConfiguration, ISubscription(topic)
(4) Topic=>Model<Topic>=> IObserer<T>.OnNext=>ISubscription<T>

Saturday, August 29, 2015

Lock Free Volatile Field Updates


        void LockfreeUpdate(ref double volatileUpdateTarget, double value)
        {
            SpinWait sw = new SpinWait();
            while (true)
            {
                // after this line, other thread can update the ref double,
                double comparandAsSnapshot = volatileUpdateTarget;

                //w/o barrier, before instruction changing volatileUpdateTarget move to after Snapshot=> comparandAsSnapshot stale=>extra spin
                Thread.MemoryBarrier();

                // if preempted=>updateTarget changed != comparand=> no copy, and spin.
                double? originalRefValueBeforeExchComp = Interlocked.CompareExchange(ref volatileUpdateTarget, value, comparandAsSnapshot);
                if (originalRefValueBeforeExchComp == comparandAsSnapshot) return;  // no preemption
                sw.SpinOnce();
            }
        }
 
       void LockfreeUpdate<T>(ref T volatileUpdateTarget,T value) where T: class
        {
            SpinWait sw = new SpinWait();
            while (true)
            {
                // after this line, other thread can update the ref double,
                T comparandAsSnapshot = volatileUpdateTarget;

                 // ICE has internal MemoryBarrier so just extra spin here

                // if preempted=>updateTarget changed != comparand=> no copy, and spin.
                T originalRefValueBeforeExchComp = Interlocked.CompareExchange(ref volatileUpdateTarget, value, comparandAsSnapshot);
                if (originalRefValueBeforeExchComp == comparandAsSnapshot) return;  // no preemption
                sw.SpinOnce();
            }
        }

       void LockfreeUpdate<T>(ref T volatileUpdateTarget,func<T,T> updateFunc) where T: class
        {
            SpinWait sw = new SpinWait();
            while (true)
            {
                // after this line, other thread can update the ref double,
                T comparandAsSnapshot = volatileUpdateTarget;

                // if preempted=>updateTarget changed != comparand=> no copy, and spin.
                T originalRefValueBeforeExchComp = Interlocked.CompareExchange(ref volatileUpdateTarget, 
         updateFunc(comparandAsSnapshot ), comparandAsSnapshot);
                if (originalRefValueBeforeExchComp == comparandAsSnapshot) return;  // no preemption
                sw.SpinOnce();
            }
        }


Tuesday, August 18, 2015

WPF GridCOntrol Get to Cell content in Master-Detail


           var hPanel = VisualTreeHelpers.FindChild<HierarchyPanel>(AssociatedObject);
            if (hPanel == null) return;
            
            var listOfRowAndCell= new List<Tuple<bool,int, List<Tuple<object, string>>>>();
            foreach (var hpChild in hPanel.Children)
            {
                var row = hpChild as GridRow;
                if (row == null) continue;
                var sviPanel = VisualTreeHelpers.FindChild<StackVisibleIndexPanel>(row);
                if (sviPanel == null) continue;
 
                var list= new List<Tuple<object, string>>();
                foreach (var child in sviPanel.Children)
                {
                   var cellContentPresenter = child as GridCellContentPresenter; // now we got to cell level
                   if (cellContentPresenter == null) continue;
                   var cell = cellContentPresenter.Element as DevExpress.Xpf.Grid.CellEditor;
                   if (cell == null) continue;

                    // Store Visible Text Value for later Validation
                    var ev = cell.Edit.EditValue;
                    var fn = cell.Column.FieldName;
                   list.Add(new Tuple<object, string>(ev,fn));
                }

                if (row.RowDataContent == null || row.RowDataContent.DataContext == null  || row.RowDataContent.DataContext as RowData==null) continue;
                int rh = (row.RowDataContent.DataContext as RowData).RowHandle.Value;
                listOfRowAndCell.Add(new Tuple<bool,int, List<Tuple<object, string>>>(IsMasterRow(row),rh,list));
            }

Tuesday, July 14, 2015

Hang Analysis

SRV*c:\temp*http://msdl.microsoft.com/download/symbols
SRV*http://msdl.microsoft.com/download/symbols
.cordll


!ntsdexts.locks= !locks
 kb (Display Stack Backtrace) command
 ~
~4 kb
~6 kb

Example:
0:006>  !locks -v
CritSec ftpsvc2!g_csServiceEntryLock+0 at 6833dd68
LockCount          0 (Ignore)
 
CritSec isatq!AtqActiveContextList+a8 at 68629100
LockCount          2 (possible deadlock)
OwningThread       a3
 
critSec +24e750 at 24e750
LockCount          6
OwningThread       a9

 ~ 
   ....
   4  Id: 1364.a3 Suspend: 1 Teb: 7ffdb000 Unfrozen
   ...
   6  Id: 1364.a9 Suspend: 1 Teb: 7ffd9000 Unfrozen

0:006>  ~4 kb 
  4  id: 97.a3   Suspend: 0 Teb 7ffd9000 Unfrozen
ChildEBP RetAddr  Args to Child
014cfe64 77f6cc7b 00000460 00000000 00000000 ntdll!NtWaitForSingleObject+0xb
014cfed8 77f67456 0024e750 6833adb8 0024e750 ntdll!RtlpWaitForCriticalSection+0xaa  (1st under Args to Child to wait for 6=a9)

0:006>  ~6 kb 
ChildEBP RetAddr  Args to Child
0155fe38 77f6cc7b 00000414 00000000 00000000 ntdll!NtWaitForSingleObject+0xb
0155feac 77f67456 68629100 6862142e 68629100 ntdll!RtlpWaitForCriticalSection+0xaa (68629100=2 thread, wait for 2=a3)

Dead lock found.

https://msdn.microsoft.com/en-us/library/windows/hardware/ff540592(v=vs.85).aspx




!threads 
!clrstack 
~e!clrstack 
!syncblk 
!dso

loadby sos clr
~*e !clrstack
~21s
!dso
!do [hex]

~*kb
!threads


https://www.google.com/webhp?sourceid=chrome-instant&ion=1&espv=2&ie=UTF-8#q=What+cause+WPF+GUI+Hang

https://www.google.com/webhp?sourceid=chrome-instant&ion=1&espv=2&ie=UTF-8#q=what+cause+GUI+Hang+in+WPF

.symbolpath
.symbolpath+ c:\temp
.symfix
vertarget
|
.hh
.chain   ( shows psscor4.dll not loaded as extension so .load psscor4.dll)
!clrstack  ( clr=net 4.0 )
.psscor4.help
.peb
!runaway ( for devi Monday report)

!= extesion sos psscor

Hang
~2s;k
~*k
~*e!clrstack
!syncblk
!finalizequeue  (Ready for finalizer >>10000 => blocked)
k kb kn kp kv  ( show arg to child-- deadlock )
!cs ( find cs owner 10a8 => id 0)
~~[10a8]s
kv r   ( list address on stack, register)
!cs @rbx  ( dump critical section object rbx=... from register)


Exception
!dae
!pe
!u
u;!u  native , managed
!eeversion

Memory
!address  (Free 1G but largest contiquous is 50M => Fragmentation memory problem)
!eeheap-gc !eeheap-loader
!dda
!dumpdomain
!dumpheap-stat
!clrusage

Dump source psudo code
!clrstack  (=> will show Marble.exe BadFuncion() as point of intersts)
!savemodule Marble.exe


http://theartofdev.com/windbg-cheat-sheet/

dt RTL_CRITICAL_SECTION
critsec 0x7e459
!analyze -v -hang

.foreach (ex {!dumpheap -type Exception -short}){.echo "********************************";!pe -nested ${ex} }

!dumpheap -type Exception -short
.loadby C:\Windows\Microsoft.NET\Framework64\v4.0.30319\sos.dll clr
.load C:\Windows\Microsoft.NET\Framework64\v4.0.30319\sos.dll

Wednesday, May 6, 2015

INTQ Rx


Explain various ISchedulers
.Immediate  --- Single Threaded
.CurrentThread  -- Single Threaded + Msq Q for chain nest
.NewThread  -- EventLoopScheduler of its own
.TaskPool/ThreadPool --- out of order
.EventLoopScheduler  --- true multi-threading Func<ThreadStart,Thread> !=CurrentThread
.DispatcherScheduler --pitfall, .instance=> new instance not started

Explain IObservable<int> Publish/Connect extension methods?
How this compare to Lazy<T> vs. List<T>
When this can lose some data ? ( subscribe after connect.

How Publish will allow subscribe all has the same set of data?
Why .RefCount() is better?
Auto Connect +eagar dispose();

CompareSubscribeSafe vs. Subcribe.Subscribe()?
translate Synchronous Exception to OnError

How do you use Observable.FromEventPatterh?
Observable.FromEventPattern<EventHandler, EventArgs>

What  SelectMany does when using Buffer(2,2)?
(0,1,2,...)=>((0,1),(3,4)..) flattern 

What does CombineLatest return?
a list

Compare Zip vs. Merge? How Cancat fit in?
Different Type needs Func to map, same type.

How do you use Any, All, Contain?

How do you use Distinct, DistinctUntilChanged, Skip, SkilUntil, Take, TakeUntil?

How to generate Observable<T> as Test data?
 IEnumerable<IObservable<long>> getSeq()
{
  yield return Observable.Create<long>( obsr => {
               return Observable.Timer(TimeSpan.FromSeconds(1)). select (i=>1L)
                     .subscribe(obsr)
               });
 }

What is a Subject?
observer and Observable

How do u use StartWith?
Concat at 1st place

Compare Merge, Amb, Switch?
Ambigous io1,io2,io3.. first reponded turn off others
Switch switch the most recent io, turn off others. e.g. search box narrow down.





Tuesday, May 5, 2015

INTQ --Threading, C#


Explain SpinLock, SpinWait? vs lock
sl.enter/exit while(!flag {sw.Spin(100);}

Explain how Memory Barrier works?
Thread.MemoryBarrier(), Caching Optimization can move instruction around

What is Re-entrant?

How Semaphore works?
SemaphoreSlimw= new (3);_sm.Wait(); block after 3 entrer; sm.Release();

Explain InterLock.Increment/Decrement for 64-bit on 32-bit environment?
need two separate instrument InterLock.Increment(ref i);

How to use Cancellaton Token in Task?
CancelationTokenSource src. src.Token pass in

What are SynchronizationContext?
Send/Post, Dispatcher, WF/ASPNet

How do you use BlockingCollection?

How the exception in Thread handled?
WPF/WF App.DispatcherUnhandledExpcetion/ThreadExcetion UI Thread
AppDomain.Current.UnhandledException
General --Process Shutdown, Calling thread will not see it.

How to use TaskCompletionSource?
StateMachine, Task  workflow, tcs.Task ReadOnly, tcs.SetResult/Cancel/Exception

How to use Parallel.For ?
Parallel.For(1,100,Action<int>)

why Binary search is O(logn)?


What is Volatile, [Thread Static] and Thread Local?
access by all thread, not optimize, each static field has its own copy, each thread has its own.

Is Lazy thread safe ?
set by 1st thread, if IsThreadSafe=true;

What is Priority Inversion?
L hold up H due to resource lock, M comes in unblocked so M>L, make L temporarity High to exec, release H

what is Thread Stavation ?
L cannot do much since H occupy.

Explain how Monitor.Pulse/Wait work?
Pulse signal to get on ReadyQueue, Wait to sit on waitQueue. vs. Enter/Exit

How to setup BeginInvoke/EndInvoke for Action?
Action a; a.BeginInvoke(new AsyncCallback(cb_f,a));
void (cb_f(IAsyncResult ar) { Action a=ar.AsyncState as Action; a.EndInvoke();}

Explain Dinning Philosopher Problem? (Minitor, Executor, Manager)

What is Mutex?
Mutex.TryOpenExisting("Name", out m); m.WaitOne(); m.ReleaseMutex();

What is Multi-cast Delegate?
D d1,d2; MuticastDelegate mcd=D.Combine(d1,d2);

How much does it cost to set up a thread?
200K CPU cycle, 1M Stack,64 bit 6 Kernal Pages, 2K cycle for Context Switching.

Explain GC and WeakReference
Reachable -- strong ref, Unreachable/FinalizerQueue =long/short weakref, 2-phase GC.
WeakReference wObj= new(TrackResurrection=true); wObj.Target is strongRef but check null needed.

What is an example of a Closure?
Func f=delegate { int i=5; i=outside var; return 5;}

Explain Syntax for Enumerable.Aggragate((acc,i)=>acc+i)

Explain UML notations of Realization/Inheritance/Aggragation/Composition/Association

Explain Design Pattern Visitor/Singleton/

What is Rx CombineLastest?


Monday, May 4, 2015

INTQ -WPF


What are dependency properties? How to u used it (binding)

What are behavior?


Various Layout panel (Stack,Grid, Canvas, Dock, Wrap)

Attached Property

INPC

What is ICommand and how to set it up? how do you use DelegateCommand

Dynamic vs. static resources

How to specify Grid Column Width 26,26*, auto?

What is adorner

What are routed events ? type Direct, Bubbling, Turnelling

What are automationId?

How do u bind bool to visibility?

what is multibinding

How do u used ConverterParameter

Explain Unity vs. MEF. What is dependency injection

What is the problem of TextBox binding double? (string.EMpty to null ,TargetNullValue={x:Static sys:String.Empty} } )

Explian Visual vs. logical tree

Explain FrameworkElement, UIElement, Visual, DependencyObject, DispatcherObject,

Explain these triggers ( Property Trigger, Event Trigger, Data Trigger, Muti Trigger)

Explain ItemsControl, ContentPresenter,DataTemplate,ContentControl, ItemTemplate,

What is TypeConverter ?


Explain Template, ContentTemplate, ControlTempalte and DataTemplate? 
  e.g <ItemsControl Template=CT/P ItemTeplate=DT ItemsPanel=ItemPanelTemp/WrapP />


Explain the syntax <ContentControl binding to datasource and use DataTemplate to display
    <ContentControl Content={Binding Source={StaticRes} ContentTemplate={StaticRes DT1} />
    <DataTemplate x:key=DT1> ...</DT>

How do you restyle a button by replace its template?
  <style targetType=Button><setter prop=OvewrrideDefaultDefaultStyle v=true/>
    <setting Property="Template><setter.value><ControlTemplate>...

What is Theme and how do you use it in your UserControl?
<App.Res><ResDict source="1.xaml" 

Explain two way to use EventTrigger?
   <Button><i:Interaction.Triggers><t:EventTrigger EventNam=><i:InvokeCommandAction>
   <TextBox><TB.Triggers><EventTrigger><BeginStoryBoard>
<Win.Triggers><EventTrigger RoutedEvent=><StoryBoard>

Listing places where you can use DataTemplate?
  <style><style.triggers><datatemplate binding=><setter>
<ContentControl ContentTemplate />

How FrameworkElement.CommandBindings work?

How to use DataTrigger in Style?
<Style.Triggers><DataTrigger Bidng Value><DataTrigger.EnterActions><BeginStoryBoard>

What is TemplateBinding ?
   <ControlTemplate x;Key=CT><StackPanel><Textblock text={TemplateBinding Content}/>
      <Button Content=123 Template={StaticRes CT}/>

How do you use DataTemplate in a ListBox through style and use a datatrigger?

Describe MultiBinding vs. Multi trigger syntax?
<TB.Text><MB Converter><Binding/><Binding/>
<Style.Triggers><MDT><*.Conditions><Cond bind val/><Cond /><Setter ../>

Describe the structure usage of HeaderedItemsControl /
.Header
.Itemtemp
.template
 <ControlTemp><StackPan><ContentPresenter Content={Templatebinding Header} />
    <ItemsPresenter/>

Describe ItemsControl templating?
  <ITC><*.Template><ControlTemp><ItemPresenter/>
       <*.ItemsPanel><O|ItemPanelTemp>
       <*.ItemTemplate><DataTemp>
       <*.TemContainerStyle<Style>