Wednesday, February 29, 2012

Deep Copy Helper


       public static T DeepCopy<T>(T obj)
        {
            if (obj == null)
                throw new ArgumentNullException("Object cannot be null");
            return (T)Process(obj);
        }

        static object Process(object obj)
        {
            if (obj == null)
                return null;
            Type type = obj.GetType();
            if (type.IsValueType || type == typeof(string))
            {
                return obj;
            }
            else if (type.IsArray)
            {
                Type elementType = Type.GetType(
                     type.FullName.Replace("[]", string.Empty));
                var array = obj as Array;
                Array copied = Array.CreateInstance(elementType, array.Length);
                for (int i = 0; i < array.Length; i++)
                {
                    copied.SetValue(Process(array.GetValue(i)), i);
                }
                return Convert.ChangeType(copied, obj.GetType());
            }
            else if (type.IsClass)
            {
                object toret = Activator.CreateInstance(obj.GetType());
                //FieldInfo[] fields = type.GetFields(BindingFlags.Public |
                //            BindingFlags.NonPublic | BindingFlags.Instance);
                FieldInfo[] fields = GetAllFields(type).ToArray();
                foreach (FieldInfo field in fields)
                {
                    object fieldValue = field.GetValue(obj);
                    if (fieldValue == null)
                        continue;
                    field.SetValue(toret, Process(fieldValue));
                }
                return toret;
            }
            else
            {
                return null;
                //throw new ArgumentException("Unknown type");
            }
        }

        public static IEnumerable<FieldInfo> GetAllFields(Type t) { 
            if (t == null)         return Enumerable.Empty<FieldInfo>();
            BindingFlags flags = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static | BindingFlags.Instance
                | BindingFlags.DeclaredOnly; 

            return t.GetFields(flags).Union(GetAllFields(t.BaseType)); 
        } 

Note that If we restrict to Serializable then using Memory Stream can deep copy

   class Program
    {
        static void Main(string[] args)
        {
            Outside o = new Outside() { Data = new Inside() { Name = "n1", Price = 199 } };

            Outside o_sc = o.ShadowCopy;
            o_sc.Data.Name = "Changed"; // change o as well since Shadow copy reference
            Outside o_dc = o.DeepCopy;
            o_dc.Data.Name = "Reset"; // not affect o
        }
    }

    [Serializable]
    public class Outside
    {
        public Inside Data { get; set; }
        public Outside ShadowCopy { get { return  MemberwiseClone() as Outside ; } }
        public Outside DeepCopy
        {
            get
            {
                MemoryStream m = new MemoryStream();
                BinaryFormatter b = new BinaryFormatter();
                b.Serialize(m, this);
                m.Position = 0;
                return b.Deserialize(m) as Outside;
            }
        }
        
    }

    [Serializable]
    public class Inside
    {
        public string Name { get; set; }
        public double Price { get; set; }
    }

Sunday, February 19, 2012

HTML5 Canvas API


<canvas w h id="cv"/>

var ctx=document.getElementById("cv").getContext('2d');

Path Drawing:
ctx.beginPath();
ctx.moveTo(x,y);
ctx.lineTo(x1,y1);
ctx.closePath();

Fill
ctx.fillRec();
ctx.fillStyle='rgba(0,0,0,0.2)'; alpha 0.2 for black.

Mouse move vs. Touch move
cv.onMouseMove= function Draw(e) {..}
document.addEventListener('touchmove', function (e) { });

e.preventDefault(); not allow Ipad Giggle.
e.targetTouches[0].pageX;
ctx.transform (matrix+d);
cx.scale(60%);




Tuesday, January 31, 2012

Correlated Action ComboBox Behavior


<UserControl xmlns:i="http://schemas.microsoft.com/expression/2010/interactivity"
             xmlns:loc="clr-namespace:TestCorrTextBoxCustBehavior">

       <ComboBox Height="23" HorizontalAlignment="Left" Margin="12,48,0,0" Name="cb1" VerticalAlignment="Top" Width="120" >
            <i:Interaction.Behaviors>
                <loc:CorrelatedActionComboBoxBehavior SourceRegularExpression="['Basket Swap'|'CDS']" SourceTriggerType="RegExpression"  TargetControlId="lb1" TargetActionType="SetValue" TargetValue="2"/>
            </i:Interaction.Behaviors>
            <ComboBoxItem>1</ComboBoxItem>
            <ComboBoxItem>Basket Swap</ComboBoxItem>
            <ComboBoxItem>CDS</ComboBoxItem>
        </ComboBox>
        <TextBox Height="23" HorizontalAlignment="Left" Margin="268,48,0,0" Name="textBox2"  VerticalAlignment="Top" Width="120" />
        <ListBox Name="lb1" Width="100" Height="200" Margin="355,91,48,20">
            <ListBoxItem>1</ListBoxItem>
            <ListBoxItem>2</ListBoxItem>
            <ListBoxItem>3</ListBoxItem>
        </ListBox>



   public class CorrelatedActionComboBoxBehavior : Behavior</ComboBox>
    {

        public SourceTriggerType SourceTriggerType { get; set; }
        public string SourceRegularExpression { get; set; }
        public string TargetControlId { get; set; }
        public TargetActionType TargetActionType { get; set; }
        public string TargetValue { get; set; }
       
        protected override void OnAttached()
        {
            if (!(AssociatedObject is ComboBox)) return;
            object obj = AssociatedObject.Parent;
            Control mw = ((System.Windows.Controls.Panel)(obj)).Parent as Window;
            if (mw==null)
             mw = ((System.Windows.Controls.Panel)(obj)).Parent as Control;
            if (mw == null) return;

            AssociatedObject.DropDownClosed += (sender, e) =>
                { 
                    ComboBox cb = AssociatedObject as ComboBox;
                    if (SourceTriggerType == SourceTriggerType.RegExpression)
                    {
                        Regex r = new Regex(SourceRegularExpression);

                        Control c = FindChild(mw, TargetControlId);
                        c.IsEnabled = true;
                        if (r.IsMatch(cb.Text) )
                        {
                           if ( TargetActionType== TargetActionType.Disable ) c.IsEnabled = false;
                           if (TargetActionType == TargetActionType.SetValue)
                           {
                               ListBox lb = c as ListBox;
                               if (lb != null && TargetValue!="") SetListBoxValue(lb, TargetValue);
                           }

                        }
                    }
                };
        }

        private void SetListBoxValue(ListBox lb, string p)
        {
            for(int i=0;i< lb.Items.Count;i++)
            {
                if ((lb.Items[i] as ListBoxItem).Content.ToString()  == p) lb.SelectedIndex = i;
            }
        }

        public static T FindChild(DependencyObject parent, string childName)    where T : DependencyObject {      
            // Confirm parent and childName are valid.   
            if (parent == null) return null;    
            T foundChild = null;    
            int childrenCount = VisualTreeHelper.GetChildrenCount(parent);  
            for (int i = 0; i < childrenCount; i++)   {   
                var child = VisualTreeHelper.GetChild(parent, i);    
                // If the child is not of the request child type child   
                T childType = child as T;    
                if (childType == null)     {     
                    // recursively drill down the tree    
                    foundChild = FindChild(child, childName);     
                    // If the child is found, break so we do not overwrite the found child.     
                    if (foundChild != null) break;     }    
                else if (!string.IsNullOrEmpty(childName))     {   
                    var frameworkElement = child as FrameworkElement;     
                    // If the child's name is set for search     
                    if (frameworkElement != null && frameworkElement.Name == childName)       {    
                        // if the child's name is of the request name       
                        foundChild = (T)child;         break;       }     }  
                else     {       
                    // child element found.      
                    foundChild = (T)child;       break;     }   }  
            return foundChild; } 

     }

    public enum SourceTriggerType
    {
        RegExpression
    }

    public enum TargetActionType
    {
        Disable,
        SetValue
    }

Monday, January 30, 2012

WPF Custom Behavior

(1) Behavior is a gneric type <>, non-generic one has no public ctor
(2)  Need System.Interactivity.Dll from Blend SDK or MVVM light donwload

<Window x:Class="TestCustomBehavior.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="350" Width="525"
        xmlns:i="http://schemas.microsoft.com/expression/2010/interactivity"
        xmlns:ei="http://schemas.microsoft.com/expression/2010/interactions"
        xmlns:local="clr-namespace:TestCustomBehavior"
         >
    <Grid>
        <TextBlock Background="LightBlue" Height="23" HorizontalAlignment="Left" Margin="134,140,0,0" Name="textBlock1" Text="Drag Me Around" VerticalAlignment="Top" >
            <i:Interaction.Behaviors>
                <local:DragBehavior></local:DragBehavior>
            </i:Interaction.Behaviors>
        </TextBlock>
    </Grid>
</Window>



namespace TestCustomBehavior
{
    public class DragBehavior : Behavior<UIElement>
    {
        Point startPosMouse, startPosElement; int i = 0;
        TranslateTransform trans = new TranslateTransform();
        protected override void OnAttached()
        {
            Window parent = Application.Current.MainWindow;
            AssociatedObject.RenderTransform = trans;
            AssociatedObject.MouseLeftButtonDown += (sender, e) =>
                {
                    if (i == 0)
                    {
                        startPosElement = AssociatedObject.TranslatePoint(new Point(), parent); i = 1;
                    }
                    startPosMouse = e.GetPosition(parent);
                    AssociatedObject.CaptureMouse();
                };
            AssociatedObject.MouseLeftButtonUp += (sender, e) =>
                {
                    AssociatedObject.ReleaseMouseCapture();
                };

            AssociatedObject.MouseMove += (sender, e) =>
                {
                    Vector diff = e.GetPosition(parent) - startPosElement;
                    if (AssociatedObject.IsMouseCaptured)
                    {
                        trans.X= diff.X;
                        trans.Y = diff.Y;
                    }

                };
        }
    }
}

Sunday, January 29, 2012

WPF Printing using FixedDcoument


Print Preview Popup as FixedDocument

(1) PageContent will has Compiler Error but can stil render with FixedPage---Known Defect of WPF.
(2) Fixed document will has toolbar shown by WPF, no coded needed. So this is simplest printing

<Window x:Class="TestWPFPrinting.PrintPreview"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="PrintPreview" Height="300" Width="300">
    <FixedDocument Name="customerReport">

        <PageContent>

            <FixedPage>
                <Label FontSize="20" Margin="100,20,0,0">REPORT</Label>
                <ListView  BorderThickness="0" Margin="50,100,0,0" FontSize="14" Width="Auto" Height="Auto" ItemsSource="{Binding}">
                    <ListView.View>
                        <GridView x:Name="gridReport">

                            <GridViewColumn Width="200" Header="FirstName" DisplayMemberBinding="{Binding Path=FirstName}">

                                <GridViewColumn.CellTemplate>
                                    <DataTemplate>
                                        <Label/>
                                    </DataTemplate>
                                </GridViewColumn.CellTemplate>
                            </GridViewColumn>
                            <GridViewColumn Width="200" Header="LastName" DisplayMemberBinding="{Binding Path=LastName}">
                                <GridViewColumn.CellTemplate>
                                    <DataTemplate>
                                        <Label/>
                                    </DataTemplate>
                                </GridViewColumn.CellTemplate>
                            </GridViewColumn>
                        </GridView>
                    </ListView.View>
                </ListView>

            </FixedPage>

        </PageContent>
    </FixedDocument>
</Window>

Bind to Data
   public partial class PrintPreview : Window
    {
        private List<Customer> _customers;
        public PrintPreview(List<Customer> customers) 
        {
            InitializeComponent();
            _customers = customers;
            // generate report 
            this.DataContext = _customers; 
        }
    }

    public class Customer
    {
        private string _firstName;
        private string _lastName;

        public string FirstName
        {
            get { return _firstName; }
            set { _firstName = value; }
        }

        public string LastName
        {
            get { return _lastName; }
            set { _lastName = value; }
        }
    }

Main Form
       private void button1_Click(object sender, RoutedEventArgs e)
        {

            List<Customer> customers = new List<Customer>();

            for (int i = 1; i <= 200; i++)
            {
                Customer customer = new Customer();
                customer.FirstName = "FirstName " + i;
                customer.LastName = "LastName " + i;
                customers.Add(customer);
            }
            PrintPreview w = new PrintPreview(customers);
            w.Show();


Sunday, December 25, 2011

Using AppFabric


Client App Config:

<configSections>
    <!-- required to read the <dataCacheClient> element -->
    <section name="dataCacheClient" type="Microsoft.ApplicationServer.Caching.DataCacheClientSection,
            Microsoft.ApplicationServer.Caching.Core, Version=1.0.0.0, 
            Culture=neutral, PublicKeyToken=31bf3856ad364e35" allowLocation="true" allowDefinition="Everywhere"/>
  </configSections>

  <dataCacheClient>
    <transportProperties maxBufferPoolSize="7" maxBufferSize="200000000"/>


    <!-- (optional) specify local cache
      <localCache
         isEnabled="true"
         sync="TimeoutBased"
         objectCount="100000"
         ttlValue="300" /> -->

    <!--(optional) specify cache notifications poll interval
      <clientNotification pollInterval="300" /> -->

    <hosts>
      <host name="10.32.68.136" cachePort="22233"/>
      <!--<host
         name="CacheServer2"
         cachePort="22233"/>-->
    </hosts>
  </dataCacheClient>
Client Code No Config:
           DataCacheFactoryConfiguration cfg= new DataCacheFactoryConfiguration();
            cfg.Servers= new DataCacheServerEndpoint[]
            {
                new DataCacheServerEndpoint("10.32.68.136",22233)//jqdappfabric.dev.gmo.tld",22233)
            };
            Microsoft.ApplicationServer.Caching.DataCacheFactory f = new DataCacheFactory(cfg);
            Console.WriteLine("Factory Created");
            DataCache c=f.GetDefaultCache();
            Console.WriteLine("Cache Connected");
            Console.WriteLine("Put into Cache");
            c.Put("k1","v1");
            Console.WriteLine("Get From Cache");
            Console.WriteLine(c.Get("k1"));
Client Code with Config:
          DataCacheFactory cf = new DataCacheFactory();
            DataCache cache = cf.GetDefaultCache();
            cache.Put("AllEntityHierarchy", list);
            object obj = cache.Get("AllEntityHierarchy");
NOTE: if Visual Studio 2010 Intelle-trace shows "No DNS entry" then use Hosts file.
   

Some usefull PowShellCommand:
 
 import/export-CacheClusterConfig: shows/set user permission.
 start/stop-cachecluster
 grant/invoke-CacheAllowedClientAccount

Thursday, December 1, 2011

WebSocket Handler


Separate Open and Message and use Collection to Broadcast
public class JsonWebSocketHandler : WebSocketHandler
{

WebSocketCollection _wsCns = new WebSocketCollection();
public override void OnMessage(string message)
{
JavaScriptSerializer ser = new JavaScriptSerializer();
_wsCns.Broadcast(ser.Serialize( new
{
data="Test",
id=1
}));
}

public override void OnOpen()
{
_wsCns.Add(this);
}
}

IHttpHandler can inject WebSocketHanldler (Extension Method for Context)

public void ProcessRequest(HttpContext context)
{
if (context.IsWebSocketRequest)
{
context.AcceptWebSocketRequest(new JsonWebSocketHandler());
}
}

JavaScript also need to separate Open and Send

$(function () {
var cn = new WebSocket("ws://localhost/TestJsonWebSocket/jswsh.ashx");
$("#b").click( function ()
{
cn.onmessage = function (msg) {
alert(msg);
}
});

$("#b2").click(function () {
cn.send(window.JSON.stringify({ type: 1 }));
}
);

});