Wednesday, July 25, 2012

High Performance WPF/WCF


Serveral Keys for High Performance:
(1) WPF need to use ThreadPool (Task/ParallelFor) to call WCP in the backgroud
(2) Return data should be on Queues for Dispatcher Timer to pick up and update UI
(3) WCF Instancing.Single and Concurrency.Multiple seems to have better network 
through-put than Single/Single 
( Total B/Sec in Win8 Resource Monitor 220 vs 280, 20%+). But this not a serious performance Testing)
(4) one thing for sure: when Task is removed, UI will be slugish.





   public delegate void OnHeartbeat();
  
    public partial class MainWindow : Window
    {
        const int NUM = 5000;
        public event OnHeartbeat Heartbeat;
        DispatcherTimer t;
        DispatcherTimer t2;
        List<RealtimeData> dataList = new List<RealtimeData>();
        Dictionary<int, Queue> qList = new Dictionary<int, Queue<string>>();

        public MainWindow()
        {
            InitializeComponent();
            t = new DispatcherTimer() { Interval = new TimeSpan(0, 0, 0, 0, 1) };
            t.Tick += new EventHandler(t_Tick);
            t2 = new DispatcherTimer() { Interval = new TimeSpan(0, 0, 0, 0, 1) };
            t2.Tick += new EventHandler(t_Tick2);
            AddGridCell();
            t.Start();
            t2.Start();
        }

        void t_Tick(object sender, EventArgs e)
        {
            if (Heartbeat != null) Heartbeat();
        }

        void t_Tick2(object sender, EventArgs e)
        {
   
            Task.Factory.StartNew(() =>
            {
                Parallel.For(0, NUM, (ii) =>
               // for (int ii = 0; ii < NUM; ii++)
                {
                    try
                    {
                        ServiceReference1.Service1Client c = new ServiceReference1.Service1Client();
                        qList[ii].Enqueue(c.GetData(ii));
                        c.Close();
                    }
                    catch (Exception ex)
                    {
                        EventLog.WriteEntry("Application", ex.Message + " " + ex.StackTrace);
                    }
                });
               // }
            });
        }

        void AddGridCell()
        {

            for (int i = 0; i < NUM; i++)
            {
                qList.Add(i, new Queue());
                RealtimeData rtD = MakeDataItem(i);
                this.Heartbeat += rtD.UpdateData;
                dataList.Add(rtD);
                wrapPanel1.Children.Add(rtD);
            }
        }

  
        RealtimeData MakeDataItem(int i)
        {
            return new RealtimeData(qList[i]) { Width = 50, Height = 50, BorderBrush = new SolidColorBrush(Colors.Black), BorderThickness = new Thickness(2) };
        }

      
    
    }

    public class RealtimeData : UserControl
    {
        Label lb = new Label();
        Queue<string> _q; 
        public RealtimeData(Queue<string> q)
        {
            _q = q;
            this.AddChild(lb);
        }

        public void UpdateData()
        {
            int i = _q.Count;
            if (_q.Count > 0) lb.Content =i.ToString()+" "+ _q.Dequeue();
        }
 
    }




  // [ServiceBehavior(InstanceContextMode = InstanceContextMode.Single, ConcurrencyMode=ConcurrencyMode.Multiple)]
    [ServiceBehavior(InstanceContextMode = InstanceContextMode.Single, ConcurrencyMode = ConcurrencyMode.Single)]
    public class Service1 : IService1
    {
      
        public string GetData(int value)
        {
          //  Thread.SpinWait(300000);
            Random r = new Random();
            return string.Format(r.NextDouble().ToString());
        }

    }

Tuesday, July 17, 2012

WPF Prism MVVM using Unity and Mef

Summary: We need to Unity/Mef Bootstrap into Shell as Top Window, where two things
happen: the normal WPF Window.Show() and enable Dependency Injection (DI) as early
 as possible using UnityContainer.Resolve<Shell> or 
CompositeContainer.GetExportTypes<>. Note that basic services like
 EventAggregator are constructed by Unity/Mef and will be passed along through 
Container/Aggregate Catalog.
Note that WPF DataContext is set in ShellWindos Constructor for Unity and DInjected
 for Mef through [Import].


bootstrapper.cs

    #region Unity Bootstrapper

    class DemoUnityBootstrapper : UnityBootstrapper
    {

        protected override System.Windows.DependencyObject CreateShell()
        {
            return  Container.Resolve<ShellWindow>();  // must be resolved by Container to do DI
        }
        protected override void InitializeShell()
        {
            (Application.Current.MainWindow =(Window) Shell).Show();
        }

    }

    #endregion

    #region Mef Bootstrapping

    class DemoMefBootstrapper : MefBootstrapper
    {

        protected override System.Windows.DependencyObject CreateShell()
        {
            return new ShellWindow2(Container,AggregateCatalog);  //avoid DI [Export] on ShellWindow2
        }

        protected override void InitializeShell()
        {
            (Application.Current.MainWindow = (Window)Shell).Show();
        }

    }

    #endregion

App Startup

        protected override void OnStartup(StartupEventArgs e)
        {
                DemoUnityBootstrapper dub = new DemoUnityBootstrapper();
                dub.Run(true);

                DemoMefBootstrapper dmb = new DemoMefBootstrapper();
                dmb.Run(true);           
        }


Shell as Window

        public ShellWindow(IUnityContainer container)  //DI
        {
            InitializeComponent();
            // again, DI require Container.Resolve.
            var vm = container.Resolve<PrismDemo.MVVM.ViewModel>();
            var view = container.Resolve<PrismDemo.MVVM.View>();

            view.DataContext = vm;
            cc.Content = view;
        }

        public ShellWindow2(CompositionContainer c, AggregateCatalog a) //not DI
        {
            InitializeComponent();
           
            a.Catalogs.Add(new AssemblyCatalog(Assembly.GetExecutingAssembly()));
            IView v2 = c.GetExportedValue<IView>();  // invoke  Import-Export matching on V
            cc.Content = v2;
        }

View for Mef only, Unity has no code

    [Export(typeof(IView))]  // for Container.GetExport
    public partial class View2 : UserControl , IView
    {
        public View2()
        {
            InitializeComponent();
        }

        [Import]  // Import will Match Export of VM2
        public ViewModel2 ViewModel
        {
            set { this.DataContext = value; }
        }

        // declare which view is it for Modularity
        public string ViewName
        {
            get
            {
                return "View2";
            }
            set
            {
                throw new NotImplementedException();
            }
        }
    }

Xaml
    <Grid>
       <StackPanel>
        <TextBlock Background="#FF15ABB7">MVVM View, Data binding</TextBlock> 
        <TextBox Text="{Binding Path=SingleValue, Mode=TwoWay}" />
        </StackPanel>
    </Grid>


ViewMode

    public class ViewModel : INotifyPropertyChanged
    {
        IEventAggregator _eventAggregator;
        public ViewModel(IEventAggregator ea)  //Unity Ctor DI
        {
            _eventAggregator = ea;
        }

        string _SingleValue="test";
        public string SingleValue
        {
            get { return _SingleValue;}
            set 
            {
                _SingleValue=value;
                PropertyChanged(this, new PropertyChangedEventArgs("SingleValue"));
                Debug.Assert(_eventAggregator != null);  // test Event Aggregator get DInjected
            }
        }

        public event PropertyChangedEventHandler PropertyChanged;
    }

    [Export(typeof(ViewModel2))]
    public class ViewModel2 : NotificationObject 
    {
        [Import]  // Exported by Mef base Aggregate Catalog
        public IEventAggregator ea { get; set; }

        IEventAggregator propEa;
        [ImportingConstructor]
        public ViewModel2(IEventAggregator ea2)
        {
            propEa = ea2;
        }


        string _SingleValue = "test";
        public string SingleValue
        {
            get { return _SingleValue; }
            set
            {
                _SingleValue = value;
                RaisePropertyChanged("SingleValue");
                Debug.Assert(ea != null & propEa != null); // test Event Aggregator get DInjected as Ctor and Prop
            }
        }
    }




Saturday, July 14, 2012

Trading Signals from EMA and RSI

[hist_date, hist_high, hist_low, hist_open, hist_close, hist_vol] =get_hist_stock_data('AAPL','2012');
data=hist_close;
[lead,lag]=movavg(data,5,20,'e');
s=zeros(size(data));
s(lead<=lag)=-1;
s(lead>lag)=1;
r=[0;s(1:end-1).*diff(data)];
R=cumsum(r);

% ax(1) = subplot(2,1,1);
% plot([data,lead,lag]); grid on
% legend('Close','Lead','Lag','Location','Best')
% title(['Data, Lead and Lag MA'])
% ax(2) = subplot(2,1,2);
% plot([s*50,cumsum(r)]); grid on
% legend('signal long and short','Cumulative Return','Location','Best')
% linkaxes(ax,'x')

rsi=rsindex(data,14)
s1=zeros(size(data));
s1(rsi>75)=-1;
s1(rsi<25)=1;
r1=[0;s1(1:end-1).*diff(data)];
R1=cumsum(r);

ax(1) = subplot(2,1,1);
plot([data]); grid on
legend('Close','Location','Best')
title(['Close'])
ax(2) = subplot(2,1,2);
plot([s1*25,R1]); grid on
legend('RSI Signal long short,no action','Cumulative Return','Location','Best')
linkaxes(ax,'x')

Interesting javascript code


Get Radio button value and update Telerik Paging for refresh presevation
   // F12 and debugger showed the structure
    $(document).ready(function() {
        var rb = $("input[id='rbfilterType']:radio:checked").attr('value');
        $("a[href*='TheGrid-page']").each(function(i) {
            var h = this.href;
            this.href =replaceQueryString(this.href, "filterType",rb);
        }
       );
    }
    )
    function replaceQueryString(url, param, value) {
        var re = new RegExp("([?|&])" + param + "=.*?(&|$)", "i");
        if (url.match(re))
            return url.replace(re, '$1' + param + "=" + value + '$2');
        else
            return url + '&' + param + "=" + value;
    } 

Using CSS Scrollbar to replace malfunction Teleric Scrollbar
 // find the inner table and add scrollbar heigth to hide v-bar
    $(document).ready(function() {
        var h = $("#grdTestList table").height();
        var h1 = h + 45;
        $("#grdTestList").attr("style", "overflow:auto;height:"+h1+"px");

    }
    )

Refreshing

<input type="button" value="Close and Refresh" onclick="javascript:document.location.reload();" />

            <input type="button" value="Close and Refresh" onclick="javascript:Window_onClose();" />
    
    
    <script type="text/javascript">
        function Window_onClose() {
            var window = $('#editDialog').data('tWindow');
            window.close();
            document.getElementById("submit").click();
        }
    </script>


Modify Telrik UI using jQuery

    $(document).ready(function() {

        var anof = $("a.fa:contains('Add new record')")
        anof.text("Add location");

        var anofr = $("a.fra:contains('Add new record')")
        anofr.text("Add man");
        anofr.mouseup(function(event) { setCookie("pos", event.pageY, 1); });
        var pos = getCookie("pos");
        if (!isNaN(pos)) scrollTo(0, pos);  // maintain scroll position
        setCookie("pos", "", 0);

        var url = window.location.href;
        if (url.indexOf("grd-mode=edit", 0) <= 0) {  // edit mode
            $("#save").click(function(e) {
                e.preventDefault();
            });
        }

         anof.click(function() {
            anof[0].href = removeParameter(anof[0].href, "grd-mode")
        });
        anofr.click(function() {
            anofr[0].href = removeParameter(anofr[0].href, "grd-mode")
        });
    }

    )

Friday, July 13, 2012

State Machine Desing Pattern






  #region SM definition and setup

    public interface IState
    {
        void EventSink(string eventData);
        void GoToNextState();
    }

    public class StateMachine
    {
        List _states ;
        public IState CurrentState { get; set; }
        public StateMachine()
        {
            _states = new List() { new State1(this), new State2(this)};  // omited Start and End State
        }

        public void SignalEvent(string infor)
        {
            if (infor == "Start")
            {
                CurrentState = (from _ in _states where _.GetType() == typeof(State1) select _).FirstOrDefault();
            }
            CurrentState.EventSink(infor);
        }

        internal void MoveState(IState st)
        {
            if (st.GetType() == typeof(State1))  // State2 would have move to End State
                CurrentState = (from _ in _states where _.GetType() == typeof(State2) select _).FirstOrDefault();
        }
    }

    #endregion


    #region Concrete States

    public class State1 : IState
    {
        StateMachine _sm;
        public State1(StateMachine sm)
        {
            _sm = sm;
        }
        public void EventSink(string eventData)
        {
            if (eventData == "RequiredInforType1Received")
            {
                Console.WriteLine("Processing Type1 Infor");
                Console.WriteLine("Passed, move to state2");
                GoToNextState();
            }
        }

        public void GoToNextState()
        {
            _sm.MoveState(this);
        } 
  
    }


    public class State2 : IState
    {
        StateMachine _sm;
        public State2(StateMachine sm)
        {
            _sm = sm;
        }
        public void EventSink(string eventData)
        {
            if (eventData == "RequiredInforType2Received")
            {
                Console.WriteLine("Processing Type2 Infor");
                Console.WriteLine("Passed, move to end state");
                GoToNextState();
            }
        }

        public void GoToNextState()
        {
            _sm.MoveState(this);
        }
    }

    #endregion

        static void Main(string[] args)
        {
            StateMachine sm = new StateMachine();
            sm.SignalEvent("Start");
            sm.SignalEvent("RequiredInforType1Received");
            sm.SignalEvent("RequiredInforType12Received");
            
            Console.ReadKey();
        }

Wednesday, July 4, 2012

IoC inject data into DropDownListFor

  DropDownListFor(m=>m.Name, ViewData["TheList"] requires repeatedly build ViewData. AutoFac IoCContainer Dependency Injection Could be used to avoid duplicating these code:

(1) We need to build Referenc List Types so we can resolve a Generic Type for IoC (i.e we cannot use Enum)
(2) Dependency Inject will inject a Repository IReferenceListRepository
(3) The generic Type SelectionList  must be able to render a list of SelectItem to feed into DropDownListFor base(LinqExpression, IEnumeralb)
(4) DropDownListFor Extension can now  build a generic type using type input param

    #region Reference List types

    public class USStatesRefList : ReferenceListType { }
    public class ApppealStatusesRefList : ReferenceListType { }
    public class EscalationToRefList : ReferenceListType { }

    public class ReferenceListType
    {
        public int Id { get; set; }
        public string Description { get; set; }
        public string ShortName { get; set; }
    }

    #endregion

  #region Ref Data Repository

    public interface IReferenceListRepository
    {
        IEnumerable<T> All<T>();
    }

    public class ReferenceListRepository : IReferenceListRepository
    {
        public IEnumerable<T> All()
        {
            // TODO; Build List from Database or RavenDB
            if (typeof(T)==typeof(USStatesRefList))
            {
              List<USStatesRefList> list= new List<USStatesRefList>() { new USStatesRefList() { Id=1, ShortName="MA", Description="MASS"}, new USStatesRefList() {Id=2, ShortName="NY",Description="Empire State"}};
              return (IEnumerable <T> ) list.AsEnumerable();
            }
            return default(IEnumerable<T>);
        }
    }
    #endregion

  #region Selection List -- can fill dropdown

    public class SelectionList<T> : IReferenceListRenderer where T : ReferenceListType
    {
       
        IEnumerable<T> _All { get;  set; }

       // Repository get injected here
        public SelectionList(IReferenceListRepository repository)
        { 
           _All = repository.All<T>();
        }

        public List<SelectListItem> RenderList(IConvertible value)
        {
            return (from p in _All
                   select
                       new SelectListItem
                       {
                           Value = null, // p.Id.ToString(),  DropDownList mal function if Value get set
                           Text =p.ShortName,// string.Format("{0} ({1})", p.Description, p.Id),
                           Selected =ValueEqual(p,value)
                       }).ToList();
        }

        public bool ValueEqual(ReferenceListType p, IConvertible value)
        {
            // For selection List, shortname matching ToString() is the only valid case
            return p.ShortName == Convert.ToString(value);
        }
    }

    public interface IReferenceListRenderer
    {
        List<SelectListItem> RenderList(IConvertible value);
    }

    #endregion


   #region Drop Down List  without using ViewData

    public static class DropDownListExtensions
    {
        public static MvcHtmlString DropDownListFor<TModel, TProperty>(this HtmlHelper<TModel> h,
                                                                       Expression<Func<TModel, TProperty>> expression,
                                                                       Type listType) where TProperty : IConvertible
        {

            var property = expression.Compile()(h.ViewData.Model);

            var SelectionListT = typeof(SelectionList<>).MakeGenericType(listType);
            var listR = DependencyResolver.Current.GetService(SelectionListT) as IReferenceListRenderer;
           List<SelectListItem> list = listR.RenderList(property);
            return h.DropDownListFor(expression,list );
        }
    }

    #endregion

@Html.DropDownListFor(m => m.Name, typeof(USStatesRefList));

Boiler Template code to hook up IoC

 protected void Application_Start()
        {
      var builder = new ContainerBuilder();
            builder.RegisterControllers(typeof(MvcApplication).Assembly);//Assembly.GetExecutingAssembly());
            builder.RegisterModelBinders(Assembly.GetExecutingAssembly());
            builder.RegisterModule(new ApplicationModule());
            
            var container = builder.Build();
            DependencyResolver.SetResolver(new AutofacDependencyResolver(container));

   public class ApplicationModule : Module
    {
        protected override void Load(ContainerBuilder builder)
        {
           // builder.RegisterInstance<ILog>(LogManager.GetLogger("TheInstance"));
            builder.RegisterType<ReferenceListRepository>().As<IReferenceListRepository>().InstancePerLifetimeScope();
            builder.RegisterGeneric(typeof(SelectionList<>)).SingleInstance();
           
        }


Monday, July 2, 2012

Using AutoFac IocContainer to inject Log4Net into MVC3

Nugget AutoFac, AutoFac.MVC3 and Log4Net into a MVC3 project

Create a Module to register

    public class ApplicationModule : Module
    {
        protected override void Load(ContainerBuilder builder)
        {
           // builder.RegisterInstance(LogManager.GetLogger("TheInstance"));
           
        }
        protected override void AttachToComponentRegistration(Autofac.Core.IComponentRegistry componentRegistry, Autofac.Core.IComponentRegistration registration)
        {
           
            registration.Preparing += registration_Preparing;
        }

        static void registration_Preparing(object sender, Autofac.Core.PreparingEventArgs e)
        {
            var t = e.Component.Activator.LimitType;
            e.Parameters = e.Parameters.Union(
                new[]
                {
                                new ResolvedParameter((p, i) => p.ParameterType == typeof(ILog), (p, i) => LogManager.GetLogger(t))  
                }
                );
        }
    }



Create Container, Register, Build and setResolver


       protected void Application_Start()
        {
           ...

            var builder = new ContainerBuilder();
            builder.RegisterControllers(typeof(MvcApplication).Assembly);//Assembly.GetExecutingAssembly());
            builder.RegisterModule(new ApplicationModule());
            var container = builder.Build();
            DependencyResolver.SetResolver(new AutofacDependencyResolver(container));
        }

Inject into COnstructor

  public class HomeController : Controller
    {

        public HomeController(ILog log)
        {