Wednesday, September 30, 2009

Measuring Execution Time in C#

Motivation

Sometimes, while writing program

, we can get into situations when we need to measure execution times of various tasks.

Each programming language provides some mechanism to retrieve the current time from the system. If we read and store the system time at various moments, we can compute time intervals by substracting the values of system time taken at diffent moments.

We will see how to read the system time and how to measure time intervals in C#.

Reading the system time in C#

In C#, the DateTime class is used for storing the value of the system time at a specified moment. A DateTime instance stores

both date and time information. The DateTime class can be found in the System namespace.

In order to retrieve the current system time, we can use the static property Now of the DateTime class. For example the following two lines of code


DateTime currentSystemTime = DateTime.Now;
Console.WriteLine(currentSystemTime);
print out something like this:

4/17/2005 4:05:35 PM

We can print the date and time information stored in a DateTime instance in various formats, but we do not focus on them here, since our purpose is only to see how to measure time intervals.

Measuring time intervals in C#

In C#, there exists a dedicated class that stores information about a time interval. The name of the class is TimeSpan and it can be found in the System namespace.

The TimeSpan class is very easy to use. If we have an instance of TimeSpan class, we can assign to it directly a difference of two DateTime instance. See the code below to see how to do this.


/* Read the initial time. */
DateTime startTime = DateTime.Now;
Console.WriteLine(startTime);

/* Do something that takes up some time. For example sleep for 1.7 seconds. */
Thread.Sleep(1700);

/* Read the end time. */
DateTime stopTime = DateTime.Now;
Console.WriteLine(stopTime);

/* Compute the duration between the initial and the end time. */
TimeSpan duration = stopTime - startTime;
Console.WriteLine(duration);

The output of this code looks something like this:


4/17/2005 4:12:30 PM
4/17/2005 4:12:31 PM
00:00:01.7224768

As we see, by default the time interval is printed in the format hh:mm:ss.msec. If we want to retrieve separately the number of hours, minutes, seconds or milliseconds, we can do it through the properties of the TimeSpan class. Look at the code below to see how to do this.


/* Read the initial time. */
DateTime startTime = DateTime.Now;
Console.WriteLine(startTime);

/* Do something that takes up some time. For example sleep for 1.7 seconds. */
Thread.Sleep(1700);

/* Read the end time. */
DateTime stopTime = DateTime.Now;
Console.WriteLine(stopTime);

/* Compute the duration between the initial and the end time.
* Print out the number of elapsed hours, minutes, seconds and milliseconds. */
TimeSpan duration = stopTime - startTime;
Console.WriteLine("hours:" + duration.Hours);
Console.WriteLine("minutes:" + duration.Minutes);
Console.WriteLine("seconds:" + duration.Seconds);
Console.WriteLine("milliseconds:" + duration.Milliseconds);

The result of running this code is something like this:


4/17/2005 4:17:28 PM
4/17/2005 4:17:30 PM
hours:0
minutes:0
seconds:1
milliseconds:712

If we look more attentively, we will realize that this mode of retrieving the hours, minutes, seconds and milliseconds is not very useful. Because each field is returned separately and if we want to find out the total number of hours, minutes or seconds or milliseconds we have to manually sum up the individual fields.

Luckily, the TimeSpan class also provides some properties for directly retrieving the total elapsed hours, minutes, seconds and milliseconds. Look at the following code to see how these properties can be read.


/* Read the initial time. */
DateTime startTime = DateTime.Now;
Console.WriteLine(startTime);

/* Do something that takes up some time. For example sleep for 1.7 seconds. */
Thread.Sleep(1700);

/* Read the end time. */
DateTime stopTime = DateTime.Now;
Console.WriteLine(stopTime);

/* Compute the duration between the initial and the end time.
* Print out the number of elapsed hours, minutes, seconds and milliseconds. */
TimeSpan duration = stopTime - startTime;
Console.WriteLine("hours:" + duration.TotalHours);
Console.WriteLine("minutes:" + duration.TotalMinutes);
Console.WriteLine("seconds:" + duration.TotalSeconds);
Console.WriteLine("milliseconds:" + duration.TotalMilliseconds);

The result of this code is something like:


4/17/2005 4:23:27 PM
4/17/2005 4:23:29 PM
hours:0.000475684
minutes:0.02854104
seconds:1.7124624
milliseconds:1712.4624
Which is indeed much more useful, isn't it?

More advanced operations on time intervals

C# allows more advanced operations on time intervals. For example we can compute the sum of two TimeSpan instances, and the result is also of TimeSpan type.

Look at the following code to see how we can measure two separate time intervals and then easily compute the total execution time.


/* Read the initial time. */
DateTime startTime1 = DateTime.Now;

/* Do something that takes up some time. For example sleep for 1.7 seconds. */
Thread.Sleep(1700);

/* Read the end time. */
DateTime stopTime1 = DateTime.Now;

/* Compute and print the duration of this first task. */
TimeSpan duration1 = stopTime1 - startTime1;
Console.WriteLine("First task duration: {0} milliseconds.", duration1.TotalMilliseconds);

/* Do something that does not have to be measured.
* For example sleep for a while. */
Thread.Sleep(900);

/* Now we want to measure another task. We store the start time. */
DateTime startTime2 = DateTime.Now;

/* We perform the second task which again takes up some time.
* For example we can sleep for 2.1 seconds. */
Thread.Sleep(2100);

/* We store the end time of the second task. */
DateTime stopTime2 = DateTime.Now;

/* Compute and print the duration of this second task. */
TimeSpan duration2 = stopTime2 - startTime2;
Console.WriteLine("Second task duration: {0} milliseconds.", duration2.TotalMilliseconds);

/* Compute the total execution time. */
TimeSpan totalDuration = duration1 + duration2;
Console.WriteLine("Total duration: {0} milliseconds.", totalDuration.TotalMilliseconds);

The ouput obtained by running this code is:


First task duration: 1702.448 milliseconds.
Second task duration: 2103.024 milliseconds.
Total duration: 3805.472 milliseconds.

In the same manner we can compute the difference between two TimeSpan instances. Again the result will be of TimeSpan type.

Conclusions

As we could see, the combination of DateTime and TimeSpan classes is very powerfull. It allows us to very easily record the system time and then measure execution times. These two classes can save us a lot of headaches if we know about their existence.

Wednesday, September 23, 2009

C# Snippets: Directory Listing in C#

This will process a directory and get a list of all the files in the directory, returning them as a StringBuilder object.
using System;
using System.Collections.Generic;
using System.Text;
using System.IO;

namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
StringBuilder dirList = directoryListing("C:\\Inetpub", "");
Console.WriteLine(dirList.ToString());
}

static StringBuilder directoryListing(string path, string indent)
{
StringBuilder result = new StringBuilder();
DirectoryInfo di = new DirectoryInfo(path);
DirectoryInfo[] rgDirs = di.GetDirectories();

foreach (DirectoryInfo dir in rgDirs)
{
result.AppendLine(indent + dir.Name);
result.Append(directoryListing(path, indent + "..").ToString());
}
return result;
}
}
}

C# Snippets: Saving User Preferences and Settings

Almost every application will at some stage need to store information, settings or user preferences to a file so that they can be retrieved at a later date. This has formerly be done using INI configuration files and more recently using the system Registry. This snippet will show you how to save settings in the Registry, to a SQL Database or to an XML file.

The first thing you need is a class that holds all the data you need to save, in this example we are creating a simple class called UserPreferences which contains two strings and an integer.

public class UserPreferences
{
private string _DisplayName;
public string DisplayName
{
get { return _DisplayName; }
set { _DisplayName = value; }
}

private string _Company;
public string Company
{
get { return _Company; }
set { _Company = value; }
}

private int _SomeValue;
public int SomeValue
{
get { return _SomeValue; }
set { _SomeValue = value; }
}
}

This class will form a basis for each of the derived classes that we will use for storing the information in XML, Registry and Database.

XML Serialization :

Attribute before the declaration or create a class that implements the ISerializable interface.


To save the user preferences class to an XML file simply create an XML Writer and invoke the Serialise method.


UserPreferences up = new UserPreferences();

XmlSerializer mySerializer = new XmlSerializer(typeof(UserPreferences));
StreamWriter myWriter = new StreamWriter("c:/prefs.xml");
mySerializer.Serialise(myWriter, up);
myWriter.Close();

To read the data back in, you simply call the Deserialise method.


UserPreferences up;

XmlSerializer mySerializer = new XmlSerializer(typeof(UserPreferences));
FileStream myFileStream = new FileStream("c:/prefs.xml",FileMode.Open);

up = (myTestClass)mySerializer.Deserialize(myFileStream);

You could also implement the IFormatter interface which will allow you to format the data and save it within a SOAP XML package using SoapFormatter or using a BinaryFormatter to store the data in a binary format.


Saving Settings within a SQL Database :

If you are developing an application that relies on data stored within a database (i.e. the program will not function without the database) then it makes sense to store configuration settings for the application within the database as well. This allows for a distributed model where the application can be downloaded to any client machine and settings retrieved from a central source.

We need to create an implementation of the class that will handle saving to the database. I am going to create a derived class which inherits the properties of UserPreferences as well as two new methods; one for saving to the database and one for loading the data back. Since we need to load the data each time the program is run (when we instantiate the UserPrefererences class) we can put the loading code into the constructor for the class.



public class SQLUserPreferences : UserPreferences
{
public SQLUserPreferences()
{
string connectionString = "Data Source=.\\SQLEXPRESS;AttachDbFilename=\"C:\\DOCUMENTS AND SETTINGS\\TROTTT\\MY DOCUMENTS\\VISUAL STUDIO 2005\\PROJECTS\\WINDOWSAPPLICATION5\\WINDOWSAPPLICATION5\\DATABASE1.MDF\";Integrated Security=True;Connect Timeout=30;User Instance=True";
SqlConnection sqlCon = new SqlConnection(connectionString);

sqlCon.Open();
string commandString = "SELECT * FROM appSettings WHERE UserLogon = '" +
System.Environment.UserDomainName + "\\" +
System.Environment.UserName.ToString() + "'";

SqlCommand sqlCmd = new SqlCommand(commandString, sqlCon);
SqlDataReader dr = sqlCmd.ExecuteReader();

while (dr.Read())
{
// Index 0 contains the domain/username used
// as a primary key for the database.
_DisplayName = dr.GetString(1);
_Company = dr.GetString(2);
_SomeValue = dr.GetInt32(3);
}

dr.Close();
sqlCon.Close();
}

public void Save()
{
string connectionString = "Data Source=localhost; Integrated Security=SSPI; Initial Catalog=appSettings";
SqlConnection sqlCon = new SqlConnection(connectionString);

sqlCon.Open();
string commandString = "UPDATE appSettings SET " +
"DisplayName = '" + _DisplayName + "', " +
"Company = '" + _Company + "', " +
"SomeValue = " + _SomeValue +
" WHERE UserLogon = '" +
System.Environment.UserDomainName + "//" +
System.Environment.UserName + "'";

SqlCommand sqlCmd = new SqlCommand(commandString, sqlCon);
sqlCmd.ExecuteNonQuery();
sqlCon.Close();
}
}


Saving Settings to the Registry :

The Windows registry is a general purpose mechanism for storing information that is to be maintained when a Windows application terminates. The .Net framework provides a class that provides easy access to registry methods. The registry contains many locations, called keys, such as HKEY_LOCAL_MACHINE and HKEY_CURRENT_USER. These are a few of the read only base keys that contain information about users, the operating system, the software installed and the settings for the current logged on user.

We are going to create a similar derived class to the one we created for SQL Databases; in fact the technique is exactly the same. You will need to add a reference to the namespace Microsoft.Win32.


public class RegUserPreferences : UserPreferences
{
public RegUserPreferences()
{
RegistryKey UserPrefs = Registry.CurrentUser.OpenSubKey("SOFTWARE\\Your-Company-Name\\App-Name", true);

if (UserPrefs != null)
{
_DisplayName = UserPrefs.GetValue("DisplayName");
_Company = UserPrefs.GetValue("Company");
_SomeValue = UserPrefs.GetValue("SomeValue");
}
else
{
// Key did not exist so use defaults
_DisplayName = System.Environment.UserName;
_CompanyName = System.Environment.UserDomainName;
_SomeValue = 0;
}
}

public void Save()
{
RegistryKey UserPrefs = Registry.CurrentUser.OpenSubKey("SOFTWARE\\Your-Company-Name\\App-Name", true);

if (UserPrefs == null)
{
// Value does not already exist so create it
RegistryKey newKey = Registry.CurrentUser.OpenSubKey("SOFTWARE\\Your-Company-Name", true);
UserPerfs = newKey.CreateSubKey("App-Name");
}

UserPerfs.SetValue("DisplayName", _DisplayName);
UserPerfs.SetValue("Company", _Company);
UserPerfs.SetValue("SomeValue", _SomeValue);
}
}


...

C# Snippets: To Obtain Current Application Directory

From time to time you may need to access a file within the current application folder. .Net provides a property that is set to the absolute path to the application executable, and a method can be used to extract the folder name.

using System.IO;
using System.Windows.Forms;

string appPath = Path.GetDirectoryName(Application.ExecutablePath);


Console Application project types will have to manually add a reference to the System.Windows.Forms assembly for the Application object to be exposed.

C# Snippets: Beeping the PC Speaker in C#

[DllImport("Kernel32.dll")]
public static extern bool Beep(UInt32 frequency, UInt32 duration);
public static void BeepMe()
{
int Frequency = 500;
int DurationInMS = 100;
Beep(Frequency, DurationInMS);
}

..

C# Snippets: Lorem Ipsum Generator

.

C# Snippets: Foreach Loop Over Hashtable

foreach (string key in hash.Keys)
{
Console.WriteLine(key + '=' + hash[key]);
}

...

C# - Data Types and Ranges

C# supports all the major data types and more. This page lists the most common types and the ranges of values they can hold.

All minimum and maximum values can be found using (data type).MinValue and (data type).MaxValue (e.g. int.MinValue).

Type Size[Bytes] Description Minimum Maximum Example
bool 1 Named literal false true
sbyte 1 Signed byte -128 127
byte 1 Unsigned byte 0 255
short 2 Signed short integer -32768 32767
ushort 2 Unsigned short 0 65535
int 4 Signed integer -2147483648 2147483647
uint 4 Unsigned integer 0 4294967295
long 8 Signed long int -9.2233E+18 9.2233E+18
ulong 8 Unsigned long int 0 18446E+19
char 2 Unicode character, contained 0 128 a,b,4
within single quotes.
float 4 floating point -3.402823E+38 3.402823E+38 3.14159
double 8 Floating point -1.7976931E+308 1.7976931E+308 3.14159
decimal 16 Floating point, accurate to
the 28th decimal place. -7.9228E+24 7.9228E+24
object 8+ Base type for all other types n/a n/a n/a
string 20+ Immutable character array n/a n/a "Hello World"

...

C# Snippets: String to byte[ ] and byte[ ] to String

String to byte array:
public static byte[] StrToByteArray(string str)
{
System.Text.ASCIIEncoding encoding = new System.Text.ASCIIEncoding();
return encoding.GetBytes(str);
}

Byte array to string:

public static string ByteArrayToStr(byte[] byteArray)
{
System.Text.ASCIIEncoding encoding = new System.Text.ASCIIEncoding();
return encoding.GetString(byteArray);
}

C# Snippets: List Box Data Binding

Using datasets and SQL Server to bind data to controls is all very well and good, but what if you don't have a database? You could add items from an array or list using a foreach loop, but luckily there is a better way.

.Net allows you to easily bind a list object to a list box control without the need to iterate through every item in the list. This method even works for custom types such as classes or structures.

In this example I have created a custom Person structure that holds first name and last name. I then set the data source of a list box to the instance of the Person object. When the program is run, the list box will contain "John" and "Jane". For advanced data types you can set the property to be displayed using the DisplayMember property of the list box.

public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}

private void Form1_Load(object sender, EventArgs e)
{
Person[] People = new Person[] {
new Person("John","Smith"),
new Person("Jane" ,"Doe")};
lstPersons.DataSource = People;
lstPersons.DisplayMember = "FirstName";
}
}

public struct Person
{
private string firstName, lastName;

public Person(string firstName, string lastName)
{
this.firstName = firstName;
this.lastName = lastName;
}

public string FirstName
{
get
{
return firstName;
}
}

public string LastName
{
get
{
return lastName;
}
}
}
...

C# Snippets: Limit Text Box Entry to Numeric Only

private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
const char Delete = (char)8;
e.Handled = !Char.IsDigit(e.KeyChar) && e.KeyChar != Delete;
}
...

Tuesday, September 22, 2009

Q) My LoginPage needs validate the UserId & Password with the Stored data in Excel sheet?

C#:  I’m developing a Login Page for my application. Here I am using Excel sheet for the storing the user credentials.

Q1) Here, what I have to do is, when an user gives his credentials and clicks Login button,
i) Load the “USERIDS” Excel sheet into the DataTable’s Object.
ii) Now check the User Id which is given the “tbuserid” textbox with “USER_ID” column of the “USERIDS” table.
iii) If the User Id is matched, then check with the corresponding matched record’s “PASSWORD” field, [i.e., not entire PASSWORD field needs to check]

[Note: If the User Id is not matched, then no need to check the password field. And sheow the alert message with the “ErrorProvider” control]

iv) If the User Id & Password both are matched, then close this login form & open the “Form1” Form.




Q2) The Password field Textbox should be visible with the ‘*’ character.

Problem: I have getting error message when i clicking the Login button after the credentials are given.



By the following Connection string statement is used:

con1 = new OleDbConnection("Provider=Microsoft.JET.Oledb.4.0;Data Source=D:\\USERIDS.xls;Extended Properties=Excel 8.0; HDR=Yes;IMEX=1");


http://social.msdn.microsoft.com/Forums/en-US/user/threads?user=My%20Best%20Solutions

Saturday, September 19, 2009

Trick: Clearing data from all TextBox Fast

If there have lots of textboxes in the form And wants to clear the content fast, then use the following code. I assumed that all the textboxes inside a groupbox control[i.e., groupBox1].

foreach(Control ctrl in groupBox1.Controls)
{
if(ctrl is TextBox)
{
TextBox t = (TextBox)ctrl;
t.Text = String.Empty;
}
}

Note: If the textboxes are on the form directly then replace the "groupBox1.Controls" to "this.Controls".

Friday, September 18, 2009

How to Create a MS-Access DataBase file by Clicking a button in C#.Net?



string fpath=null;

private void button2_Click(object sender, EventArgs e)
{
fpath="D:\\xyz.mdb";

if (System.IO.File.Exists(fpath))
fpath = "D:\\xyz-" + DateTime.Now.ToString("dd-mm-yy") + ".mdb";

CreateDatabase(fpath); //CreateDataBase method Call
System.Diagnostics.Process.Start(fpath); //Opens the Created File
}

public static bool CreateDatabase(string fullFilename)
{
bool succeeded = false;
try
{
string newDB = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + fullFilename;
Type objClassType = Type.GetTypeFromProgID("ADOX.Catalog");

if (objClassType != null)
{
object obj = Activator.CreateInstance(objClassType);

// Create MDB file
obj.GetType().InvokeMember("Create", System.Reflection.BindingFlags.InvokeMethod, null, obj,
new object[] { "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + newDB + ";" });

succeeded = true;

// Clean up
System.Runtime.InteropServices.Marshal.ReleaseComObject(obj);
obj = null;
}
}
catch (Exception ex)
{
//Tools.ShowMessage("Could not create database file: " + fullFilename + "\n\n" + ex.Message, "Database Creation Error");
MessageBox.Show(ex.ToString());
}
return succeeded;
}

Supporting Different Versions of MS-Access's Using OLEDB Connection

Change:

// Create MDB file
obj.GetType().InvokeMember("Create", System.Reflection.BindingFlags.InvokeMethod, null, obj,
new object[]{"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + newDB + ";" });

to:
// Create MDB file
obj.GetType().InvokeMember("Create", System.Reflection.BindingFlags.InvokeMethod, null, obj,
new object[]{"Provider=Microsoft.Jet.OLEDB.4.0;Jet OLEDB:Engine Type=4;Data Source=" + newDB + ";" });


http://support.microsoft.com/kb/230501/EN-US/ shows the different versions and their constant numbers.
sqldataaccess/thread

Thursday, September 17, 2009

Q) What's Wrong in this? Getting "NullReferenceObject Exception"

C#:
I have getting "System.NullReferenceException: Object refernce not set to an instance of an object, at" .
This Exception is getting when giving the some text into the textbox's & Clicking Button of Windows Control Library form (usercontrol) which is placed the UC_submitcontrol usercontrol on the UCTestApp1 Windows Form and Execute.

See the Pictures:



Code for UC_SubmitControl1:
namespace UC_SubmitControl1
{
public partial class UC_SubmitScreen : UserControl
{
public delegate void SubmitClickHandler();
public event SubmitClickHandler SubmitbtnClicked;

public UC_SubmitScreen()
{
InitializeComponent();
}

private void btnSubmit_Click(object sender, EventArgs e)
{
if(tbText.Text.Length==0)
MessageBox.Show("Please Enter Some Text..!");
else
{
OnSubmitClicked();
}
}

protected virtual void OnSubmitClicked()
{
if (SubmitbtnClicked != null)
{
SubmitbtnClicked(); // Notify Subscribers
}
}

public string Prop_TextHere
{
get { return tbText.Text; }
set { tbText.Text = value; }
}
}
}


See the Picture for UC_TestApp1 [Windows Application]


Code for UC_TestApp1:
namespace UC_TestApp1
{
public partial class Form1 : Form
{
private UC_SubmitControl1.UC_SubmitScreen submitscrObj;
//private System.ComponentModel.Container components = null;


public Form1()
{
InitializeComponent();
}

private void uC_SubmitScreen1_SubmitbtnClicked()
{
try
{
MessageBox.Show(String.Format("Hello, {0}!", submitscrObj.Prop_TextHere));
//string aa = submitscrObj.Prop_TextHere;
//MessageBox.Show("Hello ", +aa.ToString()+" !");
//this.Close();
}
catch (Exception e)
{
MessageBox.Show(e.ToString());
this.Close();
}
}
}
}

Monday, September 14, 2009

How do i make MDI Parent & Child Forms in C#.NET as looks like as Master & Child Pages in ASP.NET?

C#:
I have to develop project that looks like "Master & child" Pages in ASP.net, i.e., "MDI-Parent & MDI-child" But here i need not want the titlebar for child form and should not have child form minimizeble (i.e, ChildForm should be fit in the content part of a MDI-Parent form).

Here my idea is, First i have to design a MDI Parent form with companies Logo picture bar & 3 buttons(Rounded Rectangular image buttons) namely "EntryForm" button, "UpdateForm" button, "ViewForm" button. In that if i clicked "EntryForm" button, then the Entryform MDI-child should be should in that MDI-Parent Form and as the same for other two buttons also. Note: Even though the MDI-Child form should works as it as independent form

Note:

At Present i'm using the Custom User controls, But getting confusions in linking the custom user control forms. I have used (designed) 3 custom controls (UC_EntryForm, UC_UpdateForm, UC_ViewForm) as a child form looks. And One Normal Window Form with BackGround Companies Logo picture and a Panel (into which the custom controls will shown) & 3 buttons. For each button has needs a code to load a specific custom user control. How?



Thursday, September 10, 2009

How to write code : for every button click, should add the Date data (taking from textbox1) into "Sample" Table which as Date field


C#:In my application program, i have textbox named "Curdate" with my prefferred format. when i click a button1, the data (from the "Curdate" textbox) is add into the "CDate" field of the Table "DateTb".
if the table have not existed, then it should be create a table "DateTb" along with a field "CDate" and add the data (as row-by row)

Note: This the same process for i need to use the ExcelSheet, Ms-Access, SQLsever2005.

How to insert a Line of data in the middle of the Existiong Text File?

class InsertMidLine11
{
static string path = "@/../../test1.txt"; //refers to bin folder
static string data = "Line5";
static int lineno = 10;

static void Main(string[] args)
{
InsertIntoFile(path,data,lineno);
}

public static void InsertIntoFile(string Path, string Data, int LineNumber)
{
StringBuilder result = new StringBuilder();
FileStream fs = new FileStream(Path, FileMode.Open, FileAccess.ReadWrite);
int lines = 0;
using (StreamReader sr = new StreamReader(fs))
{
string line;
while ((line = sr.ReadLine()) != null)
{
if (lines == (LineNumber - 1))
{
result.Append(Data);
result.Append(" | ");
}
result.Append(line);
result.Append(" | ");
lines++;
}
}
string fullstr = result.ToString();
string[] text = fullstr.Split('|');
using (StreamWriter sw = new StreamWriter(Path))
{
for (int i = 0; i < text.Length; i++)
{
string item = text[i].Trim();
sw.WriteLine(item);
Console.WriteLine(item);
}
}
}
}

That results:

Some Line1
Some Line2
Some Line3
Some Line4
Some Line5
Some Line6

Here i have to insert a Line "Some Line10" infront of the Line "Some Line5" that Looks as:

Some Line1
Some Line2
Some Line3
Some Line4
Some Line10
Some Line5
Some Line6


Note: first create test1.txt along above data and place this in the current project's bin folder.

Wednesday, September 9, 2009

Visual C# Samples, Specifications, Quick Reference and Visual C# General FAQ

http://social.msdn.microsoft.com/Forums/en-US/csharpgeneral/thread/2d666562-ed08-4461-bf92-7808913b4e96

Number to Text in console Program



namespace Number2Text01
{
class Program
{
static string str;
static void Main(string[] args)
{
Console.Write("\n Enter Three Digit number::");
int amt = int.Parse(Console.ReadLine());
int temp,i;
//static string str;
string[] Hundreds = new string[] { "One Hundred", "Two hundred", "Three Hundreds", "Four Hundreds", "Five hundred", "Six hundred", "Seven Hundreds", "Eight hundred", "Nine hundred" };
string[] Tens = new string[] { "", "Ten", "Twenty", "Thirty", "Fourty", "Fifty", "Sixty", "Seventy", "Eight", "Ninty" };
string[] Ones = new string[] {"","One","Two","Three","Four","Five","Six","Seven","Eight","Nine" };

int[] arr = new int[3];
temp=amt;
i = 0;
while (temp != 0)
{
arr[i] = (temp % 10);
temp = temp / 10;
i++;
}
i -= 1;
while (i != -1)
{
if (i == 2)
str = Hundreds[arr[i]-1];
if (i == 1)
str += " and " + Tens[arr[i]];
if (i == 0)
str +=" " + Ones[arr[i]];
i--;
}
Console.WriteLine("\n\t Given number is "+amt+" and the Text is "+str);
Console.Read();
}
}
}

Number to Text1



namespace Number2Text1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}

private void button1_Click(object sender, EventArgs e)
{
string[] ones ={"One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten", "Eleven", "Twelve", "Thirteen", "Fourteen", "Fifteen", "Sixteen", "Seventeen", "Eighteen", "Nineteen" };
string[] tens ={ "Ten", "Twenty", "Thirty", "Fourty", "Fifty", "Sixty", "Seventy", "Eighty", "Ninty" };
string[] hundreds = { "One hundred", "Two hundred", "Three hundred", "Four hundred", "Five hundred", "Six hundred", "Seven hundred", "Eight hundred", "Nine hundred" };
int Val, i;
string Res = " ";
Val = Convert.ToInt32(textBox1.Text);
if (Val > 999 && Val < 10000)
{
i = Val / 1000;
Res = ones[i-1] + " Thousand ";
Val = Val % 1000;
}
if (Val > 99 && Val < 1000)
{
i = Val / 100;
Res = Res + hundreds[i - 1];
Val = Val % 100;
}
if (Val > 19 && Val < 100)
{
i = Val / 10;
Res = Res + tens[i-1];
Val = Val % 10;
}
if (Val > 0 && Val < 20)
{
Res = Res + ones[Val-1];
textBox2.Text = Res;
}
textBox2.Text = Res;
}

private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
if (((e.KeyChar > 47 && e.KeyChar < 58)||(e.KeyChar ==8)) != true)
e.Handled = true;
}

private void button3_Click(object sender, EventArgs e)
{
textBox1.Clear();
textBox2.Clear();
textBox1.Focus();
}
}
}

Generate Random Number22



namespace RandomNoGenerate2
{
public partial class Form2 : Form
{
public Form2()
{
InitializeComponent();
}

int min, max, val = 0;
Random rdm;
bool b;
private void Form2_Load(object sender, EventArgs e)
{
for (int i = 1; i <= 30; i++)
{
comboBox1.Items.Add(i);
}

randomnoforcombo5();
}

private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
rdm = new Random();
min = Convert.ToInt32(txt_min.Text);
max = Convert.ToInt32(txt_max.Text);
val = rdm.Next(min, max);
comboBox1.Text = val.ToString();
}

private void link_Check_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
{
for (int i = 0; i < listBox2.Items.Count; i++)
{
if (comboBox2.Text == listBox2.Items[i].ToString())
{
comboBox2.BackColor = Color.Tomato;
return;
}
}
listBox2.Items.Add(comboBox2.Text);
comboBox2.BackColor = Color.White;
}

private void comboBox3_SelectedIndexChanged(object sender, EventArgs e)
{
for (int i = 0; i < listBox3.Items.Count; i++)
{
if (comboBox3.Text == listBox3.Items[i].ToString())
{
comboBox3.BackColor = Color.Tomato;
return;
}
}
listBox3.Items.Add(comboBox3.Text);
comboBox3.BackColor = Color.White;
}

private void comboBox4_SelectedIndexChanged(object sender, EventArgs e)
{
listBox4.Items.Add(comboBox4.Text);
comboBox4.Items.Remove(comboBox4.Text);
}

private void linkLabel5_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
{
Form2_Load(sender, e);
}
private void randomnoforcombo5()
{
rdm = new Random();
min = Convert.ToInt32(txt_min.Text);
max = Convert.ToInt32(txt_max.Text);
val = rdm.Next(min, max);
comboBox5.Text = val.ToString();
}
}
}

Generate Random Number2




namespace RandomNoGenerate2
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}

int min,max,val=0;
Random rdm;
bool b;
private void btn_RGenerate_Click(object sender, EventArgs e)
{
rdm = new Random();
min = Convert.ToInt32(txt_min.Text);
max = Convert.ToInt32(txt_max.Text);
val = rdm.Next(min, max);
textBox1.Text = val.ToString();
}

private void btn_Add_Click(object sender, EventArgs e)
{
b = false;
rdm = new Random();
min = Convert.ToInt32(txt_min.Text);
max = Convert.ToInt32(txt_max.Text);
val = rdm.Next(min, max);
textBox1.Text = val.ToString();

for (int i = 0; i < listBox1.Items.Count; i++)
{
if (val == Convert.ToInt32(listBox1.Items[i]))
b=true;
}
if(b)
textBox1.BackColor = Color.Red;
else
textBox1.BackColor = Color.White;

}
}
}

Generate Random Number1




namespace RandomNoGenerate1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}

private void btn_RGenerate_Click(object sender, EventArgs e)
{
Random rdm= new Random();
textBox1.Text = rdm.Next(100, 1000).ToString();
listBox1.Items.Add(textBox1.Text);
}

private void btn_Add_Click(object sender, EventArgs e)
{
//listBox1.Items.Add(textBox1.Text);
}
}

Named and optional parameters in C# 4.0


One commonly heard grievance about C# was how it did not support optional parameters. Well C# 4.0 not only has that, but you can also specify parameters by name.

Consider the following two examples :

public void RepeatText(string text, int count = 3)
{
while (count-- > 0)
{
Console.WriteLine(text);
}

Console.WriteLine();
}

public void RepeatDecoratedText(string text, string decoration = "Mr.", int count = 3)
{
while (count-- > 0)
{
Console.WriteLine("{0} {1}", decoration, text);
}

Console.WriteLine();
}

RepeatText has an optional parameter count with a default value of 3, while RepeatDecoratedText has two optional parameters. The MSIL generated for these methods are as follows (simplified, and not exact) :

.method public void RepeatText(string text, [opt] int32 count)
{
.param [2] = int32(3)

.method public void RepeatDecoratedText(string text, [opt] string decoration, [opt] int32 count)
{
.param [2] = string('Mr.')
.param [3] = int32(3)

[opt] is a parameter attribute that indicates that this parameter is optional and that the default value will be specified by .param entries. These methods can now be called as follows:

RepeatText("Nish");
RepeatText("Ant", 2);

The compiler generates code with the optional values filled in as needed:

RepeatText("Nish", 3); <-- 2nd param set via .param value RepeatText("Ant", 2); <-- No extra work needed You can also now pass an argument by name. This is particularly useful when you want to skip some optional args, but provide others. RepeatDecoratedText("Nish", count: 2); RepeatDecoratedText(count: 2, text: "Ant"); RepeatDecoratedText(decoration: "The super", count: 2, text: "Ant"); That gets compiled as: RepeatDecoratedText("Nish", "Mr." 2); RepeatDecoratedText("Ant", "Mr.", 2); RepeatDecoratedText("Ant", "The Super", 2); So basically, the parameters are either filled in via the named values provided or via the default optional values. Note that you can write optional value methods using attributes too. Example: public void RepeatTextDuplicate(string text, [Optional, DefaultParameterValue(3)] int count) { RepeatText(text, count); } // . . . RepeatTextDuplicate("Nish"); RepeatTextDuplicate("Nishant", 5); The MSIL generated for this method is identical to what you’d have got with the direct C# syntax (used earlier). As with dynamic types, apparently the biggest beneficiaries of these new named and optional parameter features are developers who interop with Office. Just like in VBScript you can now avoid having to provide optional arguments, and can also provide a named argument directly. For others, optional parameters will definitely help reduce the number of method overloads you need to write, and where there are methods that have more than a few optional parameters, the ability to call them by specifying named parameters will result in cleaner and more legible code. referred from voidnish

Tip : Flush the KeyBoard buffer in C#

Q) How to flush the keyboard buffer in a C# console application?

Sol:

Here’s a simple to do this :

private static void FlushKeyboard()
{
while (Console.In.Peek() != -1)
Console.In.Read();
}

Now you can use it as follows :

char x = (char)Console.Read();
FlushKeyboard();
char y = (char)Console.Read();
Console.WriteLine("{0}, {1}", x, y);

Even if you enter more than a single character after the first call to Read(), the second Read() will not be affected.

...

Tuesday, September 8, 2009

How to make the numeric values as left alignment in DataGridView control ?

C#:
How to show the numerical values as Left alignment in the datagridview control as making the positions of the digits (like Thousand hundreds tens ones)

How to compute the numeric values of DataGridView's Column [Field] and result value to be in next row?

C#:
In my application program, i had placed a DataGridView for tabular format. Here what i
need is to calculate the numeric values of a column which is in datagridview and the
result should be in the next row of that column and/or some other textbox named as resulttb.
For Example,[from the below figure] i need to calculate the total sum of the numeric
Field"Execution" like (15+25+2000+500000+10 = 502050)& "Sup_Execution" like
(2+2+50000+100000+100=150104) these total results should be placed in followed row of that
field and also in the resulttb textbox control.




And also i needs to calculate "Total"field(hidden) that the value get from the fields
(Execution) * (Sup_Execution) of row wise.

Followers