C#.Net [Tips & FAQ]

Tuesday, December 14, 2010

Mathematical Functions in .NET


Math.Abs() Returns the absolute value.

Math.Abs(-10) returns 10.

Math.Ceiling() Returns an integer that is greater than or equal to a number.

Math.Ceiling(5.333) returns 6.

Fix() Returns the integer portion of a number.

Fix(5.3333) returns 5.

Math.Floor() Returns an integer that is less than or equal to a number.

Fix(5.3333) returns 5.

Int() Returns the integer portion of a number.

Int(5.3333) returns 5.

Math.Max() Returns the larger of two numbers.

Math.Max(5,7) returns 7.

Math.Min() Returns the smaller of two numbers.

Math.Min(5,7) returns 5.

Math.Pow() Returns a number raised to a power.

Math.Pow(12,2) returns 144.

Rnd() Returns a random number between 0 and 1. Used in conjunction with Randomizestatement to initialize the random number generator.

Math.Round() Rounds a number to a specified number of decimal places. Rounds up on .5.

Math.Round(1.1234567,5) returns 1.12346.

Math.Sign() Returns the sign of a number. Returns -1 if negative and 1 if positive.

Math.Sign(-5) returns -1.

Math.Sqrt() Returns the square root of a positive number.

Math.Sqrt(144) returns 12.

String Functions in .NET

Several built-in string functions used to perform string manipulations

Function in ASP.NET

Asc() Returns the character code of the first character of a string.

Asc("A") returns 65.

Chr() Returns the display character of a character code.

Chr(65) returns "A".

GetChar() Returns the character at a specified position in a string, counting from 1.

GetChar("This is a string", 7) returns "s".

InStr() Returns the starting position in a string of a substring, counting from 1.

InStr("This is a string", "string") returns 11.

InStrRev() Returns the starting position in a string of a substring, searching from the end of the string.

InStr("This is a string", "string") returns 11.

LCase() Returns the lower-case conversion of a string.

LCase("THIS IS A STRING") returns "this is a string".

Left() Returns the left-most specified number of characters of a string.

Left("This is a string", 4) returns "This".

Len() Returns the length of a string.

Len("This is a string") returns 16.

LTrim() Removes any leading spaces from a string.

LTrim(" This is a string") returns "This is a string".

Mid() Returns a substring from a string, specified as the starting position (counting from 1) and the number of characters.

Mid("This is a string", 6, 4) returns "is a".

Replace() Replaces all occurences of a substring in a string.

Replace("This is a string", " s", " longer s") returns "This are a longer string" (replaces an "s" preceded by a blank space).

Right() Returns the right-most specified number of characters of a string.

Right("This is a string", 6) returns "string".

RTrim() Removes any trailing spaces from a string.

RTrim("This is a string ") returns "This is a string".

Str() Returns the string equivalent of a number.

Str(100) returns "100".

Space() Fills a string with a given number of spaces.
"This" & Space(5) & "string" returns "This string".

StrComp() Compares two strings. Return values are 0 (strings are equal), 1 (first string has the greater value), or -1 (second string has the greater value) based on sorting sequence.

StrComp("This is a string", "This string") returns -1.

StrReverse() Reverses the characters in a string.

StrReverse("This is a string") returns "gnirts a si sihT".

Trim() Removes any leading and trailing spaces from a string.

Trim(" This is a string ") returns "This is a string".

UCase() Returns the upper-case conversion of a string.

UCase("This is a string") returns "THIS IS A STRING".

Val() Converts a numeric expression to a number.

Val( (1 + 2 + 3)^2 ) returns 36.

Tips for Stored Procedures Optimization

Use stored procedures instead of heavy-duty queries.

This can reduce network traffic, because your client will send to server only stored procedure name (perhaps with some parameters) instead of large heavy-duty queries text. Stored procedures can be used to enhance security and conceal underlying data objects also. For example, you can give the users permission to execute the stored procedure to work with the restricted set of the columns and data.

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

Include the SET NOCOUNT ON statement into your stored procedures to stop the message indicating the number of rows affected by a Transact-SQL statement.

This can reduce network traffic, because your client will not receive the message indicating the number of rows affected by a Transact-SQL statement.

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

Call stored procedure using its fully qualified name.

The complete name of an object consists of four identifiers: the server name, database name, owner name, and object name. An object name that specifies all four parts is known as a fully qualified name. Using fully qualified names eliminates any confusion about which stored procedure you want to run and can boost performance because SQL Server has a better chance to reuse the stored procedures execution plans if they were executed using fully qualified names.

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

Consider returning the integer value as an RETURN statement instead of an integer value as part of a recordset.

The RETURN statement exits unconditionally from a stored procedure, so the statements following RETURN are not executed. Though the RETURN statement is generally used for error checking, you can use this statement to return an integer value for any other reason. Using RETURN statement can boost performance because SQL Server will not create a recordset.

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

Don't use the prefix "sp_" in the stored procedure name if you need to create a stored procedure to run in a database other than the master database.

The prefix "sp_" is used in the system stored procedures names. Microsoft does not recommend to use the prefix "sp_" in the user-created stored procedure name, because SQL Server always looks for a stored procedure beginning with "sp_" in the following order: the master database, the stored procedure based on the fully qualified name provided, the stored procedure using dbo as the owner, if one is not specified. So, when you have the stored procedure with the prefix "sp_" in the database other than master, the master database is always checked first, and if the user-created stored procedure has the same name as a system stored procedure, the user-created stored procedure will never be executed.

*****************************************************************
Use the sp_executesql stored procedure instead of the EXECUTE statement.

The sp_executesql stored procedure supports parameters. So, using the sp_executesql stored procedure instead of the EXECUTE statement improve readability of your code when there are many parameters are used. When you use the sp_executesql stored procedure to executes a Transact-SQL statements that will be reused many times, the SQL Server query optimizer will reuse the execution plan it generates for the first execution when the change in parameter values to the statement is the only variation.

*****************************************************************
Use sp_executesql stored procedure instead of temporary stored procedures.

Microsoft recommends to use the temporary stored procedures when connecting to earlier versions of SQL Server that do not support the reuse of execution plans. Applications connecting to SQL Server 7.0 or SQL Server 2000 should use the sp_executesql system stored procedure instead of temporary stored procedures to have a better chance to reuse the execution plans.

*****************************************************************
If you have a very large stored procedure, try to break down this stored procedure into several sub-procedures, and call them from a controlling stored procedure.

The stored procedure will be recompiled when any structural changes were made to a table or view referenced by the stored procedure (for example, ALTER TABLE statement), or when a large number of INSERTS, UPDATES or DELETES are made to a table referenced by a stored procedure. So, if you break down a very large stored procedure into several sub-procedures, you get chance that only a single sub-procedure will be recompiled, but other sub-procedures will not.

*****************************************************************
Try to avoid using temporary tables inside your stored procedure.

Using temporary tables inside stored procedure reduces the chance to reuse the execution plan.

*****************************************************************
Try to avoid using DDL (Data Definition Language) statements inside your stored procedure.

Using DDL statements inside stored procedure reduces the chance to reuse the execution plan.

*****************************************************************
Add the WITH RECOMPILE option to the CREATE PROCEDURE statement if you know that your query will vary each time it is run from the stored procedure.

The WITH RECOMPILE option prevents reusing the stored procedure execution plan, so SQL Server does not cache a plan for this procedure and the procedure is recompiled at run time. Using the WITH RECOMPILE option can boost performance if your query will vary each time it is run from the stored procedure because in this case the wrong execution plan will not be used.

*****************************************************************
Use SQL Server Profiler to determine which stored procedures has been recompiled too often.

To check the stored procedure has been recompiled, run SQL Server Profiler and choose to trace the event in the "Stored Procedures" category called "SP:Recompile". You can also trace the event "SP:StmtStarting" to see at what point in the procedure it is being recompiled. When you identify these stored procedures, you can take some correction actions to reduce or eliminate the excessive recompilations.
*****************************************************************

Tuesday, November 23, 2010

Create/Remove Controls In/From a Containers like GroupBox Dynamically

My Task is " I developed an application by retrieving a list of Tables from the database into combobox. I choosed a table & Clicked 'OK' button, That Table should be display into the groupbox1 with labels & Textboxes. And when i choosed another Table from Combobox, old controls should be remove from the groupbox1 & again new controls should be generate according to numberofcolumns, fieldnames.

PROBLEM: The problem getting with "foreach" & "for ". Where the problem is resovled with "for "

If u wana see my code:
-----------------------------------------------------------------------------------------------

public void RemoveCtrls()
{
//MessageBox.Show(gb_DataBox.Controls.Count.ToString());

//foreach (Control ctrl in gb_DataBox.Controls)
//{
//if (!(ctrl is Button))//(ctrl.GetType() == typeof(Button)) //(((Button)ctrl).Text != "Next")
//{
// MessageBox.Show(ctrl.GetType().Name + " : " + ctrl.Name.ToString());
// gb_DataBox.Controls.Remove(ctrl);
// ctrl.Dispose();
//}
// }

int c = gb_DataBox.Controls.Count;

//for (int i = 1; i < i =" c">= 0; i--)
{
if (!(gb_DataBox.Controls[i] is Button))
{
//if (gb_DataBox.Controls[i].GetType().ToString())//.EndsWith(".ctl1"))

MessageBox.Show(gb_DataBox.Controls[i].GetType().Name + " : " + gb_DataBox.Controls[i].Name.ToString());
gb_DataBox.Controls.Remove(gb_DataBox.Controls[i]);
}
}
}

private void btn_ConnectDB_Click(object sender, EventArgs e)
{
//Make Default values
y = 20;
gb_DataBox.Height = 100;//50;

RemoveCtrls();
//cn = new SqlConnection("Data Source=.;Initial Catalog=master;User ID=sa;Password=123");

query = txtQuery.Text;
try
{
cmd = new SqlCommand(query, cn);

if (cn.State == ConnectionState.Open)
cn.Close();

cn.Open();
dr = cmd.ExecuteReader();

lb = new Label[dr.FieldCount];
txt = new TextBox[dr.FieldCount];

for (int i = 0; i < lb.Length; i++)
{
lb[i] = new Label();
txt[i] = new TextBox();
lb[i].Text = dr.GetName(i);
lb[i].Name = dr.GetName(i);
txt[i].Name = dr.GetName(i);
lb[i].Location = new Point(100, y + 3);
txt[i].Location = new Point(200, y);
//MessageBox.Show(lb[i].Text.ToString());
//MessageBox.Show(txt[i].Name.ToString());
gb_DataBox.Controls.Add(lb[i]);
gb_DataBox.Controls.Add(txt[i]);
y += 30;

gb_DataBox.Height += txt[i].Height;// +3;
this.Height = groupBox2.Height + gb_QueryBox.Height + gb_DataBox.Height + 100;
//this.AutoScroll = true;
int c = gb_DataBox.Controls.Count;
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
cn.Close();
}
btn_Next.Enabled = true;
}

private void btn_Next_Click(object sender, EventArgs e)
{
if (dr.Read())
{
for (int i = 0; i < lb.Length; i++)
txt[i].Text = dr.GetValue(i).ToString(); //dr[i].ToString();
}
else
{
MessageBox.Show("No More Records..");
cn.Close();
btn_Next.Enabled = false;
}
}
------------------------------------------------------------------------------------------------

Wednesday, September 8, 2010

DELEGATES AND EVENTS

Delegates
Delegates are a construct for abstracting and creating objects that reference methods and can be used to call those methods. Delegates form the basis of event handling in C#. A delegate declaration specifies a particular method signature. References to one or more methods can be added to a delegate instance. The delegate instance can then be "called" which effectively calls all the methods that have been added to the delegate instance. A simple example:


delegate void Procedure();

class DelegateDemo
{
static void Method1()
{
Console.WriteLine("Method 1");
}
static void Method2()
{
Console.WriteLine("Method 2");
}
void Method3()
{
Console.WriteLine("Method 3");
}

static void Main()
{
Procedure someProcs = null;
someProcs += new Procedure(DelegateDemo.Method1);
someProcs += new Procedure(DelegateDemo.Method2);
DelegateDemo demo = new DelegateDemo();
someProcs += new Procedure(demo.Method3);
someProcs();
}
}

In this example, the delegate is declared by the line delegate void Procedure();
This statement is a complete abstraction. It does not result in executable code that does any work. It merely declares a delegate type called Procedure which takes no arguments and returns nothing. Next, in the Main() method, the statement Procedure someProcs = null; instantiates a delegate. Something concrete has now been created.
The assignment of someProcs to null means that it is not initially referencing any methods. The statements someProcs += new Procedure(DelegateDemo.Method1); and someProcs += new Procedure(DelegateDemo.Method2);
add two static methods to the delegate instance. (Note: the class name could have been left off of DelegateDemo.Method1 and DelegateDemo.Method2 because the statement is occurring in the DelegateDemo class.)
The statement someProcs += new Procedure(demo.Method3); adds a non-static method to the delegate instance.

For a non-static method, the method name is preceded by an object reference. When the delegate instance is called, Method3() is called on the object that was supplied when the method was added to the delegate instance. Finally, the statement someProcs(); calls the delegate instance. All the methods that were added to the delegate instance are now called in the order that they were added.

Methods that have been added to a delegate instance can be removed with the -= operator:
someProcess -= new Procedure(DelegateDemo.Method1);
In C# 2.0, adding or removing a method reference to a delegate instance can be shortened as follows:
someProcess += DelegateDemo.Method1;
someProcess -= DelegateDemo.Method1;
Invoking a delegate instance that presently contains no method references results in a NullReferenceException.
Note that if a delegate declaration specifies a return type and multiple methods are added to a delegate instance, then an invocation of the delegate instance returns the return value of the last method referenced. The return values of the other methods cannot be retrieved (unless explicitly stored somewhere in addition to being returned).

Events
An event is a special kind of delegate that facilitates event-driven programming. Events are class members which cannot be called outside of the class regardless of its access specifier. So, for example, an event declared to be public would allow other classes the use of += and -= on the event, but firing the event (i.e. invoking the delegate) is only allowed in the class containing the event. A simple example:


delegate void ButtonClickedHandler();
class Button
{
public event ButtonClickedHandler ButtonClicked;
public void SimulateClick()
{
if (ButtonClicked != null)
{
ButtonClicked();
}
}
...
}


A method in another class can then subscribe to the event by adding one of its methods to the event delegate:
Button b = new Button();
b.ButtonClicked += MyHandler;
Even though the event is declared public, it cannot be directly fired anywhere except in the class containing the event.
Events are used extensively in GUI programming and in the System.Windows.Forms namespace.

Difference Between ToString() vs Convert.ToString() vs (string) cast

There is a simple but important difference between these three…

ToString() raise exception when the object is null

So in the case of object.ToString(), if object is null, it raise NullReferenceException.

Convert.ToString() return string.Empty in case of null object

(string) cast assign the object in case of null

So in case of MyObject o = (string)NullObject;

The StringBuilder and String classes provide ways to perform string manipulation. If your program requires many manipulations, then the StringBuilder class will likely be more efficient than using the String class. The String class provides an immutable object, which means that once the value of the string instance is set, it cannot be changed. Even though it appears that the application is changing the value of the string instance, it is actually returning a new instance of the String class in memory. For this reason, the StringBuilder class will likely cause less overhead in your application. This set of samples shows some basic manipulation using both the StringBuilder and String classes.


Contents:
The following examples will show how to use the StringBuilder class to append, insert, and replace text within a StringBuilder instance. It will also show how to use the String class to copy, split, and find a substring within a given String instance.
The self-extracting archive contains all source code for this set of samples. The file contains the following directories:

• Code: Contains subfolders for all the samples (see descriptions below):
• BuilderAppend
• BuilderInsert
• BuilderReplace
• StringCopy
• StringSplit
• StringSubstring
• Doc: Contains all documentation, including descriptions of samples, installation instructions, and information on how to use the sample application.
• Misc: Contains any additional files required to run the sample application.


How to Use

Run the self-extracting archive to install the sample files. All of the examples here are separate console applications that can be opened in Visual Studio.NET and run accordingly.

Description


StringBuilder.Append
The Append method takes the specified argument and appends it to the end of the existing value held in a StringBuilder object. This example is a console application that asks the user to input his/her name. The application takes the name entered by the user and appends it to the greeting that is held in the StringBuilder object Greeting. The Append method of the StringBuilder class has 19 overloads. This example uses the Append method of the String object to append Name to the Greeting. The StringBuilder Greeting is initialized with no value, and the value Good Morning is appended to the string representation. Next, the name the user enters is appended to this greeting with the code:

Greeting.Append(", "+Name+"!");

StringBuilder.Insert
The Insert method takes a specified argument and inserts the value at the specified location within the existing value of the StringBuilder object. This example is a console application similar to the Append example. The application takes the name entered by the user and inserts it at the specified location. The Insert method has 18 overloads. This example uses the Insert method of the String object to insert the name you enter after the words "Good Morning" and before the "!" with the following code:

Greeting.Insert(12, ", "+Name);

The first argument is an integer value representing the location within the string to insert the value. The second argument is the value to insert into the existing string. If the integer value supplied is greater than the length of the string value contained within the StringBuilder object (for example, if the value 35 is entered here), an exception of type System.ArgumentOutOfRangeException will occur.

StringBuilder.Replace
The Replace method searches the existing string value and replaces all instances of the value with another specified value. This example builds on the Insert example by asking the user to also enter a nickname into the application. If the user has entered a name and a nickname, then the application will replace the original name with the nickname in the StringBuilder Greeting object with the following code:

Greeting.Replace(Name, Nickname);

String.Copy
The Copy method of the String class creates a new instance of a string with the same value as the string being copied. In this example the user enters some text, and that value is placed into a string object named inputText. The application copies this value into the new object named copiedText and appends some additional text in the following code:

string inputText = Console.ReadLine();
string copiedText = string.Copy(myText);
copiedText+=" more text";

Notice that the Copy method is a static method of the String class and therefore is called using the class name and not the instance name.

String.Split and String.Join
The Split method identifies a substring within the specified string delimited by one or more characters. The substring values are placed into a string array. In this example, the string instance textOriginal contains the value "Value 1, Value 2, Value 3". The application calls the Split method and initializes the textarray string array with the following code:

string[] textArray = text.Split(',');

The example then loops through all of the values in the array and writes them to the screen.
The Join method of the String class concatenates a specified character string within values of a string array and produces a single string. In this example, the textarray string array is re-joined using a ":" with the following code:

string newJoin = string.join(":", textArray);

Notice that the Join method is a static method of the String class and therefore is called using the class name and not the instance name.

String.Substring
The Substring method returns a string representation from a specified start point. This method has two overloads where one method also accepts a length argument. In this example, a string is extracted from the original string instance beginning at the 4th character and having a length of 3.

string Contained = originalString.Substring(4, 3).ToString();



Followers