Tuesday, March 24, 2009

Connection Strings at Run Time

If you have a scenario where you want to generate the connection string at runtime or you have the part of a connection string in config file and want to form the remaining part of it at run time. And sometimes, it’s the requirement saying not to store this kind of sensitive information in the configuration files. Using DbConnectionStringBuilder class you can achieve the same. Below are some of the useful Microsoft articles on this:


http://msdn.microsoft.com/enus/library/system.data.common.dbconnectionstringbuilder(v=vs.80).aspx#Y1208


http://msdn.microsoft.com/en-us/library/ms254947(v=vs.80).aspx

Code Contracts in .Net 4.0

Introduction

Microsoft Code Contacts is a very exciting new feature for creating reliable software and enhancing code quality by bringing the advantages of design-by-contract programming in all .NET programming languages. Contract Programming practice was first introduced by Bertrand Meyer in Eiffel programming language.

The contracts classes’ new namespace System.Diagnostics.Contracts is in mscorlib of .NET 4.0, while .NET 3.5 has a small separate library named Microsoft.Contracts which needs an explicit reference.


Benefits


  • The Code Contracts provide users with a number of benefits:
    Contracts are declarative - The syntax for code contracts is standard, quite rich and variegated to express preconditions, postconditions, and invariants
  • Contracts document the design decisions and facilitate code evaluation
  • Improved testing - Code contracts provide static checking, runtime checking and documentation generation
  • Contracts static verification helps
    · Early error detection and avoids passing defects downstream
    · Clarify responsibility at API boundaries
  • We can set up expectations about the behavior of an interface
  • Inherited contracts - A contract defined on a class (concrete or abstract type) or interface is automatically inherited by derived classes, which reduces code duplication
  • Reliability, Correctness, Fast Problem Resolution, Adaptability, Usability, and Speed are which enhances quality in External Customer's view
  • Readability, Reusability, Easy Maintenance, Easy Diagnosis and Easy Deployment are which enhances quality in Internal Developer's viewGood development practices lead to quality software and help control costs

The contract take the form of pre-conditions, post-conditions and object invariant, below is the list of Assertion types and its use. Contracts act as checked documentation of external and internal APIs to programmers, unlike comments, which can become stale with changes in the code.


Precondition
Define what is required on entry to a method. If the caller (client) fails to respect the precondition, the caller is defective and exception is thrown on violation. Failure in precondition suggests client code is defective.

Pre-condition is functionally equivalent to the more common form of the argument validation.

Postcondition
Verifies that code did what it was supposed to do. Failure in postcondition suggests supplier code is defective or environmental.

Object Invariant
Must ALWAYS be true for an object on entry to and exit from any public feature. Once checked on entry to a public feature, it is not checked again until exit from the entry point, even if several other public features are called in the course of execution.

Assertion
Checking and specifying conditions at intermediate points. When an assertion is useful but a precondition or postcondition is not the right choice.

Assumption
Inform static checker of conditions believed to be true. Useful when static checking is used and checker cannot determine correctness of an assertion.

The code contracts are used to improve testing via runtime checking, static checking. For example, you might have rules to which the properties and fields of a given class should always conform to. These rules can then be checked both statically at compile-time using static checker and at runtime when the application executes by the runtime checker.

Static checker looks code before we run it and error messages are conveniently shown in the Visual Studio Error-List window, it finds things as early as possible, as we all knows that finding bugs early is the way to make cost effective changes to our code.

Both static checking and runtime behavior can be configured in the properties window for the project. This allows us to have a strategy to include all the contracts in the initial release of the product, if adoption will be slow. In this scenario, the contracts would allow you to more easily diagnose unusual cases as the product experienced usage by a diverse number of end-users for the first time. Later, these uncommon defects have been repaired, and the product has demonstrated its stability and reliability, you could release a newer version with more limited contracts enabled.

We can also use code contracts for documentation generation. The documentation generator arguments exist in XML doc files with contract information.

Automatic testing tools, such as Pex, take advantage of contracts to generate more meaningful unit tests by filtering out meaningless test arguments that don't satisfy the pre-conditions.


Limitations

  • Sometimes post-conditions can be expensive
  • Not all violations are recognized by the static checker.

Example

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
//To make code contract classes visible, we need to add a diagnostic namespace.
using System.Diagnostics.Contracts;
namespace CodeContractDemo2008
{
public class Rational
{
int N;
int D;
public Rational(int n, int d)
{
Contract.Requires(0 < n =" n;" d =" d;"> 0);
Contract.Invariant(this.N >= 0);
}

public int ToInt()
{
Contract.Ensures(Contract.Result() >= 0);
return this.N / this.D;
}
}
class Program
{
public static void Foo(int n)
{
Contract.Requires(n > 0);
int x = 0, y = 2;
while (x <= n) { x++; y++; } //We need to prove the assertions after the loop, and we can prove more complex assertions Contract.Assert(y == x + 2); Contract.Assert(x >= 0);
}
static void Main(string[] args)
{
Rational r = new Rational(3, 4);
//Foo(2);
Console.WriteLine(r.ToInt());
}
}
}

Mapping an XML to Business Objects using LINQ

Class Customer

Private _iD As Integer
Public Property ID() As Boolean
Get
Return _iD
End Get
Set(ByVal Value As Boolean)
_iD = Value
End Set
End Property

Private _name As String
Public Property Name() As String
Get
Return _name
End Get
Set(ByVal Value As String)
_name = Value
End Set
End Property

Private _department As String
Public Property Department() As String
Get
Return _department
End Get
Set(ByVal Value As String)
_department = Value
End Set
End Property

Private _orderList As New List(Of Order)
Public Property OrderList() As List(Of Order)
Get
Me.LoadOrders()
Return Me._orderList
End Get

Set(ByVal value As List(Of Order))
Me._orderList = value
End Set
End Property

Private Sub LoadOrders()

End Sub
End Class


Class Order
Private _name As String
Public Property Name() As String
Get
Return _name
End Get
Set(ByVal Value As String)
_name = Value
End Set
End Property

Private _quantity As String
Public Property Quantity() As String
Get
Return _quantity
End Get
Set(ByVal Value As String)
_quantity = Value
End Set
End Property

End Class

Module Module1

Sub Main()

Const documentPath As String = "D:\Others\My Tools\Sample Projects\TestVBConsole\TestVBConsole\Customer.xml"

Dim document As XDocument = LoadDocument(documentPath)

Dim customer = From cust In document.Elements("Customer") _
Select New Customer _
With { _
.ID = cust.Element("ID").Value _
, .Name = cust.Element("Name").Value _
, .Department = cust.Element("Department").Value _
, .OrderList = (From order In cust.Elements("OrderList").Elements("Order") _
Select New Order() With { _
.Name = order.Element("ItemId").Value, _
.Quantity = order.Element("Quantity").Value}).ToList() _
}

Dim moreQuantityOrders = From cust In customer _
From orderList In cust.OrderList _
Where (orderList.Quantity > 1)

Console.ReadLine()
End Sub

Private Function LoadDocument(ByVal documentPath As String) As XDocument

Dim document = XDocument.Load(documentPath)
Return document

End Function

End Module

Nullable Types

This feature was added to C# 2005. This allows us to assign value ‘null’ to a value-type variables including struct. Lets take a scenario we have an ‘age’ field which is of type int in database, the value for this field could be all the values that can be assigned to value-type int plus it could be ‘null’ value (undefined or not used or empty). This is possible using nullable type variables; we can assign the exact value of age as it is in the database to our nullable-type variable.

The nullable type is declared with the ? symbol just next to any value-type.

Value-Type? myVariable;

int age? = null;

Nullable types are instances of the System.Nullable struct. The two important Properties of the Nullable struct are HasValue and Value. In the below example, age.HasValue returns false as there is no value assigned to age int value-type.

using System;
class MyClass
{
static void Main()
{
int? age;
age = null;
int simpleInt=-1;

if (age.HasValue)
simpleInt = age.Value;

Console.WriteLine("Age is {0} Years", simpleInt);
Console.ReadLine();
}
}


We cannot create a nullable type based on a reference type.

MyClass? obj = new MyClass?(); //Error: The type 'ConsoleApplication1.MyClass' must be a non-nullable value type in order to use it as parameter 'T' in the generic type or method 'System.Nullable'

Nullable(T).GetValueOrDefault returns either the assigned value, if the value is not assigned (null) it will return the default value of the respective value-type, in the below example age.GetValueOrDefault() returns 0 – the defult alue for int value-type as the age is null (undefined)

int? age;
age = null;
int simpleInt = age.GetValueOrDefault();

Conditional and Null-Coalescing Operators (??):

We can assign a default value to the nullable variable using Null-Coalescing Operator (??). In the below example if age nullable type is null then the default of -1 is assigned.

using System;
class MyClass
{
static void Main()
{
int? age;
age = null;

int simpleInt = age ?? -1;

Console.WriteLine("Age is {0} Years", simpleInt);
Console.ReadLine();
}
}


Below code is used to identify nullable types.

if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(Nullable<>))
{
//...
}

type.IsGenericType is to test if the property is a generic type
type.GetGenericTypeDefinition() == typeof(Nullable<>) to know if its a nullable type

Attributes in C#

Attributes adds the information to the program entities such as an Assembly, Module, Class, Struct, Enum, Constructor, Method, Property, Field, Event, Interface, Parameter, Delegate. The information that Attribute contains is inserted into the assembly, at run time. The compiler can retrieve/queried this information at run-time using reflection.

Using predefined attributes:

There can be predefined or user-defined/custom attributes. Before digging into custom attributes we will have a quick look at using user-defined attributes, some of them are:

System.AttributeUsageAttribute - Describe the ways in which an attribute class can be used, we are going to know how to use it in a few minutes in custom attributes section.

System.Diagnostics.ConditionalAttribute - Used to define conditional methods.

Conditional Attribute is used to create conditional methods; this method is being called if a specific preprocessor symbol is defined using #define, if not the method will be bypassed/resumed. The conditional method much return void, it should be the member of a class rather than an Interface and we cannot override it. Below is the example on this.

#define MYCONSTANT
using System;
using System.Diagnostics; //We must use this namespace for using conditional attributes

public class MyClass {

[Conditional("MYCONSTANT")]
public void MyMethod1( ) {
Console.WriteLine("MyMethod1 - MYCONSTANT is defined");
}

[Conditional("MYCONSTANT")]
public void MyMethod2( ) {
Console.WriteLine("MyMethod2 - DEBUG");
}
}

public class TestClass {
public static void Main( ) {
MyClass obj = new MyClass( );
obj.MyMethod1( ); //this is called only when MYCONSTANT is defined
obj.MyMethod2( ); //this method will be called when the Compile parameter is being used from command prompt e.g. "csc Program.cs /d:DEBUG"
}
}


System.Runtime.InteropServices.DllImportAttribute - DllImportAttribute attribute provides the information needed to call a function exported from an unmanaged DLL, example below tells how to use DllImport to import the Win32 MessageBox function.

using System;
using System.Runtime.InteropServices;

class Example
{
[DllImport("user32.dll", CharSet = CharSet.Unicode)]
public static extern int MessageBox(IntPtr hWnd, String text, String caption, uint type);

static void Main()
{
// Call the MessageBox function using platform invoke.
MessageBox(new IntPtr(0), "Hello World!", "Hello Dialog", 0);
}
}

System.ObsoleteAttribute - Used to mark a member as deprecated or obsolete, see below is the example on this.

namespace ConsoleApplication1
{
class TestClass
{
[Obsolete("Do not use Method1 its old, use Method2", true)]
static void Method1()
{
}

static int Method2()
{
return 0;
}

static void Main()
{
Method1(); //this will give compile Error - ConsoleApplication1.TestClass. Method1()' is obsolete: 'Do not use Method1 its old, use Method2'

int i = Method2(); //No Errors

Console.ReadLine();
}


}
}


User-defined/Custom attributes

Now lets look at making our own custom attributes.


Using the Attribute classes:

Deriving System.Attribute just makes our class an Attribute class. We can use the Attribute convention as a suffix to our custom class like ‘HelpAttribute’ but can be referred only by class name [Help(" this is my description about the program entity")]
Compiler is intelligent enough to add the word Attribute to the specified attribute name and search for it in System.Attribute derived classes first and then in our custom class.

AttributeUsage attribute:

AttributeUsage is used on custom attributes to control the usage of our attribute. We can control to all the program entities using AttributeTargets. ‘AttributeTargets.Class’ is used to allow only for Class declarations; ‘AttributeTargets.Method’ is to allow only for Method declarations and so on. Use ‘AttributeTargets.All’ to allow our custom attributes to be used by the all program entities.

[AttributeUsage(AttributeTargets.All, AllowMultiple = true, Inherited = false )]

The AllowMultiple = true let us to use the attributes multiple times for the same programme entity. Below is the example:

[Help("This is the test class")]
[Help("more desc..., this is possible with AllowMultiple=true")]
class TestClass
{...}


if AllowMultiple = false, then you will get the compiler error as ‘Duplicate 'Help' attribute’ for the above code. The property Inherited = true let the base class attributes inherited to the derived classes. Further more we can use multiple AttributeTargets like below.

[AttributeUsageAttribute(AttributeTargets.PropertyAttributeTargets.FieldAttributeTargets.ParameterAttributeTargets.ReturnValue, AllowMultiple = false)]
public class XmlArrayAttribute : Attribute


Positional parameters and Named parameters:

Attribute classes can have positional parameters and named parameters. Positional parameters are defined by public instance constructor of an attribute class and named parameters are defined by non-static public read-write field and property of an attribute class, we called it named because when setting the value we have to name them. In the below example Version is the named parameter where as the description passed through public instance constructor is positional.

[Help("This is the test class", Version="1.2")]
class TestClass
{...}


To give you a better idea they both are shown in the below example.

Limited parameters types:

We can use a limited parameters types for an attribute class they are : bool, byte, char, double, float, int, long, short, string, System.Type, object, public enum.

Attributes Identifiers:

attribute identifiers are used to let the compiler the entity on which it can placing the attribute. the identifiers can be assembly, module, type, method, property, event, field, param, return.
below example tells the compiler to attace the attribute to entire assembly.

[assembly: Help("this is assembly")]

Querying attributes:

Reflection is the ability to get the metadata of the object at run-time; we need to use this to query the attached attributes of the type.

using System;
using System.Reflection;
using System.Diagnostics;

namespace ConsoleApplication1
{
[AttributeUsage(AttributeTargets.All, AllowMultiple = true, Inherited = false)]
public class HelpAttribute : Attribute
{
protected String description;
public HelpAttribute(string description) // Positional parameter
{
this.description = description;
}

public String Description // Named parameter
{
get
{
return this.description;
}
}

protected String version;
public String Version // Named parameter
{
get
{
return this.version;
}
set
{
this.version = value;
}
}
}

[Help("This is my sample test Class.")]
public class MyClass
{
[Help("This is my String member variable.")]
public string sMember;

[Help("This is my Integer member variable.")]
public int iCounter;

[Help("This is my Integer protected member variable.")]
protected int jCounter;

[Help("This is a my test Method.")]
public void TestMethod1() { }

[Help("This is a my test Method2.")]
public void TestMethod2() { }

[Help("This is a my test Method3", Version = "7.1")]
[Help("more description about the class, this is possible with AllowMultiple=true")]
public void TestMethod3() { }
}

class TestClass
{
static void Main()
{
Type type = typeof(MyClass);
HelpAttribute HelpAttr;

//Querying Class Attributes
foreach (Attribute attr in type.GetCustomAttributes(true))
{
HelpAttr = attr as HelpAttribute;
if (null != HelpAttr)
{
Console.WriteLine("Description of MyClass:\n{0}", HelpAttr.Description);
}
}

//Querying Class method attributes
foreach (MethodInfo method in type.GetMethods())
{
foreach (Attribute attr in method.GetCustomAttributes(true))
{
HelpAttr = attr as HelpAttribute;
if (null != HelpAttr)
{
Console.WriteLine("Description of {0}:\n{1}", method.Name, HelpAttr.Description);
}
}
}

//Querying Class Attributes for public fields
foreach (FieldInfo field in type.GetFields())
{
foreach (Attribute attr in field.GetCustomAttributes(true))
{
HelpAttr = attr as HelpAttribute;
if (null != HelpAttr)
{
Console.WriteLine("Description of {0}:\n{1}", field.Name, HelpAttr.Description);
}
}
}
Console.ReadLine();
}
}
}

Indexers

Indexers treats object as an array or collection, we can access the indexer’s elements using square brackets ([]) it enables an object to be indexed and provide array-like or collection-like access to the classes. Indexer defined much like properties. C# developers also called this as smart arrays.

this [argument list]
{
get
{
// Get codes goes here
}
set
{
// Set codes goes here
}
}

Eg.
namespace ConsoleApplication1
{
public class Customer
{
public int Id;
public string Name;
public string City;
public Customer(int id, string name, string city)
{
Id = id;
Name = name;
City = city;
}
}

class SampleCollection
{
// Declare an array to store the data elements.
private T[] arr = new T[100];

// Define the indexer, which will allow client code
// to use [] notation on the class instance itself.
// (See line 2 of code in Main below.)
public T this[int i]
{
get
{
// This indexer is very simple, and just returns or sets
// the corresponding element from the internal array.
return arr[i];
}
set
{
arr[i] = value;
}
}
}

class MyPoint
{
static void Main()
{
SampleCollection stringCollection = new SampleCollection();

// Use [] notation on the type.
stringCollection[0] = "Hello, World";
stringCollection[1] = "Mohammed Ghouse";
Console.WriteLine(stringCollection[0]);
Console.WriteLine(stringCollection[1]);

SampleCollection stringCollection2 = new SampleCollection();
stringCollection2[0] = 786;
stringCollection2[1] = 123;
Console.WriteLine(stringCollection2[0]);
Console.WriteLine(stringCollection2[1]);

SampleCollection stringCollection3 = new SampleCollection();

Customer cust1 = new Customer(1,"Ghouse","Kadapa");
Customer cust2 = new Customer(2, "Mohammed", "Bangalore");

stringCollection3[0] = cust1;
stringCollection3[1] = cust2;
Console.WriteLine(stringCollection3[0].Name);
Console.WriteLine(stringCollection3[1].Name);

Console.ReadLine();
}

}
}


1. this keyword refers to the object to which indexer belongs
2. ref and out parameter modifiers are not permitted
3. Indexers can be overloaded just like member functions
4. Indexer doesn’t have a name; it is recognized by its signature - types and number of parameters
5. There is nothing called static indexers
6. A base class indexer is inherited and can be overridden in the derived class.


class BaseClass
{
public virtual int this[int index]
{
get
{
Console.Write("from BaseClass Get assessors");
return 1;
}
set
{
Console.Write("from BaseClass Set assessors");
}
}
}
class DerivedClass : BaseClass
{
public override int this[int index]
{
get
{
Console.Write("from DerivedClass Get assessors");
return 2;
}
set
{
Console.Write("from DerivedClass Set assessors");
}
}
}
class MyClient
{
public static void Main()
{
BaseClass obj1 = new DerivedClass();
obj1[0]= 123;
Console.WriteLine(obj1[0]);
}
}
7. To avoid index errors it’s always better to check index limits in get and set assessors.
Interfaces can have indexers with the exception that it's indexers don’t have modifiers and obviously no implementation of assessors in interfaces, below is the e.g.

public interface ISomeInterface
{
// Indexer declaration:
string this[int index]
{
get;
set;
}

}

Structs vs. Classes

Standard question which I would like to ask to the rejected candidates as one of the last questions to make them feel that they have not done very badly in their interview ;)

A struct is a user-defined value type created on the stack. It may contain both reference and value types. It’s used to represent a light weight object which consumes a small memory such as point, color and the like.

Unlike classes, the fields of a struct cannot be initialized. It will give an error saying ‘cannot have instance field initializers in structs’.

struct MyStruct
{
int x = 0; // error
int y = 0; // error
}


Structs cannot contain explicit parameter less constructors (default constructor), but we can have one or more constructors. C# compiler provides implicitly provides default constructor to initialize the default values for the members of a struct.

struct MyStruct
{
int i,j;

MyStruct() // error
{
//...
}

MyStruct(int i) //correct
{
this.i = i;
this.j = 0;
}

MyStruct(int i, int j) //correct
{
this.i = i;
this.j = j;
}
}


We can create struct objects as below, in the second case; we must initialize the struct fields before using it as it’s just a declaration.

1. MyStruct obj = new MyStruct();
2. MyStruct obj;


Below is the example showing Structs pass by value and Classes passed by reference

namespace ConsoleApplication1
{
class MyClass
{
public int iVariable;
}

struct MyStruct
{
public int iVariable;
}

class TestClass
{
public static void Method1(MyStruct s)
{
s.iVariable = 200;
}
public static void Method2(MyClass c)
{
c.iVariable = 200;
}

static void Main()
{
MyStruct objStruct = new MyStruct();
MyClass objClass = new MyClass();

objClass.iVariable = 100;
objStruct.iVariable = 100;

Console.Write(objClass.iVariable);
Console.Write(objStruct.iVariable);

//As it is a struct being passed as value
Method1(objStruct);

//As it is a class being passed as reference
Method2(objClass);
Console.Write(objStruct.iVariable);
Console.Write(objClass.iVariable);
Console.ReadLine();
}
}
}