Showing posts with label C#. Show all posts
Showing posts with label C#. Show all posts

Sep 10, 2013

Interactive Extensions


LINQ provides lot of ways to query the objects or XML. But we might need some more features\extensions which will be handy in real development. Let us explore a library which provides more extensions\features to the existing framework.


Introduction

The Reactive Extensions (Rx) is a library for composing asynchronous and event-based programs using observable sequences (provides notification information) and LINQ-style query operators.

The Interactive Extensions (Ix) is a .NET library which extends LINQ to Objects to provide many of the operators available in Rx but targeted for IEnumerable. In simple terms, it provides a lot of new features to LINQ to Object which is not available in Framework. Ix is sub-set of Rx.

This will install System.Interactive.dll file. EnumerableEx class provides a set of additional static methods that allow querying enumerable sequences.


Execute below command in Nuget Package Manager Console to install:
install-package Ix-Main


Let us discuss few features:

Do: This lazily invokes an action for each value in the sequence. That means it invokes\executes an action for each value in enumeration.


Sample Code:
static void Main(string[] args)
{
      DisplayNumbersDo();
}
static void DisplayNumbersDo()
{

      int addnumber = 10;
      //Let us create a set of numbers 
      var numbers = new int[] { 6, 1, 4, 2, 6 };

      var result = numbers.Do(n => Console.WriteLine(n + addnumber));
      Console.WriteLine("Before Enumeration");
      foreach (var item in result)
      {
          //The action will be invoked when we actually enumerate 
      }
      Console.WriteLine("After Enumeration");
      Console.ReadLine();
}


ForEach: Enumerates the sequence and invokes the given action for each value in the sequence.

Sample Code:
static void Main(string[] args) { List names = new List { "ram", "nagesh" }; names.ForEach(s => Console.WriteLine(s)); ; Console.ReadLine(); }


Scan: Generates a sequence of accumulated values by scanning the source sequence and applying an accumulator function. 

Sample Code:
static void Main(string[] args) { List names = new List { "ram ", "nagesh" }; names.Scan((x,y) => x + y).ForEach(s => Console.WriteLine(s)); Console.ReadLine(); }



Below are few more methods which might be useful:

Repeat: Repeats and concatenates the source sequence infinitely.

SkipLast: Bypasses a specified number of contiguous elements from the end of the sequence and returns the remaining elements.

TakeLast: Returns a specified number of contiguous elements from the end of the sequence.


You can install Interactive Extensions in Visual Studio 2010 also.





Sep 5, 2013

Code Contracts

Code Contracts

Code Contracts are static library methods used from any .NET program to specify the code’s behavior. Runtime checking and static checking tools are both provided for taking advantage of contracts. Code Contracts is a subset of a larger Microsoft Research Project called Spec# (pronounced "Spec Sharp"). 

In simple, its add-on that you can install in Visual Studio. This library offers number of attributes and helper classes to perform various validations/conditions at various levels.

You can download add-on from here

After installing make sure you have "Code Contracts" tab in project properties.


Make changes to project properties as below:



Add Using statement as below:
using System.Diagnostics.Contracts;


Preconditions:
Preconditions are those which needs to be executed at the beginning of the method. They generally used to validate parameter values like object is not null, Argument null exception, int > 0 etc.

Normal precondition looks like this:

public static int GetEmployeeCount(int intDeptId)   {
         if (intDeptId == 0)
           throw new Exception("Invalid Department Id");
            
        //logic here
        return 10;
}

We can write the same code in a better way as below:


public static int GetEmployeeCount(int intDeptId)   {        Contract.Requires(intDeptId > 0);
       //logic here
       return 10; }




Static Checking:
Instead of raising exception after callign method, it would be much easier if we can raise exception at the time of calling method. This is static checking. For this, you need to enable "Show squigglies" option in Project properties.

Code:
public static int GetEmployeeCount(int intDeptId)
  {
      Contract.Requires(intDeptId != 0,
             "Zero is not allowed for Department Id.");
      //logic here
      return intDeptId;
}

While performing static checking, error message will be shown as below:



Post-Condition:
These conditions are nothing but validations after executing a method. These are very useful in case of validation objects, dataset from database, etc. You have option to save old values in OldValue before calling method.
In below example, we are ensuring the output of the GetEmployeeCount is greated than 5.

Code:

Contract.Ensures(Dept.GetEmployeeCount(5) > 0);


Interface Contracts:
We can write contracts for interface methods required creating contract class to hold them.

We can use below attributes:
ContractClass: Need to defined for Interface. Ex: [ContractClass(typeof(IDeptContract))]

ContractClassFor: Need to defined for class implements interface. Ex: [ContractClassFor(typeof(IDept))]

Conclusion:
Code Contracts will be very useful, if we can use it in a proper manner and follow some guidelines. This can be used in Business Layer for validating objects before passing it to Data Layer. This will reduce lines of code and errors/mistakes while writing validation logic.

For complete documentation, please refer this link



Aug 22, 2013

Getting Browser Info in ASP.Net

Getting Browser details in ASP.Net

A Web application can access the current instance of the HttpBrowserCapabilities object using the HttpRequest.Browser property. This object is read-only, and contains properties for each capability. The HttpBrowserCapabilities object is cached and might be used again for a different request from the same type of browser.
Predefined browser definition files are stored in the %SystemRoot%\Microsoft.NET\Framework\version\CONFIG\Browsers directory. Application-level browser-definition files can be placed in the application's App_Browsers directory. In both locations, browser definition files must have a .browser file name extension.

How it works?
At run-time, browser-definition file information is merged into a collection of known browsers in a BrowserCapabilitiesFactory object. When a request is made, ASP.NET identifies the requesting browser by the request header, and compiles an HttpBrowserCapabilities object that corresponds to the type of the requested browser. This is done by starting with an empty dictionary, and applying the following recursive steps against the browser definition tree:
  1. Start at the default browser definition, which is always considered a successful match.
  2. Merge capability values specified in this browser definition into the capabilities dictionary for this browser. Values specified in a browser definition override values set in a parent.
  3. Evaluate each child definition to determine a match. For each matching child, start at step 1 again. Browser definitions are evaluated after gateway definitions. If the user agent matches more than one browser definition or more than one gateway definition, an exception is thrown at run-time.


Syntax for Browser Definition File:

<browsers>
   <browser id="browser name" parentID="parent browser name"             refID="reference ID">
       <identification>
           <userAgent match="regular expression"
                      nonMatch="regular expression" />
           <header match="regular expression"                   name="header name" nonMatch="regular expression" />
           <capability match="regular expression"            name="capability name" nonMatch="regular expression" />
       </identification>
       <capture>
           <userAgent match="regular expression" />
           <header match="regular expression" name="header name" />
           <capability match="regular expression" name="capability name" />
       </capture>
       <capabilities>
           <capability name="capability name" value="capability value" />
       </capabilities>
       <controlAdapters markupTextWriterType="type name">
           <adapter adapterType="name of adapter class" controlType="name of control class" />
       </controlAdapters>
       <sampleHeaders>
           <header name="header name" value="header value" />
       </sampleHeaders>
   </browser>
   <gateway id="gateway ID" parentID="parent browser ID">
       <!-- Same child elements as for <browser>.
       <identification></identification>
       <capture></capture>
       <capabilities></capabilities>
       <controlAdapters></controlAdapters>
       <sampleHeaders></sampleHeaders>
        -->
   </gateway>
   <defaultBrowser id="Default"  parentID="parent browser ID"
                   refID="reference ID" >
       <!-- Same child elements as for <browser>.
       <identification></identification>
       <capture></capture>
       <capabilities></capabilities>
       <controlAdapters></controlAdapters>
       <sampleHeaders></sampleHeaders>
        -->
   </defaultBrowser>
</browsers>



Sample C# code to read browser details in ASP.Net:

System.Web.HttpBrowserCapabilities browser = Request.Browser;
    string s = "Browser Capabilities\n"
        + "Type = "                    + browser.Type + "\n"
        + "Name = "                    + browser.Browser + "\n"
        + "Version = "                 + browser.Version + "\n"
        + "Major Version = "           + browser.MajorVersion + "\n"
        + "Minor Version = "           + browser.MinorVersion + "\n"
        + "Platform = "                + browser.Platform + "\n"
        + "Is Beta = "                 + browser.Beta + "\n"
        + "Is Crawler = "              + browser.Crawler + "\n"
        + "Is AOL = "                  + browser.AOL + "\n"
        + "Is Win16 = "                + browser.Win16 + "\n"
        + "Is Win32 = "                + browser.Win32 + "\n"
        + "Supports Frames = "         + browser.Frames + "\n"
        + "Supports Tables = "         + browser.Tables + "\n"
        + "Supports Cookies = "        + browser.Cookies + "\n"
        + "Supports VBScript = "       + browser.VBScript + "\n"
        + "Supports JavaScript = "     + 
            browser.EcmaScriptVersion.ToString() + "\n"
        + "Supports Java Applets = "   + browser.JavaApplets + "\n"
        + "Supports ActiveX Controls = " + browser.ActiveXControls 
              + "\n"
        + "Supports JavaScript Version = " +
            browser["JavaScriptVersion"] + "\n";

For more information refer below link:
http://msdn.microsoft.com/en-us/library/vstudio/ms228122(v=vs.100).aspx



Jul 15, 2013

Custom Encryption of connection strings in Configuration files using Certificates



This article will explain how to implement custom encryption of connection strings in configuration files using certificates for security reasons.

In most of the applications, connection strings will be mentioned encrypted format in configuration files. To provide more security to the applications we can use custom encryption using certificates. This will provide more security to the applications.

Steps:
  • Generate the certificate using the following command which will also store the certificate under the Current User - Personal store
    • Command to generate the test certificate :
    • makecert -r -pe -n "CN=CSProtectedConfigCertificate" -b 01/01/2000 -e 01/01/2036 -eku 1.3.6.1.5.5.7.3.1 -ss my -sr CurrentUser -sky exchange -sp "Microsoft RSA SChannel Cryptographic Provider" -sy 12
  • Create a Custom Library project in Visual Studio and add this certificate to the project.
  • Create class and implement methods for Encrypting and Decrypting similar to this link.
  • Build this solution and register the DLL in GAC using Visual Studio Command Prompt

gacutil.exe -i CustomProtectedConfigurationProvider.dll
  • Update below configuration details in machine.config or web.config:

CertificateName="CSProtectedConfigCertificate"   type="CustomProtectedConfigurationProvider.CustomProtectedConfigProvider,                   CustomProtectedConfigurationProvider, Version=1.0.0.0, Culture=neutral,PublicKeyToken=e03f7ad78f283bbf,processorArchitecture=MSIL"
   />



  • Execute below commands for encrypting and decrypting connection strings which is used in configuration file:
    • Command for Encrypting connection string (this will encrypt connection string in configuration file):
    • aspnet_regiis -pe "connectionStrings" -prov "CustomProtectedConfigurationProvider" -pkm

    • Command for decrypting connection string(this will decrypt connection string in configuration file:
    • aspnet_regiis -pd "connectionStrings" -pkm




May 23, 2013

C# 5.0 Features


New Features in C#.Net 5.0

1. Asynchronous functions (Async and Await): Using Async and Await, you can use resources in the .NET Framework, to create an asynchronous method as easily as you create a synchronous method.



Asynchronous methods are the methods that you define using async and await.



2. Caller Information: Caller Information attributes provide the information about the caller to a method. You can obtain the file path of the source code, the line number in the source code, and the member name of the caller. Caller Information helps us in tracing, debugging, and creating diagnostic tools.



3. Windows Runtime Support: C# and .NET now have deep integration with the Windows Runtime. C# project can compiled into a WinMD file and then referenced from a HTML/JavaScript project. WinRT’s flavor of COM uses the same metadata format used by the Common Language Runtime. This information is stored in WINMD files that show the structure, though not the implementation, of all the public classes. Windows Runtime returns an HRESULT instead of throwing an exception. For well-known HRESULT values, the corresponding exception is thrown, otherwise a COMException is used.



4. Compiler APIs: This feature is supposed to come after C# 5.0 – the APIs will expose whatever knowledge the compiler has about the code to the IDE and the developers, through Syntax Tree APIs, Symbol APIs, Binding and Flow analysis APIs and Emit APIs.


References:
http://msdn.microsoft.com/en-us/library/hh156499.aspx