Blog Archive

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.





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>


Sunday, April 19, 2015

Simpler test of IList.CombineLatest without Group by

            var q0 = Observable.Interval(TimeSpan.FromSeconds(1)).Select(s => new MarketData(0,s));
            var q1 = Observable.Interval(TimeSpan.FromSeconds(2)).Select(s => new MarketData(1, s));
            var q2 = Observable.Interval(TimeSpan.FromSeconds(1)).Select(s => new MarketData(2, s));


             var list012 = new List<IObservable>();
             list012.AddRange(new[] { q0.Select(t => t.Qty), q1.Select(t => t.Qty), q2.Select(t => t.Qty) });
            list012.CombineLatest().Select(t => t.Sum()).Subscribe(d => Console.WriteLine("sum012="+d+" "+DateTime.Now ));

            var list12 = new List<IObservable>();
            list12.AddRange(new[] { q1.Select(t => t.Qty), q2.Select(t => t.Qty) });
            list12.CombineLatest().Select(t => t.Sum()).Subscribe(d => Console.WriteLine("sum12=" + d + " " + DateTime.Now));
            Console.ReadLine();

    public class MarketData
    {
        public int? DepthIndex;
        public decimal? Qty;

        public MarketData(int? d, decimal? q)
        {
            DepthIndex = d;
            Qty = q;
            Console.WriteLine("ctor " +d+" "+ q+" "+DateTime.Now );
        }
    }

        public static IObservable<IList<TSource>> CombineLatest<TSource>(this IObservable<IObservable<TSource>> sources)
  {

   return Observable.Create<IList<TSource>>(
    observer =>
    {
     var gate = new object();

     var latest = new List<TSource>();
     var hasValueFlags = new List<bool>();

     var sourceCount = 0;
     var consecutiveActiveSourcesCount = 0;
     var outerCompleted = false;

     var outerSubscription = new SingleAssignmentDisposable();
     var disposables = new CompositeDisposable(outerSubscription);

     outerSubscription.Disposable = sources.Subscribe(
      source =>
      {
       int index;

       lock (gate)
       {
        sourceCount++;

        index = latest.Count;

        latest.Add(default(TSource));
        hasValueFlags.Add(false);
       }

       var subscription = new SingleAssignmentDisposable();

       disposables.Add(subscription);

       subscription.Disposable = source.Subscribe(
        value =>
        {
         lock (gate)
         {
          latest[index] = value;

          if (consecutiveActiveSourcesCount < hasValueFlags.Count)
          {
           hasValueFlags[index] = true;

           while (consecutiveActiveSourcesCount < hasValueFlags.Count && hasValueFlags[consecutiveActiveSourcesCount])
           {
            consecutiveActiveSourcesCount++;
           }
          }

          if (consecutiveActiveSourcesCount >= 2)
          {
           observer.OnNext(latest.Take(consecutiveActiveSourcesCount).ToList().AsReadOnly());
          }
         }
        },
        observer.OnError,
        () =>
        {
         bool completeNow;

         lock (gate)
         {
          disposables.Remove(subscription);

          sourceCount--;

          completeNow = outerCompleted && sourceCount == 0;
         }

         if (completeNow)
         {
          observer.OnCompleted();
         }
        });
      },
      observer.OnError,
      () =>
      {
       bool completeNow;

       lock (gate)
       {
        outerCompleted = true;

        completeNow = sourceCount == 0;
       }

       if (completeNow)
       {
        observer.OnCompleted();
       }
      });

     return disposables;
    });
  }
 

CombineLastest on Several IObservables


// Source code at http://rxx.codeplex.com/ is the critical part of this solution
       static void Main(string[] args)
        {
            DateTime dtStart = DateTime.Now;
            var mktData = GenerateObservable<MarketData>(1, dt => new MarketData() { DepthIndex=RandomInt(10),Qty=RandomInt(777) }, 1, dt => dt < dtStart.AddSeconds(30));
            var grpByDepthMktData=   mktData.GroupBy(k => k.DepthIndex).Select(g => new QtyAt(g.Key, g));

            grpByDepthMktData.Select(d => d.Qtys.StartWith(0)).CombineLatest().Select(t => t.Sum()).Subscribe(d=>Console.WriteLine("sum all "+d));

            var mktData1 = mktData.Where(m => m.DepthIndex >= 1);
            var grpByDepthMktData1 = mktData1.GroupBy(k => k.DepthIndex).Select(g => new QtyAt(g.Key, g));

            grpByDepthMktData1.Select(d => d.Qtys.StartWith(0)).CombineLatest().Select(t => t.Sum()).Subscribe(d => Console.WriteLine(d));

         Console.ReadLine();
}

        static IObservable<T> GenerateObservable<T>(int seconds4Iteration, Func<DateTime, T> newT, int nextInSeconds, Func<DateTime, bool> continuation)
        {
            DateTime dtStart = DateTime.Now;
            return Observable.Generate(dtStart, continuation, dt => dt.AddSeconds(seconds4Iteration), newT, dt => TimeSpan.FromSeconds(nextInSeconds));
        }

       static int? RandomInt(int max)
        {
            
            Random r=new Random();
            return r.Next(max);
        }


    public class MarketData
    {
        public int? DepthIndex;
        public decimal? Qty;
    }

    public class QtyAt
    {
        public int? Depth;
        public IObservable<decimal?> Qtys;
        public QtyAt(int? depth, IObservable<MarketData> qtys)
        {
            Qtys = qtys.Select(m=>m.Qty);
        }
    }


    public static partial class Observable2
    {

        public static IObservable<Tuple<T1, T2>> CombineLatest<T1, T2>(this IObservable<T1> first, IObservable<T2> second)
        {
            return first.CombineLatest(second, Tuple.Create);
        }

        public static IObservable<IList<TSource>> CombineLatest<TSource>(this IEnumerable<IObservable<TSource>> sources)
        {
            return Observable.Defer(() =>
            {
                var count = 0;
                var completed = false;

                return sources.MarkLast()
                    .Select(tuple =>
                    {
                        count++;
                        completed = tuple.Item1;

                        return tuple.Item2;
                    })
                    .ToObservable()
                    .CombineLatest()
                    .SkipWhile(list => !completed || list.Count < count);
            });
        }

        internal static IEnumerable<Tuple<bool, TSource>> MarkLast<TSource>(this IEnumerable<TSource> source)
        {

            using (var enumerator = source.GetEnumerator())
            {
                if (enumerator.MoveNext())
                {
                    bool moveNext;

                    do
                    {
                        var value = enumerator.Current;

                        moveNext = enumerator.MoveNext();

                        yield return Tuple.Create(!moveNext, value);
                    }
                    while (moveNext);
                }
            }
        }

          public static IObservable<IList<TSource>> CombineLatest<TSource>(this IObservable<IObservable<TSource>> sources)
  {

   return Observable.Create<IList<TSource>>(
    observer =>
    {
     var gate = new object();

     var latest = new List<TSource>();
     var hasValueFlags = new List<bool>();

     var sourceCount = 0;
     var consecutiveActiveSourcesCount = 0;
     var outerCompleted = false;

     var outerSubscription = new SingleAssignmentDisposable();
     var disposables = new CompositeDisposable(outerSubscription);

     outerSubscription.Disposable = sources.Subscribe(
      source =>
      {
       int index;

       lock (gate)
       {
        sourceCount++;

        index = latest.Count;

        latest.Add(default(TSource));
        hasValueFlags.Add(false);
       }

       var subscription = new SingleAssignmentDisposable();

       disposables.Add(subscription);

       subscription.Disposable = source.Subscribe(
        value =>
        {
         lock (gate)
         {
          latest[index] = value;

          if (consecutiveActiveSourcesCount < hasValueFlags.Count)
          {
           hasValueFlags[index] = true;

           while (consecutiveActiveSourcesCount < hasValueFlags.Count && hasValueFlags[consecutiveActiveSourcesCount])
           {
            consecutiveActiveSourcesCount++;
           }
          }

          if (consecutiveActiveSourcesCount >= 2)
          {
           observer.OnNext(latest.Take(consecutiveActiveSourcesCount).ToList().AsReadOnly());
          }
         }
        },
        observer.OnError,
        () =>
        {
         bool completeNow;

         lock (gate)
         {
          disposables.Remove(subscription);

          sourceCount--;

          completeNow = outerCompleted && sourceCount == 0;
         }

         if (completeNow)
         {
          observer.OnCompleted();
         }
        });
      },
      observer.OnError,
      () =>
      {
       bool completeNow;

       lock (gate)
       {
        outerCompleted = true;

        completeNow = sourceCount == 0;
       }

       if (completeNow)
       {
        observer.OnCompleted();
       }
      });

     return disposables;
    });
  }
 
    }

Thursday, March 5, 2015

Break Gradient Color into Pieces

       void GetGradiencePieces()
        {
            
            var lgbHigh = new LinearGradientBrush(Colors.Red, Colors.White, 90.0);
            var lgbLow = new LinearGradientBrush(Colors.Orange, Colors.White, 90.0);
            Color clr;
            for (int i = 1; i < 21; i++)
            {
                if (i > 10 && i < 30)
                {
                    float f = (i - 10)/20.0f;
                     clr = GetColorSampleFromLinearGradientBrush(lgbHigh, f);
                }
            }

        }

        Color GetColorSampleFromLinearGradientBrush(LinearGradientBrush lgb, float y)
        {
            double max = lgb.GradientStops.Max(n => n.Offset);

            double min = lgb.GradientStops.Min(n => n.Offset);


            //Find gradient stops that surround the input value
            GradientStop gs0 = lgb.GradientStops.OrderBy(n => n.Offset).Last();
            GradientStop gs1 = lgb.GradientStops.OrderBy(n => n.Offset).First();
            Color cx = new Color();
            if (lgb.ColorInterpolationMode == ColorInterpolationMode.ScRgbLinearInterpolation)
            {
                float aVal = (gs1.Color.ScA - gs0.Color.ScA) * y + gs0.Color.ScA;
                float rVal = (gs1.Color.ScR - gs0.Color.ScR) * y + gs0.Color.ScR;
                float gVal = (gs1.Color.ScG - gs0.Color.ScG) * y + gs0.Color.ScG;
                float bVal = (gs1.Color.ScB - gs0.Color.ScB) * y + gs0.Color.ScB;
                cx = Color.FromScRgb(aVal, rVal, gVal, bVal);
            }
            else
            {
                byte aVal = (byte)((gs1.Color.A - gs0.Color.A) * y + gs0.Color.A);
                byte rVal = (byte)((gs1.Color.R - gs0.Color.R) * y + gs0.Color.R);
                byte gVal = (byte)((gs1.Color.G - gs0.Color.G) * y + gs0.Color.G);
                byte bVal = (byte)((gs1.Color.B - gs0.Color.B) * y + gs0.Color.B);
                cx = Color.FromArgb(aVal, rVal, gVal, bVal);
            }
            return cx;
        }

Saturday, February 28, 2015

INPC with Equality check


    public class ViewModelBase : INotifyPropertyChanged
    {
        public event PropertyChangedEventHandler PropertyChanged;

        public void SetProperty<T>(ref T field, T value, Expression<Func<T>> exp)
        {
            if (EqualityComparer<T>.Default.Equals(field, value)) return;
            field = value;
            if (PropertyChanged != null)
            {
                MemberExpression me = exp.Body as MemberExpression;
                if (me != null && me.Member != null)
                    PropertyChanged(this, new PropertyChangedEventArgs(me.Member.Name));
            }
        }
    }

Saturday, February 7, 2015

Code Snippet to walk Visual Tree for Dev Express GridControl Specifics


        private void AssociatedObject_LayoutUpdated(object sender, EventArgs e)
        {
            var v = AssociatedObject.View;

            HierarchyPanel hp = VisualTreeHelpers.FindChild(v);
            GridRow grs = VisualTreeHelpers.FindChild(hp);
            var ie = v.FindLogicalChildren();
            var ie2 = v.FindVisualChildren();
            int i1 = ie.Count();
            int i2 = ie2.Count();

            int i3 = hp.FindVisualChildren().Count();  
        }

        private GridControl dgc;
        private bool b;
        private void AssociatedObject_MasterRowExpanded(object sender, RowEventArgs e)
        {
             dgc= AssociatedObject.GetDetail(e.RowHandle) as GridControl;
             dgc.ItemsSourceChanged+=dgc_ItemsSourceChanged;
            var i = dgc.ItemsSource;
            var col = dgc.ItemsSource as ObservableCollection;
            col.CollectionChanged += col_CollectionChanged;

        }

        private void BlankoutColumns(int rowHandle)
        {
            var dgc = AssociatedObject.GetVisibleDetail(rowHandle) as GridControl;
            var dc = dgc.View.DataControl as GridControl;
            
            for (int i = 0; i < dc.VisibleRowCount; i++)
            {
                int h = dc.GetRowHandleByVisibleIndex(i);
                foreach (var c in  dc.Columns) 
                {
                    if (c.Name == "ChildName")
                    {
                        var v = dc.GetCellValue(h, c);
                       // c.CellTemplate = new DataTemplate(); // take out data template so next update never shown
                     //   dc.SetCellValue(h, c, null); // blank out already rendered text
                    }
                }
            }
        }
            DependencyPropertyDescriptor propertyDescriptor = DependencyPropertyDescriptor.FromProperty(GridViewBase.VisibleColumnsProperty, typeof(GridViewBase));
            propertyDescriptor.AddValueChanged(AssociatedObject.View, VisibleColumnsChanged);


Thursday, January 1, 2015

Enable/Disable, Start/Stop PnP device -- not for production



namespace JQD
{
    #region Enum and StructLayout, safe handle

    internal enum DiFunction
    {
        SelectDevice = 1,
        InstallDevice = 2,
        AssignResources = 3,
        Properties = 4,
        Remove = 5,
        FirstTimeSetup = 6,
        FoundDevice = 7,
        SelectClassDrivers = 8,
        ValidateClassDrivers = 9,
        InstallClassDrivers = (int)0xa,
        CalcDiskSpace = (int)0xb,
        DestroyPrivateData = (int)0xc,
        ValidateDriver = (int)0xd,
        Detect = (int)0xf,
        InstallWizard = (int)0x10,
        DestroyWizardData = (int)0x11,
        PropertyChange = (int)0x12,
        EnableClass = (int)0x13,
        DetectVerify = (int)0x14,
        InstallDeviceFiles = (int)0x15,
        UnRemove = (int)0x16,
        SelectBestCompatDrv = (int)0x17,
        AllowInstall = (int)0x18,
        RegisterDevice = (int)0x19,
        NewDeviceWizardPreSelect = (int)0x1a,
        NewDeviceWizardSelect = (int)0x1b,
        NewDeviceWizardPreAnalyze = (int)0x1c,
        NewDeviceWizardPostAnalyze = (int)0x1d,
        NewDeviceWizardFinishInstall = (int)0x1e,
        Unused1 = (int)0x1f,
        InstallInterfaces = (int)0x20,
        DetectCancel = (int)0x21,
        RegisterCoInstallers = (int)0x22,
        AddPropertyPageAdvanced = (int)0x23,
        AddPropertyPageBasic = (int)0x24,
        Reserved1 = (int)0x25,
        Troubleshooter = (int)0x26,
        PowerMessageWake = (int)0x27,
        AddRemotePropertyPageAdvanced = (int)0x28,
        UpdateDriverUI = (int)0x29,
        Reserved2 = (int)0x30
    }

    [Flags()]
    internal enum SetupDiGetClassDevsFlags
    {
        Default = 1,
        Present = 2,
        AllClasses = 4,
        Profile = 8,
        DeviceInterface = (int)0x10
    }


    internal enum StateChangeAction
    {
        Enable = 1,
        Disable = 2,
        PropChange = 3,
        Start = 4,
        Stop = 5
    }

    [Flags()]
    internal enum Scopes
    {
        Global = 1,
        ConfigSpecific = 2,
        ConfigGeneral = 4
    }

    [StructLayout(LayoutKind.Sequential)]
    internal struct PropertyChangeParameters
    {
        public int Size;
        // part of header. It's flattened out into 1 structure.
        public DiFunction DiFunction;
        public StateChangeAction StateChange;
        public Scopes Scope;
        public int HwProfile;
    }

    internal enum SetupApiError
    {
        NoAssociatedClass = unchecked((int)0xe0000200),
        ClassMismatch = unchecked((int)0xe0000201),
        DuplicateFound = unchecked((int)0xe0000202),
        NoDriverSelected = unchecked((int)0xe0000203),
        KeyDoesNotExist = unchecked((int)0xe0000204),
        InvalidDevinstName = unchecked((int)0xe0000205),
        InvalidClass = unchecked((int)0xe0000206),
        DevinstAlreadyExists = unchecked((int)0xe0000207),
        DevinfoNotRegistered = unchecked((int)0xe0000208),
        InvalidRegProperty = unchecked((int)0xe0000209),
        NoInf = unchecked((int)0xe000020a),
        NoSuchHDevinst = unchecked((int)0xe000020b),
        CantLoadClassIcon = unchecked((int)0xe000020c),
        InvalidClassInstaller = unchecked((int)0xe000020d),
        DiDoDefault = unchecked((int)0xe000020e),
        DiNoFileCopy = unchecked((int)0xe000020f),
        InvalidHwProfile = unchecked((int)0xe0000210),
        NoDeviceSelected = unchecked((int)0xe0000211),
        DevinfolistLocked = unchecked((int)0xe0000212),
        DevinfodataLocked = unchecked((int)0xe0000213),
        DiBadPath = unchecked((int)0xe0000214),
        NoClassInstallParams = unchecked((int)0xe0000215),
        FileQueueLocked = unchecked((int)0xe0000216),
        BadServiceInstallSect = unchecked((int)0xe0000217),
        NoClassDriverList = unchecked((int)0xe0000218),
        NoAssociatedService = unchecked((int)0xe0000219),
        NoDefaultDeviceInterface = unchecked((int)0xe000021a),
        DeviceInterfaceActive = unchecked((int)0xe000021b),
        DeviceInterfaceRemoved = unchecked((int)0xe000021c),
        BadInterfaceInstallSect = unchecked((int)0xe000021d),
        NoSuchInterfaceClass = unchecked((int)0xe000021e),
        InvalidReferenceString = unchecked((int)0xe000021f),
        InvalidMachineName = unchecked((int)0xe0000220),
        RemoteCommFailure = unchecked((int)0xe0000221),
        MachineUnavailable = unchecked((int)0xe0000222),
        NoConfigMgrServices = unchecked((int)0xe0000223),
        InvalidPropPageProvider = unchecked((int)0xe0000224),
        NoSuchDeviceInterface = unchecked((int)0xe0000225),
        DiPostProcessingRequired = unchecked((int)0xe0000226),
        InvalidCOInstaller = unchecked((int)0xe0000227),
        NoCompatDrivers = unchecked((int)0xe0000228),
        NoDeviceIcon = unchecked((int)0xe0000229),
        InvalidInfLogConfig = unchecked((int)0xe000022a),
        DiDontInstall = unchecked((int)0xe000022b),
        InvalidFilterDriver = unchecked((int)0xe000022c),
        NonWindowsNTDriver = unchecked((int)0xe000022d),
        NonWindowsDriver = unchecked((int)0xe000022e),
        NoCatalogForOemInf = unchecked((int)0xe000022f),
        DevInstallQueueNonNative = unchecked((int)0xe0000230),
        NotDisableable = unchecked((int)0xe0000231),
        CantRemoveDevinst = unchecked((int)0xe0000232),
        InvalidTarget = unchecked((int)0xe0000233),
        DriverNonNative = unchecked((int)0xe0000234),
        InWow64 = unchecked((int)0xe0000235),
        SetSystemRestorePoint = unchecked((int)0xe0000236),
        IncorrectlyCopiedInf = unchecked((int)0xe0000237),
        SceDisabled = unchecked((int)0xe0000238),
        UnknownException = unchecked((int)0xe0000239),
        PnpRegistryError = unchecked((int)0xe000023a),
        RemoteRequestUnsupported = unchecked((int)0xe000023b),
        NotAnInstalledOemInf = unchecked((int)0xe000023c),
        InfInUseByDevices = unchecked((int)0xe000023d),
        DiFunctionObsolete = unchecked((int)0xe000023e),
        NoAuthenticodeCatalog = unchecked((int)0xe000023f),
        AuthenticodeDisallowed = unchecked((int)0xe0000240),
        AuthenticodeTrustedPublisher = unchecked((int)0xe0000241),
        AuthenticodeTrustNotEstablished = unchecked((int)0xe0000242),
        AuthenticodePublisherNotTrusted = unchecked((int)0xe0000243),
        SignatureOSAttributeMismatch = unchecked((int)0xe0000244),
        OnlyValidateViaAuthenticode = unchecked((int)0xe0000245)
    }

    [StructLayout(LayoutKind.Sequential)]
    internal struct DeviceInfoData
    {
        public int Size;
        public Guid ClassGuid;
        public int DevInst;
        public IntPtr Reserved;
    }

    internal class SafeDeviceInfoSetHandle : SafeHandleZeroOrMinusOneIsInvalid
    {

        public SafeDeviceInfoSetHandle()
            : base(true)
        {
        }

        protected override bool ReleaseHandle()
        {
            return NativeMethods.SetupDiDestroyDeviceInfoList(this.handle);
        }

    }

    #endregion

    internal class NativeMethods
    {

        private const string setupapi = @"setupapi.dll";

        private NativeMethods()
        {
        }

        [DllImport(@"setupapi.dll", SetLastError = true)]
        public static extern bool SetupDiClassGuidsFromName(string ClassName, ref Guid ClassGuidArray1stItem, UInt32 ClassGuidArraySize, out UInt32 RequiredSize);

        [DllImport(setupapi, CallingConvention = CallingConvention.Winapi, SetLastError = true)]
        [return: MarshalAs(UnmanagedType.Bool)]
        public static extern bool SetupDiCallClassInstaller(DiFunction installFunction, SafeDeviceInfoSetHandle deviceInfoSet, [In()]
ref DeviceInfoData deviceInfoData);

        [DllImport(setupapi, CallingConvention = CallingConvention.Winapi, SetLastError = true)]
        [return: MarshalAs(UnmanagedType.Bool)]
        public static extern bool SetupDiEnumDeviceInfo(SafeDeviceInfoSetHandle deviceInfoSet, int memberIndex, ref DeviceInfoData deviceInfoData);

        [DllImport(setupapi, CallingConvention = CallingConvention.Winapi, CharSet = CharSet.Unicode, SetLastError = true)]
        public static extern SafeDeviceInfoSetHandle SetupDiGetClassDevs([In()]ref Guid classGuid, [MarshalAs(UnmanagedType.LPWStr)]string enumerator, IntPtr hwndParent, SetupDiGetClassDevsFlags flags);

        [DllImport(@"setupapi.dll", SetLastError = true, CharSet = CharSet.Auto)]
        [return: MarshalAs(UnmanagedType.Bool)]
        public static extern bool SetupDiGetDeviceInstanceId(
         IntPtr DeviceInfoSet,
         ref DeviceInfoData did,
         [MarshalAs(UnmanagedType.LPTStr)] StringBuilder DeviceInstanceId,
         int DeviceInstanceIdSize,
         out int RequiredSize
        );

        [SuppressUnmanagedCodeSecurity()]
        [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
        [DllImport(setupapi, CallingConvention = CallingConvention.Winapi, SetLastError = true)]
        [return: MarshalAs(UnmanagedType.Bool)]
        public static extern bool SetupDiDestroyDeviceInfoList(IntPtr deviceInfoSet);

        [DllImport(setupapi, CallingConvention = CallingConvention.Winapi, SetLastError = true)]
        [return: MarshalAs(UnmanagedType.Bool)]
        public static extern bool SetupDiSetClassInstallParams(SafeDeviceInfoSetHandle deviceInfoSet, [In()]ref DeviceInfoData deviceInfoData, [In()]ref PropertyChangeParameters classInstallParams, int classInstallParamsSize);

        [DllImport("setupapi.dll", CharSet = CharSet.Auto)]
        public static extern int CM_Get_Device_ID(
           UInt32 dnDevInst,
           IntPtr buffer,
           int bufferLen,
           int flags
        );
    }
}


        private void Button_Click_2(object sender, RoutedEventArgs e)
        {
            bool enable = true;
            NewMethod(enable);
        }

        private static void NewMethod(bool enable)
        {
            Guid classGuid = new Guid("745a17a0-74d3-11d0-b6fe-00a0c90f57da");
            JQD.SafeDeviceInfoSetHandle handle = JQD.NativeMethods.SetupDiGetClassDevs(ref classGuid, null, IntPtr.Zero, JQD.SetupDiGetClassDevsFlags.Present);

            List lit = new List();
            JQD.DeviceInfoData[] diDataAll = GetDeviceInfoData(handle);
           
            foreach (JQD.DeviceInfoData did in diDataAll)
            {
                int nBytes = 32;
                IntPtr ptrInstanceBuf = Marshal.AllocHGlobal(nBytes);
                JQD.NativeMethods.CM_Get_Device_ID((uint)did.DevInst, ptrInstanceBuf, nBytes, 0);
                string InstanceID = Marshal.PtrToStringAuto(ptrInstanceBuf);
                if (InstanceID.Contains(@"VID_053A&PID_0B01"))
                {
                    lit.Add(did);
                }

                Marshal.FreeHGlobal(ptrInstanceBuf);
            }
            //return;
            //foreach (JQD.DeviceInfoData did in lit)
            //{
                JQD.DeviceInfoData diData = lit[0];

                JQD.PropertyChangeParameters @params = new JQD.PropertyChangeParameters();

                @params.Size = 8;
                @params.DiFunction = JQD.DiFunction.PropertyChange;
                @params.Scope = JQD.Scopes.Global;
                if (enable)
                {
                    @params.StateChange = JQD.StateChangeAction.Start;
                }
                else
                {
                    @params.StateChange = JQD.StateChangeAction.Stop;
                }

                bool result = JQD.NativeMethods.SetupDiSetClassInstallParams(handle, ref diData, ref @params, Marshal.SizeOf(@params));

                result = JQD.NativeMethods.SetupDiCallClassInstaller(JQD.DiFunction.PropertyChange, handle, ref diData);
            //}
        }

        private static JQD.DeviceInfoData[] GetDeviceInfoData(JQD.SafeDeviceInfoSetHandle handle)
        {
            List data = new List();
            JQD.DeviceInfoData did = new JQD.DeviceInfoData();
            int didSize = Marshal.SizeOf(did);
            did.Size = didSize;
            int index = 0;
            while (JQD.NativeMethods.SetupDiEnumDeviceInfo(handle, index, ref did))
            {
                data.Add(did);
                index += 1;
                did = new JQD.DeviceInfoData();
                did.Size = didSize;
            }
            return data.ToArray();
        }

Query PnP device health Status


            string VendorMatching = "VID_053A&PID_0B01"; // Vendor Id Prod Id Minor Revisioin
            using (ManagementObjectSearcher searcher = new ManagementObjectSearcher("root\\CIMV2", "SELECT * FROM Win32_PnPEntity")) //Win32_PnPEntity Win32_USBHub
            {
                foreach (ManagementObject queryObj in searcher.Get())
                {
                    var v = new
                    {
                        ConfigManagerErrorCode = queryObj.Properties["ConfigManagerErrorCode"].Value,
                        Status = queryObj.Properties["Status"].Value,
                        StatusInfo = queryObj.Properties["StatusInfo"].Value,
                        Availability = queryObj.Properties["Availability"].Value,
                        LastErrorCode = queryObj.Properties["LastErrorCode"].Value,

                        DeviceID = queryObj.Properties["DeviceID"].Value,
                        PNPDeviceID = queryObj.Properties["PNPDeviceID"].Value,
                        ClassGuid = queryObj.Properties["ClassGuid"].Value,                        
                        HardwareID = queryObj.Properties["HardwareID"].Value,
                    };
                    if (v.DeviceID.ToString().Contains(VendorMatching)) 
                        
                        Debug.WriteLine(v);
                }
            }

// Win32_PnPEntity class has Error Code
// { ConfigManagerErrorCode = 0, Status = OK, StatusInfo = , Availability = , LastErrorCode = , DeviceID = HID\VID_053A&PID_0B01&MI_01&COL04\9&98E7406&0&0003, PNPDeviceID = HID\VID_053A&PID_0B01&MI_01&COL04\9&98E7406&0&0003, ClassGuid = {745a17a0-74d3-11d0-b6fe-00a0c90f57da}, HardwareID = System.String[] }

WMI USB Play and Play Device Add, Remove and Modify Event Watcher


        private ManagementEventWatcher watcherAttach;
        private ManagementEventWatcher watcherRemove;
        private ManagementEventWatcher watcherMod;

            watcherAttach = new ManagementEventWatcher();

              //object sender, EventArrivedEventArgs e
            watcherAttach.EventArrived += (s,e) =>
                {
                    var propData = e.NewEvent.Properties["TargetInstance"];
                    var mbObj = propData.Value as ManagementBaseObject;
                    if (mbObj.Properties["DeviceID"].Value.ToString().Contains(@"HID\VID_053A&PID_0B01"))
                    {

                     // Instance Id can be passed into various API  instId = queryObj.GetPropertyValue("PNPDeviceID").ToString();
                        Debug.WriteLine("Preh device added");
                    }
                };
            watcherAttach.Query = new WqlEventQuery("SELECT * FROM __InstanceCreationEvent " +
               "WITHIN 2 "+
              "WHERE TargetInstance ISA 'Win32_PnPEntity'");
            watcherAttach.Start();


            watcherRemove.Query =  new WqlEventQuery("SELECT * FROM __InstanceModificationEvent " +
               "WITHIN 2 " +
              "WHERE TargetInstance ISA 'Win32_PnPEntity'");

            watcherMod.Query =  new WqlEventQuery("SELECT * FROM __InstanceDeletionEvent " +
               "WITHIN 2 " +
              "WHERE TargetInstance ISA 'Win32_PnPEntity'");


            watcherAttach.Stop();
            watcherRemove.Stop();
            watcherAttach.Dispose();
            watcherRemove.Dispose();