Monday, 30 December 2013

Introduction to Threads in C#

Introduction to Threads In C#

Threads: Threads are often called lightweight processes. However they are not process.es A Thread is a small set of executable instructions, which can be used to isolate a task from a process. Multiple threads are efficient way to obtain parallelism of hardware and give interactive user interaction to your applications.
C# Thread:. . Net Framework has thread-associated classes in System.Threading namespace. The following steps demonstrate how to create a thread in C#.
Step 1. Create a System.Threading.Thread object.
Creating an object to System.Threading.Thread creates a managed thread in .Net environment. The Thread class has only one constructor, which takes a ThreadStart delegate as parameter. The ThreadStart delegate is wrap around the callback method, which will be called when we start the thread.
Step 2: Create the call back function
This method will be a starting point for our new thread. It may be an instance function of a class or a static function. Incase of instance function, we should create an object of the class, before we create the ThreadStart delegate. For static functions we can directly use the function name to instantiate the delegate. The callback function should have void as both return type and parameter. Because the ThreadStart delegate function is declared like this. (For more information on delegate see MSDN for “Delegates”).
Step 3: Starting the Thread.
We can start the newly created thread using the Thread’s Start method. This is an asynchronous method, which requests the operating system to start the current thread.
For Example:
 
// This is the Call back function for thread.           

Public static void MyCallbackFunction()

{
while (true)

  {
  System.Console.WriteLine(“ Hey!, My Thread Function Running”);

………

  } 

}

public static void Main(String []args)

{

// Create an object for Thread

Thread MyThread = new Thread(new ThreadStart 
(MyCallbackFunction));

MyThread.Start()

……

}


Killing a Thread:

We can kill a thread by calling the Abort method of the thread. Calling the Abort method causes the current thread to exit by throwing the ThreadAbortException.
MyThread.Abort(); 
Suspend and Resuming Thread:
We can suspend the execution of a thread and once again start its execution from another thread using the Thread object’s Suspend and Resume methods.
  MyThread.Suspend() // causes suspend the Thread Execution. 
  MyThread.Resume() // causes the suspended Thread to resume its execution.
 
Thread State:
A Thread can be in one the following state.

Thread State
Description
Unstarted
Thread is Created within the common language run time but not Started still.
Running
After a Thread calls Start method
WaitSleepJoin
After a Thread calls its wait or Sleep or Join method.
Suspended
Thread Responds to a Suspend method call.
Stopped
The Thread is Stopped, either normally or Aborted.

We can check the current state of a thread using the Thread’s ThreadState property.
Thread Priorty:
The Thread class’s ThreadPriority property is used to set the priority of the Thread. A Thread may have one of the following values as its Priority:  Lowest, BelowNormal, Normal, AboveNormal, Highest. The default property of a thread is Normal.

Monday, 23 December 2013

MVVM Pattern in WPF: A Simple Tutorial for Absolute Beginners

MVVM Pattern in WPF

The Background on Model-View-ViewModel

Many developers like to keep their XAML projects cleanly structured using a pattern called MVVM (model view view model). MVVM prescribes separating the nonvisual classes that encapsulate interaction logic, business logic and data from the visual classes that actually render things to the screen. This separation makes the code easier to maintain: first, it prevents the UI from becoming a monolithic class with display controls, interaction logic and business logic all stuffed in side by side; and second, it enables you to automate the testing of interaction logic and user interface mappings instead of relying on expensive, unreliable manual testing. It also helps to facilitate a 'lookless' view, where the visual design can be changed without changing the code – at least so long as the data and operations remain the same.
MVVM Diagram
Example diagram of MVVM design pattern.
In MVVM, instead of writing C# or Visual Basic code to directly set and get properties of controls in the view, you create a view model which represents the information being presented in the view, and use data binding to keep the view and the view model in sync. For example, a login view model might have Username and Password properties, which the view would bind to text boxes.
We might also have an interaction rule that the 'enter your credentials' prompt should be visible only if the Username or Password box is empty.’ Then the view model would have an IsAwaitingCredentials property, which it would update as the Username and Password changed. This encapsulates the interaction rule in a way that doesn't depend on a view being present, making it easy to unit test. The view then binds TextBlock.Visibility to the IsAwaitingCredentials property.
Similarly, XAML can represent initiating actions either by commands or by events. In the MVVM world, commands work much like properties – a view model can contain commands to which control properties can bind. Events traditionally require code in the view to wire them up, but frameworks such as Caliburn Micro can automatically map events in the view to methods in the view model, eliminating the need to manually hook up event handlers. Either of these approaches allows us to encapsulate and test the possible user actions independently of the presence of an actual view.

What about other patterns?

While it's also possible for XAML applications to use other UI separation patterns such as MVC (model view controller) or MVP (model view presenter), XAML's support for data binding and commands make MVVM a particularly good fit for the various XAML platforms.

Using WPF Elements with MVVM

Mindscape's WPF, Silverlight and Windows Phone controls have been designed to fit easily with the MVVM architecture so that you can enjoy fast, functional, beautiful controls without compromising your clean design. WPF Elements ships with a dashboard sample that demonstrates using Mindscape WPF controls in an MVVM architecture. You can open the sample in Visual Studio 2010 using a shortcut in the start menu.
WPF Elements Dashboard

Sunday, 22 December 2013

LINQ to SQL Tips and Tricks

Loading a delay-loaded property

LINQ to SQL lets you specify that a property is delay-loaded meaning that it is not normally retrieved as part of normal query operations against that entity. This is particularly useful for binary and large text fields such as a photo property on an employee object that is rarely used and would cause a large amount of memory to be consumed on the client not to mention traffic between the SQL and application.
There are times however when you want all these binaries returned in a single query, say for example returning all the photos for the company photo intranet page:
var db = new NorthwindContext();
var loadOptions = new DataLoadOptions();
loadOptions.LoadWith<Employee>(e => e.Photo);
db.LoadOptions = loadOptions; 

Intercepting create, update and delete operations

There are times it is useful to be able to listen in to when these events happen and perform your own logic, perhaps auditing or logging for some scenarios. The easiest way to do this is to implement some specially-named methods on your data context, perform your action and then to dispatch the call back to LINQ to SQL.
The format of these specially-named methods is [Action][Entity] and then you should pass back control to LINQ to SQL using ExecuteDynamic[Action] where [Action] is either Insert, Update or Delete. One example of such usage might be:
partial class NorthwindContext {
  partial void InsertEmployee(Employee instance) {
     instance.CreatedBy = CurrentUser;
     instance.CreatedAt = DateTime.Now;
     ExecuteDynamicInsert(instance);
  }

  partial void UpdateEmployee(Employee instance) {
     AuditEmployeeOwnerChange(instance);
     instance.LastModifiedAt = DateTime.Now;
     ExecuteDynamicUpdate(instance);
  }

  partial void DeleteEmployee(Employee instance) {
     AuditDelete(instance, CurrentUser);
     ExecuteDynamicDelete(instance);
  }
}

Take full control of  the TSQL

There are times when LINQ to SQL refuses to cook up the TSQL you wanted either because it doesn’t support the feature or because it has a different idea what makes an optimal query.
In either case the Translate method allows you to deliver your own TSQL to LINQ to SQL to process as if it were its own with execution, materialization and identity mapping still honored. For example:
var db = new PeopleContext();
if (db.Connection.State == System.Data.ConnectionState.Closed)
    db.Connection.Open();

var cmd = db.GetCommand(db.Persons.Where(p => p.CountryID == 1));
cmd.CommandText = cmd.CommandText.Replace("[People] AS [t0]", 
                                          "[People] AS [t0] WITH (NOLOCK)");
var results = db.Translate<Person>(cmd.ExecuteReader());

Complex stored procedures

When working with stored procedures the LINQ to SQL designer and SQLMetal tools need a way of figuring out what the return type will be. In order to do this without actually running the stored procedure itself they use the SET FMTONLY command set to ON so that SQL Server will just parse the stored procedure instead.
Unfortunately this parsing does not extend to tdynamic SQL or temporary tables so you must change the return type from the scalar integer to one of the known entity types by hand. You could use the following command at the start to let it run regardless given the subsequent warning.
SET FMTONLY OFF
If your stored procedure can not safely handle being called at any time with null parameters set the return type by hand instead.

Cloning an entity

There are many reasons you might want to clone an entity – you may want to create many similar ones, you could want to keep it around longer than the DataContext it came from – whatever your reason implementing a Clone method can be a pain but taking advantage of the DataContractSerializer can make light work of this providing your DBML is set to enable serialization.
public static T Clone<T>(T source) {
    var dcs = new System.Runtime.Serialization.DataContractSerializer(typeof(T));
    using (var ms = new System.IO.MemoryStream()) {
        dcs.WriteObject(ms, source);
        ms.Seek(0, System.IO.SeekOrigin.Begin);
        return (T)dcs.ReadObject(ms);
    }
}
And then to clone simply:
var source = myQuery.First();
var cloned = Clone(source);
Be aware that this comes with a little overhead in the serialization and deserialization process.

Sunday, 15 December 2013

A LINQ tutorial for beginners

LINQ

LINQ is Microsoft’s technology to provide a language-level support mechanism for querying data of all types. These types include in memory arrays and collections, databases, XML documents and more, since version 3.5 and Visual Studio 2008. (.NET 4 and Visual Studio 2010 added support for the Parallel LINQ features).

Need for LINQ

  • Here is the issue that we cannot programmatically interact with a database at the native language level. This means syntax errors often go undetected until runtime.
  • Differing data types utilized by a particular data domain, such as database or XML data types versus the native language
  • XML parsing, iterating, and manipulation can be quite tedious. an XmlDocument must be created just to perform various operations on the XML fragment

Advantages of LINQ

  • Query is integrated into the language. Gone are the days of writing a SQL query into a string and not detecting a syntax error until runtime, for example we forget the name of a field of the table (or reference) or it has been changed in DB.
  • In addition to query features, LINQ to XML provides a more powerful and easier-to-use interface for working with XML data, as though it were a database.
  • Example:
    XElement books = XElement.Parse(
           @"<books>
                <book>
                <title>Pro LINQ: Language Integrated Query in C#2010</title>
                <author>Joe Rattz</author>
                </book>
                <book>
                <title>Pro .NET 4.0 Parallel Programming in C#</title>
                <author>Adam Freeman</author>
                </book>
                <book>
                <title>Pro VB 2010 and the .NET 4.0 Platform</title>
                <author>Andrew Troelsen</author>
                </book>
                </books>");
    
    //XElement Xbooks = XElement.Parse(@"XMLFile.xml");
    var titles =
    from book in books.Elements("book")
    where (string)book.Element("author") == "Joe Rattz"
    select book.Element("title");
    foreach (var title in titles)
        Console.WriteLine(title.Value);
  • Not only for querying data but for formatting, validating, and even getting data into the necessary format : example string array to integer array and sort. can also use select new for complex classes
    Example:
    string[] numbers = { "0042", "010", "9", "27" };            
    int[] nums = numbers.Select( 
    s => Int32.Parse(s)).OrderBy(s => ).ToArray(); 
    foreach (int num in nums) 
    Console.WriteLine(num);

Syntax of LINQ

Two syntaxes are available for LINQ queries:
  • Query expression syntax
  • from str in strings where str.Length==3 select str; 
  • Standard dot notation syntax
  • stringList.Where(s => s.Length == 3).Select(s=>s); 

Type of LINQ

  • LINQ to Objects
  • LINQ to XML
  • LINQ to DataSet
  • LINQ to SQL
  • LINQ to Entities.

More about LINQ

  • They are queries returning a set of matching objects, a single object, or a subset of fields from an object or set of objects. In LINQ, this returned set of objects is called a sequence, and most LINQ sequences are of typeIEnumerable<T>.
  • We can use the "Cast" or "OfType" operators for Legacy Collections to convert them to IEnumerable to use LINQ.
  • The LINQ query actually take place the first time a result from it is needed. This is typically when the query results variable is enumerated.
  • And this may lead to the situation: deferred query is passed undetected with error.--> deferred query example (disadvantage)
  • Example:
    string[] strings = { "one", "two", null, "three" };
    Console.WriteLine("Before Where() is called.");
    IEnumerable<string> ieStrings = strings.Where(s => s.Length == 3);
    Console.WriteLine("After Where() is called.");            
    foreach (string s in ieStrings) 
    { 
      Console.WriteLine("Processing " + s); 
    }
  • Calling the actual query each time is needless work. It might make more sense to have a query initialization method that gets called once for the lifetime of the scope and to construct all the queries there (advantage).
  • List<string> strings = new List<string>(); 
    strings.Add("one"); 
    strings.Add("two"); 
    strings.Add("three"); 
    
    IEnumerable<string> ieStrings = strings.Where(s => s.Length == 3); 
    foreach (string s in ieStrings) 
    { 
      Console.WriteLine("Processing " + s); 
    } 
    
    Console.ReadKey(); 
    strings.Add("six"); 
    Console.WriteLine("source enumerable changed but query is not invoked again"); 
    //query is not invoked explicitly, ieStrings is not changes 
    foreach (string s in ieStrings) 
    { 
      Console.WriteLine("Processing " + s); 
    }
    
  • In Linq To Entity, string can be passed in where clause as a condition using “it” as variable refenrence.
  • Example:
    VCAB_CMS_DBEntities context = new VCAB_CMS_DBEntities(); 
    string condition = "it.DocName=='Shakuntala Devi'"; 
    int pageCount= context.EDOC.Where(condition).Select(c => c.DocPageCount).First(); 

Language additions with LINQ

Lambda expressions

i => ((i & 1) == 1)
This expression refers to an anonymous method with left side as input to the method and right side as the output.

Expression trees

IEnumerable<int> numsLessThanFour = nums.Where(i => i < 4).OrderBy(i => i);
The Where operator is called first, followed by the OrderBy operator. But an expression tree allows the simultaneous evaluation and execution of all operators in a query, a single query can be made instead of a separate query for each operator.

The keyword var, object and collection initialization, and anonymous types

var address = new { address = "105 Elm Street", 
  city = "Atlanta", state = "GA", postalCode = "30339" };
Compiler generated anonymous class name looks like: <>f__AnonymousType5`4[System.String,System.String,System.String,System.String].
Collection initialization allows you to specify the initialization values for a collection, just like you would for an object:
List<string> presidents = new List<string> { "Adams", "Arthur", "Buchanan" };

Extension methods

  • Used to extend a sealed class like adding factorial method in int class or adding todouble method in string class.
  • Extension methods are methods that, although static, can be called on an instance (object) of a class rather than on the class itself.
  • Specifying a method’s first argument with the “this” keyword modifier will make that method an extension method.
  • Extension methods can be declared only in static classes.
public static class ExtendsStringClass{ 
    public static double ToDouble(this string s){ 
        return Double.Parse(s); 
    } 
} 

class Program{ 
static void Main(string[] args){ 
        double pi = "3.1415926535".ToDouble(); 
        Console.WriteLine(pi); 
        MyWidget myWidget = new MyWidget(); 
        Console.ReadKey(); 
    }     
} 

Partial methods

  • A partial method can exist only in a partial class
  • A partial method must return void.
  • Partial methods are private but must not specify the private modifier
Example: To make the generated entity classes more usable, partial methods have been added to them. You can add another module that declares the same entity class, implement these partial methods, and be notified every time a property is about to be changed and after it is changed

Query expressions

  • Query expressions allow LINQ queries to be expressed in nearly SQL form, with just a few minor deviations.
  • The “from” statement precedes the select statement, hence intelliSense has the scope of what variables to offer you for selection.