Trading System.Net

Thursday, October 15, 2015

Notes on GIT

Create Repo using Git GUI https://Wxxx@ReporServer.net:8443/scm/Repositories/RepoName.git http://git-scm.com/book

Tuesday, September 22, 2015

Using Grid to layout ItemsControl Items

The key is to use ItemContainerStyle setting Grid.Coulumn and Grid.Row


        <ItemsControl ItemsSource="{Binding VDItems}" Grid.Row="1" AllowDrop="True" Name="itemsCtlVD" VerticalAlignment="Stretch" HorizontalAlignment="Stretch" Background="White">
            <ItemsControl.ItemsPanel>
                <ItemsPanelTemplate>
                    <Grid ShowGridLines="False">
                        <Grid.ColumnDefinitions>
                            <ColumnDefinition />
                            <ColumnDefinition />
                            <ColumnDefinition />
                            <ColumnDefinition />
                            <ColumnDefinition />
                            <ColumnDefinition />
                        </Grid.ColumnDefinitions>
                    </Grid>
                </ItemsPanelTemplate>
            </ItemsControl.ItemsPanel>

          
            <ItemsControl.ItemContainerStyle>
                <Style>
                    <Setter Property="Grid.Column"
                    Value="{Binding ColumnIndex}" />
                    <Setter Property="Grid.Row"
                    Value="{Binding RowIndex}" />
                </Style>
            </ItemsControl.ItemContainerStyle>

            
            <ItemsControl.ItemTemplate>
                <DataTemplate>
                    <Border BorderThickness="0.2" BorderBrush="LightGray" Background="{Binding Background}" >
                        <Viewbox Stretch="Uniform" StretchDirection="DownOnly">
                            <Label Content="{Binding Data}" FontWeight="Bold" Foreground="{Binding Foreground}">
                            </Label>
                        </Viewbox>
                        <i:Interaction.Triggers>
                            <i:EventTrigger EventName="MouseLeftButtonUp">
                                <i:InvokeCommandAction Command="{Binding ClickTradeCommand}"
                                                       CommandParameter="{Binding .}" ></i:InvokeCommandAction>
                            </i:EventTrigger>
                        </i:Interaction.Triggers>
                    </Border>
                </DataTemplate>
            </ItemsControl.ItemTemplate>
        </ItemsControl>

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.