Monday, 15 September 2014

Posted by Prasad KM | 06:54 Categories:
Introduction of  Dot net 4.0 to 4.5

.NET Framework 4


NET Framework 4 on 29 September 2008. The Public Beta was released on 20 May 2009.
  • Parallel Extensions to improve support for parallel computing, which target multi-core or distributed systems. To this end, technologies like PLINQ (Parallel LINQ), a parallel implementation of the LINQ engine, and Task Parallel Library, which exposes parallel constructs via method calls., are included.
  • New Visual Basic .NET and C# language features, such as implicit line continuations, dynamic dispatch, named parameters, and optional parameters.
  • Support for Code Contracts.
  • Inclusion of new types to work with arbitrary-precision arithmetic (System.Numerics.BigInteger) and complex numbers (System.Numerics.Complex).
  • Introduce Common Language Runtime (CLR) 4.0.
  • Parallel Thread Processing(Task).

Core Features

  • Ability to limit how long the regular expression engine will attempt to resolve a regular expression before it times out.
  • Ability to define the culture for an application domain.
  • Console support for Unicode (UTF-16) encoding.
  • Support for versioning of cultural string ordering and comparison data.
  • Better performance when retrieving resources.
  • Zip compression improvements to reduce the size of a compressed file.
  • Ability to customize a reflection context to override default reflection behavior through the CustomReflectionContext class.

Managed Extensibility Framework (MEF)

  • Support for generic types.
  • Convention-based programming model that enables you to create parts based on naming conventions rather than attributes.
  • Multiple scopes.

Tools

  • Resource File Generator (Resgen.exe) enables you to create a .resw file for use in Windows Store apps from a .resources file embedded in a .NET Framework assembly.
  • Managed Profile Guided Optimization (Mpgo.exe) enables you to improve application startup time, memory utilization (working set size), and throughput by optimizing native image assemblies. The command-line tool generates profile data for native image application assemblies.

.NET Framework 4.5

  • NET for Metro style Apps
  • Portable Class Libraries
  • Core New Features and Improvements
  • Parallel Computing
  • Web
  • Networking
  • Windows Presentation Foundation (WPF)
  • Windows Communication Foundation (WCF)
  • Windows Workflow Foundation (WF)
  • The features of .NET framework 4.5
    To summarize:
    • Installation
      .NET Framework 4.5 does not support Windows XP or Windows Server 2003, and therefore, if you have to create applications that target these operating systems, you will need to stay with .NET Framework 4.0. In contrast, Windows 8 and Windows Server 2012 in all of their editions include .NET Framework 4.5.
    • Support for Arrays Larger than 2 GB on 64-bit Platforms
    • Enhanced Background Server Garbage Collection
    • Support for Timeouts in Regular Expression Evaluations
    • Support for Unicode 6.0.0 in Culture-Sensitive Sorting and Casing Rules on Windows 8
    • Simple Default Culture Definition for an Application Domain
    • Internationalized Domain Names in Windows 8 Apps

 

Core new features and improvements


  • Ability to reduce system restarts by detecting and closing .NET Framework 4 applications during deployment. See Reducing System Restarts During .NET Framework 4.5 Installations.
  • Support for arrays that are larger than 2 gigabytes (GB) on 64-bit platforms. This feature can be enabled in the application configuration file. See the <gcAllowVeryLargeObjects> element, which also lists other restrictions on object size and array size.
  • Better performance through background garbage collection for servers. When you use server garbage collection in the .NET Framework 4.5, background garbage collection is automatically enabled. See the Background Server Garbage Collection section of the Fundamentals of Garbage Collection topic.
  • Background just-in-time (JIT) compilation, which is optionally available on multi-core processors to improve application performance. See ProfileOptimization.
  • Ability to limit how long the regular expression engine will attempt to resolve a regular expression before it times out. See the Regex.MatchTimeout property.
  • Ability to define the default culture for an application domain. See the CultureInfo class.
  • Console support for Unicode (UTF-16) encoding. See the Console class.
  • Support for versioning of cultural string ordering and comparison data. See the SortVersion class.
  • Better performance when retrieving resources. See Packaging and Deploying Resources in Desktop Apps.
  • Zip compression improvements to reduce the size of a compressed file. See the System.IO.Compression namespace.
  • Ability to customize a reflection context to override default reflection behavior through the CustomReflectionContext class.
  • Support for the 2008 version of the Internationalized Domain Names in Applications (IDNA) standard when the System.Globalization.IdnMapping class is used on Windows 8.
  • Delegation of string comparison to the operating system, which implements Unicode 6.0, when the .NET Framework is used on Windows 8. When running on other platforms, the .NET Framework includes its own string comparison data, which implements Unicode 5.x. See the String class and the Remarks section of the SortVersion class.
  • Ability to compute the hash codes for strings on a per application domain basis. See <UseRandomizedStringHashAlgorithm> Element.
  • Type reflection support split between Type and TypeInfo classes. See Reflection in the .NET Framework for Windows Store Apps.

    Parallel computing

    The .NET Framework 4.5 provides several new features and improvements for parallel computing. These include improved performance, increased control, improved support for asynchronous programming, a new dataflow library, and improved support for parallel debugging and performance analysis.

Enhanced Background Server Garbage Collection

.NET Framework 4.5 changes the default mode for server garbage collection to the new background server garbage collection. Thus, whenever you enable the gcServer element in the run-time schema to change from the default workstation garbage collection to server garbage collection, you will be activating the new mode.
For example, line 7 in the following App.config example of a 64-bit .NET Framework 4.5 console application activates background server garbage collection:

Example :
1
2
3
4
5
6
7
8
9
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
    <startup>
        <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
    </startup>
    <runtime>
      <gcServer enabled ="true" />
    </runtime>
</configuration>
A common problem with previous versions of the .NET Framework with multithreaded applications was frequent garbage collections that blocked all the threads until the collection completed. That was typical with workstation garbage collection and the pattern is known as "workstation garbage collection overhead."
Whenever you couldn't reduce the memory pressure in your algorithms, you usually achieved a speedup by enabling the server garbage collection, also known as "Server GC," by simply enabling the gcServer element in the run-time schema. The Server GC would maximize throughput and improve scalability as the number of available cores increased because it dedicated more threads to garbage collection and reduced the overall time to complete garbage collection. The drawback was that it required scheduling more threads than the workstation garbage collection mechanism.
The new background server garbage collection usually creates a managed heap and one dedicated background garbage-collection thread per logical core. Each background garbage-collection thread has its appropriate thread-affinity setting assigned to each available logical core. These background garbage-collection threads don't time out and can remove dead objects and expand heap. The improved algorithms reduce the amount of foreground garbage collections, and hence, improve overall throughput.
The good news is that you don't have to make changes in your code. If you were already using server garbage collection, you will usually notice increased throughput and fewer threads blocked until foreground collection finishes in .NET Framework 4.5.

Support for Timeouts in Regular Expression Evaluations

.NET Framework 4.5 introduces a new constructor for the System.Text.RegularExpressions.Regex class that accepts a TimeSpan matchTimeout parameter to establish a timeout for the regular expression resolution. When you specify a value for the new matchTimeout parameter, if the regular expression engine doesn't resolve the regular expression in the specified time, it will throw a RegexMatchTimeoutException exception. This way, when you have very complex regular expressions, you have an easy way to establish a timeout and you don't have to use complex workarounds to generate your own timeout mechanisms.
The following code uses the new constructor with a 1000 milliseconds TimeSpan parameter to establish a 1,000 milliseconds timeout:

1
2
3
4
var regex = new Regex(
    @"^(?<proto>\w+)://[^/]+?(?<port>:\d+)?/",
    RegexOptions.None,
    TimeSpan.FromMilliseconds(1000));

 Asynchronous operations

In the .NET Framework 4.5, new asynchronous features were added to the C# and Visual Basic languages. These features add a task-based model for performing asynchronous operations.


Windows Communication Foundation (WCF)

In the .NET Framework 4.5, the following features have been added to make it simpler to write and maintain Windows Communication Foundation (WCF) applications:
  • Simplification of generated configuration files.
  • Support for contract-first development.
  • Ability to configure ASP.NET compatibility mode more easily.
  • Changes in default transport property values to reduce the likelihood that you will have to set them.
  • Updates to the XmlDictionaryReaderQuotas class to reduce the likelihood that you will have to manually configure quotas for XML dictionary readers.
  • Validation of WCF configuration files by Visual Studio as part of the build process, so you can detect configuration errors before you run your application.
  • New asynchronous streaming support.
  • New HTTPS protocol mapping to make it easier to expose an endpoint over HTTPS with Internet Information Services (IIS).
  • Ability to generate metadata in a single WSDL document by appending ?singleWSDL to the service URL.
  • Websockets support to enable true bidirectional communication over ports 80 and 443 with performance characteristics similar to the TCP transport.
  • Support for configuring services in code.
  • XML Editor tooltips.
  • ChannelFactory caching support.
  • Binary encoder compression support.
  • Support for a UDP transport that enables developers to write services that use "fire and forget" messaging. A client sends a message to a service and expects no response from the service.
  • Ability to support multiple authentication modes on a single WCF endpoint when using the HTTP transport and transport security.
  • Support for WCF services that use internationalized domain names (IDNs).




What's new in the .NET Framework 4.5.1

  • 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.

    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
  • 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"
  • 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
  • What's new in the .NET Framework 4.5.2


    • New APIs for ASP.NET apps. The new HttpResponse.AddOnSendingHeaders and HttpResponseBase.AddOnSendingHeaders methods let you inspect and modify response headers and status code as the response is being flushed to the client app. Consider using these methods instead of the PreSendRequestHeaders and PreSendRequestContent events; they are more efficient and reliable.
      The HostingEnvironment.QueueBackgroundWorkItem method lets you schedule small background work items. ASP.NET tracks these items and prevents IIS from abruptly terminating the worker process until all background work items have completed. This method can't be called outside an ASP.NET managed app domain.
      The new HttpResponse.HeadersWritten and HttpResponseBase.HeadersWritten properties return Boolean values that indicate whether the response headers have been written. You can use these properties to make sure that calls to APIs such as HttpResponse.StatusCode (which throw exceptions if the headers have been written) will succeed.
    • Resizing in Windows Forms controls. This feature has been expanded. You can now use the system DPI setting to resize components of the following additional controls (for example, the drop-down arrow in combo boxes):

Tuesday, 4 March 2014

Posted by Prasad KM | 08:51 Categories:

Static Constructor in C#

A static constructor is used to initialize any static data, or to perform a particular action that needs to be performed once only. It is called automatically before the first instance is created or any static members are referenced.

Static constructors have the following properties:

  1. A static constructor does not take access modifiers or have parameters or it will not support to access modifiers.
  2. A static constructor is called automatically to initialize the class before the first instance is created or any static members are referenced.
  3. A Static constructor executing Opposite direction of normal constructors.
  4. A static constructor cannot be called directly.
  5. The user has no control on when the static constructor is executed in the program.
  6. A typical use of static constructors is when the class is using a log file and the constructor is used to write entries to this file.
  7. Static constructors are also useful when creating wrapper classes for unmanaged code, when the constructor can call the Load Library method.
  8. If a static constructor throws an exception, the runtime will not invoke it a second time, and the type will remain uninitialized for the lifetime of the application domain in which your program is running.\

Example :

    public class ClassA
    {
      
        public ClassA()
        {}
        static ClassA()
        { }

     }

    public class ClassB : ClassA
    {
        static ClassB()
        { }

        public ClassB()
        { }
    }


 Main function :


ClassB instance =new ClassB()
Executing Steps

1. Static constructor in ClassB.
2. Static constructor in ClassA.
3. Public constructor in ClassA.
4 Public constructor in ClassB.





Saturday, 12 October 2013

Posted by Prasad KM | 02:35 Categories:


Introduction
This article will explain six important concepts: 

1.      Stack : 
2.      Heap,
3.      Value types,
4.      Reference types,
5.      Boxing,
6.      Unboxing. 

This article starts explaining what happens internally when you declare a variable and then it moves ahead to explain two important concepts: stack and heap. The article then talks about reference types and value types and clarifies some of the important fundamentals around them.
The article concludes by demonstrating how performance is hampered due to boxing and unboxing, with a sample code.
What goes inside when you declare a variable?
When you declare a variable in a .NET application, it allocates some chunk of memory in the RAM. This memory has three things: the name of the variable, the data type of the variable, and the value of the variable.
That was a simple explanation of what happens in the memory, but depending on the data type, your variable is allocated that type of memory. There are two types of memory allocation: stack memory and heap memory. In the coming sections, we will try to understand these two types of memory in more detail.

Stack and heap
In order to understand stack and heap, let’s understand what actually happens in the below code internally.
public void Method1()
{
    // Line 1
    int i=4;

    // Line 2
    int y=2;

    //Line 3
    class1 cls1 = new class1();
}
It’s a three line code, let’s understand line by line how things execute internally.
  • Line 1: When this line is executed, the compiler allocates a small amount of memory in the stack. The stack is responsible for keeping track of the running memory needed in your application.
  • Line 2: Now the execution moves to the next step. As the name says stack, it stacks this memory allocation on top of the first memory allocation. You can think about stack as a series of compartments or boxes put on top of each other.
Memory allocation and de-allocation is done using LIFO (Last In First Out) logic. In other words memory is allocated and de-allocated at only one end of the memory, i.e., top of the stack.
  • Line 3: In line 3, we have created an object. When this line is executed it creates a pointer on the stack and the actual object is stored in a different type of memory location called ‘Heap’. ‘Heap’ does not track running memory, it’s just a pile of objects which can be reached at any moment of time. Heap is used for dynamic memory allocation.
One more important point to note here is reference pointers are allocated on stack. The statement, Class1 cls1; does not allocate memory for an instance of Class1, it only allocates a stack variable cls1 (and sets it to null). The time it hits the new keyword, it allocates on "heap".
Exiting the method (the fun): Now finally the execution control starts exiting the method. When it passes the end control, it clears all the memory variables which are assigned on stack. In other words all variables which are related to int data type are de-allocated in ‘LIFO’ fashion from the stack.
The big catch – It did not de-allocate the heap memory. This memory will be later de-allocated by the garbage collector.

Now many of our developer friends must be wondering why two types of memory, can’t we just allocate everything on just one memory type and we are done?
If you look closely, primitive data types are not complex, they hold single values like ‘int i = 0’. Object data types are complex, they reference other objects or other primitive data types. In other words, they hold reference to other multiple values and each one of them must be stored in memory. Object types need dynamic memory while primitive ones needs static type memory. If the requirement is of dynamic memory, it’s allocated on the heap or else it goes on a stack.

Value types and reference types
Now that we have understood the concept of Stack and Heap, it’s time to understand the concept of value types and reference types. Value types are types which hold both data and memory on the same location. A reference type has a pointer which points to the memory location.
Below is a simple integer data type with name i whose value is assigned to another integer data type with name j. Both these memory values are allocated on the stack.
When we assign the int value to the other int value, it creates a completely different copy. In other words, if you change either of them, the other does not change. These kinds of data types are called as ‘Value types’.

When we create an object and when we assign an object to another object, they both point to the same memory location as shown in the below code snippet. So when we assign obj to obj1, they both point to the same memory location.
In other words if we change one of them, the other object is also affected; this is termed as ‘Reference types’.

So which data types are ref types and which are value types?
In .NET depending on the data type, the variable is either assigned on the stack or on the heap. ‘String’ and ‘Objects’ are reference types, and any other .NET primitive data types are assigned on the stack. The figure below explains the same in a more detail manner.
http://www.codeproject.com/KB/dotnet/6importentStepsDotNet/7.jpg
Boxing and unboxing
Wow, you have given so much knowledge, so what’s the use of it in actual programming? One of the biggest implications is to understand the performance hit which is incurred due to data moving from stack to heap and vice versa.
Consider the below code snippet. When we move a value type to reference type, data is moved from the stack to the heap. When we move a reference type to a value type, the data is moved from the heap to the stack.
This movement of data from the heap to stack and vice-versa creates a performance hit.
When the data moves from value types to reference types, it is termed ‘Boxing’ and the reverse is termed ‘UnBoxing’.

If you compile the above code and see the same in ILDASM, you can see in the IL code how ‘boxing’ and ‘unboxing’ looks. The figure below demonstrates the same.
http://www.codeproject.com/KB/dotnet/6importentStepsDotNet/9.jpg
Performance implication of boxing and unboxing
In order to see how the performance is impacted, we ran the below two functions 10,000 times. One function has boxing and the other function is simple. We used a stop watch object to monitor the time taken.
The boxing function was executed in 3542 ms while without boxing, the code was executed in 2477 ms. In other words try to avoid boxing and unboxing. In a project where you need boxing and unboxing, use it when it’s absolutely necessary.
With this article, sample code is attached which demonstrates this performance implication.

Currently I have not included source code for unboxing but the same holds true for it. You can write code and experiment it using the stopwatch class.

  • RSS
  • Delicious
  • Digg
  • Facebook
  • Twitter
  • Linkedin
  • Youtube