Wednesday, December 7, 2011

Difference between for and foreach loop in c#

The for loop executes a statement or a block of statements repeatedly until a specified expression evaluates to false.  there is need to specify the loop bounds( minimum or maximum).
int j = 0;
for (int i = 1; i <= 5; i++)
{
j = j + i ;
}

The foreach statement repeats a group of embedded statements for each element in an array or an object collection.you do not need to specify the loop bounds minimum or maximum.
int j = 0;
int[] tempArr = new int[] { 0, 1, 2, 3, 5, 8, 13 };
foreach (int i in tempArr )
{
j = j + i ;
}

Difference between an abstract class and interface Class


eature
Interface
Abstract class
Declaration and implementation of Methods
Contain only declaration of functions and methods. It does not provide implementation of methods.
We Can provide default implementation of methods.
Implement Every Method or Override every method
The derived class must implement all the methods of interface.
Not necessary to implement all methods.
Fields and Constants
Fields can not be define
Fields can be define.
Access Modfiers
An interface cannot have access modifiers for the functions, properties etc everything is assumed as public
An abstract class can contain access modifiers for the functions, properties

Page Life cycle in asp.net


Event Life cycle of ASP.NET 2.0

To track the flowing of events in web application, you need to add “trace = true” in page directive as shown below.
       <% @Page Trace=”true”%>
PreInit 
1)    Entry point of page life cycle.
2)    We can create or re-create dynamic controls.
3)    We can change master page dynamically.
4)    We can change theme properties dynamically in this control.
Init -
1)    All Control are initialized in this event
2)    The init event of each controls occurs first then init event for page occurs.

Init Complete –
1)    Page is initialized.
2)    Use this event to make changes in view state that you want to make sure are affected after the next post back.

PreLoad –
1)    This event is called before the loading of the page is completed. 

Load –
1)    This event is raised for the Page first and then for all child controls.
2)    The view state can be accessed at this stage.
3)    This event indicates that the controls have been fully loaded.

LoadComplete -
1) This event signals indicates that the page has been loaded in the memory.
2) It also marks the beginning of the rendering stage.

PreRender –
1)    If you need to make any final updates to the contents of the controls or the page, then use this event. 
2)    It first fires for the page and then for all the controls.

PreRenderComplete - 
         1) Is called to explicitly state that the PreRender phase is completed. 

SaveStateComplete –
1)   In this event, the current state of the control is completely saved to the ViewState.
                   
Unload 
1)                             1)  This event is typically used for closing files and database connections.


Stages and corresponding events in the life cycle of the ASP.NET page cycle:

 
Stage
Events/Method
Page Initialization
Page_Init
View State Loading
LoadViewState
Postback data processing
LoadPostData
Page Loading
Page_Load
PostBack Change Notification
RaisePostDataChangedEvent
PostBack Event Handling
RaisePostBackEvent
Page Pre Rendering Phase
Page_PreRender
View State Saving
SaveViewState
Page Rendering
Page_Render
Page Unloading
Page_UnLoad

multiple catch blocks in a single try statement

Yes. Multiple catch blocks may be put in a try block. See code example below, to see multiple catch blocks being used in C#. 

class ClassA
{
public static void Main()
{
int y = 0;
try
{
val = 100/y;
Console.WriteLine("Line not executed");
}
catch(DivideByZeroException ex)
{
Console.WriteLine("DivideByZeroException" );
}
catch(Exception ex)
{
Console.WritLine("Some Exception" );
}
finally
{
Console.WriteLine("This Finally Line gets executed always");
}
Console.WriteLine("Result is {0}",val);
}
}

Asp.net Cross-Page PostBack example & Post Back

 Post Back means sending the data to server and return the data in same page.

 Cross-Page Post Back means sending the data from one page to another page.

Example:
 CrossPagePostBack.aspx 

 <%@ Page Language="C#" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<script runat="server">

</script>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>asp.net cross page postback example</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <h2 style="color:Red">asp.net Cross-Page PostBack example</h2>
        <asp:Label 
            ID="Label1" 
            runat="server"
            Text="ProductID"
            ForeColor="DodgerBlue"
            >
        </asp:Label>
        <asp:TextBox 
            ID="TextBox1" 
            runat="server" 
            ForeColor="AliceBlue" 
            BackColor="DodgerBlue"
            >
        </asp:TextBox>
        <br />        
        <asp:Label 
            ID="Label2" 
            runat="server"
            Text="Product Name"
            ForeColor="DodgerBlue"
            >
        </asp:Label>
        <asp:TextBox 
            ID="TextBox2" 
            runat="server" 
            ForeColor="AliceBlue" 
            BackColor="DodgerBlue"
            >
        </asp:TextBox>
        <br />
        <asp:Button 
            ID="Button1" 
            runat="server" 
            Text="Submit data" 
            Font-Bold="true"
            ForeColor="DodgerBlue"
            PostBackUrl="~/NextPage.aspx"
            />
    </div>
    </form>
</body>
</html>

NextPage.aspx 

<%@ Page Language="C#" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<script runat="server">
    protected void Page_Load(object sender, System.EventArgs e) {
        TextBox pvProductID = (TextBox)PreviousPage.FindControl("TextBox1");
        TextBox pvProductName = (TextBox)PreviousPage.FindControl("TextBox2");
        Label1.Text ="You came from: "+ PreviousPage.Title.ToString();
        Label2.Text = "Product ID: " + pvProductID.Text.ToString();
        Label2.Text += "<br />Product Name: " + pvProductName.Text.ToString();

        string imageSource = "~/Images/" + pvProductID.Text + ".jpg";
        Image1.ImageUrl = imageSource;
        Image1.BorderWidth = 2;
        Image1.BorderColor = System.Drawing.Color.DodgerBlue;
    }
</script>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>asp.net Cross-Page PostBack example: how to submit a page to another page</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <h2 style="color:Teal">asp.net cross page postback example</h2>
        <asp:Label ID="Label1" runat="server" ForeColor="Crimson">
        </asp:Label>
        <br />
        <asp:Label ID="Label2" runat="server" ForeColor="SeaGreen">
        </asp:Label>
        <br />
        <asp:Image ID="Image1" runat="server" />
    </div>
    </form>
</body>
</html>
 

 OUTPUT:
[CrossPagePostBack1.gif] 

[CrossPagePostBack2.gif] 

Ways To Optimize C# Code

Code optimization is an important aspect of writing an efficient C# application. The following tips will help you increase the speed and efficiency of your C# code and applications.

1. Knowing when to use StringBuilder

You must have heard before that a StringBuilder object is much faster at appending strings together than normal string types.
The thing is StringBuilder is faster mostly with big strings. This means if you have a loop that will add to a single string for many iterations then a StringBuilder class is definitely much faster than a string type.
However if you just want to append something to a string a single time then a StringBuilder class is overkill. A simple string type variable in this case improves on resources use and readability of the C# source code.
Simply choosing correctly between StringBuilder objects and string types you can optimize your code.

2. Comparing Non-Case-Sensitive Strings

In an application sometimes it is necessary to compare two string variables, ignoring the cases. The tempting and traditionally approach is to convert both strings to all lower case or all upper case and then compare them, like such:
str1.ToLower() == str2.ToLower()
However repetitively calling the function ToLower() is a bottleneck in performace. By instead using the built-in string.Compare() function you can increase the speed of your applications.
To check if two strings are equal ignoring case would look like this:
string.Compare(str1, str2, true) == 0 //Ignoring cases
The C# string.Compare function returns an integer that is equal to 0 when the two strings are equal.

3. Use string.Empty

This is not so much a performance improvement as it is a readability improvement, but it still counts as code optimization. Try to replace lines like:
if (str == "")
with:
if (str == string.Empty)
This is simply better programming practice and has no negative impact on performance.
Note, there is a popular practice that checking a string's length to be 0 is faster than comparing it to an empty string. While that might have been true once it is no longer a significant performance improvement. Instead stick with string.Empty.

4. Replace ArrayList with List<>

ArrayList are useful when storing multiple types of objects within the same list. However if you are keeping the same type of variables in one ArrayList, you can gain a performance boost by using List<> objects instead.
Take the following ArrayList:
ArrayList intList = new ArrayList();
intList.add(10);
return (int)intList[0] + 20;
Notice it only contains intergers. Using the List<> class is a lot better. To convert it to a typed List, only the variable types need to be changed:
List<int> intList = new List<int>();

intList.add(10)

return intList[0] + 20;
There is no need to cast types with List<>. The performance increase can be especially significant with primitive data types like integers.

5. Use && and || operators

When building if statements, simply make sure to use the double-and notation (&&) and/or the double-or notation (||), (in Visual Basic they are AndAlso and OrElse).
If statements that use & and | must check every part of the statement and then apply the "and" or "or". On the other hand, && and || go thourgh the statements one at a time and stop as soon as the condition has either been met or not met.
Executing less code is always a performace benefit but it also can avoid run-time errors, consider the following C# code:
if (object1 != null && object1.runMethod())
If object1 is null, with the && operator, object1.runMethod()will not execute. If the && operator is replaced with &object1.runMethod() will run even if object1 is already known to be null, causing an exception.

6. Smart Try-Catch

Try-Catch statements are meant to catch exceptions that are beyond the programmers control, such as connecting to the web or a device for example. Using a try statement to keep code "simple" instead of usingif statements to avoid error-prone calls makes code incredibly slower. Restructure your source code to require less try statements.

7. Replace Divisions

C# is relatively slow when it comes to division operations. One alternative is to replace divisions with a multiplication-shift operation to further optimize C#. The article explains in detail how to make the conversion.

Conclusion

As you can see these are very simple C# code optimizations and yet they can have a powerful impact on the performance of your application. To test out the optimizations, try out the free Optimizing Utility.

Profiling

An important concept when it comes to increasing the speed and efficiency of you C# code, is code profiling. A good profiler can not only let you know about the speed bottlenecks in your applications, but it can also help you with memory management. The best .Net profiler is probably RedGates ANTS Profiler. They have a free trial at their homepage you can download before purchasing the full product.

Source From : http://www.vcskicks.com/optimize_csharp_code.php 

Dot Net Video Tutorial

Best Dot Net Video Tutorial Click the Below Link For More Info

 Click Here

Ado.net Interview Question


ExecuteReader : Use for accessing data. It provides a forward-only, read-only, connected recordset.
ExecuteNonQuery : Use for data manipulation, such as Insert, Update, Delete.
ExecuteScalar : Use for retriving 1 row 1 col. value., i.e. Single value. eg: for retriving aggregate function. It is faster than other ways of retriving a single value from DB.

Visual Studio Keyboard Shortcuts


Visual Studio 2003 & 2005 Default Keyboard Shortcuts
Text Manipulation Copy Ctrl + C
Cut
Ctrl + X Paste Ctrl + V
Undo
Ctrl + Z Redo Ctrl + Shift + Z
Transpose characters
Ctrl + T Transpose Lines Shift + Alt + T
Transpose Words
Ctrl + Shift + T Cut Line Ctrl + L
Delete Line
Ctrl + Shift + L Insert Line Above Ctrl + Enter
Insert Line Below
Ctrl + Shift + Enter Delete word to right Ctrl + Delete
Delete word to left
Ctrl + Backspace Collapse All Ctrl + M, O
Toggle outlining
Ctrl + M, M Toggle All Outlining Ctrl + M, L
Comment Selection
Ctrl + K, C Uncomment Selection Ctrl + K, U
Format Selection
Ctrl +K, F Format Document Ctrl + K, D
Make lowercase
Ctrl + U Make uppercase Ctrl + Shift + U
Delete horizontal whitespace
Ctrl + K, \ Toggle overtype/insert Insert
Toggle wordwrap
Ctrl +R, R Toggle whitespace Ctrl + R, W
Text Navigation Document end Ctrl + End
Document start
Ctrl + Home Go to line Ctrl + G
Go to matching brace
Ctrl + [ Scroll line Ctrl + [Up/Down]
Next word
Ctrl + Right Previous word Ctrl + Left
Next bookmark
Ctrl + K, N Previous bookmark Ctrl + K, P
Quick info
Ctrl + K, I
Text Selection Extend Selection Shift + [Arrow]
Select to end of document
Ctrl + Shift + End Select to start of document Ctrl + Shift + Home
Select to matching brace
Ctrl + Shift + ] Select to end of line Shift + End
Select to start of line
Shift + Home Extend selection by page Shift + [Page Up/Down]
Select to bottom of view
Ctrl + Shift + Page Down Select to top of view Ctrl + Shift + Page Up
Select All
Ctrl + A Select Word Ctrl + W
Select to last position
Ctrl + = Select to next word Ctrl + Shift + Right
Select to previous word
Ctrl + Shift + Left
Searching/Referencing Find all references Shift + F12
Next Location
F8 Previous Location Shift + F8
Find
Ctrl + F Find in Files Ctrl + Shift + F
Find Next
F3 Find Previous Shift + F3
Find Next Selected
Ctrl + F3 Find Previous Selected Ctrl + Shift + F3
Replace
Ctrl + H Replace in Files Ctrl + Shift + H
Debugging Apply Code Changes Alt + F10
Run
F5 Run w/o Debug Ctrl + F5
Restart
Shift + F5 Run to Cursor Ctrl + F10
Set Next Statement
Ctrl + Shift + F10 Step Over F10
Step Into
F11 Step Out Shift + F11
Call stack
Ctrl + Alt + C Breakpoints Ctrl + Alt + B
Disassembly
Ctrl + Alt + D Exceptions Ctrl + Alt + E
Immediate
Ctrl + Alt + I Modules Ctrl + Alt + U
Quick Watch
Ctrl + Alt + Q Registers Ctrl + Alt + G
Running Documents
Ctrl + Alt + N Threads Ctrl + Alt + T
View Autos
Ctrl + Alt + V, A View Locals Ctrl + Alt + V, L
View This
Ctrl + Alt + V, T View Watch 1-4 Ctrl + Alt + W, [1-4]
View Memory 1-4
Ctrl + Alt + M, [1-4] Toggle Breakpoint F9
New breakpoint
Ctrl + B Clear All Breakpoints Ctrl + Shift + F9
Attach to processes
Ctrl + Alt + F9
Designer View Code F7
View Designer
Shift + F7

Twitter Delicious Facebook Digg Stumbleupon Favorites More

 
Design by Free WordPress Themes | Bloggerized by Lasantha - Premium Blogger Themes | SharePoint Demo