Thursday, August 20, 2009

Execute the stored procedure with parameters.

SqlConnection sqlConn = new SqlConnection("...");
sqlConn.Open();

SqlCommand command= new SqlCommand("stored_procedure_name", sqlConn);
command.CommandType = CommandType.StoredProcedure;

// add parameter
command.Parameters.AddWithValue("@id", id);


int affectedRows = command.ExecuteNonQuery();

Change colors in console application

Console.BackgroundColor = ConsoleColor.White;
Console.ForegroundColor = ConsoleColor.Yellow;

split string to array

Let us suppose your string contains comma as a separator eg. "123,34,534,678,33,5556,343"

string s= "123,34,534,678,33,5556,343"
string[] sbstring= s.Split(',');

foreach (string i in sbstring)
{
Console.WriteLine(i);
}

Check for DBNull value

SqlDataReader myreader = command.ExecuteReader();
if( myreader["column_name"] != DBNull.Value)
{
//code goes here
}
or

SqlDataReader myreader = command.ExecuteReader();
if(myreader["column_name"] != Convert.DBNull)
{
//code goes here
}

Friday, August 14, 2009

Javascript function to allow only alphabets (lower and upper case).


function AllowCharacterOnly(myevent)
{
var Val = (myevent.which) ? myevent.which : myevent.keyCode
if ((Val > 64 && Val < 91) || (Val > 96 && Val < 123))
{
return true;
}
return false;

}


input type="text" id=txtChracter onkeypress="return AllowCharacterOnly(event)"

Javascript to allow user to enter only numeric value.


function AllowNumericValue(myevent)
{
var charVal = (myevent.which) ? myevent.which : myevent.keyCode
if (charVal > 31 && (charVal < 48 || charVal > 57))
{
return false;
}
return true;

}


input type="text" id="Text2" onkeypress="return AllowNumericCharacters(event)"

Javascript function to show an alert if user entered a non numeric value.


function ValidationCheckforNumeric(txtVal)
{
var len = txtVal.value.length;
var charVal = 0;
for (var i=0;i {
charVal = txtVal.value.charCodeAt(i);
if (!((charVal >= 48 && charVal <= 57)))
{
alert("Only Numeric Values are Allowed");
txtVal.value = '';
txtVal.focus();
return false;
}
}
return true;
}


input type="text" id="txtNumber" onchange='ValidationCheckforNumeric(this)'

Javascript code for checking null value in Textbox.


function CheckForEmptyTextbox()
{
var s;
var txtValue;
txtValue = document.getElementById('TextBox1');
if (txtValue.value == '')
{
s = confirm('TextBox1 is blank, do you want to continue?');
return s;
}
return true;

}

Button1.Attributes.Add("onclick", "javascript: CheckForEmptyTextbox();");

Interview Questions in Windows Form.

• What is the difference between Debug.Write and Trace.Write? When should each be used?
The Debug.Write call won't be compiled when the DEBUGsymbol is not defined (when doing a release build). Trace.Write calls will be compiled. Debug.Write is for information you want only in debug builds, Trace.Write is for when you want it in release build as well.

• Difference between Anchor and Dock Properties?
Dock Property->Gets or sets which edge of the parent container a control is docked to. A control can be docked to one edge of its parent container or can be docked to all edges and fill the parent container. For example, if you set this property to DockStyle.Left, the left edge of the
control will be docked to the left edge of its parent control. Additionally, the docked edge of the control is resized to match that of its container
control.
Anchor Property->Gets or sets which edges of the control are anchored to the edges of its container. A control can be anchored to one or more edges of its parent container. Anchoring a control to its parent ensures that the anchored edges remain in the same position relative to the edges of the parent container when the parent container is resized.

• When would you use ErrorProvider control?
ErrorProvider control is used in Windows Forms application. It is like Validation Control for ASP.NET pages. ErrorProvider control is used to provide validations in Windows forms and display user friendly messages to the user if the validation fails.
E.g
If we went to validate the textBox1 should be empty, then we can validate as below
1). You need to place the errorprovide control on the form
private void textBox1_Validating(object sender, System.ComponentModel.CancelEventArgs e)
{
ValidateName();
}
private bool ValidateName()
{
bool bStatus = true;
if (textBox1.Text == "")
{
errorProvider1.SetError (textBox1,"Please enter your Name");
bStatus = false;
}
else
errorProvider1.SetError (textBox1,"");
return bStatus;
}
it check the textBox1 is empty . If it is empty, then a message Please enter your name is displayed.

• Can you write a class without specifying namespace? Which namespace does it belong to by default??
Yes, you can, then the class belongs to global namespace which has no name. For commercial products, naturally, you wouldn't want global namespace.

• You are designing a GUI application with a windows and several widgets on it. The user then resizes the app window and sees a lot of grey space, while the widgets stay in place. What's the problem?
One should use anchoring for correct resizing. Otherwise the default property of a widget on a form is top-left, so it stays at the same location when resized.

• How can you save the desired properties of Windows Forms application?
.config files in .NET are supported through the API to allow storing and retrieving information. They are nothing more than simple XML files, sort of like what .ini files were before for Win32 apps.

• So how do you retrieve the customized properties of a .NET application from XML .config file?
Initialize an instance of AppSettingsReader class. Call the GetValue method of AppSettingsReader class, passing in the name of the property and the type expected. Assign the result to the appropriate variable.

• Can you automate this process?
In Visual Studio yes, use Dynamic Properties for automatic .config creation, storage and retrieval.

• My progress bar freezes up and dialog window shows blank, when an intensive background process takes over.
Yes, you should've multi-threaded your GUI, with taskbar and main form being one thread, and the background process being the other.

• What's the safest way to deploy a Windows Forms app?
Web deployment: the user always downloads the latest version of the code, the program runs within security sandbox, properly written app will not require additional security privileges.

• Why is it not a good idea to insert code into InitializeComponent method when working with Visual Studio?
The designer will likely through it away, most of the code inside InitializeComponent is auto-generated.

• What's the difference between WindowsDefaultLocation and WindowsDefaultBounds?
WindowsDefaultLocation tells the form to start up at a location selected by OS, but with internally specified size. WindowsDefaultBounds delegates both size and starting position choices to the OS.

• What's the difference between Move and LocationChanged? Resize and SizeChanged?
Both methods do the same, Move and Resize are the names adopted from VB to ease migration to C#.

• How would you create a non-rectangular window, let's say an ellipse?
Create a rectangular form, set the TransparencyKey property to the same value as BackColor, which will effectively make the background of the form transparent. Then set the FormBorderStyle to FormBorderStyle.None, which will remove the contour and contents of the form.

• How do you create a separator in the Menu Designer?
A hyphen '-' would do it. Also, an ampersand '&\' would underline the next letter.

• How's anchoring different from docking?
Anchoring treats the component as having the absolute size and adjusts its location relative to the parent form. Docking treats the component location as absolute and disregards the component size. So if a status bar must always be at the bottom no matter what, use docking. If a button should be on the top right, but change its position with the form being resized, use anchoring.

• How do you trigger the Paint event in System.Drawing?
Invalidate the current form, the OS will take care of repainting. The Update method forces the repaint.

• With these events, why wouldn't Microsoft combine Invalidate and Paint, so that you wouldn't have to tell it to repaint, and then to force it to repaint?
Painting is the slowest thing the OS does, so usually telling it to repaint, but not forcing it allows for the process to take place in the background.

• How can you assign an RGB color to a System.Drawing.Color object?
Call the static method FromArgb of this class and pass it the RGB values.

• What class does Icon derive from?
Isn't it just a Bitmap with a wrapper name around it? No, Icon lives in System.Drawing namespace. It's not a Bitmap by default, and is treated separately by .NET. However, you can use ToBitmap method to get a valid Bitmap object from a valid Icon object.

• Before in my VB app I would just load the icons from DLL. How can I load the icons provided by .NET dynamically?
By using System.Drawing.SystemIcons class, for example System.Drawing.SystemIcons.Warning produces an Icon with a warning sign in it.

• When displaying fonts, what's the difference between pixels, points and ems?
A pixel is the lowest-resolution dot the computer monitor supports. Its size depends on user's settings and monitor size. A point is always 1/72 of an inch. An em is the number of pixels that it takes to display the letter M.

Wednesday, August 12, 2009

Best Practises during ASP.Net development.

• Minimize the amount and complexity of data stored in a session state. The larger and more complex the data is, the cost of serializing/deserializing of the data is higher.
• Avoid unnecessary round-trips to the server - Code like validating user input can be handled at the client side itself.
• Use Page.IsPostback to avoid unnecessary processing on a round trip.
• Use Server.Transfer for redirecting between pages in the same application. This will avoid unnecessary client-side redirection.
• Don't rely on exceptions in the code. Exceptions reduce performance. Do not catch the exception itself before handling the condition
• Save server control view state only when necessary.
• Use server controls in appropriate circumstances. Even though are they are very easy to implement, they are expensive because they are server resources
• The in-proc model of session management is the fastest of the three options. SQL Server option has the highest performance hit.
• Disable session when not using it.
• Choose the best suited session-state provider - In-process is the fastest option.
• Use SQL server stored procedures for data access.
• Use the SQLDataReader class for a fast forward-only data cursor.
• Cache data and page output whenever possible.
• Disable debug mode before deploying the application.
• For multiple Response.Write instead of creating strings using concatenation.
• String Concatenation can really decrease the performance of your application if it is not handled properly.
• Resources should be cleaned up when an exception occurs.So close the resources in the finally block. Using a try/finally block ensures that resources are disposed even if an exception occurs.
• Use index properly in sql server.

Saturday, August 8, 2009

ClientScriptManager

The ClientScriptManager class can be used to invoke client callbacks in situations when it is desirable to run server code from the client without performing a postback.
ClientScriptManager class has a different useful methods which are :
1. RegisterClientScriptBlock() Method:
The RegisterClientScriptBlock() method allows you to place a JavaScript function at the top of the page and it gets executed on startup of the page when the page loads in the browser.
There are two overloads for this method:
a)RegisterClientScriptBlock(Type, String, String)
b) RegisterClientScriptBlock(Type, String, String, Boolean)
Eg. To display the message box before the controls get actually rendered:


protected void Page_Load(object sender, EventArgs e)
{
if (!Page.ClientScript.IsClientScriptBlockRegistered("HelloAlert"))
{
script.RegisterClientScriptBlock(this.GetType(), "Message", "alert('hi')",true);

}
}


Note: IsClientScriptBlockRegistered() will return true if a script block is already registered with the same key and so we can prevent the registration of duplicate script.
2. RegisterStartupScript() Method:
Using this method it is possible to access page controls in the script block.Only difference between RegisterStartupScript() Method and RegisterClientScriptBlock() method is that RegisterStartupScript() methods will execute the scripts after page controls but before form close tag whereas RegisterClientScriptBlock() method will fire before the page controls get rendered.
There are two overloads for this method:
a) RegisterStartupScript (Type, String, String)
b) RegisterStartupScript (Type, String, String, Boolean)
Eg. Suppose you want to display the messagebox with the textbox value:

txtMessage.Text = "You are learning javascript features.";
if (!Page.ClientScript.IsStartupScriptRegistered ("AlertMessage"))
{
script.RegisterStartupScript (this.GetType(), " AlertMessage ",
"alert(document.getElementById(txtMessage).value)",true);
}

3. RegisterOnSubmitStatement() Method: To get the confirmation from the user before submitting the form.
Eg. Suppose you want to ask the user using confirm dialog box before contuing to next page .

protected void Page_Load(object sender, EventArgs e)
{
if (!Page.ClientScript.IsClientScriptBlockRegistered(this.GetType(), "ConfirmScript"))
{
script.RegisterOnSubmitStatement(this.GetType(), " ConfirmMessage ", "return
confirm('Are you sure you want to continue to next page.')");
}
}

It will show a confirm box having ok and cancel option.
4. RegisterClientScriptInclude() Method
This method allows you to register a JavaScript reference with the Page object .
There are two overloads for this method:
a) RegisterClientScriptInclude(String,String)
b) RegisterClientScriptInclude(Type,String,String)

Thursday, August 6, 2009

Difference between a.Equals(b) and a == b

If both a and b are value type then then you will get same result in a.Equals(b) and a == b.
but in case of reference type both behaves differently :
eg.

string a = new string(new char[] {'d', 'a', 'n', 'c', 'e'});
string b = new string(new char[] {'d', 'a', 'n', 'c', 'e'});
object c = a;
object d = b;

Console.WriteLine (a==b);
Console.WriteLine (a.Equals(b));
Console.WriteLine (c==d);
Console.WriteLine (c.Equals(d));
}
}

Output will be;

True
True
False
True

Tuesday, August 4, 2009

Dynamic creation of textbox using C#

Dynamix creation of 5 textbox in windows application using C#:

int x = 10;
int y = 20;
List dynamictxt = new List();
for (int i = 0; i < 5; i++)
{
TextBox txtbox = new TextBox();
txtbox.Name = "textbox" + i.ToString();
txtbox.Location = new Point(x, y * i);
dynamictxt.Add(txtbox);
this.Controls.Add(txtbox);

}

On lost focus of textbox get the product of two textboxes in javascript.

Hi,
Please check the following code:

function Prod(input1,input2,output)
{
var first = document.getElementById(input1);
var second = document.getElementById(input2);
var third = document.getElementById(output);

third.value = first.value * second.value;
}

Use the html textboxes and on the second textbox call the function onblur

onblur="Prod('txtVal','txtVal2','txtProd');"

What’s different about switch statements in C#?

C# does not support an explicit fall through from one case label to another. If you want, you can use goto a switch-case or goto default.

case 1:
cost += 5;
break;
case 2:
cost += 10;
goto case 1;