Blog Archive

Thursday, August 28, 2014

Set property value without reference types

Including Reference could mess up code (e.g circulare refernce or DI failure). So use reflection while walk up down logical tree will fix that. In fact, runtime type resolution in dynamic language does just that.
        void SetPropertyOfAncestor(FrameworkElement framewkElement, string AncestorTypeName,string propName, object propValue)
        {
            FrameworkElement current = VisualTreeHelper.GetParent(framewkElement) as FrameworkElement;
            while (current != null)
            {
                Type t = current.GetType();
                if (t.Name == AncestorTypeName)
                {
                    PropertyInfo pi = t.GetProperty(propName);
                    if (pi != null)
                    {
                        pi.SetValue(current, propValue, null);
                        return;
                    }
                    else
                    {
                        current = VisualTreeHelper.GetParent(current) as FrameworkElement;
                    }
                }
                else
                {
                    current = VisualTreeHelper.GetParent(current) as FrameworkElement;
                }
            }
        }

Tuesday, August 19, 2014

WPF UI Automation C# and IronPython Code

Tools: add referecne to UIAutmationClient and UIAutomationTypes. Inspect.exe under local Windows SDK 
directory, used for find AutomationId, name of logical tree, similar to Scoop.

            Process p = Process.Start(@"..\..\..\TryoutUITesting\bin\Debug\TryoutUITesting.exe");
            AutomationElement desktop = AutomationElement.RootElement;
            AutomationElement mainWin =null;
            while( (mainWin= desktop.FindFirst(TreeScope.Children, new PropertyCondition(AutomationElement.NameProperty, "MainWindow")))==null) {}
          AutomationElement button=  mainWin.FindFirst(TreeScope.Children, new PropertyCondition(AutomationElement.AutomationIdProperty, "btn"));
          InvokePattern buttonClick = button.GetCurrentPattern(InvokePattern.Pattern) as InvokePattern;
          buttonClick.Invoke();

          AutomationElement textbox = mainWin.FindFirst(TreeScope.Children, new PropertyCondition(AutomationElement.AutomationIdProperty, "tbx"));
          TextPattern textboxText= textbox.GetCurrentPattern(TextPattern.Pattern) as TextPattern;
          string result = textboxText.DocumentRange.GetText(-1);
          Debug.Assert(result == "Foo");

from System.Diagnostics import Process
from System.Diagnostics import Debug

import clr
clr.AddReference("UIAutomationClient")
clr.AddReference("UIAutomationTypes")
from System.Windows.Automation import *
from System.Windows.Automation import PropertyCondition


def main():
    p=Process.Start("C:\\working\\TryoutWPFTesting\\TryoutWPFTesting\\bin\\Debug\\TryoutWPFTesting.exe")
    desktop=AutomationElement.RootElement

    mainWin =None
    while (mainWin==None): 
        mainWin= desktop.FindFirst(TreeScope.Children, PropertyCondition(AutomationElement.NameProperty, "MainWindow"))

    button=  mainWin.FindFirst(TreeScope.Children, PropertyCondition(AutomationElement.AutomationIdProperty, "btn"))
    buttonClick = button.GetCurrentPattern(InvokePattern.Pattern)
    buttonClick.Invoke()
 
    textbox = mainWin.FindFirst(TreeScope.Children, PropertyCondition(AutomationElement.AutomationIdProperty, "tbx"))
    textboxText= textbox.GetCurrentPattern(TextPattern.Pattern)
    result = textboxText.DocumentRange.GetText(-1);
    Debug.Assert(result == "Foo");
    p.WaitForExit()

if __name__=="__main__":
    main()

Tuesday, August 12, 2014

Git Branching Strategy

Pull = update your feature branch or local copy before commit/merge.
Fetch = update local master, not your branch
Fast Forward != merge
Merge = heavies and post feature development

Rebase = Complicated, carry history, Pull down code relative to upstream/mster.


Three rebase Scenarios

Monday, August 11, 2014

Custom Region Adapter

IRegionManager can register view with Region but by default only works for Content Control (single item), ItemsControl (2+ Items)
   <ContentControl Grid.Row="1"  cal:RegionManager.RegionName="{x:Static def:RegionNames.PricingGridRegion}" />
    regMgr.RegisterViewWithRegion("PricingGridRegion", typeof(DurationTraderView));

        <!--<ItemsControl cal:RegionManager.RegionName="{x:Static def:RegionNames.PricingGridRegion}"/>-->

        <StackPanel cal:RegionManager.RegionName="{x:Static def:RegionNames.PricingGridRegion}" Orientation="Horizontal" FlowDirection="RightToLeft" />

Custom Region Adapter is needed to register into Stack Panel:

    public class StackPanelRegionAdapter : RegionAdapterBase<StackPanel>
    {
        public StackPanelRegionAdapter(RegionBehaviorFactory factory) : base(factory) { }


        protected override void Adapt(IRegion region, StackPanel regionTarget)
        {
            region.Views.CollectionChanged+=(s,ea)=>
                {
                    if(ea.Action== NotifyCollectionChangedAction.Add)
                    {
                        foreach(FrameworkElement fe in ea.NewItems)
                        {
                         regionTarget.Children.Add(fe);
                        }
                    }
                };
        }

        protected override IRegion CreateRegion()
        {
            return new AllActiveRegion();
          //  return new SingleActiveRegion(); // if onely one item
        }

    }

    public class Module : IModule
    {
        public void Initialize()
        {
            IRegion reg = _regMgr.Regions[RegionNames.PricingGridRegion];
            reg.Add(_container.Resolve<SampleView>());
            reg.Add(_container.Resolve<SampleView>());
            reg.Add(_container.Resolve<SampleView>());
            reg.Add(_container.Resolve<SampleView>());
            reg.Add(_container.Resolve<SampleView>());
        }


Saturday, August 9, 2014

Basis Spread and Butterfly Spread Trading

Simplest Price based spread trading

Friday, August 8, 2014

Covariant and Contravariant

Note that these constraints can be overridden by code, extension method to convert anything to anything

    class Program
    {
        static void Main(string[] args)
        {
            IW<String> iwStr = new W<string>("Test");
            IW<object> iwObj =  iwStr.ToObject2();
        } 
    }

    public interface IW<T>
    {
        T W { get;  }
    }

    public class W<T> : IW<T>
    {
        T _w;
        public W(T w)
        {
            _w = w;
        }
        T IW<T>.W
        {
            get { return _w; }
        }
    }

    public static  class Ext
    {
        public static IW<object> ToObject2(this IW<string> iw)
        {
            return new W<object>(iw.W);
        }
    }

Thursday, August 7, 2014

Notes on Expression Blend

1. Gradient can used on Background and Opacity Mask. the latter could be on an Image

2. Control States are model by Visual State Group (Common, Focused) and a grid can have Opacity set for two group if not conflict
    These states are visible only Edit Template --> Edit Copy for a control.

3. Two workspace under windows: Design and Animation. The 1st relates to animation by Assets-> Control  StoryBoard action and 
set event trigger  and StoryBoard1.

4. Animation workSpace can utilize Transform Property and specifically Layout Transform to do Rotation. It may need to first turn off 
recording for StoryBoard to set key frame at 0 sec, then recording on to drag to sec to rotate 360 and restore size back.

5. Any group of Path, Drawing, Image, Controls can be Object/Timeline -->select multiple--> right click->Control->make User Control.
Its code behind can define a public prop showing up in Properties Grid Misc when it is hosted in a MainWindow.xaml.

6. Shape Set Operation and arbitrary path generation: any two shape can object->Combine -->(Unit, Substract, Intersect), including 
TextBlock where text can be substracted.  Also can convert Shape to path by Object->Path-->Convert to path. 

7. Carry User Control around: User Control build in Control Library Project can be used in WPF project seen under Assets Tab. 
Need to add project references. This also works even for any project type but have to manually add/remove when UC changes. Also add existing
 item as UC but that is just a copy of Xaml and cs and new changes will not automatically moved.

8. Easing Function: must select a Key Frame for property visible, in Animation Workspace. KeySpline =Simple cubic,Hold-in=no interpolation,
 direct to the end. 

9. Layout Controls: Grid's ScrollbarVisibility Property checkbox are attached property ScrollViewer.* and
 does not work well. So directly set it on ScrollViewer if you can; DockPanel LastChildFill also attached
 property and override the last child dock.

10. Layout Controls has Canvas and Grid, Grid has two mode: Grid Model and Canvas mode. the latter mode is not Canvas but behave 
like one --- child control are absolutely positioned not responding to Grid resizing.

11. Layout controls Border is very different: it has Border Brush, Back Ground, Corner Radius. But it can only hold one child.
 To host more children need to Object->Group into --> Grid to add grid and drag on more child.