Saturday, March 19, 2011

Extension Methods in C#

What is an Extension Method ?Extension method helps you to add new methods to an existing types like int,
string or to your custom types(classes).I will explain with an example to make it more clear;Int datatype has a method called ToString().Now I want a method on Int to
find out whether it is an Odd or Even (Say IsEven()). How to do it ? Use Extension Method!

Why Extension Methods ?My first question here is how do we achieve the above task(adding IsEven()
function) without Extension Method?Yes, we can do this by Extending Int type to another class and write IsEven
function there. But in this case you have to create an object of this class
to use this new function. If you use extension methods you don't need to do
all these things!
Suppose if you have a class but no source code and want to add a new function
to this class, use Extension Methods..

How to use Extension Methods ?I will give 2 examples for this. One is adding IsEven() to the built in Int
type. In second example I will show you how to add a new method to our custom class using Extension method.
All your extension methods should be static and it should be in a static
class. Also, the first parameter of the extension method describes to which
type this method should be part of.
Adding IsEven() method to Int Type:
namespace OperationsMethods
{
public static class ExtensionMethods
{
public static bool IsEven(this int val)
{
int result= val%2;
return result == 0 ? true : false;
}
}
}
How to use it? see below code..
protected void Page_Load(object sender, EventArgs e)
{
int num = 100;
bool isEven=num.IsEven();
Response.Write(isEven.ToString());
}


Example 2: Adding method to custom type
Below is my operation class:
namespace Business{
public class operations
{
public operations()
{ }
public int Add(int num1, int num2)
{ return num1 + num2; }
}
}
Now I want to add a new method called Substract() to this class using
extension method. So here goes our Extension method:
namespace OperationsMethods
{
public static class ExtensionMethods
{
public static int Substract(this operations op, int num1, int num2)
{ return num1 - num2; }
}
}
Using this...
protected void Page_Load(object sender, EventArgs e)
{
operations obj = new operations();
int res= obj.Substract(500, 200);
Response.Write(res.ToString());
}

Friday, January 28, 2011

JQuery Basics...

$('#name').val() - Get value of object having id 'name'
$(this) - Current HTML element
$("p") - All PARAGRAPH elements
$("p.intro") - All PARAGRAPH elements with class="intro"
$(".intro") - All elements with class="intro"
$("#intro") - The first element with id="intro"
$("ul li:first") - The first li element of each ul
$("[href$='.jpg']") - All elements with an href attribute that ends with ".jpg" $("div#intro .head")- All elements with class="head" inside a div element with id="intro"
$("p").css("background-color","yellow");


Method Description

bind() - Add one or more event handlers to matching elements
blur() Triggers, or binds a function to the blur event of selected elements
change() Triggers, or binds a function to the change event of selected elements
click() Triggers, or binds a function to the click event of selected elements dblclick() Triggers, or binds a function to the dblclick event of selected elements delegate() Add one or more event handlers to current, or future, specified child elements of the matching elements
die() Remove all event handlers added with the live() function

focus() - Triggers, or binds a function to the focus event of selected elements
focusin() - Binds a function to the focusin event of selected elements
focusout() - Binds a function to the focusout event of selected elements
hover() - Binds one or two functions to the hover event of selected elements
keydown() - Triggers, or binds a function to the keydown event of selected elements
keypress() - Triggers, or binds a function to the keypress event of selected elements
keyup() - Triggers, or binds a function to the keyup event of selected elements
live() - Add one or more event handlers to current, or future, matching elements
load() - Triggers, or binds a function to the load event of selected elements
mousedown() - Triggers, or binds a function to the mouse down event of selected elements
mouseenter() - Triggers, or binds a function to the mouse enter event of selected elements
mouseleave() - Triggers, or binds a function to the mouse leave event of selected elements
mousemove() - Triggers, or binds a function to the mouse move event of selected elements
mouseout() - Triggers, or binds a function to the mouse out event of selected elements
mouseover() - Triggers, or binds a function to the mouse over event of selected elements
mouseup() - Triggers, or binds a function to the mouse up event of selected elements
one() - Add one or more event handlers to matching elements. This handler can only be triggered once per element
ready() - Binds a function to the ready event of a document
(when an HTML document is ready to use)
resize() Triggers, or binds a function to the resize event of selected elements
scroll() Triggers, or binds a function to the scroll event of selected elements
select() Triggers, or binds a function to the select event of selected elements
submit() Triggers, or binds a function to the submit event of selected elements
toggle() Binds two or more functions to the toggle between for the click event for selected elements
trigger() Triggers all events bound to the selected elements
triggerHandler() Triggers all functions bound to a specified event for the selected elements
unbind() Remove an added event handler from selected elements
undelegate() Remove an event handler to selected elements, now or in the future
unload() Triggers, or binds a function to the unload event of selected elements

    Monday, January 3, 2011

    Generics in DotNet

    I always learn things by comparing to stuffs I already know!!!

    Generics mainly have 4 parts;

    1. List

    List is a better way of doing ArrayList. ArrayList is flexible enough to store any kind of data. It treats every entry as objects. This is not a good thing when it come to type conversiion both in terms of perdormance and operation. That's where the importance of type safe list comes in to the picture. When the collection is more type safe, it is less prone to errors.
    So List is a arrayList kind of collection where you are restricted to store only specific type, but unlimited.
    eg: List ids=new List;
    List ids=new List;

    2. Dictionary

    We can compare Dictionary to HashTable.

    Saturday, January 1, 2011

    Exception handling and logging

    Exception - Is an unusual occurance in the logic of the application, eg: divide by zero, reading corrupted file.. etc.
    Exception Handling - Managing these exceptions in order to make sure that it does not stop application from running and not distirbing the end user
    Exception Handling Methods
    1. Structured Exception Handling (try-catch-finally-throw)
    eg:
    try
    {
    throw new System.IO.FileNotFoundException;
    }
    catch(System.IO.FileNotFoundException)
    {}
    catch(System.UnauthorizedAccessException)
    {}
    catch(Exception ex)
    {}
    finally
    {}

    2. Using Error Events
    Error events can be used against exception that were not foreseen or handled elsewhere.
    Page_Error - Page level
    Global_Error - Global.asax
    Application_Error - Global.asax
    To get the last error occured in the application use Server.GeLastError() and to clear the excpetions use Server.ClearError()
    GetLastError() can be used only before redirecting to a new page.

    3. Using Error Pages
    This is a high level way of handling exceptions especially for application wide errors which are outside the scope of code. For eg: to handle IIS errors like 404 Page Not Found

    There are 3 ways of using it:
    a) Specify Error Pages corresponding to Error Code in IIS itself. Exceptions registered with IIS can be seen from custom errors section of application properties.
    If we are redeploying the application in IIS, we have to redo these settings all over again.

    b) Specify error pages in CustomErrors tag in web.config
    <customerrors defaultredirect="1.aspx" mode="on">
    <error redirect="Error.aspx" statuscode="404">
    </customerrors>
    mode ="on" - To view error pages while running locally
    mode="RemoteOnly" - To view error pages when ru
    nning from client
    Error page type should be supportable by asp.net

    c) Specify Error page in ErrorPage attribute of Page

    Because of redirection, context for error is lost, Server.GetLastError() returns nothing

    Tracing
    Tracing is used for logging exceptions
    How to enable tracing in .net...

    This will write the trace at the end of each file.
    To write the trace in to a file;
    pageOutput="false"
    requestLimit="20" - This will restrict the tracing for the first 20 requests
    To enable tracing at the page level - trace="true"