Thursday, May 15, 2008

.Net Windows Forms Database Connectivity with Ado .Net

Database connectivity refers to the ability of an application to connect to database system in order to store, retrieve, update or delete data.

ADO.Net is a data access technology of .Net. ADO.Net contains Managed Providers and DataSet.

Managed providers provide libraries to connect to various databases.

 Two important Managed Providers are SqlClient and OleDb.

SqlClient namespace contains classes required for interacting with SQL Server.

OleDb is used to connect to any RDBMS say Oracle, Access and even SQL Server. 

But it is recommended using SqlClient with Sql Server, since SqlClient is tailor made for Sql Server. 

SqlConnection class is used for establishing a live session between front end and back end. 

In the connection string we specify the connection options like Database instance, security mode, etc.

Connection string is passed as a constructor to the SqlConnection. 

In this example we are using Integrated Security, ie. using the windows credential for connecting to SQL Server. 

 SqlDataReader is a read-only forward only recordset. 


In the SqlCommand's constructor we are passing the SqlCommand.

 

 Inorder to create an SqlDataReader the ExecuteReader method of SqlCommand have to be used.

SqlDataReader Read() Method
After creating the SqlDataReader we use the Read method for iterating throug the SqlDataReader and filling the ListBox.

using System.Data.SqlClient;


using System.Data.SqlClient;

SqlConnection cnn; 
SqlCommand cmd; SqlDataReader dr; 
private void Form1_Load(object sender, EventArgs e)
{
    cnn = new SqlConnection("Integrated Security=sspi;Initial Catalog=Northwind");
    cnn.Open();
    cmd = new SqlCommand("select * from Categories", cnn);
    dr = cmd.ExecuteReader();
    while (dr.Read())
    {
        lstCategories.Items.Add(dr["CategoryName"].ToString());
    }
}




VB .Net


 Imports System.Data.SqlClient 

 Dim cnn As New SqlConnection 

Dim cmd As SqlCommand 

Dim dr As SqlDataReader

 Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load

 cnn = New SqlConnection("integrated security=sspi;initial catalog=Northwind; 

data source=.\sqlExpress") 

cnn.Open() 

cmd = New SqlCommand("select* from categories", cnn) 

dr = cmd.ExecuteReader() 

While (dr.Read()) 

lstCategories.Items.Add(dr("categoryName")) 

End While 

End Sub


'









Inserting Records from Front End 

For inserting records use the ExecuteNonQuery() method of SqlCommand class. 


  
 using System.Data.SqlClient; 

SqlConnection cnn; SqlCommand cmd; private void Form1_Load(object sender, EventArgs e) { 

cnn = new SqlConnection("Integrated Security=sspi;Initial Catalog=Shalvin"); 

cnn.Open(); 

 private void btnInsert_Click(object sender, EventArgs e) { 

cmd = new SqlCommand("insert into Categories values ('Condiments')", cnn); cmd.ExecuteNonQuery(); 

MessageBox.Show("Record saved"); 

}

 

VB .Net

Imports System.Data.SqlClient

Dim cnn as SqlConnection Dim cmd as SqlCommand

Private Sub Form_Load(.. cnn = new SqlConnection("Integrated Security=sspi;Initial Catalog=Shalvin") cnn.Open() End Sub

Private Sub btnInsert_Click(sender as object, e as EventArgs) .. cmd = new SqlCommand("insert into Categories values ('Condiments')", cnn)

cmd.ExecuteNonQuery() MessageBox.Show("Record saved") End Sub

Connecting to Sql Server 2005

cnn = new SqlConnection("Data Source=.\\sqlexpress;Integrated Security=sspi;Initial Catalog=Shalvin");

Inserting values of TextBox

The previous example cannot be used in real time since on clicking the button the same data will be inserted to the table. In this example we are constructing an Sql statement by concatenating the contents of TexBox as shown in the highlighted code. After inserting the values we blanking the control and bringing the focus back to the control.
using System.Data.SqlClient;

SqlConnection cnn;
SqlCommand cmd;

private void Form1_Load(object sender, EventArgs e)
{
cnn = new SqlConnection("Integrated Security=sspi;Initial Catalog=Shalvin");
cnn.Open();
}

private void btnInsert_Click(object sender, EventArgs e)
{
string strSql = "insert into Categories values ('" + txtCategoryName.Text + "')";
cmd = new SqlCommand(strSql, cnn);
cmd.ExecuteNonQuery();
MessageBox.Show("Record saved");
BlankControls();
}
private void BlankControls()
{
txtCategoryName.Text = "";
txtCategoryName.Focus();
}














DataSet DataGrid

DataSet is an offline disconnected data store. SqlDataAdapter is an intemediary between the RDBMS and DataSet. The methods of SqlDataAdapter are Fill and Update. Fill Method is used for filling a DataSet. Update Method is used synchronizing the RDBMS with changes in DataSet.
using System.Data.SqlClient;

SqlConnection cnn;
SqlDataAdapter da;
DataSet ds = new DataSet();

private void Form1_Load(object sender, EventArgs e)
{
	cnn = new SqlConnection("Integrated Security=sspi;Initial Catalog=Shalvin");

	da = new SqlDataAdapter("select * from Categories", cnn);
	da.Fill(ds, "Shalvin");
	dataGridView1.DataSource = ds.Tables["Shalvin"];
}

VB .Net

Imports System.Data Imports System.Data.SqlClient Public Class frmGrid Dim cnn As SqlConnection Dim ds As New DataSet Dim da As SqlDataAdapter Private Sub frmGrid_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load cnn = New SqlConnection("Integrated Security=sspi;Initial Catalog=Northwind") cnn.Open() da = New SqlDataAdapter("select * from Categories", cnn) da.Fill(ds, "Cat") DataGridView1.DataSource = ds.Tables("Cat") End Sub End Class

DataSet with Multiple DataTables A DataSet is a collection of DataTables along with other objects just like Database is a collection of Tables (views, stored procedures, etc.). This example requires DataGrid insted of GridView Control.

using System.Data.SqlClient; SqlConnection cnn; SqlDataAdapter da; DataSet ds = new DataSet(); private void Form1_Load(object sender, EventArgs e) { cnn = new SqlConnection("Integrated security=sspi;Initial Catalog=Northwind"); da = new SqlDataAdapter("select CategoryId, CategoryName, Description from categories", cnn); da.Fill(ds, "Cat"); da = new SqlDataAdapter("select ProductId, ProductName, UnitPrice from Products", cnn); da.Fill(ds, "Prod"); dataGrid1.DataSource = ds; }

VB .Net

Imports System.Data Imports System.Data.SqlClient Public Class frmGrid Dim cnn As SqlConnection Dim ds As New DataSet Dim da As SqlDataAdapter Private Sub frmGrid_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load cnn = New SqlConnection("Integrated Security=sspi;Initial Catalog=Northwind") cnn.Open() da = New SqlDataAdapter("select CategoryId, CategoryName, Description from Categories", cnn) da.Fill(ds, "Cat") da = New SqlDataAdapter("select ProductId, ProductName, UnitPrice from Products", cnn) da.Fill(ds, "Prod") DataGrid1.DataSource = ds End Sub

DataTable DataColumn and DataRow Visit http://shalvinpd.blogspot.com/2008/03/datatable-datacolumn-and-datarow-aspnet.html for Asp.net code of DataTable DataColum and DataRow. DataSet is an offline disconnected Data Store. DataSet is a collection of DataTables. A DataTable Contains DataRow and DataColumns. The following code illustrating creating DataTable, DataRow and DataColumn. This approached can be used for creating a temporary storage of structured data. DataTable dt = new DataTable("Purchase"); DataColumn dc; DataRow dr; private void Form1_Load(object sender, EventArgs e) { dc = new DataColumn("ProductName"); //Adding the column to the Columns colluction of DataTable dt.Columns.Add(dc); dc = new DataColumn("Price"); //Adding the column to the Columns colluction of DataTable dt.Columns.Add(dc); //Adding a new row to the table dr = dt.NewRow(); dr["ProductName"] = "Microsoft Mouse"; dr["Price"] = 400; dt.Rows.Add(dr); dgPurchase.DataSource = dt; } Creating AutoIncrement Colum for DatTable Just like Sql Server is having an identity column, we can have an auto increment column for out datatable. Set the AutoIncrement property of column to true you can optionally set the AutoIncrementSeed and AutoIncrementStep. DataTable dt = new DataTable("Purchase"); DataColumn dc; DataRow dr; private void Form1_Load(object sender, EventArgs e) { dc = new DataColumn(("Product ID"), System.Type.GetType("System.Int32")); dc.AutoIncrement = true; dc.AutoIncrementSeed = 100; dc.AutoIncrementStep = 1; dt.Columns.Add(dc); dc = new DataColumn("ProductName"); dt.Columns.Add(dc); dc = new DataColumn("Price"); dt.Columns.Add(dc); dr = dt.NewRow(); dr["ProductName"] = "Microsoft Mouse"; dr["Price"] = 400; dt.Rows.Add(dr); dr = dt.NewRow(); dr["ProductName"] = "Shalvin's C# Tutorial Video"; dr["Price"] = 4000; dt.Rows.Add(dr); dgPurchase.DataSource = dt; }

DataSet and ComboBox's DisplayMember Property

Combox's DisplayMember property is used to specify the column to display in a ComboBox.

using System.Data.SqlClient; SqlConnection cnn; SqlDataAdapter da; DataSet ds = new DataSet(); private void Form1_Load(object sender, EventArgs e) { cnn = new SqlConnection("Integrated Security=sspi;Initial Catalog=Northwind"); da = new SqlDataAdapter("select CategoryId, CategoryName, Description from Categories", cnn); da.Fill(ds, "Cat"); cboCategories.DataSource = ds.Tables["Cat"]; cboCategories.DisplayMember = "CategoryName"; }

Login Module in Windows Forms Table and Stored Procedure create table UserTable (UserId int identity(1,1) primary key, RoleId int, UserName varchar(20), Password varchar(20)) create procedure spusertable(@pMode char(1), @pUserId int = null, @pRoleId int = null, @pUserName varchar(20) = null,@ppassword varchar(20) = null) as if @pMode = 'S' select * from Usertable else if @pMode = 'I' insert into usertable values(@pRoleid,@pUsername,@ppassword) else if @pmode='D'delete from usertable where userid=@puserid go Windows Forms SqlConnection cnn; SqlCommand cmd; SqlDataReader dr; int count; private void btnLogin_Click(object sender, EventArgs e) { cmd = new SqlCommand("select count(*) from usertable where UserName = '" + txtUserName.Text + "'and password = '" + txtPassword.Text + "'", cnn); count = Int32.Parse(cmd.ExecuteScalar().ToString()); if (count != 0) { frmMain fm = new frmMain(); fm.Show(); this.Hide(); } else MessageBox.Show("Invalid User"); } }

Monday, May 12, 2008

StringBuilder Class in .Net

StringBuilder class is mutable where as String Class is immutable. The value is said to be mutable because it can be modified once it has been created by appending, removing, replacing, or inserting characters.
StringBuilder class is well suited for String Manipulation tasks.

using System.Text;

private void btnString_Click(object sender, EventArgs e)
{
StringBuilder sb = new StringBuilder();
sb.Append("Shalvin");
MessageBox.Show(sb.ToString());

sb.Insert(0, "Hello ");
MessageBox.Show(sb.ToString());

sb.Insert(6, "how are you ");
MessageBox.Show(sb.ToString());
sb.Remove(6, 8);
MessageBox.Show(sb.ToString());

sb.Replace("Shalvin", "Shalvin P D");
MessageBox.Show(sb.ToString());

MessageBox.Show(sb.Length.ToString());
}

Wednesday, April 16, 2008

Generics and Collection Initializer in .Net

Before explaining Generics lets take up an example of ArrayList.

ArrayList

using System.Collections;

int intTotal = 0;
ArrayList alMarks = new ArrayList();
private void btnTotal_Click(object sender, EventArgs e)
{
alMarks.Add(98);
alMarks.Add(99);
alMarks.Add(89);
//alMarks.Add("Shalvin");

foreach (int i in alMarks)
intTotal += i;

MessageBox.Show(intTotal.ToString());
}



'VB .Net
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Dim intTotal As Integer = 0
Dim alMarks As New ArrayList()
alMarks.Add(98)
alMarks.Add(99)
alMarks.Add(89)
For Each i As Integer In alMarks
intTotal += i
Next
MessageBox.Show(intTotal.ToString())
End Sub



It works perfectly fine. Nothing prevents you from giving a string value to array list as shown in the commented line in the code. Because an arraylist accepts parameter of type object. But when you run the application you will receive a runtime error.

Generics
Framework 2.0 introduced generic collection which as type safe collections.

List<int> intMarks = new List<int>();
private void Form1_Load(object sender, EventArgs e)
{
intMarks.Add(98);
intMarks.Add(90);
intMarks.Add(99);

int sum = 0;
foreach (int i in intMarks)
sum += i;
MessageBox.Show(sum.ToString());
}


VB.Net
Dim intMarks As New List(Of Integer)
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
intMarks.Add(98)
intMarks.Add(90)
intMarks.Add(99)

Dim sum As Integer = 0

For Each i As Integer In intMarks
sum += i
Next
MessageBox.Show(sum.ToString())
End Sub

Now if you try to give a string value to the the generic list you will get a compiler error which proves the fact that generics are type safe.

C# 3.0 Collection Initializer
With C# 3.0 it is possible to initialize a list as follows:



which is undoubtedly a great code saver.

Generic List of Custom Class

class Session
{
public string Speaker { get; set; }
public string SessionName { get; set; }
}


List<Session> glSessions = new List<Session>{
new Session{Speaker = "Shalvin P D", SessionName= "Entity Framework 4"},
new Session{Speaker="Praseed Pai", SessionName="Powershell"}};

dataGrid1.ItemsSource = glSessions;


Related Blog
Linq to Objects
Hashtable and DictionaryEntry ReadOnlyCollectionBase Class




Monday, April 14, 2008

Code Access Security - Code Snippets

Refuse writing to a drive

using System.Security.Permissions;
using System.Security;
using System.IO;

[assembly: FileIOPermissionAttribute(SecurityAction.RequestRefuse , Write="d:\\")]
[assembly:FileIOPermissionAttribute(SecurityAction.RequestMinimum, Read=@"c:\")]
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{

StreamWriter sw;
private void button1_Click(object sender, EventArgs e)
{
sw = File.CreateText("d:\\Shalvin.txt");
sw.WriteLine("Hello");
sw.Close();
}
}
}

You will receive a runtime error when you attempt to write to d:.

Tuesday, April 8, 2008

.Net Serialization (Code Snippets)

Serialization is the process of saving the state of an object into persistant medium for storage in file system, transmission over network or passing data between processes.

The serialized file is having information about the data being serialized so that on deserialization you get exactly the same data that you serialized. The data can be serialized as a binary file, xml or SOAP file.
Serialization is used for persisting complex data and not primitive types.

Binary Serializing an ArrayList
BinaryFormatter class is used for binary serializing and deserializing an object.
Create a strem to hold the serialized file. Call the Serialize method of BinaryFormatter.

using System.IO;
using System.Collections;
using System.Runtime.Serialization.Formatters.Binary;
using System.Diagnostics;

BinaryFormatter bf;
FileStream fs;
private void btnSerialize_Click(object sender, EventArgs e)
{
ArrayList al = new ArrayList();
al.Add("Shalvin");
al.Add("Aravindakshan");
fs = new FileStream("c:\\Shalvin.data", FileMode.Create);
bf = new BinaryFormatter();
bf.Serialize(fs, al);
fs.Close();
MessageBox.Show("File serialized successfully");
Process.Start("notepad", "c:\\Shalvin.data");
}

Binary Deserializing an ArrayList

using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
using System.Collections;

FileStream fs;
BinaryFormatter bf;
private void Form1_Load(object sender, EventArgs e)
{
fs = new FileStream("c:\\Shalvin.data", FileMode.Open);
bf = new BinaryFormatter();
ArrayList al = (ArrayList)bf.Deserialize(fs);
listBox1.DataSource = al;
}

Binary Serializing a Hybrid Dictionary

HybridDictionary is optimized for key-based item retrieval from both small and large collections.

using System.Collections;
using System.Collections.Specialized;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;

HybridDictionary hd;
FileStream fs;
BinaryFormatter bf;

private void Form1_Load(object sender, EventArgs e)
{
hd = new HybridDictionary();
hd.Add("Sh", "Shalvin");
hd.Add("Sa", "Saji");

foreach (DictionaryEntry de in hd)
listBox1.Items.Add(de.Key + " " + de.Value);

fs = new FileStream(@"c:\Sh.data", FileMode.Create);
bf = new BinaryFormatter();
bf.Serialize(fs, hd);
fs.Close();
}

Creating a Very Simple Contact Management Form

We will take up creating a simple data entry form of a contact management form. To make things simple I am tracking only the name and phone no. Unlike similar systems I am not making use of database.
Instead I am serializing the data in the FormClosing event.
In the form load event I am checking for the existence of the serialized file. If the file does not exist I manually creating DataTable, DataRows and DataColumns.
If the serialized file does exist then I am deserialising it and bringing the data to the grid.









































using System.IO;
using System.Runtime.Serialization.Formatters.Binary;


DataTable dt;
DataColumn dc;
DataRow dr;
BinaryFormatter bf = new BinaryFormatter();
FileStream fs;
private void Form1_Load(object sender, EventArgs e)
{
if(File.Exists("c:\\Contacts.dat"))
{
FileStream fs = new FileStream("c:\\Contacts.dat", FileMode.Open);
dt = (DataTable)bf.Deserialize(fs);
dataGridView1.DataSource = dt;
fs.Close();
}
else{
dt = new DataTable("Contacts");
dc = new DataColumn("Name");
dt.Columns.Add(dc);
dc = new DataColumn("Phone");
dt.Columns.Add(dc);

dataGridView1.DataSource = dt;
}
}
private void btnAdd_Click(object sender, EventArgs e)
{
dr = dt.NewRow();
dr["Name"] = txtName.Text;
dr["Phone"] = txtPhone.Text;
dt.Rows.Add(dr);
}
}

private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
fs = new FileStream("c:\\Contacts.dat", FileMode.Create);
bf.Serialize(fs, dt);
fs.Close();
}

XmlSerializing and Deserializing ArrayList

XML Serialization should be the choice if you are working in heterogeneous platform. The process is similar except that you use XMLSerializer of System.Xml.Serialization namespace and should specify the type using typeof at the time of initializing the XMLSerializer.

using System.IO;
using System.Collections;
using System.Xml.Serialization;
private void btnSerialize_Click(object sender, EventArgs e)
{
FileStream fs = new FileStream(@"c:\ShalvinAl.xml", FileMode.Create);
XmlSerializer xs = new XmlSerializer(typeof(ArrayList));
ArrayList al;
al = new ArrayList();
al.Add("Shalvin.com");
al.Add("shalvinpd.blogspot.com");
xs.Serialize(fs, al);
fs.Close();
MessageBox.Show("File serialized");
System.Diagnostics.Process.Start("iexplore", @"c:\ShalvinAl.xml");
}

private void btnDeserialize_Click(object sender, EventArgs e)
{
FileStream fs = new FileStream(@"c:\ShalvinAl.xml", FileMode.Open);
XmlSerializer xs = new XmlSerializer(typeof(ArrayList));
ArrayList al = (ArrayList)xs.Deserialize(fs);
listBox1.DataSource = al;
}


Serializing a Class
For serializing a class you should add the Serializable attribute to the class.
//Person.cs

[Serializable]
class Person
{
public string name;
public string Specialization;

public Person(string _name, string _Specialization)
{
name = _name;
Specialization = _Specialization;
}
public Person() { }

public override string ToString()
{
return name + " is Specializting in " + Specialization ;
}
}

using System.Runtime.Serialization.Formatters.Binary;
using System.IO;
private void btnSerialize_Click(object sender, EventArgs e)
{
Person sp = new Person("Shalvin", "ASP.Net");

// Create file to save the data to
FileStream fs = new FileStream("c:\\Person.Dat", FileMode.Create);

// Create a BinaryFormatter object to perform the serialization
BinaryFormatter bf = new BinaryFormatter();

// Use the BinaryFormatter object to serialize the data to the file
bf.Serialize(fs, sp);

// Close the file
fs.Close();

System.Diagnostics.Process.Start("notepad", "c:\\Person.Dat");
}

Windows Generated Code for Contact Management System


private void InitializeComponent()
{
this.btnAdd = new System.Windows.Forms.Button();
this.dataGridView1 = new System.Windows.Forms.DataGridView();
this.txtPhone = new System.Windows.Forms.TextBox();
this.txtName = new System.Windows.Forms.TextBox();
this.label2 = new System.Windows.Forms.Label();
this.label1 = new System.Windows.Forms.Label();
this.SuspendLayout();
//
// btnAdd
//
this.btnAdd.Location = new System.Drawing.Point(209, 58);
this.btnAdd.Name = "btnAdd";
this.btnAdd.Size = new System.Drawing.Size(29, 23);
this.btnAdd.TabIndex = 11;
this.btnAdd.Text = "+";
this.btnAdd.UseVisualStyleBackColor = true;
this.btnAdd.Click += new System.EventHandler(this.btnAdd_Click);
//
// dataGridView1
//
this.dataGridView1.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize;
this.dataGridView1.Location = new System.Drawing.Point(26, 87);
this.dataGridView1.Name = "dataGridView1";
this.dataGridView1.Size = new System.Drawing.Size(240, 150);
this.dataGridView1.TabIndex = 10;
//
// txtPhone
//
this.txtPhone.Location = new System.Drawing.Point(103, 61);
this.txtPhone.Name = "txtPhone";
this.txtPhone.Size = new System.Drawing.Size(100, 20);
this.txtPhone.TabIndex = 9;
//
// txtName
//
this.txtName.Location = new System.Drawing.Point(103, 29);
this.txtName.Name = "txtName";
this.txtName.Size = new System.Drawing.Size(100, 20);
this.txtName.TabIndex = 8;
//
// label2
//
this.label2.AutoSize = true;
this.label2.Location = new System.Drawing.Point(52, 68);
this.label2.Name = "label2";
this.label2.Size = new System.Drawing.Size(38, 13);
this.label2.TabIndex = 7;
this.label2.Text = "Phone";
//
// label1
//
this.label1.AutoSize = true;
this.label1.Location = new System.Drawing.Point(52, 36);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(35, 13);
this.label1.TabIndex = 6;
this.label1.Text = "Name";
//
// Form1
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(292, 266);
this.Controls.Add(this.btnAdd);
this.Controls.Add(this.dataGridView1);
this.Controls.Add(this.txtPhone);
this.Controls.Add(this.txtName);
this.Controls.Add(this.label2);
this.Controls.Add(this.label1);
this.Name = "Form1";
this.Text = "Shalvin Contact Management System";
this.FormClosing += new System.Windows.Forms.FormClosingEventHandler(this.Form1_FormClosing);
this.Load += new System.EventHandler(this.Form1_Load);
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private System.Windows.Forms.Button btnAdd;
private System.Windows.Forms.DataGridView dataGridView1;
private System.Windows.Forms.TextBox txtPhone;
private System.Windows.Forms.TextBox txtName;
private System.Windows.Forms.Label label2;
private System.Windows.Forms.Label label1;



Related Blogs
System.IO Namespace in .Net


Happy Programming
shalvin.com

Sunday, April 6, 2008

System.IO Namespace in .Net

Streams are the means for reading from and writing to the disk and communicating across the network.
Knowledge of working with streams is very essential. Make sure you master these skills before venturing into Cryptography, Compression, Serialization, etc.
File and Directory classes of System.IO namespace contains static method for working with Files and Directories.

Creating a text file and writing to it

The following example demonstrates the easiest way to create a file and writing into it using StreamWriter class.

using System.IO;

StreamWriter sw;
private void btnCreateText_Click(object sender, EventArgs e)
{
sw = File.CreateText(@"f:\ShalvinPD.txt");
sw.WriteLine("Shalvin P D");
sw.WriteLine("Web site : shalvin.com");
sw.Close();
}


















StreamReader class for reading from a file










StreamReader sr = new StreamReader("f:\\ShalvinPD.txt");
txtData.Text = sr.ReadToEnd();



Creating an Html Page on Fly

Certain job sites creates as web page for you based on the information you provided about yourself. Let's see how to do it in .Net.

using System.IO;







Creating an Asp .Net Page on Fly






Creating, Deleting and Checking for the existence of a Directory

Directory class can be used for typical operations such as copying, moving, renaming, creating, and deleting directories.
private void btnCreate_Click(object sender, EventArgs e)
{
Directory.CreateDirectory("c:\\Shalvin");

}

private void btnExist_Click(object sender, EventArgs e)
{
if (Directory.Exists("c:\\Shalvin"))
MessageBox.Show("Directory exist");
else
MessageBox.Show("Directory doesn't exist");
}

private void btnDeletingDirectory_Click(object sender, EventArgs e)
{
if (Directory.Exists("c:\\Shalvin"))
{
Directory.Delete("c:\\Shalvin");
MessageBox.Show("Directory deleted successfully");
}
else
MessageBox.Show("Directory doesn't exist");
}
}

Listing All Drives

Listing all drives is as simple as creating an array of DriveInfo class, calling the DriveInfo.GetDrives methos and Iteraing throught the DriveInfo collection.

StreamWriter sw;
private void Form1_Load(object sender, EventArgs e)
{
DriveInfo[] diDrives = DriveInfo.GetDrives();
foreach (DriveInfo diDrive in diDrives)
listBox1.Items.Add(diDrive);
}


Retriving the Drive Type, Free Space and Total Size of Drives

StreamWriter sw;
private void Form1_Load(object sender, EventArgs e) {
try
{
DriveInfo[] diDrives = DriveInfo.GetDrives();
foreach (DriveInfo diDrive in diDrives)
{
listBox1.Items.Add(diDrive);
listBox1.Items.Add(String.Format("Drive Type : {0}", diDrive.DriveType));
listBox1.Items.Add(String.Format("Free Space : {0}", diDrive.AvailableFreeSpace));
listBox1.Items.Add(String.Format("Total Size : {0}", diDrive.TotalSize)); listBox1.Items.Add(" ");
}
}
catch (Exception ex) { }
}

Writing to a BinaryFile using BinaryWriter Class







BinaryReader and BinaryWriter Classes can be used to store and retrieve primitive datatypes like Integer, string, etc. as binary file.








using System.IO;


BinaryWriter objBinaryWriter;
BinaryReader br;
FileStream fs;

private void btnCreate_Click(object sender, EventArgs e)
{
try
{
fs = new FileStream(@"c:\Shalvin.data", FileMode.Create);
objBinaryWriter = new BinaryWriter(fs);


objBinaryWriter.Write(98);
objBinaryWriter.Write(88);
objBinaryWriter.Write(99);

objBinaryWriter.Close();
fs.Close();

MessageBox.Show("Binary file created successfully");
}
catch (IOException ioe)
{
MessageBox.Show("Device is not ready");
}
catch (Exception ex)
{
MessageBox.Show(ex.Message.ToString());
}
}




































Adding Line Number to a File

using System.IO;


StreamReader sr = new StreamReader("c:\\Code.txt");
StreamWriter sw = new StreamWriter("c:\\S1.txt");
private void button1_Click(object sender, EventArgs e)
{
int i = 1;
while (! sr.EndOfStream)
{
string s = sr.ReadLine();
sw.WriteLine(i.ToString() + " " + s);
i++;
}
sw.Close();
System.Diagnostics.Process.Start("notepad", "c:\\S1.txt");
}

































































Picture Viewer

































using System.IO;
using System.Collections;

ArrayList al = new ArrayList();



int i;
private void Form1_Load(object sender, EventArgs e)
{
DirectoryInfo di = new DirectoryInfo("c:\\");
FileInfo[] fi = di.GetFiles();
foreach (FileInfo f in fi)
if (f.Extension == ".jpg")
{
listBox1.Items.Add(f.FullName);
al.Add(f.FullName);
}
}
private void listBox1_SelectedIndexChanged(object sender, EventArgs e){
pictureBox1.Load(listBox1.Text);
}
private void btnNext_Click(object sender, EventArgs e)
{
if (i < al.Capacity - 1)
{
pictureBox1.Load(al[i].ToString());
i++;
}
else
MessageBox.Show("End of file");
}






Generating Text File from Database Table






using System.Data.SqlClient;
using System.IO;




SqlConnection cnn;
SqlCommand cmd;
SqlDataReader dr;
StreamWriter sw = new StreamWriter("c:\\Categories.txt");
private void Form1_Load(object sender, EventArgs e)
{
cnn = new SqlConnection("Integrated Security=sspi;Initial Catalog=Northwind");
cnn.Open();
cmd = new SqlCommand("select * from Products", cnn);
dr = cmd.ExecuteReader();
while (dr.Read())
sw.WriteLine(String.Format("{0} \t {1} ", dr["ProductId"], dr["ProductName"].ToString()));
sw.Close();
System.Diagnostics.Process.Start("notepad", "c:\\Categories.txt");
}

VB.Net


Imports System.Data.SqlClient
Imports System.IO
Imports System.Diagnostics


Dim cnn As SqlConnection
Dim cmd As SqlCommand
Dim dr As SqlDataReader
Dim sw As New StreamWriter("c:\\Products.txt")
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
cnn = New SqlConnection("Integrated security=sspi;Initial Catalog=Northwind")
cnn.Open()
cmd = New SqlCommand("select * from products", cnn)
dr = cmd.ExecuteReader
While (dr.Read())
sw.WriteLine(String.Format("{0} {1} {2} {1} {3}", dr("ProductID"), vbTab, dr("ProductName"), dr("UnitPrice")))
End While
sw.Close()
Process.Start("notepad", "c:\\Products.txt")
End Sub


Output






















Parsing a Tab Delimited Text File





using System.IO;
StreamReader sr = new StreamReader("c:\\Categories2.txt");
private void Form1_Load(object sender, EventArgs e)
{
while (!sr.EndOfStream)
{
string s = sr.ReadLine();
string[] sa = s.Split('\t');
listBox1.Items.Add(sa[0]);
listBox2.Items.Add(sa[1]);
listBox3.Items.Add(sa[2]);
}
}

VB .Net

Imports System.IO

Dim sr As New StreamReader("c:\\Produc.txt")
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
While Not sr.EndOfStream
Dim s As String = sr.ReadLine
Dim sa() = s.Split(vbTab)
ListBox1.Items.Add(sa(0))
ListBox2.Items.Add(sa(1))
ListBox3.Items.Add(sa(2))
End While
End Sub

Related Blogs






Isolated Storage (Code Snippets)







.Net Serialization







Gdi+ Code Snippets

Gdi+ DrawString, DrawLine and DrawRectangle

private void Form1_Paint(object sender, PaintEventArgs e)
{
Graphics g = e.Graphics;
g.DrawString("Shalvin.com", Font, Brushes.Blue, 50, 50);
g.DrawLine(Pens.Red , 50, 50, 200, 50);
Rectangle rect = new Rectangle(50, 100, 200,200);
g.DrawRectangle(Pens.Blue, rect);
}

VB .Net
Private Sub Form1_Paint(ByVal sender As System.Object, ByVal e As System.Windows.Forms.PaintEventArgs) Handles MyBase.Paint
Dim g As Graphics = e.Graphics
g.DrawString("Shalvin.com", Font, Brushes.Blue, 50, 50)
g.DrawLine(Pens.Red, 50, 50, 200, 50)
Dim rect As Rectangle = New Rectangle(50, 100, 200, 200)
g.DrawRectangle(Pens.Blue, rect)
End Sub
























FillEllipse and FillRectangle
private void Form1_Paint(object sender, PaintEventArgs e)
{
Graphics g = e.Graphics;
g.FillRectangle(Brushes.Blue, 50, 50, 100, 100);
g.FillEllipse(Brushes.Yellow, 50, 150, 150, 200);
}

VB .Net
Private Sub Form1_Paint(ByVal sender As System.Object, ByVal e As System.Windows.Forms.PaintEventArgs) Handles MyBase.Paint
Dim g As Graphics = e.Graphics
g.FillRectangle(Brushes.Blue, 50, 50, 100, 100)
g.FillEllipse(Brushes.Yellow, 50, 150, 150, 200)
End Sub

DrawPie

private void Form1_Paint(object sender, PaintEventArgs e)
{
Graphics g = e.Graphics;
g.DrawPie(Pens.Blue, 50, 50, 100, 100, 0, 90);
}

VB .Net
Private Sub Form1_Paint(ByVal sender As System.Object, ByVal e As System.Windows.Forms.PaintEventArgs) Handles MyBase.Paint
Dim g As Graphics = e.Graphics
g.DrawPie(Pens.Blue, 50, 50, 100, 100, 0, 90)
End Sub





































AntiAlias
using System.Drawing.Drawing2D;

private void Form1_Paint(object sender, PaintEventArgs e)
{
Graphics g = e.Graphics;
g.SmoothingMode = SmoothingMode.AntiAlias;
g.DrawLine(Pens.Red, 50, 50, 200, 50);
g.DrawLine(Pens.Blue, 50, 50, 500, 400);
}



















Circle Form with GraphicsPath Class

GraphicsPath is a collection of lines and paths which can be used to draw the outlines of shapes, fill the interiors of shapes, etc.

using System.Drawing.Drawing2D;

private void Form1_Paint(object sender, PaintEventArgs e)
{
GraphicsPath gp;
gp = new GraphicsPath();
gp.AddEllipse(new Rectangle(5, 5, this.Width - 15, this.Height - 15));

this.Region = new Region(gp);
}


VB .Net

Imports System.Drawing.Drawing2D

Public Class Form1

Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load

Dim gp As GraphicsPath
gp = New GraphicsPath
gp.AddEllipse(New Rectangle(0, 0, Me.Width - 40, Me.Height - 40))
gp.AddEllipse(New Rectangle(20, 0, 40, Me.Height - 40))
Me.Region = New Region(gp)
End Sub

End Class



Related Blog
Gdi+ Brushes Code Snippets


Wednesday, April 2, 2008

VB.Net : The Console Way

Though C# is my favorite language I never under estimated VB.Net. In fact my expertise on VB.Net paid me dividends in the programming career.

So event if you are a C# programmer I will strongly recommend learning VB.Net because the best .Net resources are in VB .Net. Examples are dotnetnuke and Asp.Net Unleashed by Stephen Walther.

Instead of taking the Visual Studio approach I am taking the Console and Notepad way. By doing so one can be well versed with the internals of the language.
Also instead of using the Visual Studio Command Prompt and using the Dos Command Prompt.
For doing so am copying a folder called v2.0.50727 from C:\WINDOWS\Microsoft.NET\Framework folder and pasting it in d:. This folder is the .Net Framework 2.o folder which is a an important folder. So instead of inadvertently removing any filed this approach is the better approach instead of going for PATH command.
I am renaming the folder to say DotNet.

Simple Console Application
Now open notepad and type the following code :

Public Class Hello
Shared Sub Main
System.Console.WriteLine("Hello")
End Sub
End Class

Save it as say 1Hello.vb.
Now open the command prompt cd to the newly rename folder that is DotNet and give the vbc (Visual Basic compiler) command followed by the file name.
If there are no errors it will create an exe with the same name that of the file name and you can invoke the exe by typing the name of the exe.














In this example we are creating an class library and inside the class library a Main method. Here the Main method is Shared which is equivalent to static in C#. It denotes that one need not create an instance of class for invoke this method.

It is followed by statement System.Console.WriteLine("Hello") which is meant for displaying Hello message in the command prompt.

Here System is a namespace, Console is a class and WriteLine is a method.

Memory Variable and String Concatenation

Public Class Hello
Shared Sub Main
Dim strName as String
System.Console.WriteLine("Enter your name : ")
strName = System.Console.ReadLine()
System.Console.WriteLine("Hello " & strName)
End Sub
End Class

For declaring a memory variable in VB .Net the syntax is Dim as DataType. The string concatenation operator in &.

Integer Memory Variable

Imports system

Class Cal
Shared Sub Main
Dim i,j,res as integer

Console.WriteLine("Integer 1 : ")
i= Console.ReadLine()

Console.WriteLine ("Integer 2 :")
j= Console.ReadLine()
res =i+j

Console.WriteLine("Sum : " + res.ToString())
End Sub
End Class

Function
Imports system
Class FunctionEg
Shared Sub Main
Dim res as IntegerConsole.WriteLine("Enter value : ")
res = Sqrt(Console.Read())
Console.WriteLine("Square Root is " + res.ToString)
End Sub

Public Shared Function Sqrt(i as Integer) As Integer
return i * i
End Function
End Class











Creating a Form

Imports System.Windows.Forms
Public Class frmHello
Inherits Form

Shared Sub Main
Application.Run(new frmHello)
End Sub
End Class

.Net is having a namespace called System.Windows.Forms. For creating a form you can create a class which inherits from Form class of System.Windows.Forms.
Application.Run(new frmHello)
Begins running a standard application message loop on the current thread, and makes the frmHello visible.

Class Constructor
Imports System.Windows.Forms

Public Class frmHello
Inherits Form

Dim btnHello As Button
Shared Sub Main
Application.Run(new frmHello)
End Sub

Sub New
Me.Text = "shalvin.com"
End Sub

End Class

Constructors are used to initialize a class and is the first method that is called when an instance of class is created.
To create a constructor in VB .Net create a procedure name Sub New.

Adding Controls to Form
Imports System.Windows.Forms

Public Class frmHello
Inherits Form

Dim btnHello As Button
Shared Sub Main
Application.Run(new frmHello)
End Sub

Sub New
Me.Text = "shalvin.com"

btnHello = new Button
btnHello.Text = "Hello"
Me.Controls.Add(btnHello)
End Sub

End Class

In this example we are creating an Object variable of type Button, setting it's text property and adding it into the Controls collection of the form.

Event Handling
Imports System.Windows.Forms

Public Class frmHello
Inherits Form

Dim WithEvents btnHello As Button
Shared Sub Main
Application.Run(new frmHello)
End Sub

Sub New
Me.Text = "shalvin.com"

btnHello = new Button
btnHello.Text = "Hello"
Me.Controls.Add(btnHello)
End Sub

Private sub btnHello_Click(sender As Object, e As EventArgs) Handles btnHello.Click
MessageBox.Show("shalvin.com")
End Sub
End Class



Related Blog


.Net Intermediate Language