Category Archives: C#

Q How can you prevent a cleint by using Action method in MVC?

I have two actions inside my controller (shoppingCartController)

public ActionResult Index()
{
	//some stuff here
	return View(viewModel);
}

public ActionResult AddToCart(int id)
{

	return RedirectToAction("Index");

}

Is there anyway to prevent the users from directly calling the index action by typing the url in the browser?
For example: If the user browses to shoppingCart/index be redirected to Home/Index.
Solution
You could use the [ChildActionOnly] attribute on your action method to make sure it’s not called directly, or use the ControllerContext.IsChildAction property inside your action to determine if you want to redirect.
For example:

//[ChildActionOnly]
public ActionResult Index()
{
    if(!ControllerContext.IsChildAction)
    {
       //perform redirect here
    }

    //some stuff here
    return View(viewModel);
}

Reference:
https://stackoverflow.com/questions/9407172/asp-net-mvc-how-to-prevent-browser-from-calling-an-action-method

 

Leave a comment

Filed under C#, Interview question, MVC, Uncategorized

Q Explain deferred execution vs. immediate execution in LINQ. Provide examples.

In LINQ, deferred execution simply means that the query is not executed at the time it is specified. Specifically, this is accomplished by assigning the query to a variable. When this is done, the query definition is stored in the variable but the query is not executed until the query variable is iterated over. For example:

DataContext productContext = new DataContext();

var productQuery = from product in productContext.Products
where product.Type == "SOAPS"
select product; // Query is NOT executed here

foreach (var product in productQuery) // Query executes HERE
{
	Console.WriteLine(product.Name);
}

You can also force immediate execution of a query. This can be useful, for example, if the database is being updated frequently, and it is important in the logic of your program to ensure that the results you’re accessing are those returned at the point in your code where the query was specified. Immediate execution is often forced using a method such as Average, Sum, Count, List, ToList, or ToArray. For example:

DataContext productContext = new DataContext();

var productCountQuery = (from product in productContext.Products
where product.Type == "SOAPS"
select product).Count(); // Query executes HERE

Ref
https://www.toptal.com/dot-net/interview-questions

Leave a comment

Filed under C#, Interview question

How does HTTPS works?

How does HTTPS works?

  1. Client request for secure Https  page.
  2. Web server respond by sending certificate with public key.
  3. Client checks the validity of the certificate and create a symmetric session key using the public key and sends it back to Web serer.
  4. Web server decrypt the symmetric session key using it’s private key and sends page encrypted using the symmetric session key.
  5. Secure session has now been established between Client browser & Web server.

ssl-in-a-nutshell

HTTPS pages typically use one of two secure protocols to encrypt communications – SSL (Secure Sockets Layer) or TLS (Transport Layer Security). Both the TLS and SSL protocols use what is known as an ‘asymmetric’ Public Key Infrastructure (PKI) system. An asymmetric system uses two ‘keys’ to encrypt communications, a ‘public’ key and a ‘private’ key. Anything encrypted with the public key can only be decrypted by the private key and vice-versa.

The ‘private’ key should be kept strictly protected and should only be accessible the owner of the private key. In the case of a website, the private key remains securely ensconced on the web server. Conversely, the public key is intended to be distributed to anybody and everybody that needs to be able to decrypt information that was encrypted with the private key.

HTTPS-workflow

 

Leave a comment

Filed under .Net, ASP.Net, C#, WCF

Benefit of const

A Very similar to a #define in C, const “variables” in the .NET Framework don’t have their own actual storage location but rather are substituted into the Microsoft Intermediate Language (MSIL) instructions at compile time where they are referenced. For example, if I have the following C# code

int myInt = 5; 
Console.WriteLine(myInt);

csc.exe will generate this MSIL:

ldc.i4.5 stloc.0 ldloc.0 call void [mscorlib]System.Console::WriteLine(int32)

In other words, it loads the value 5, stores it to the myInt variable, then loads this value back onto the execution stack, and prints it out using Console.WriteLine.

If you change the myInt variable to be a constant, like so

const int myInt = 5; 
Console.WriteLine(myInt);

the MSIL generated will be:

ldc.i4.5 call void [mscorlib]System.Console::WriteLine(int32)

Now, wherever myInt is referenced in the code, instead of having to do a “ldloc.0” to get the value from the variable, the MSIL just loads the constant value which is hardcoded into the MSIL. As such, there’s usually a small performance and memory advantage to using constants.
However, in order to use them you must have the value of the variable at compile time, and any references to this constant at compile time, even if they’re in a different assembly, will have this substitution made. Constants are certainly a useful tool if you know the value at compile time.
If you don’t, but want to ensure that your variable is set only once, you can use the readonly keyword in C# (which maps to initonly in MSIL) to indicate that the value of the variable can only be set in the constructor; after that, it’s an error to change it. This is often used when a field helps to determine the identity of a class, and is often set equal to a constructor parameter.

Leave a comment

Filed under C#

Yield keyword in C#

What is the use of c# “Yield” keyword.

Leave a comment

Filed under C#

Garbage Collector

When space is not available on heap, new keyword triggers GC for heap cleanup and then reclaims the space

Leave a comment

Filed under C#

what is lock?

lock marks a statement block as critical section and ensures one thread doesn’t enter critical section with another thread.
lock can be applied on an object. Avoid lock on public type. Below lock should be avoided:

  • lock (this) is a problem if the instance can be accessed publicly.
  • lock (typeof (MyType)) is a problem if MyType is publicly accessible.
  • lock(“myLock”) is a problem because any other code in the process using the same string, will share the same lock.

Best practice is to define private object or private static object variable to protect data common to all instance.

class Account
    {
        decimal balance;
        private Object thisLock = new Object();

        public void Withdraw(decimal amount)
        {
            lock (thisLock)
            {
                if (amount > balance)
                {
                    throw new Exception("Insufficient funds");
                }
                balance -= amount;
            }
        }
    }

for more explanation refer:
http://msdn.microsoft.com/en-us/library/c5kehkcz.aspx

Leave a comment

Filed under C#

What makes thread-safe?

  • struct & immutable are thread safe. so string is also thread safe as all you can do is read them.
  • Reading is safe, if all the threads are reading.
  • If a method only access variable scoped within the method then it is thread safe beacuse each thread has it’s own stack.
  • Also if method calls other method which only use local scoped variables.
public class Thing
{
    public int ThreadSafeMethod(string parameter1)
    {
        int number; // each thread will have its own variable for number.
        number = this.GetLength(parameter1);
        return number;
    }

    private int GetLength(string value)
    {
        int length = value.Length;
        return length;
    }
}

 

  • but if a method use any properties or fields then you need to use lock to ensure the values are not modified by a different thread.
public class Thing
{
    private string someValue; // all threads will read and write to this same field value

    public int NonThreadSafeMethod(string parameter1)
    {
        this.someValue = parameter1;

        int number;

        // Since access to someValue is not synchronised by the class,
        // a separate thread could have changed its value.
        number = this.someValue.Length;
        return number;
    }
}

To ensure proper concurrency you need to use lock.

Leave a comment

Filed under C#

MVC Life Cycle Explained

1) An application has one and only one Route Table. This Route Table is setup in the Global.asax file
Initially Application_Start() event is called for the application, where we set all the Routes in the static RouteTable.Route collection (which is of type RouteCollection)

routes.MapRoute(
 "Default", // Route name
 "{controller}/{action}/{id}", // URL with parameters
 new { controller = "Home", action = "Index", id = UrlParameter.Optional }
 );

All route object map route Url to MVCRouteHandler which implement IHttpHandler.

2) The UrlRoutingModule class matches an HTTP request to a route in an ASP.NET MVC application.
UrlRoutingModule passes HttpContext object to RouteTable. The HttpContext object includes Url, form parameters, query string, cookies with the current request.

ControlFlow of MVC

3) The MapRoute method being invoked inside of the RegisterRoutes method is an extension method. Every route registered with MapRoute is configured to use MvcRouteHandler, which is a RouteHandler provided by MVC framework.
It is route handler job to find the HTTP Handler (which implement IHttpHandler) for a request, in MVC this handler is called MvcHandler.

4) When control reaches this MvcHandler, it extract the controller parameter from RouteData and send them to ControllerFactory. It is the factory responsibility to return a controller. All controller in MVC implement IController.
MVC framework provide a default controller factory named DefaultControllerFactory that will search assemblies in appdomain to the Controller with implement IController & ends with Controller. Then the same instance is returned to the MvcHandler. When MvcHandler has a IController reference, it invokes the Execute() on controller.

5) The Execute() method extract members from the Request object and some of which act as method parameter.
The Execute() method finds method of the controller by using reflection on Controller class. It finds the method (action) which matches the route and executes it.

6) When controller transfer to RenderView() method, the call is delegated to ViewEngine’s RenderView() method. It uses ViewLocator class to find the View. And all master page, ViewBag, ViewData are set.

References :
http://msdn.microsoft.com/en-us/magazine/dd695917.aspx

image

2 Comments

Filed under C#

Reverse String

Below is the code in two approach:


class ReverseString
    {
        public string Reverse(string str)
        {
            char[] chr = str.ToArray();
            StringBuilder news = new StringBuilder();

            for (int i = str.Length - 1; i >= 0; i--)
                news.Append(str[i]);

            return news.ToString();
        }

        public string ReverseRecursive(string str)
        {
            if (str.Length > 0)
                return str[str.Length - 1] + ReverseRecursive(str.Substring(0, str.Length - 1));
            else
                return str;
        }
    }

class MainReverse
    {
        public static void Main(string[] args)
        {
            Console.Write("Enter the string: ");
            string s = Console.ReadLine();
            ReverseString rs = new ReverseString();
            Console.WriteLine("\nReverse: " + rs.Reverse(s));
            Console.ReadLine();
        }
    }

Refrences :
http://en.support.wordpress.com/code/posting-source-code/

Leave a comment

Filed under C#

What is Dependency Injection (DI)

Dependency Injection allows you to inject object into the class, rather then relying on class to create object.

http://msdn.microsoft.com/en-us/magazine/cc163739.aspx

http://weblogs.asp.net/shijuvarghese/archive/2008/10/24/asp-net-mvc-tip-dependency-injection-with-unity-application-block.aspx

http://www.mikesdotnetting.com/Article/117/Dependency-Injection-and-Inversion-of-Control-with-ASP.NET-MVC

Leave a comment

Filed under C#

Differences Article

Response.Redirect vs Server.transfer

http://quickdotnetsolutions.blogspot.in/2011/05/difference-between-responseredirect-and.html

 

wcf service over web services.

http://quickdotnetsolutions.blogspot.in/2011/05/advantages-of-wcf-service-over-web.html?utm_source=blog&utm_medium=gadget&utm_campaign=bp_random

Leave a comment

Filed under ASP.Net, C#, WCF

What can’t be saved in ViewState?

Any data (Serialized) that you want to access over the postback can be saved in ViewState.

DataReader can’t be serialized as it is in Connected mode. So you can save DataReader in ViewState.

Leave a comment

Filed under C#

Cookies

Cookies are sent to the browser via the HttpResponse object that exposes a collection called Cookies. You can access the HttpResponse object as the Response property of your Page class.

You can also set a cookie’s date and time expiration. Expired cookies are deleted by the browser when a user visits the site that wrote the cookies. you can set the expiration date to be 50 years from now.

If you do not set the cookie’s expiration, the cookie is created but it is not stored on the user’s hard disk. When the user closes the browser, the cookie is discarded. Those are called non- Persistant cookies.
eg: non-persistent cookies are useful if the user is working on a public computer, where you do not want to write the cookie to disk due to security reason.

You can add cookies to the Cookies collection in a number of ways.

Response.Cookies["userName"].Value = "patrick";
Response.Cookies["userName"].Expires = DateTime.Now.AddDays(1);

HttpCookie aCookie = new HttpCookie("lastVisit");
aCookie.Value = DateTime.Now.ToString();
aCookie.Expires = DateTime.Now.AddDays(1);
Response.Cookies.Add(aCookie);

Cookies with More Than One Value
You can store multiple name-value pairs in a single cookie.
eg: instead of creating two separate cookies named userName and lastVisit, you can create a single cookie named userInfo that has the subkeys userName and lastVisit.
Benefits
1) cookie attribute such as expiration can be applied to single cookie file instead of each cookie individually.
2) as we know we can’t store more then 20 cookies per site, so by using single cookie like above we save on number of cookies per site.

Response.Cookies["userInfo"]["userName"] = "patrick";
Response.Cookies["userInfo"]["lastVisit"] = DateTime.Now.ToString();
Response.Cookies["userInfo"].Expires = DateTime.Now.AddDays(1);

HttpCookie aCookie = new HttpCookie("userInfo");
aCookie.Values["userName"] = "patrick";
aCookie.Values["lastVisit"] = DateTime.Now.ToString();
aCookie.Expires = DateTime.Now.AddDays(1);
Response.Cookies.Add(aCookie);

Controlling Cookie Scope
By default, all cookies for a site are stored together on the client, and all cookies are sent to the server with any request to that site. In other words, every page in a site gets all of the cookies for that site. However, you can set the scope of cookies in two ways:
Limiting Cookies to a Folder or Application
To limit cookies to a folder on the server, set the cookie’s Path property, as in the following example:

HttpCookie appCookie = new HttpCookie("AppCookie");
appCookie.Value = "written " + DateTime.Now.ToString();
appCookie.Expires = DateTime.Now.AddDays(1);
appCookie.Path = "/Application1";
Response.Cookies.Add(appCookie);

The path can either be a physical path under the site root or a virtual root. The effect will be that the cookie is available only to pages in the Application1 folder. So cookie will be available to path http://www.contoso.com/Application1/ or any page beneath that folder.

Limiting Cookie Domain Scope
By default, cookies are associated with a specific domain. For example, if your site is http://www.contoso.com, the cookies you write are sent to the server when users request any page from that site. If your site has subdomains—for example, contoso.com, sales.contoso.com, and support.contoso.com—then you can associate cookies with a specific subdomain.

Response.Cookies["domain"].Value = DateTime.Now.ToString();
Response.Cookies["domain"].Expires = DateTime.Now.AddDays(1);
Response.Cookies["domain"].Domain = "support.contoso.com";

Reading Cookies
When a browser makes a request to the server, it sends the cookies for that server along with the request. In your ASP.NET applications, you can read the cookies using the HttpRequest object, which is available as the Request property of your Page class. structure of the HttpRequest is same as HttpResponse object, so you can read them much the same way as you wrote them.

if(Request.Cookies["userName"] != null)
Label1.Text = Server.HtmlEncode(Request.Cookies["userName"].Value);

if(Request.Cookies["userName"] != null)
{
HttpCookie aCookie = Request.Cookies["userName"];
Label1.Text = Server.HtmlEncode(aCookie.Value);
}

HtmlEncode method was called to encode the contents of a cookie to make sure executable script are not added into the cookie.
Similarly reading a subkey: Server.HtmlEncode(Request.Cookies[“userInfo”][“userName”]);
The subkeys in a cookie are typed as a collection of type NameValueCollection. Therefore, another way to get an individual subkey is to get the subkeys collection and then extract the subkey value by name, as shown in the following example:
System.Collections.Specialized.NameValueCollection
UserInfoCookieCollection;

UserInfoCookieCollection = Request.Cookies["userInfo"].Values;
Label1.Text =
Server.HtmlEncode(UserInfoCookieCollection["userName"]);
Label2.Text =
Server.HtmlEncode(UserInfoCookieCollection["lastVisit"]);

Leave a comment

Filed under C#

Access Modifiers in C#

In C# there are 5 different types of Access Modifiers.

Modifier Description
public There are no restrictions on accessing public members.
private Access is limited to within the class definition. This is the default access modifier type if none is formally specified
protected Access is limited to within the class definition and any class that inherits from the class
internal Access is limited exclusively to classes defined within the current project assembly
protected internal Access is limited to the current assembly and types derived from the containing class. All members in current project and all members in derived class can access the variables.

DEFAULT ACCESS MODIFIER

An enum has default modifier as public.

class has default modifiers as Internal.

An interface has default modifier as public.

struct has default modifier as Internal.

methods, fields, and properties has default access modifier as “Private” if no modifier is specified.

Access modifiers

Leave a comment

Filed under C#

Stack, heap, Value types, Reference types, boxing, and unboxing

When you declare a variable in .Net, it allocates some chunk of memory in RAM. This memory has three things :
name
data type &
value of the variable.
Depending upon the data type there are two types of memory allocation: Stack and Heap


The Stack is responsible for keeping track of the running memory needed in your application.

Heap doesn’t track the running memory. It is just a pile of object which can be reached at any time. It is dynamic memory allocation.

eg:

public void Method1()
{
// Line 1
int i=4;

// Line 2
int y=2;

//Line 3
class1 cls1 = new class1();
}

Line1: When Line1 is executed the compiler allocate small chunk of memory in the Stack.

Line2: It allocates memory for y on top of the first memory in Stack (LIFO).
Line3: Here an object is created. When this line is executed it creates a pointer on Stack and the actual object is stored in a Heap memory.

NB: Reference pointer is allocated on Stack. The statement
Class1 cls1;
doesn’t allocate memory for an instance of Class1, it only allocates a stack variable cls1 (and sets it to null). The time it hits new keyword, it allocates on “heap”.

Exiting the above Method
On exiting the method, it clears all the memory variable which are assigned on Stack.
But it didn’t de-allocate the heap memory. This memory will be later de-allocated by the garbage collector.

Now we have discussed about the Stack & Heap memory. Let’s move on to Value & Reference Types.

Value types
1. Value types are types which hold both memory & data on the same location i.e Stack.
2. Below we assign an int value (i) to another int value (y). Both these memory are separately allocated on stack. So if we change either of them then other doesn’t change. This is Value type.


Reference Type
1. A reference type has a pointer which points to the memory location.
2. Now when we create an object and assign an object to another object, they both point to same memory location (in heap). So if we change one of them, the other object is also affected. This is Reference type.


Type Chart


Boxing and Unboxing

Boxing
When we move data from Value type to Reference type, data is moved from Stack to Heap. It is termed as Boxing.

Unboxing
When we move data from Reference type to Value type, data is moved from Heap to stack. It is termed as Unboxing.

References:

http://www.codeproject.com/Articles/76153/Six-important-NET-concepts-Stack-heap-value-types

6 Comments

Filed under C#

Aggregation & Composition

Aggregation
Aggregation means “has-a” relationship. Here the two entity are dependent on each other but the can exist alone as well.
eg: Person and Shirt entity. Shirt is dependent upon the person who wears it, but it can exist alone as well.

Composition 

Composition means “is-a” relationship. Here the two entity are tightly dependent on each other and can’t exist alone.
Eg: Human and Heart they both are dependent on each other and can’t exist alone.

Leave a comment

Filed under C#

Abstraction vs Encapsulation

Below is the difference:

Encapsulation

Abstraction

Encapsulation is the act of packing data and function into a single unit.

Abstraction means representing the essential features without representing/hiding the background details.

Eg: Class

Eg: abstract class, interface.

Encapsulation is achieved using abstraction.

It is achieved using access modifier.

 

 

 

 

Here if we make Validate() and CreateBDObject() methods public and let the client call these method before calling Add() then it will be showing extra information to user as these two methods will only be called if we want to perform Add operation.

 

So if we follow abstraction then we make these two methods private and include them in Add() method. This way only the essential features are shown to the client and hiding the background details.

Leave a comment

Filed under C#

How to Dispose a Static member?

Static finalizer & dsetructor are not possible and these types are unloaded only when the AppDomain shuts down.

However, to make the Static object ready for Garbage collection, you can assign it to null.

static List<Customers> customers = new List<Customers>();

customers = CustomerDAC.GetCustomers();

//To unload static class

customers = null;

Leave a comment

Filed under C#

Static vs Singleton

Though both restrict to have only one instance of the class to be created but there are differences:

Static

Singleton

It doesn’t maintain any state as no object is created. It maintains the state of object.
Static class gets activated at run-time. Singleton follows lazy loading, so object gets created when required.
It doesn’t implement interface. It implement interface.
Disposing Static is not possible, as types are only unloaded when the AppDomain shut down. They can be disposed at run time.
We can’t create object of Static class. Singleton object can be used as parameter.

Ref

http://quickdotnetsolutions.blogspot.in/2011/05/difference-between-singleton-and-static.html

Leave a comment

Filed under C#

Static members in Generic class

Yes it is possible as shown below but:
Bear in mind that for every Generic type you get a different Static variable. SO if the Static member value has nothing to do with the Generic type then they shouldn’t be in Generic class. They should be declared in different class. 

Leave a comment

Filed under C#

Page Life Cycle

Below are the events:

Page_PreInit (EventArgs e)

UC_Init (EventArgs e)
CWebC_Init (EventArgs e)
Master_Init (EventArgs e)
Page_Init (EventArgs e)

UC_TrackViewState ()
CWebC_TrackViewState ()
Master_TrackViewState ()
Page_TrackViewState ()

Page_Load (EventArgs e)
Master_Load (EventArgs e)
UC_Load (EventArgs e)
CWebC_Load (EventArgs e)

Page_PreRender (EventArgs e)
Master_PreRender (EventArgs e)
UC_PreRender (EventArgs e)
CWebC_PreRender (EventArgs e)

Page_SaveViewState()
Master_SaveViewState()
UC_SaveViewState()
CWebC_SaveViewState()

Page_Render(HtmlTextWriter writer)
Master_Render(HtmlTextWriter writer)
UC_Render(HtmlTextWriter writer)
CWebC_Render(HtmlTextWriter writer)

UC_UnLoad()
CWebC_UnLoad()
Master_UnLoad()
Page_UnLoad()

Leave a comment

Filed under C#

try/catch/finally nested

We can have try..catch..finally nested in try/catch/finally blocks:

Leave a comment

Filed under C#

Const vs Readonly

 

Const

Readonly

They are Compile-Time constant means always constant. They are Run-time constant.
value can be set at declaration only. value can be set at declaration or in Constructor.
Can’t be static. Can be static

Leave a comment

Filed under C#

Difference between “==” and Equals() methods?

Value Type:- “==” & Equal() method usually compare object by value.

Reference Type:- “==” compares whether both the reference point to same object.
Equal() returns true if value at reference point to the object are equivalent.

there is an exception here for string that “==” compares value rather then object identity.

In the below example:- for value type is obvious, but for reference types s1 & s2 are different objects so it will return false where as both of objects are equivalent so it will return true.

 

 

 

 

 

 

 

 

 

 

 

 

 

 

Refrences

http://dotnetguts.blogspot.in/2007/07/difference-between-and-equals-method.html

1 Comment

Filed under .Net, C#

When is a static constructor in C# called?

A static constructor is invoked by the first of either of the following conditions:

  • Create an instance of the class.
  • Refer any of the static methods of the class.

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

For Generic Class, using different type arguments you’ll get different concrete classes, so Static Constructor will be called multiple time (once for each type)

Leave a comment

Filed under C#

Polymorphism

Polymorphism means same operation can be defined in multiple forms.
There are two types of polymorphism:
Compile Time & Run-time polymorphism

Example of Compile Time polymorphism:- Method Overloading

It means having two or more methods having same name but different signature.
-the methods can be in the same class or different class (inherited).
-constructor overloading is also possible.
-it is not mandatory to have different return type, but either the number of parameters or parameters type should be different.

Example of Run time Polymorphism:- Method Overriding

Two or more methods with same signature but different implementation but in different class (base & inherited).

eg:- Using New & Override

1 Comment

Filed under C#

Why do we need Constructor for abstract class?

Yes we can have constructor in Abstract class (though we can’t still create object of abstract class).
Because :- this way you can instantiate the data in abstract class.
And inherited classes can call the base constructor.

public abstract class A{
private string data;
protected A(string myString){
data = myString;
}
}

public class B : A {

B(string myString) : base(mystring){}
}

NOTE:- As you can’t override constructor, so we can’t have abstract constructor.

Leave a comment

Filed under .Net, C#

IEnumerable vs IEnumerator

1) IEnumerable actually uses IEnumerator. i.e IEnumerable uses IEnumerator internally through GetIEnumerator.
2) The biggest difference is states, i.e. IEnumerable does not remember the cursor state i.e currently row which is iterating through, where I enumerator does.
IEnumerator exposes few methods which uses the state like:
MoveNext()
Current()

Leave a comment

Filed under C#

Abstract method vs Virtual method

Abstract method Virtual method
1) Abstract method doesn’t have any body defined. 1) Virtual method have their body defined otherwise it will give compile-time error message “<VirtualMethod()> must declare body because it is not defined abstract, extern, or partial.
2) Mandatory to implement them. 2) Not mandatory to override them.
3) They can be defined in abstract classes only. 3) They can be defined in any instance class.

Leave a comment

Filed under .Net, C#

Difference b/w String and string ?

They both are similar datatype as “string” is the alias of “String”. The original datatype class is String (System.String). Below is few more alias we have in .net:

Leave a comment

Filed under C#

Generics

Generics has the below features:

— makes logic independent of DataTypes.

— strongly types as Array.

— flexible of DataTypes like arraylist without boxing & unboxing.

Below is the project which show use of two Generic classes CoreDemo & CoreDemoDual:

Generic Classes


2 Comments

Filed under .Net, C#

Nullable Types & Why we need them?

The .NET Framework stores value types in the stack and implicitly initializes them to their default values. For example, an int gets initialized to 0, a bool to false, and so on.
In database missing information in records represented by null values. So the problem arises when fetch data from the data base, how to represent missing null value in our program because primitive data only stores real values in C#.

Nullable variable= null;
or
int? variable= null;

You cannot create a nullable type based on a reference type. (Reference types already support the null value.)

Use the ?? operator to assign a default value that will be applied when a nullable type whose current value is null is assigned to a non-nullable type, for example int? x = null; int y = x ?? -1;

Properties
Nullable types has two important property
Hasvalue – indicate that variable contains real values or not. It returns false if variable contains no value and true if some real values is stored in it.
Value – Return real value stored in variable. It throws InvalidOperationException exception.
Method
GetValueOrDefault – Return value stored by Nullable type variable or the value passed in function.
There are two overload of this function.
Syntax
GetValueOrDefault() – returns real value or the default value of object.
GetValueOrDefault(T) – returns real value or the value passed.
Pseudocode Code for above problem
//variable define
DateTime? deathdate = null;

//for the people who is already dead
if( deathdate.Hasvalue) // checking for the nullable varialbe has value or not
age = deathdate.Value – birthdate;
//for the people who is till alive
else
age = todays date – birthdate;

Leave a comment

Filed under C#

Why need Static methods?

I use static methods when I need to get something that is relevant to that class but I don’t want to create an instance every time to get this information. With a static method you cannot access methods/properties/variables from the class. The only variables available are within the static method you are calling.

Typically Helper and Utility methods are good candidates. Often times as well, you may want to create Static as well as instance objects. Looking to the framework, there’s the File and the FileInfo, the Directory and directoryInfo. Similarly, check out the Data Access Application Block – all of the SqlHelper methods are static.

Leave a comment

Filed under C#

Extention Method with Example

Extension methods enable you to “add” methods to existing types without creating a new derived type. Extension methods are a special kind of static method, but they are called as if they were instance methods on the extended type.

eg: http://blogs.msdn.com/b/wriju/archive/2011/05/04/linq-to-xml-handling-blank-or-no-element-and-attribute.aspx

Handling blank or no Element and Attribute
public static class MyExtension
{
//This method is to handle if element is missing
public static string ElementValueNull(this XElement element)
{
if (element != null)
return element.Value;

return “”;
}
}

You can use extension methods to extend a class or interface, but not to override them. An extension method with the same name and signature as an interface or class method will never be called.if a type has a method named Process(int i), and you have an extension method with the same signature, the compiler will always bind to the instance method.

Leave a comment

Filed under C#

ABSTRACT vs INTERFACE

ABSTRACT vs INTERFACE

Abstract Class Interface
1. It is mainly used in versioning scenarios (defining core functionalities). Interface is used as contract mainly.
2. We can use abstract as well non-abstract method. All methods are abstract only. Interface is pure abstract class.
3. We can inherit only one abstract class at a time. We can implement multiple interface.
4. All access modifier can be used. We can have only public access modifier for the methods.

à We can not create object of abstract class, though abstract can have constructors.

àWe can create instance of abstract class like:

AbstractClass obj = new SubClass();

eg:

TextWriter abstract class have two sub classes i.e. StreamWriter & StringWriter

TextWriter tObj = new StreamWriter();

Leave a comment

Filed under C#

Array vs ArrayList

In yet another round of fight, today we have contenders Array and ArrayList:

ARRAY ARRAYLIST
1. Array can store single data like Char[] vowel=new Char[]; Array list you can store multiple datatypes and inserting and removing element is easy.

ArrayList a_list=new ArrayList();

2. Array is in the System namespace ArrayList is in the System.Collections namespace.
3. The capacity of an Array is fixed. ArrayList can increase and decrease size dynamically

Ex:

ArrayList list = new ArrayList();

list.Add(“One”);

list.Add(“Two”);

list.Add(“Three”);

ARRAY

ARRAYLIST

1.

Array can store single data like Char[] vowel=new Char[];

Array list you can store multiple datatypes and inserting and removing element is easy.

ArrayList a_list=new ArrayList();

2.

Array is in the System namespace

ArrayList is in the System.Collections namespace.

3.

The capacity of an Array is fixed.

ArrayList can increase and decrease size dynamically

Ex:

        ArrayList list = new ArrayList();
        list.Add("One");
        list.Add("Two");
        list.Add("Three");

Leave a comment

Filed under C#

Factorial

There are actually two ways to get factorial i.e. using recursion or without recursion:

With Recursion

protected int Factorial(int num)

{

              if (num == 1)

                      return num;

              return (num * Factorial(num – 1));

}

Without Recursion

protected int FactorialNoRecursion(int num)

{

             int result=1;

             if (num == 1)

                      return num;

              for (int i = 2; i <= num; i++)

                     result *= i;

             return result;

}

Leave a comment

Filed under C#

Abstract Class FACTS

Abstract Class FACTS

1) We can inherit abstract class from another abstract class also.

Eg:

public abstract class AbstractClass1

{
public abstract string TestMe();       

}

 It is inherited by AbstractClass2 

public abstract class AbstractClass2 : AbstractClass1

{
public abstract string DoSome();

public override string TestMe()

{

return “This is test”;

}

}

2) Abstract class can inherit Interface also.

Leave a comment

Filed under .Net, C#

Static Classes

Static classes are loaded automatically by the .NET when the program or namespace containing the class is loaded.
The main features of a static class are:
# They only contain static members.
# They cannot be instantiated.
# They are sealed.
# They cannot contain Instance Constructors

If you include instance member in static class then you will get compile time error.

static class CompanyInfo
{
public static string GetCompanyName() { return “CompanyName”; }
public static string GetCompanyAddress() { return “CompanyAddress”; }
}

Leave a comment

Filed under C#

ref vs out

ref
it is necessary to initialize them before passing to the function(compile time error, if not done).

 protected void Page_Load(object sender, EventArgs e)
{           
            int a = 20;
            Response.Write(a + “<BR>”);
            DoSome(ref a);      //we need to pass value with ref keyword
            Response.Write(a + “<BR>”);           
}

private void DoSome(ref int aa)
{
            aa = 30;
}

out
no assignment is required, but you must assign a value in which function this is passed.
If the other side doesn’t need any information about this object except where to store the object, you probably should just use ‘Out’.

protected void Page_Load(object sender, EventArgs e)
 {           
            int a = 20;           
            DoSome(out a);      //we need to pass value with out keyword
            Response.Write(a + “<BR>”);           
}

private void DoSome(out int aa)
{
            aa = 30;
}

2 Comments

Filed under .Net, C#

Exception Handling in WCF

**********************************

Server Side Exception Handling

**********************************

Exception Handling in WCF

We basically handle two types of exception in WCF service and covert them to the FaultExcetion<SomeErrorDto> to make client familiar with the exceptions. Let me explain the complete scenario with a sample application XYZ:

Catch (XYZException ex)

{

       //Convert Application specific (XYZException) exceptions to FaultException<XYZErrorDto>.

       throw ExceptionHelper.HandleXYZToFaultException(ex);

}

Catch(Exception ex)

{

      //Convert Generic Exception to FaultException<XYZErrorDto>.

       throw ExceptionHelper.HandleGenericToFaultException(ex);

}

 

Our XYZException Class

public class XYZException : System.Exception

{

    private int _errorCode;

     public int ErrorCode

    {

        get { return _errorCode; }

        set { _errorCode = value; }

    }

 

    public XYZException(string message, Exception ex)  : base(message, ex)

    {

    }

    public XYZException(string message, int code, Exception ex)  : base(message, ex)

    {

        _errorCode = code;

    }  

}

Our ExceptionHelper class:

using System;

using System.Data.SqlClient;

using System.ServiceModel;

 

public class ExceptionHelper

{

    //Used in the BL(Business Logic) layer

    public static XYZException HandleGenericToXYZException(Exception genExcep)

    {

        //Logging the Generic Execption here before converting it to Application specific

       // (XYZException) exception.

        if ((genExcep != null))

        {

            return new XYZException(genExcep . Message, genExcep);

        }

        else

        {

            return null;

        }

    }

   

    //Convert Application specific Exception to FaultException<XYZErrorDto>

    public static FaultException<XYZErrorDTO> HandleXYZToFaultException(XYZException xyzExcep)

    {

        return HandleGenericToFaultException(xyzExcep);

    } 

    //Used in WCF service.

    public static FaultException<XYZErrorDTO> HandleGenericToFaultException(Exception genExcep)

    {

        XYZErrorDTO objXYZErrDTO = new XYZErrorDTO();

        if ((genExcep != null))

        {

            objXYZErrDTO = new XYZErrorDTO(genExcep.Message);

        }

        else

        {

            objXYZErrDTO = new XYZErrorDTO(“An unexpected error has occurred in the system”);

        } 

        //Logging the Generic Execption here before converting it to FaultException.

        return new FaultException<XYZErrorDTO>(objXYZErrDTO);

    }

}

*********************

UI Exception Handling

**********************

Now it is clear the UI will only receive Exceptions of type FaultException only from server, moreover we need to handle the Generic exception raised at the UI also. So if the UI code logic involve server resource usage the we have to catch both the exceptions else there will be only catching of general exception as shown below:

 Try

{

     //Logic involve usage of server resources 

}

Catch (FaultException ex)

{

      UIExceptionHelper.HandleFaultException(ex);        

}

Catch (Exception ex)

{

      UIExceptionHelper.HandleGenericException(ex);    

}

Our UIExceptionHelper class:

using System.ServiceModel;

using System.Diagnostics.EventLog;

 public class UIExceptionHelper

{

     public static void HandleFaultException(FaultException<XYZErrorDTO> faultExcep)

    {

        try

        {

            //Logging FaultException before displaying on Screen.          

            LogManager.LogError(faultExcep, errorCode, ConfigurationManager.AppSettings(“LogCategory”));

            WebMsgBox.Show(Decl.WEB_MSG, faultExcep.Detail.Message);

        }

        catch (Exception ex)

        {

        }

    }

     public static void HandleGenericException(Exception excep)

    {

        try

        {

            //Logging the Generic message before redirecting to custom error page.

            string strMsg = excep.Message.Replace(Constants.vbCrLf, ” “);

            string strTrace = excep.StackTrace.Replace(Constants.vbCrLf, ” “);

            LogManager.LogError(excep, errorCode, ConfigurationManager.AppSettings(“LogCategory”));

            //Redirecting to Custom Error Page for Generic Exceptions.

            Response.Redirect(Decl.ERROR_PAGE + “?Error=” + strMsg + “&Trace=” + strTrace);

        }

        catch (Exception ex)

        {

        }

    }

}

Refrences

http://msdn.microsoft.com/en-US/library/seyhszts(v=VS.80).aspx

http://dhananjaykumar.net/2010/05/23/fault-contract-in-wcf-with-learning-video/

Leave a comment

Filed under C#, WCF

Asynchronous Programming

Asynchronous Programming

When you create delegate, the compiler generates three methods Invoke, BeginInvoke, EndInvoke. Invoke is used to execute delegate synchronously, and rest two methods allow you to have asynchronous programming.

BeginInvoke takes the same parameters as delegate itself, plus another two parameters- an AsyncCallback which is called after the BeginInvoke execution, and an object parameter which is made available through the AsyncState property of the IAsyncResult parameter which is passed to the AsyncCallback.

The call to BeginInvoke returns an IAsyncResult which can be used to call EndInvoke, and you don’t have to pass a callback delegate to be executed if you don’t want to – just pass null as the last but one parameter to BeginInvoke.

private delegate int DoubleMeDelegate(int x);

protected void Page_Load(object sender, EventArgs e)

{

   for (int i = 1; i < 5; i++)

  {

     DoubleMeDelegate d = new DoubleMeDelegate(DoubleMe);

     d.BeginInvoke(i, new System.AsyncCallback(InvokeMessage), d);

   }

Thread.Sleep(1900);

}

private void InvokeMessage(IAsyncResult ar)

{

   DoubleMeDelegate dEnd = (DoubleMeDelegate)ar.AsyncState;

   int result = dEnd.EndInvoke(ar);

   Response.Write(result + “<br/>”);

}

private int DoubleMe(int single)

{

   Thread.Sleep(100);

   return (2 * single);

}

Leave a comment

Filed under C#

ThreadPool

ThreadPool

ThreadPool basically maintain “pool” of threads which are waiting for work items. As thread creation is not a cheap process. By default, the thread pool has 25 threads per processor.

We can Queue up method to the ThreadPool using it’s QueueUserWorkItem method. It takes two parameters – a WaitCallback delegate to the method you want to call and the optional object to pass as parameter to the callback method.

     protected void Page_Load(object sender, EventArgs e)  

        {  

            WaitCallback callBack;   

            callBack = new WaitCallback(DoubleMe);  

            ThreadPool.QueueUserWorkItem(callBack, 1);  

            ThreadPool.QueueUserWorkItem(callBack, 2);  

            ThreadPool.QueueUserWorkItem(callBack, 3);  

        }   

        public void DoubleMe(int i)  

        {   

            // Simulation of processing time   

            Thread.Sleep(1000);  

            String result = (2*i).ToString();

            Response.Write(result + “<BR>”);  

        } 

Leave a comment

Filed under C#

Nullable Type

Nullable types are instances of the System.Nullable struct.

Variables are of two types.

Value type eg. int, char, date. A data type is a value type if it holds the data within its own memory allocation.
Reference type eg. string, object. A reference type contains a pointer to another memory location that holds the data.
 For more details on Value types and Reference type of variable, please read http://msdn.microsoft.com/en-us/library/t63sy5hs(VS.80).aspx

Reference types variable can be assigned null but value types of variables like integer can’t because they can’t contain reference, even the reference of nothing.

int i = 0;
The above statement shall throw error because we are trying to store null in the integer variable.

To avoid this we can use nullable modifier like this.

int? ii = null;
In the above code, ii is the nullable type of variable that can store either null or any integer type of variable. When a variable is declared as nullable, its extends two properties called HasValue and Value. Both property are public and read-only.

Leave a comment

Filed under C#

New vs Override

New vs Override 

Override

  • Override method actually override the virtual method.
  • When a method of a base class is overridden in a derived class (subclass), the version defined in the derived class is used.
  • This indicates for the compiler to use the last defined implementation of a method i.e. override the last implented method.
  • if you want to prevent anymore overridden from inherited class then use sealed keyword along with override.

New

  • It actually hides the base class method.
  • The new modifier instructs the compiler to use your implementation instead of the base class implementation. Any code that is not referencing your class but the base class will use the base class implementation.
  • new keyword doesn’t allow the method to be more overridden.

Example:

class BaseClass
{
public virtual void WhichClass()
{
System.Console.WriteLine(“BASE CLASS”);
}
}

class NewClass : BaseClass
{
public new void WhichClass()
{
//base.WhichClass();
System.Console.WriteLine(“NEW CLASS”);
}
}

class OverrideClass : BaseClass
{
public override void WhichClass()
{
//base.WhichClass();
System.Console.WriteLine(“OVERRIDE CLASS”);
}
}
class Program
{
static void Main(string[] args)
{
BaseClass bObj = new BaseClass();
bObj.WhichClass();
System.Console.WriteLine(“———-“);

NewClass nObj = new NewClass();
nObj.WhichClass();
System.Console.WriteLine(“———-“);

BaseClass bnObj = new NewClass();
bnObj.WhichClass();
System.Console.WriteLine(“———-“);

OverrideClass oObj = new OverrideClass();
oObj.WhichClass();
System.Console.WriteLine(“———-“);

BaseClass boObj = new OverrideClass();
boObj.WhichClass();
System.Console.WriteLine(“———-“);

Console.ReadLine();
}
}

1 Comment

Filed under .Net, C#

C# 4.0 new features

In every new release of C# there is a major new feature like in C# 2.0 (Generics), C# 3.0 (Linq), and here C# 4.0 (dynamic programming support) 

1. Named and optional parameters: Now declare optional parameters simply by providing a default value for it. And call params by name: like so,      

        // Definition of the method

        public void Method(int x, int y = 1, int z = 2)

        {        } 

        // Using the optional params

        Method(1);          // same as Method(1, 1, 2);

        Method(1, 2);       // same as Method(1, 2, 2);

        Method(1, 2, 3);   

       // Named params called, note arbitrary order and missing y

        Method(z: 1, x: 2);

 2. dynamic object:

A new type has been introduced called dynamic. The idea is that you can call any operation on the dynamic type you want, the compiler won’t check it at compile-time, but figure it out at runtime. A dynamic object is assumed to support any operation at compile-time; only at runtime will you get an error. The result of any dynamic operation is of type dynamic.

        // Instantiation
        dynamic d = 7; // implicit conversion
        dynamic d = GetStudentData(); //GetStudentData() returns object of type Student class
        // Operations on dynamic       

        d.f = d.P;           // getting and settings types fields and properties
        d[“one”] = d[“two”]; // getting and setting thorugh indexers
        int i = d + 3;       // calling operators

 
// in the previous examples if f,p are not properties on the Student class and also there is no indxer it will be   compiled successfully ,it will be detected at runtime.

Leave a comment

Filed under C#

C# 3.0 new features

1. Implicitly typed local variables and arrays:  A new keyword is introduced called var. This allows you to declare a variable and let the compiler figure out the type  

ex:

        // Declare a variable of type int

            var i = 5;

            // Declare an int array

            var a = new[] { 1, 10, 100, 1000 };

            // Usage:

            for (var i = 0; i < 5; i++) { }

            foreach (var item in MyList) { }

            using (var file = new StreamReader(“Filename.txt”)) { } 

2. Auto-implement properties: Use this when no additional logic is required in the property accessors. 

ex:

        // Previously we had to do this,

        private string _name;

        public string Name

        {

            get { return _name; }

            set { _name = value; }

        }

        // Now we can shorthand it, there’s no need to declare the _name variable

        public string Name { get; set; } // The compiler creates a private anonymous backing field

Behind the scene, compiler automatically creates private, anonymous fields that can be accessed from the above auto-implemented properties.

 3. Object and collection initializers: Set properties inline during object creation.    

 ex:

    public class A {

    public string Name { get; set; }

    public string Address { get; set; }

}

// Previously we would have to do,

A a = new A();

a.Name = “…”;

a.Address = “…”;

// Now we can do this,

A a = new A { Name = “…”, Address = “…” };

// Similarly, we can initialize collections,

List<int> MyList = new List<int> { 0, 1, 2, 3, 4 };

 4. Extension methods: Now you can add methods to existing types without creating a new derived type, recompiling or modifying the original type’s code. This is incredibly useful in writing cleaner code,

ex:

public static void ExportToExcel(this DataSet ds)
{
    //do something…
}

Extension methods are declared by specifying the “this” keyword as the modifier in the first parameter. The ExportToExcel method is declared as an extension method for the DataSet class.
Extension methods are invoked as soon the namespace of the containing static class is included.
In the below code snippet, the extension method is declared inside
namespace Orcas.Samples
{
   public static class Extensions
   {
       public static void ExportToExcel(this DataSet ds)
      {
             //do something…
      }
   }
}

Above method is invoked in the client program as,
using Orcas.Samples;
DataSet ds = new DataSet();
ds.ExportToExcel()
;

5. Anonymous types: If you need a small class with read only properties, you can now use a simple syntax,     

ex:

// a is an anonymous type, the compiler creates the class with

// private string fields _name and _address

// and public string properties Name and Address,

var a = new { Name = “Dev”, Address = “Delhi” };

// a.Name and a.Address are read-only,

string s = a.Name;

 6. Query keywords (LINQ): We are now able to use TSQL like syntax inside C# to query data sources (could be objects, collections, XML, or SQL databases). Introduces a host of new keywords like from, where, select, group, orderby, join, etc.      

ex:

// The data source,

     int[] numbers = { 0, 1, 2, 3, 4, };

     // Create the query,

     var lessthan3 =

         from num in numbers

         where num < 3

         select num;

     // Output: 0 1 2

     foreach (var m in lessthan3) {

         Console.Write(m.ToString() + ” “);

     }

7. Partial method definitions: A partical class (introduced in C# 2.0) can now have partial methods. This simply means the method signature is in one partial class and the implementation in another. There are some constraints, like the method is implicitly private (and therefore cannot be virtual) and must return void.      

 ex:

public partial class A

{

    // Method definition

    partial void Method();

}

public partial class A

{

    // Method implementation

    partial void Method() { /* Do Work */ }

} 

Leave a comment

Filed under C#

Playing with REST !

REST Services

àREST stands for Representational State Transfer, means that each unique URL is a representation of some object.

-to get the contents of that object use an HTTP GET,

-to delete you then might use a POST, PUT, or DELETE to modify the object.

àUnlike SOAP, REST is not a standard; it is just an architectural style.

àREST uses HTTP for all four CRUD (Create/Read/Update/Delete) operations.

àMuch like Web Services, a REST service is:

* Platform-independent (you don’t care if the server is Unix, the client is a Mac, or anything else),

* Language-independent (C# can talk to Java, etc.)

eg:

-The famous Twitter API is all REST.

Yahoo! offer most of their services using REST including Search API, Maps, Photos.

Flickr,

-Amazon.com offer several REST services, e.g., for their S3 storage solution

Atom is a RESTful alternative to RSS.

Like the following URL sends a REST request to Yahoo!’s web-search service:

http://search.yahooapis.com/WebSearchService/V1/webSearch?appid=YahooDemo&query=rest.

Click it, and observe the XML results, ready to be used directly.

This REST request includes two parameters:

appid“, used by Yahoo! to specify your application, and

query“, which is the actual search query.

REST vs SOAP

Yahoo’s web services are using REST and google using SOAP for their web services.

REST is Lightweight than SOAP because it does not requires lot of xml markup.

WCF 3.5 provides explicit support for RESTful communication using a new binding named WebHttpBinding.

The below code shows how to expose a RESTful service

[ServiceContract]

interface IStock

{

[OperationContract]

[WebGet(UriTemplate:=”/Stock/{StockId}”)]

int GetStock(string StockId);

}

By adding the WebGetAttribute, we can define a service as REST based service that can be accessible using HTTP GET operation, like GetStock from Stock.

We can use REST style to get order as shown in the below URL with Stock

http://localhost/stock.svc/Stock/100234

How to consume REST services

There are different ways to consume the REST services as per requirements, below I am mentioning some:

1) Here I am actually reading the Xml from REST service and writing to the file.  WebClient() is defined in System.Net
WebClient() objWebClient = new WebCleint();
objWebClient.Credentials = new NetworkCredential(uid, pwd, domain);
XmlTextReader objXmlTextReader = new XmlTextReader(objWebClient.OpenRead(path));
string objXml = string.Empty;

while(objXmlTextReader.Read())
{
   objXml = objXmlTextReader.ReadOuterXml;
}

string filePath = serverPath + “\” + Date.UtcNow.Year.Tostring();

if(File.Exists(filePath))
{  
   StreamWriter wr;
   File.Delete(filePath);
   wr = File.CreateText(filePath)
   wr.WriteLine(objXml)
   wr.Close();        
}
else
{
   StreamWriter wr;
   wr = File.CreateText(filePath)
   wr.WriteLine(objXml)
   wr.Close();
}

2) To query a REST service, like the one I mentioned above, we can use LINQ’s XML functionality.  The XElement class (declared in System.Linq.XML) provides a Load method that can retrieve an XML data from a url with GET  method:

XElement rootXml = XElement.Load(“http://search.yahooapis.com/WebSearchService/V1/webSearch?appid=YahooDemo&query=rest”);

var SearchResult = from R in rootXml.Elements()

select new { Topic = (string)R.Element(“Title”),

Detail = (string)R.Element(“Summary”),

Link = (string)R.Element(“Url”) };

foreach (var x in SearchResult)

Console.WriteLine(“{0}  {1}”, x.Topic, x.Detail, x.Link);

Console.ReadKey();

Using POST method is a bit more complex. First we have to obtain a channel by which we may POST the information. Then we have to create an instance of data entity in XML format. Finally we have to POST data through the channel.

To get access to REST service we use a HttpWebRequest since it lets use the POST method and let us specify the type of information we are posting.

HttpWebRequest channel = (HttpWebRequest)WebRequest.Create(“http://ws.geonames.org/countryInfo”);

channel.Method = “POST”;

channel.ContentType = “text/xml”;

HttpWebRequest class provides a stream to which we can write information :

StreamWriter sw = new StreamWriter(channel.GetRequestStream());

Then we can create a concerete entity to post:

XElement country = new XElement(“country” ,

new XElement(“countryCode”, “AUS”),

new XElement(“countryName” , “Australia”),

….

);

Finally we just need to save this XElement object to the stream we obtained from HttpWebRequest:

country.Save(sw);

References:

http://aspguy.wordpress.com/2008/10/10/dealing-with-rest-web-services/

http://developer.yahoo.com/dotnet/howto-rest_cs.html

2 Comments

Filed under .Net, C#

Extension Methods

They are static methods that can be invoked like an instance method. Static methods can be declared only in Static classes. Let’s see how extension methods are declared.
public static void ExportToExcel(this DataSet ds)
{
//do something…
}

Extension methods are declared by specifying the “this” keyword as the modifier in the first parameter. The ExportToExcel method is declared as an extension method for the DataSet class.
Extension methods are invoked as soon the namespace of the containing static class is included.
In the below code snippet, the extension method is declared inside
namespace Orcas.Samples
{
public static class Extensions
{
public static void ExportToExcel(this DataSet ds)
{
//do something…
}
}
}

Above method is invoked in the client program as,
using Orcas.Samples;
DataSet ds = new DataSet();
ds.ExportToExcel();

Leave a comment

Filed under C#

Auto-Implemented Properties

Auto-Implemented Properties

In C# 2.0 properties are declared as follows:

private int iEmpId;
private string strEmpName;

public int EmpId
{
get { return iEmpId; }

set { iEmpId = value; }
}

Samething is redfined in C#3.0 using auto-implemented properties like:
public class AutoProperties
{
public int EmpID { get; set; }
public string EmpName { get; set; }
public int Age { get; private set; } // read-only
}
Behind the scene, compiler automatically creates private, anonymous fields that can be accessed from the above auto-implemented properties.

Leave a comment

Filed under C#

Typed DataSet

Typed DataSet includes Type-safe into Dataset fields so as to protect it from runtime mismatch. These classes inherit directly from DataSet class.

eg: Runtime error using normal Dataset

1. Using DataSet:

 //Create DataAdapter

SqlDataAdapter daEmp = new SqlDataAdapter(“SELECT empno,empname,empaddress FROM EMPLOYEE”,conn);

//Create a DataSet Object

DataSet dsEmp = new DataSet();

//Fill the DataSet

daEmp.Fill(dsEmp,”EMPLOYEE”);

//Let us print first row and first column of the table

Console.Write(dsEmp.Tables[“EMPLOYEE”].Rows[0][0].ToString());

//Assign a value to the first column

dsEmp.Tables[“EMPLOYEE”].Rows[0][0] = “12345”;//This will generate runtime error as empno column is integer

  2. Using Typed DataSet:

 //Create DataAdapter

SqlDataAdapter daEmp = new SqlDataAdapter(“SELECT empno,empname,empaddress FROM EMPLOYEE”,conn);

//Create a DataSet Object

EmployeeDS dsEmp = new EmployeeDS ();

//Fill the DataSet

daEmp.Fill(dsEmp,”EMPLOYEE”);

//Let us print first row and first column of the table

Console.Write(dsEmp.EMPLOYEE[0].empno.ToString());

//Assign a value to the first column

dsEmp.EMPLOYEE[0].empno = “12345”;//This will generate compile time error.

 Typed dataset is very much similar to a normal dataset; the only difference is that the schema is already present for the same. And any mismatch in the column will generate compile time errors rather than runtime error as in the case of normal dataset. Also accessing the column value is much easier than the normal dataset as the column definition will be available in the schema.

  Typed DataSet can be generated in two ways,

 1) Using Visual Studio .NET IDE.

2) Using XSD.exe (Using VS.Net command prompt)

Open VS.Net command prompt and Type XSD /? For the help on this exe.

 Creating a Typed DataSet using Visual Studio .NET IDE

 Let me explain a step by step procedure to create a Typed DataSet,

 1. Open VS .Net IDE and Click on File -> New -> Project and Select Console Application.

2. Enter name for the project. Say TypedDataSetTest.

3. Right click on the solution and click on Add-> Add New Item will show a dialog box.

Select DataSet from templates pane, give the name (Say TypedDs.xsd) and click on Open. This will add file by name TypedDs.xsd to the solution.

4. Click on the Server Explorer browse to the database and drop the table on the TypedDs.xsd file. 

If we check the xml file for the same then we can see the schema for the table.

This dataset can be used in the same manner as the normal dataset to get the data.

Leave a comment

Filed under C#

Auto-Implemented Properties

In C# 2.0 properties are declared as follows:

 private int iEmpId;
        private string strEmpName;

        public int EmpId
        {
            get { return iEmpId; }

            set { iEmpId = value; }
        }

Samething is redfined in C#3.0 using auto-implemented properties like:
public class AutoProperties
{
       public int EmpID { get; set; }
       public string EmpName { get; set; }
       public int Age { get; private set; } // read-only
}
Behind the scene, compiler automatically creates private, anonymous fields that can be accessed from the above auto-implemented properties.

Leave a comment

Filed under C#

LINQ

LINQ
Using Linq ( Language Integrated Query) we can manipulate any object which is implemented by the IEnumerable<T> interface, XML, Dataset or relational database.

The core Linq assemblies are
System.Core.dll :- The core LINQ API.
System.Data.Linq.dll :- LINQ with relational databases (LINQ to SQL).
System.Data.DataSetExtensions.dll :- ADO.NET types into the LINQ programming paradigm (LINQ to DataSet).
System.Xml.Linq.dll :- LINQ with XML document data (LINQ to XML).

Linq Query Operators
from, in :- Used to start the LINQ expression.
where :- Used to filter the data.
select :- Used to select the data.
join, on, equals, into :- Performs joins based on specified key.
orderby, ascending, descending :- Allows the data to be ordered in ascending or descending order.
group, by :- Data grouped by a specified value.

Advantage of LINQ over stored procedures.
1. Debugging – It is really very hard to debug the Stored procedure but as LINQ is part of .NET, you can use visual studio’s debugger to debug the queries.
2. Deployment – With stored procedures, we need to provide an additional script for stored procedures but with LINQ everything gets complied into single DLL hence deployment becomes easy.
3. Type Safety – LINQ is type safe, so queries errors are type checked at compile time. It is really good to encounter an error when compiling rather than runtime exception!

Query Expression
string[] Weekdays = {“Sunday”, “Monday”, “Tuesday”, “Wednesday”, “Thursday”, “Friday”, “Saturday” };
IEnumerable<string> WeekdaysWithLength = from W in Weekdays
where W.Length> int.Parse(textBox1.Text)
orderby W
select W;

var WeekdaysWithLength = from W in Weekdays
where W.Length > int.Parse(textBox1.Text)
orderby W
select W;
IEnumerable<string> is the explicit object, & var is implicit object, which will convert to assign type by compiler.

Extension Methods
Linq provides a set of generic extension methods e.g. Aggregate<T>(), Max<T>(), Distinct<T>() etc.
eg:
string[] WeekdaysWithLength = (from W in Weekdays where W.Length > int.Parse(textBox1.Text)
orderby W descending select W).Distinct<string>();

Leave a comment

Filed under .Net, C#

XAML – Extensible Application Markup Language

Extensible Application Markup Language (XAML) is a .NET technology. It’s a markup language that can be used to help create desktop applications, web pages, and printable documents.
XAML is a declarative XML-based language that defines objects and their properties in XML.
It provides abbreviated markup syntax for specific types of elements that take advantage of the underlying Common Language Runtime (CLR) class constructors. Each XAML element has a name and one or more attributes. Attributes correspond directly to object properties, and the name of the XAML element exactly matches the name of a CLR class definition.
XAML is pure markup, which means that while the names of event handlers are specified as attributes, you must implement the actual logic of the event handler in code like C# or VB.net.
Every event in XAML can be assigned to a codebehind handler,which is implemented in a supported .NET language. eg: Button click event
<Button
OnClick=”ButtonClickedHandler”
Name=”MyButton”
Width=”50″
Content=”Click Me!” />

a corresponding codebehind handler is declared
void ButtonClickedHandler(object sender, RoutedEventArgs eventArgs)
{
MyButton.Width = 100;
MyButton.Content = “Thank you!”;
}

All XAML attributes can be manipulated within code because they are simply XML representations of actual CLR class attributes.
It is also acceptable to inline code in the XAML file by specifying the <x:Code> element.
All inline code must be enclosed in the <CDATA[…]]> tag to ensure that the parser does not try to interpret the code. eg:
<x:Code>
<![CDATA
void ButtonClickedHandler(object sender, RoutedEventArgs eventArgs)
{
MyButton.Width = 100;
MyButton.Content = “Thank you!”;
}
]]>
</x:Code>

for application logic developers to access specific XAML elements, the elements must be named using either the Name or ID attribute which will be used to manipulate the element in the code.
Three basic rules to follow when declaring XAML elements:
1) XAML is case-sensitive. Element and attribute names must be properly cased.
2) All attribute values, regardless of data type, must be enclosed in double quotes.
3) The resulting XML must be well-formed. like end tag etc.

Elements can be declared all on one line, or attribute declarations can be split across lines; formatting is completely up to you. Because XAML is compiled into Binary Application Markup (BAML) file (This is a binary representation of XAML auto-genned by Visual Studio) before deployment, the amount of space taken up by elements in a XAML file is irrelevant. There are no advantages to using less space by declaring elements on a single line and no disadvantages to the formatting.

All XAML elements are an XML representation of CLR classes, but not all CLR classes are represented in XAML.
XAML element represents a .NET CLR class. but not all CLR classes are represented in XAML. Most of those represented are user-interface elements and are ultimately derived from System.Windows.UIElement, System.Windows.FrameworkContentElement.

XAML elements can be organized into five basic categories
1) Root elements
A page is required to have one root element. Windows and Page elements are the most common root elements.
2) Panel elements
These elements help you to lay out your user interface.  eg: StackPanel, DockPanel, Grid and Canvas.
3) Control elements
Controls are interactive and allow the user to enter data, make choices, and perform other interactive tasks.
eg: Button, CheckBox, RadioButtonList, ComboBox, MenuItem
<MenuItem Header=”First Menu Item”>
<MenuItem Header=”First Child Item” />
<MenuItem Header=”Second Child Item” />
</MenuItem>
4) Geometric elements
This kind of elements helps you to draw shapes and geometric graphics on your UI. eg: LineGeometry, EllipseGeometry, PathGeometry.
5) Document elements
use to deal with presentation of a document. eg: Bold, LineBreak and Italic, Paragraph, List, Block, Figure and Table.
Example:
<Window x:Class=”IntroductionToXAML.Window1″
xmlns=”
http://schemas.microsoft.com/winfx/2006/xaml/presentation
xmlns:x=”
http://schemas.microsoft.com/winfx/2006/xaml
Title=”Introduction To XAML” Height=”200″ Width=”300″
>
<StackPanel>
<TextBox Name=”MyTextBox”
Width=”200″
Height=”30″
Margin=”40″ />
<Button Click=”ButtonClickHandler”
Width=”60″
Height=”20″>
Content=”Click Me!”
</Button>
</StackPanel>
<x:Code>
<![CDATA[
void ButtonClickHandler(object sender, RoutedEventArgs e)
{
MessageBox.Show(string.Format
(“You typed ‘{0}’ in TextBox!”, MyTextBox.Text), “XAML”);
}
]]>
</x:Code>
</Window>
Benefit of XAML
1) The Run Time :- The ASPX uses the ASP.Net Run Time which is loaded in the IIS, rather Silver Light Runtime is a portion of CLR. Which we can download dowload in to the Client Machine and perform operations.
2) The XAML supports Rich User Interface, which means no need of JS and others. We can use the Straight away .NET WPF Animation Functions.
3) It also supports the Out Of Browser Support. (We can use the Server Web Application as a Client Application). Its included in Silverlight 4.0
4) In XAML you do not need to put a name as identifier for your controls unless you want to refer to them from other parts of your code.

Q: Can XAML be used to develop both Web and client-server applications?
Ans: XAML is used as part of Windows Presentation Foundation to write smart client applications that take advantage of the power of the PC and benefit from all of the power of the CLR. For Windows Presentation Foundation applications, the logic runs on the client, unlike ASP.NET, which processes on the server. ASP.NET continues to be the answer to producing powerful Web applications that take advantage of the benefits of the CLR on the server.

Leave a comment

Filed under .Net, C#

Reflection in C#

You can use reflection to dynamically create an instance of a type, bind the type to an existing object, or get the type from an existing object and invoke its methods or access its fields and properties. If you are using attributes in your code, reflection enables you to access them.
eg:
This example shows how to dynamically load assembly, how to create object instance, how to invoke method or how to get and set property value.
Create instance from assembly that is in your project References
The following examples create instances of DateTime class from the System assembly.
// create instance of class DateTime
DateTime dateTime = (DateTime)Activator.CreateInstance(typeof(DateTime));
OR
Create instance from dynamically loaded assembly
All the following examples try to access to sample class Calculator from Test.dll assembly. The calculator class can be defined like this.
[C#]
namespace Test
{
public class Calculator
{
public Calculator() { … }
private double _number;
public double Number { get { … } set { … } }
public void Clear() { … }

}
}

Examples of using reflection to load the Test.dll assembly
System.Reflection.Assembly testAssembly = Assembly.LoadFile(@”c:\Test.dll”);
// get type of class Calculator from just loaded assembly
Type calcType = testAssembly.GetType(“Test.Calculator”);
// create instance of class Calculator
object calcInstance = Activator.CreateInstance(calcType);
// get info about property: public double Number
PropertyInfo numberPropertyInfo = calcType.GetProperty(“Number”);

Leave a comment

Filed under C#

Serialization

Serialization is a process of converting an object into a stream of data so that it can be is easily transmittable over the network or even stored in a database or file system. This storage location can be a physical file, database or ASP.NET Cache.
In .NET it is provided by the System.Runtime.Serialization namespace.  This namespace contains an interface called IFormatter which in turn contains the methods Serialize and De-serialize that can be used to save and load data to and from a stream.

Types
Serialization can be of the following types:

·         Binary Serialization

·         SOAP Serialization

·         XML Serialization

·         Custom Serialization
Binary Serialization
Binary serialization is a mechanism which writes the data to the output stream. All members including private & public, no matter if they are read-only. It is used commonly in .NET’s Remoting technology.
The easiest way to make a class serializable is to mark it with the Serializable attribute.
[Serializable]
public class MyObject {
public int n1 = 0;
public int n2 = 0;
public String str = null;
}

//Serialize the object
Create an instance of stream and BinaryFormatter and then call Serialize method on formatter.
MyObject obj = new MyObject();
obj.n1 = 1;
obj.n2 = 24;
obj.str = “Some String”;
IFormatter formatter = new BinaryFormatter();
Stream stream = new FileStream(“MyFile.bin”, FileMode.Create, FileAccess.Write, FileShare.None);
formatter.Serialize(stream, obj);
stream.Close();

//De-serialize the object
Create an instance of stream and BinaryFormatter and then call de-Serialize method on formatter.
IFormatter formatter = new BinaryFormatter();
Stream stream = new FileStream(“MyFile.bin”, FileMode.Open, FileAccess.Read, FileShare.Read);
MyObject obj = (MyObject) formatter.Deserialize(stream);
stream.Close();

// Here’s the proof.
Console.WriteLine(“n1: {0}”, obj.n1);
Console.WriteLine(“n2: {0}”, obj.n2);
Console.WriteLine(“str: {0}”, obj.str);

XML Seriallization
XML serialization converts (serializes) the public fields and properties of an object, into an XML stream to a XML Schema definition language (XSD) document.
Because XML is an open standard, the XML stream can be processed by any application. It use is the XmlSerializer for both serialization and de-serialization. XML Serialization is however, much slower compared to Binary serialization.

Public class Employee
{
[XmlAttribute(“empName”)]
public string EmpName
{
get
{
return empName;
}
set
{
empName = value;
}
}
}

//Serialize the object
Create an instance of stream and XmlSerializer and then call Serialize method on formatter.

DataContractSerializer

The System.Runtime.Serialization.DataContractSerializer is new in .Net 3.0. used by Wcf, but can be used for general serialization as well.

the only real key difference is that you use a WriteObject() method to serialize instead of a Serialize() method and a ReadObject() method to deserialize instead of a Deserialize() method. It works with the same types of streams, so you can write to memory, files, etc. eg:

DataContractSerializer dataContractSerializer =

new DataContractSerializer(typeof(MyType));

// Serialize from an object to a stream

dataContractSerializer.WriteObject(stream, myInstanceOfMyType);

// Deserialize from a stream to an object

myInstanceOfMyType = (MyType)dataContractSerializer.ReadObject(stream);

XmlSrializer DataContractSerialize
1 Opt-out rather than opt-in properties to serialize. This mean you don’t have to specify each and every property to serialize. Opt-in rather than opt-out properties to serialize. This mean you specify what you want serialize.
2 Can only serialize Public Properties. It can serialize properties, fields & that can be private, protected or public.
3 Slower then DataContractSerialize 10% faster then XmlSrializer
4 Cannot understand the DataContractAttribute and will not serialize it unless there is a SerializableAttribute too Can understand the SerializableAttribute also and know that it needs to be serialized
5 Use only different attributes to serialize like XmlIgnoreAttribute, XmlRootAttribute, XmlAttributeAttribute, XmlElementAttribute Use only 2 attributes to serialize i.e  DataContactAttribute & DataMemberAttribute
6 use a Serialize() & Deserialize() method. use a WriteObject() & ReadObject() method.

Leave a comment

Filed under .Net, C#

Access Modifier

Access Modifier Meaning
public Access is not restricted.
protected Access is limited to the containing class or types derived from the containing class.
internal Access is limited to the current assembly.
protectedinternal Access is limited to the current assembly or types derived from the containing class.
private Access is limited to the containing type.

Only one access modifier is allowed for a member or type, except when using the protectedinternal combination.

Access modifiers are not allowed on namespaces. Namespaces have no access restrictions.

Members of Default accessibility Allowed declared accessibility of the member
enum public None
class private public

protected

internal

private

protected internal

interface public None
struct private public

internal

private

NB A class can not be declared as Protected.

Leave a comment

Filed under .Net, C#

Singleton Pattern

Only providing one user access to a resource is not the purpose of a Singleton.  The Singleton pattern allows multiple users to share a single object. Ex: if you want to share a single data connection with multiple resource, & don’t want to open multiple connections i.e. connection pooling.The Singleton pattern ensures that a class only has one instance and provides a global point of access.

public sealed class Singleton
{
private static readonly Singleton    instance = new Singleton();
private Singleton()
{
}

public static Singleton Instance
{
get
{
return instance;
}
}
}

1) the Singleton’s constructor is set to private.This ensures that no other code in your application will be able to create an instance of this class.
2) an instance member variable is defined of the same type as the class. This instance member is used to hold the only instance of our class.
3)  The variable is static so that it is defined only once. static variables are defined at a point before their first use
4) the instance variable is readonly so that it cannot be modified – not even by any code that you may write in the class’s implementation.
5) a public Instance property is defined with only a get method that way callers can access the instance of this class without ever being able to change it. The property is also static to provide global access from anywhere in your program.

If you try to create an instance of the Singleton class using the new operator:

Singleton NewInstance = new Singleton();

Than, you will get a compiler error stating that the class cannot be created because the constructor is inaccessible due to its protection level.

Thread-Safe Singleton Code
if you are creating a multi-threaded application that needs to access a singleton across all of its threads, then you will need to create a thread-safe singleton class instead.

public sealed class MTSingleton
{
private static volatile MTSingleton    instance = null;
private static object syncRoot = new object();

// make the default constructor private, so that no can directly create it.
private MTSingleton()
{
}

// public property that can only get the single instance of this class.
public static MTSingleton Instance
{
get
{
// only create a new instance if one doesn’t already exist.
if (instance == null)
{
// use this lock to ensure that only one thread is access
// this block of code at once.
lock(syncRoot)
{
if (instance == null)
instance = new MTSingleton();
}
}
// return instance where it was just created or already existed.
return instance;
}
}
}

The instance member variable is no longer set at creation time, but in the Instance property instead.
The instance variable is declared to be volatile in order to assure that the assignment of instance complete before the instance can be accessed.
The syncRoot object is used to lock on. The lock ensures that only one thread can access the instance creation code at once.

Leave a comment

Filed under C#