Sunday, 6 July 2014

What's new in the .NET Framework 4.5.1


April 2014 updates:
  • Visual Studio 2013 Update 2 includes updates to the Portable Class Library templates to support these scenarios:
    • You can use Windows Runtime APIs in portable libraries that target Windows 8.1, Windows Phone 8.1, and Windows Phone Silverlight 8.1.
    • You can include XAML (Windows.UI.XAML types) in portable libraries when you target Windows 8.1 or Windows Phone 8.1. The following XAML templates are supported: Blank Page, Resource Dictionary, Templated Control, and User Control.
    • You can create a portable Windows Runtime component (.winmd file) for use in Store apps that target Windows 8.1 and Windows Phone 8.1.
    • You can retarget a Windows Store or Windows Phone Store class library like a Portable Class Library.
    For more information about these changes, see Cross-Platform Development with the Portable Class Library.
  • The .NET Framework content set now includes documentation for .NET Native, which is a precompilation technology for building and deploying Windows Store apps. .NET Native compiles your apps directly to native code, rather than to intermediate language (IL), for better performance. For details, see Compiling Apps with .NET Native. The .NET Native Developer Preview is available for download on the Microsoft Connect website (requires registration).
  • The .NET Framework Reference Source provides a new browsing experience and enhanced functionality. You can now browse through the .NET Framework source code online, download the reference for offline viewing, and step through the sources (including patches and updates) during debugging. For more information, see the blog entry A new look for .NET Reference Source.
For a list of new APIs in the .NET Framework 4.5.1, see New Types and Members in the .NET Framework 4.5.1.
Core new features and enhancements in the .NET Framework 4.5.1 include:
  • Automatic binding redirection for assemblies. Starting with Visual Studio 2013, when you compile an app that targets the .NET Framework 4.5.1, binding redirects may be added to the app configuration file if your app or its components reference multiple versions of the same assembly. You can also enable this feature for projects that target older versions of the .NET Framework. For more information, see How to: Enable and Disable Automatic Binding Redirection.
  • Ability to collect diagnostics information to help developers improve the performance of server and cloud applications. For more information, see theWriteEventWithRelatedActivityId and WriteEventWithRelatedActivityIdCore methods in the EventSource class.
  • Ability to explicitly compact the large object heap (LOH) during garbage collection. For more information, see the GCSettings.LargeObjectHeapCompactionModeproperty.
  • Additional performance improvements such as ASP.NET app suspension, multi-core JIT improvements, and faster app startup after a .NET Framework update. For details, see the .NET Framework 4.5.1 announcement and the ASP.NET app suspend blog post.
Improvements to Windows Forms include:
  • Resizing in Windows Forms controls. You can use the system DPI setting to resize components of controls (for example, the icons that appear in a property grid) by opting in with an entry in the application configuration file (app.config) for your app. This feature is currently supported in the following Windows Forms controls:
    PropertyGrid 
    TreeView
    Some aspects of the DataGridView (see new features in 4.5.2 for additional controls supported)
    To enable this feature, add a new <appSettings> element to the configuration file (app.config) and set the EnableWindowsFormsHighDpiAutoResizing element totrue:
    <appSettings>
       <add key="EnableWindowsFormsHighDpiAutoResizing" value="true" />
    </appSettings>
    
Improvements when debugging your .NET Framework apps in Visual Studio 2013 include:
  • Return values in the Visual Studio debugger. When you debug a managed app in Visual Studio 2013, the Autos window displays return types and values for methods. This information is available for desktop, Windows Store, and Windows Phone apps. For more information, see Examine return values of method calls in the MSDN Library.
  • Edit and Continue for 64-bit apps. Visual Studio 2013 supports the Edit and Continue feature for 64-bit managed apps for desktop, Windows Store, and Windows Phone. The existing limitations remain in effect for both 32-bit and 64-bit apps (see the last section of the Supported Code Changes (C#) article).
  • Async-aware debugging. To make it easier to debug asynchronous apps in Visual Studio 2013, the call stack hides the infrastructure code provided by compilers to support asynchronous programming, and also chains in logical parent frames so you can follow logical program execution more clearly. A Tasks window replaces the Parallel Tasks window and displays tasks that relate to a particular breakpoint, and also displays any other tasks that are currently active or scheduled in the app. You can read about this feature in the "Async-aware debugging" section of the .NET Framework 4.5.1 announcement.
  • Better exception support for Windows Runtime components. In Windows 8.1, exceptions that arise from Windows Store apps preserve information about the error that caused the exception, even across language boundaries. You can read about this feature in the "Windows Store app development" section of the .NET Framework 4.5.1 announcement.

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.