Monday, May 16, 2016

How do you pass arguments to a Thread that you create

1. Pass data using Lambda Expressions:
  1. static void Main()
  2. {
  3. String m = "yeahh!";
  4. Thread thread = new Thread ( () => PrintToConsole (m) );
  5. thread.Start();
  6. }
  7. static void PrintToConsole (string message)
  8. {
  9. Console.WriteLine (message);
  10. }

In the above example we have effectively passed m into the thread function. Any number of parameters can be passed this way.

2. Another way is to use the overloaded Thread.Start function which accepts ParamterizedThreadStart.

  1. string parameter = "xyz";
  2. Thread thread = new Thread(new ParameterizedThreadStart(PrintToConsole));
  3. thread.Start(parameter);
  4. private void PrintToConsole(object o)
  5. {
  6. String m = (String) o;
  7. Console.WriteLine(m);
  8. }

3. This is the same as (1) but the example is for .Net 4.0 Tasks

  1. Task.Factory.StartNew(() => SomeMethod(p1,p2,p3));

Thread Pool

Creating a Thread is expensive as it requires a few hundred milliseconds to create a new one. Additionally each thread requires atleast around 1MB of data. So instead of creating and destroying a thread each time we could just create a collection of preinstantiated threads and use them instead. Whenever we require a thread we ask thread pool for a thread which we can use and when we are done with it instead of destroying it we can send it back to the collection for recycling. This way we avoid the cost it incurs for creating and destroying threads. This collection of preinstantiated thread is called a Thread Pool.

Wednesday, April 27, 2016

Dependency Injection

This pattern we use to break the strongly dependency across the class level.

Say, you have Class which does Database operation inside this class you want some logger to perferm like logging the debug message into the flat file.

var log = new Logger();

It is fine up to the day later sometime we have bunch of loggers available like logging Server,console or TCP/IP etc.

Of course we do not want to change all code and replace all lines with

var logger = new Logger();
by
var logger = new TcpLogger();
It is quite good idea to introduce an Interface ILog that is implemented by all the various loggers.

ILog logger = new Logger();
or
ILog logger = new TCPLogger();
or
ILog logger = new ConsoleLogger();

Now the type interface doesn't change type any more, we always keep single interface across.

 

interface ILog       {         void Log(string msg);       }       class Logger : ILog       {         public void Log(string msg)         {           //write to file.         }       }       class TCPLogger : ILog       {         public void Log(string msg)         {           //write to Server - TCP/IP.         }       }       class ConsoleLogger : ILog       {         public void Log(string msg)         {           //write to Console.         }       }       class Database       {         ILog _ilog;         public Database(ILog ilog)         { // Dependency Injection.           _ilog = ilog;         }         public void ExecuteNonQuery(string sql)         {           //do database operaion           _ilog.Log("some Database operation happened");         }       }  

Marshaling

What is Marshaling?
Creating a bridge between the Managed code and unmanaged code . Which carries messages from the managed to the unmanaged environment and viseversa provided by CLR.

Why Marshaling?

You already know that there is no such compatibility between managed and unmanaged environments. In other words, .NET does not contain such the types HRESULT, DWORD, and HANDLE that exist in the realm of unmanaged code. Therefore, you need to find a .NET substitute or create your own if needed. That is what called marshaling.

An example is the unmanaged DWORD; it is an unsigned 32-bit integer, so we can marshal it in .NET as System.UInt32. Therefore, System.UInt32 is a substitute for the unmanaged DWORD. On the other hand, unmanaged compound types (structures, unions, etc.) do not have counterparts or substitutes in the managed environment. Thus, you'll need to create your own managed types (structures/classes) that will serve as the substitutes for the unmanaged types you use.

When I Need to Marshal?
Marshaling comes handy when you are working with unmanaged code, whether you are working with Windows API or COM components. It helps you interoperating (i.e. working) correctly with these environments by providing a way to share data between the two environments. Figure 1 shows the marshaling process, where it fall, and how it is required in the communication process between the two environments. 

Monday, April 25, 2016

Invoke() and BeginInvoke()


What's the difference between Invoke() and BeginInvoke()

Delegate.Invoke/BeginInvoke and Control.Invoke/BeginInvoke

Delegate.Invoke: Executes synchronously, on the same thread.
Delegate.BeginInvoke: Executes asynchronously, on a threadpool thread.

Control.Invoke: Executes on the UI thread, but calling thread waits for completion before continuing.
Control.BeginInvoke: Executes on the UI thread, and calling thread doesn't wait for completion.

A logical conclusion is that a delegate you pass to Invoke() can have out-parameters or a return-value, while a delegate you pass to BeginInvoke() cannot (you have to use EndInvoke to retrieve the results).

 new Thread(foo).Start();     private void foo()     {     this.Dispatcher.BeginInvoke(DispatcherPriority.Normal,     (ThreadStart)delegate()     {     myTextBox.Text = "bing";     Thread.Sleep(TimeSpan.FromSeconds(3));     });     MessageBox.Show("done");     } 

If use BeginInvoke, MessageBox pops simultaneous to the text update. If use Invoke, MessageBox pops after the 3 second sleep. Hence, showing the effect of an asynchronous (BeginInvoke) and a synchronous (Invoke) call.


Delegate.BeginInvoke() asynchronously queues the call of a delegate and returns control immediately. When using Delegate.BeginInvoke(), you should call Delegate.EndInvoke() in the callback method to get the results.

Delegate.Invoke() synchronously calls the delegate in the same thread.

why and when to use Invoke().

Both Invoke() and BeginInvoke() marshal the code you specify to the dispatcher thread.

But unlike BeginInvoke(), Invoke() stalls your thread until the dispatcher executes your code. You might want to use Invoke() if you need to pause an asynchronous operation until the user has supplied some sort of feedback.

For example, you could call Invoke() to run a snippet of code that shows an OK/Cancel dialog box. After the user clicks a button and your marshaled code completes, the invoke() method will return, and you can act upon the user's response.

Saturday, November 7, 2015

Filling a combobox on selection of another combo box

This example code will explains how to fill a combo box on the selection of another combo box and also explains about the MVVM architecture pattern.

Simple way to understand the  MVVM architecture pattern.
Let us split the MVVM as
      M                     V                       VM
  (model)             (View)               (ViewModel)
(model.cs)        (XAML file)          (ViewModel.cs)

For an example let us consider , there are two combo box , in one combo box we are filling list of countries and on selection of first combobox second combobox will be filled with the country specific languages. In addition to it let us have one text box which is going to show the country currency.

Take a look on Designing the classes.
MODEL : We are going to write methods which brings countries lists.
VIEWMODEL: An another class which contains the Property of display member of MODEL class to show on UI (VIEW)
VIEW: XAML binding of VIEWMODEL.

XAML file
<?xml version="1.0" encoding="utf-8"?>  
 <Window  
   x:Class="MvvmCombo.Window1" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"  
   Title="MvvmCombo"  
   Height="417"  
   Width="496">  
   <Grid  
     Name="mGrid"  
     HorizontalAlignment="Left"  
     VerticalAlignment="Top"  
     Width="479"  
     Height="374">  
     <ComboBox        
       ItemsSource="{Binding Countries}"         
       SelectedItem="{Binding SelectedCountry}"  
       DisplayMemberPath="DisplayName"  
       Grid.Column="1"  
       Grid.Row="1"  
       HorizontalAlignment="Left"  
       VerticalAlignment="Top"  
       Margin="10.99999999687,1.5,0,0"  
       Width="208"  
       Height="27"  
       SelectedIndex="0" />  
     <ComboBox  
       ItemsSource="{Binding Lang}"  
       Grid.Column="1"  
       Grid.Row="2"  
       HorizontalAlignment="Left"  
       VerticalAlignment="Top"  
       Margin="10.99999999687,3.50000000000006,0,0"  
       Width="208"  
       Height="26"  
       SelectedIndex="{Binding SelectedIndex}" />  
     <TextBox  
       Name="txtCur"  
       Text="{Binding Currency}"  
       IsReadOnly="True"  
       Height="29"  
       Width="208"  
       Margin="10.99999999687,3.50000000000007,0,0"  
       VerticalAlignment="Top"  
       HorizontalAlignment="Left"  
       Grid.Row="3"  
       Grid.Column="1" />  
     <Label  
       Content="Countries"  
       Grid.Column="0"  
       Grid.Row="1"  
       HorizontalAlignment="Left"  
       VerticalAlignment="Stretch"  
       Margin="8,1.5,0,5.49999999999994"  
       Width="65"  
       Height="27" />  
     <Label  
       Content="Language"  
       Grid.Column="0"  
       Grid.Row="2"  
       HorizontalAlignment="Left"  
       VerticalAlignment="Stretch"  
       Margin="8,5.00000000000006,0,5.49999999999993"  
       Width="65"  
       Height="24.5" />  
     <Label  
       Grid.Column="0"  
       Grid.Row="3"  
       HorizontalAlignment="Left"  
       VerticalAlignment="Stretch"  
       Margin="8,3.50000000000007,0,8.50000000000004"  
       Width="54"  
       Height="29"  
       Content="Currency" />  
     <TextBox  
       Name="txtCurSym"  
       IsReadOnly="True"  
       Text="{Binding CurrencySym}"  
       Grid.Column="1"  
       Grid.Row="3"  
       HorizontalAlignment="Stretch"  
       VerticalAlignment="Top"  
       Margin="251.635641460119,3.50000000000009,94.1004888627257,0"  
       Width="46"  
       Height="30" />  
     <Grid.ColumnDefinitions>  
       <ColumnDefinition  
         Width="0.182179268637068*" />  
       <ColumnDefinition  
         Width="0.817820731362932*" />  
     </Grid.ColumnDefinitions>  
     <Grid.RowDefinitions>  
       <RowDefinition  
         Height="0.0971428571428572*" />  
       <RowDefinition  
         Height="0.106124505217704*" />  
       <RowDefinition  
         Height="0.0992443324937027*" />  
       <RowDefinition  
         Height="0.102439726520331*" />  
       <RowDefinition  
         Height="0.0988269161568912*" />  
       <RowDefinition  
         Height="0.0856423173803527*" />  
       <RowDefinition  
         Height="0.410579345088161*" />  
     </Grid.RowDefinitions>  
   </Grid>  
 </Window>  


MODEL FILE
 using System;  
 using System.Collections;  
 using System.Collections.Generic;  
 using System.Globalization;  
 using System.Linq;  
 using System.Text;  
 using System.Threading.Tasks;  
 namespace MvvmCombo  
 {  
   class Model  
   {  
     public Model()  
     {  
     }  
     public List<RegionInfo> GetCountries()  
     {  
       RegionInfo country = new RegionInfo(new CultureInfo("en-US", false).LCID);  
       List<RegionInfo> countryNames = new List<RegionInfo>();  
       foreach (CultureInfo cul in CultureInfo.GetCultures(CultureTypes.SpecificCultures))  
       {  
         country = new RegionInfo(new CultureInfo(cul.Name, false).LCID);  
         countryNames.Add(country);          
       }  
       return countryNames.OrderBy(names => names.DisplayName).Distinct().ToList();  
     }  
     public List<CultureInfo> GetCountriesAll()  
     {  
       List<CultureInfo> list = new List<CultureInfo>();  
       foreach (System.Globalization.CultureInfo ci in   
         System.Globalization.CultureInfo.GetCultures(System.Globalization.CultureTypes.AllCultures))  
       {         
         list.Add(System.Globalization.CultureInfo.CreateSpecificCulture(ci.Name));  
       }  
       return list;  
     }  
   }  
 }  
\
ViewModel File
using System;  
 using System.Collections.Generic;  
 using System.Globalization;  
 using System.Linq;  
 using System.Text;  
 using System.Threading.Tasks;  
 using System.ComponentModel;  
 using System.Collections.ObjectModel;  
 namespace MvvmCombo  
 {  
   class ViewModel :INotifyPropertyChanged  
   {  
     public event PropertyChangedEventHandler PropertyChanged;   
     private RegionInfo _ri;  
     private Model _m;  
     private void OnPropertyChanged(string propertyName)  
     {  
       if (PropertyChanged != null)  
         PropertyChanged(this, new PropertyChangedEventArgs(propertyName));  
     }  
     public ViewModel(Model m)  
     {  
       _m = m;  
     }  
     private List<CultureInfo> _allCul;  
     public List<RegionInfo> Countries  
     {  
       get  
       {  
         _allCul = _m.GetCountriesAll();  
         return _m.GetCountries(); ;  
       }  
     }  
     private List<string> _lang;  
     public List<string> Lang  
     {  
       get  
       {  
         return _lang;  
       }  
     }  
     public List<string> FillLanguage()  
     {  
       return _lang =  
         _allCul.Where(c => c.EnglishName.Contains(_ri.EnglishName))  
         .Select(c=>c.EnglishName.IndexOf("(")>-1?c.EnglishName.Substring(0,c.EnglishName.IndexOf("(")):  
           c.EnglishName).Distinct().ToList();  
     }  
     private string _currencySym;  
     public string CurrencySym  
     {  
       get  
       {  
         return _currencySym;  
       }  
       set  
       {  
       }  
     }  
     public object SelectedCountry  
     {  
       set  
       {  
         _ri = value as RegionInfo;  
         FillLanguage();          
         _currencySym = _ri.CurrencySymbol;  
         OnPropertyChanged("Lang");  
         OnPropertyChanged("CurrencySym");  
       }  
     }  
   }  
 }  

Friday, October 30, 2015

When and how to use Delegate?

A delegate is a reference to a method. Whereas objects can easily be sent as parameters into methods, constructor or whatever, methods are a bit more tricky. But every once in a while you might feel the need to send a method as a parameter to another method, and that's when you'll need delegates.

 using System;  
 using System.Collections.Generic;  
 using System.Linq;  
 using System.Text;  
 using MyLibrary;  

 namespace DelegateApp {  
  /// <summary>  
  /// A class to define a person  
  /// </summary>  
  public class Person {  
   public string Name { get; set; }  
   public int Age { get; set; }  
  }  

  class Program {  
    //Our delegate  
    public delegate bool FilterDelegate(Person p);  
    static void Main(string[] args) {  
    //Create 4 Person objects  
    Person p1 = new Person() { Name = "John", Age = 41 };  
    Person p2 = new Person() { Name = "Jane", Age = 69 };  
    Person p3 = new Person() { Name = "Jake", Age = 12 };  
    Person p4 = new Person() { Name = "Jessie", Age = 25 };  
    //Create a list of Person objects and fill it  
    List<Person> people = new List<Person>() { p1, p2, p3, p4 };  
    DisplayPeople("Children:", people, IsChild);  
    DisplayPeople("Adults:", people, IsAdult);  
    DisplayPeople("Seniors:", people, IsSenior);  
    Console.Read();  
   }  
   /// <summary>  
   /// A method to filter out the people you need  
   /// </summary>  
   /// <param name="people">A list of people</param>  
   /// <param name="filter">A filter</param>  
   /// <returns>A filtered list</returns>  
   static void DisplayPeople(string title, List<Person> people, FilterDelegate filter) {  
     Console.WriteLine(title);  
     foreach (Person p in people) {  
     if (filter(p)) {  
       Console.WriteLine("{0}, {1} years old", p.Name, p.Age);  
     }  
    }  
    Console.Write("\n\n");  
   }  
   //==========FILTERS===================  
   static bool IsChild(Person p) {  
    return p.Age <= 18;  
   }  
   static bool IsAdult(Person p) {  
    return p.Age >= 18;  
   }  
   static bool IsSenior(Person p) {  
    return p.Age >= 65;  
   }  
  }  
 }  

Code Formater

Paste Here Your Source Code
Source Code Formatting Options
1) Convert Tab into Space :
2) Need Line Code Numbering :
3) Remove blank lines :
4) Embeded styles / Stylesheet :
5) Code Block Width :
6) Code Block Height :
7) Alternative Background :
Copy Formatted Source Code
 
Preview Of Formatted Code