Showing posts with label C#. Show all posts
Showing posts with label C#. Show all posts

Sunday, May 12, 2024

C# 12

C# is a popular cross platform programming language used to creating wide ranging of applications like Web, Desktop, or Mobile. 

 

You can create a C# application using wide range of options like  Visual Studio or  Visual Studio Code.

Here I am concentrating on .Net CLI with Visual Studio Code.


.Net CLI

.Net CLI (Command Line Interface) can be used to create and build .Net application.




 




As mentioned in the options dotnet -h or dotnet --help can be use to display .net help.









Creating a .Net CLI Console project.


 dotnet new console -o HelloConsole  

 

This command creates a console application within a folder called HelloConsole inside the current folder.








code . opens the current folder which comprises of the project in Visual Studio Code.


Top Level Statement


Program.cs file within project contains WriteLine method of Console class for displaying a message in the command prompt. 

C# follows Pascal case. Identifiers should stat with capital letter. So Console's C, WriteLine's W and L should be capital.

 Console.WriteLine("Hello Shalvin P D");  
Memory Variable
 string name = "Shalvin P D";  
 Console.WriteLine("Hello, {0}", name);  
Interpolation
 string name = "Shalvin";  
 Console.WriteLine($"Hello {name}");  
Multiple Memory Variable
 string name = "Shalvin";  
 string location = "Kochi";  
 Console.WriteLine($"Hello {name}, located at {location}.");  
Memory Variable Console.ReadLine
 string name;  
 Console.WriteLine("Enter your Name: ");  
 name = Console.ReadLine();  
 Console.WriteLine($"Hello {name}");  
Multiple String Memory Variables
 string name, location;  
 Console.WriteLine("Enter your Name: ");  
 name = Console.ReadLine();  
 Console.WriteLine("Enter your Location: ");  
 location = Console.ReadLine();  
 Console.WriteLine($"Hello {name}, located at {location}.");  
Integer Memory Variable
 int i, j, res;  
 i = 23;  
 j = 45;  
 res = i + j;  
 Console.WriteLine(res);  
Int32.Parse (Simple Calculator)
 int i, j, res;  
 Console.WriteLine("Enter Value 1: ");  
   i = Int32.Parse(Console.ReadLine());  
 Console.WriteLine("Enter Value 2: ");  
   j = Int32.Parse(Console.ReadLine());  
 res = i + j;  
 Console.WriteLine(res);  
If Statement
 string city;  
 Console.WriteLine("Enter the Name of the City: ");  
 city = Console.ReadLine();  
 if (city == "Kochi")  
 {  
   Console.WriteLine("Industrial Capital of Kerala");  
 }  
If else
 string city;  
 Console.WriteLine("Enter the Name of the City: ");  
 city = Console.ReadLine();  
 if (city == "Kochi")  
 {  
   Console.WriteLine("Industrial Capital of Kerala");  
 }  
 else  
 {  
   Console.WriteLine("I don't know");  
 }  
Multiple else if
 string city;  
 Console.WriteLine("Enter the Name of the City: ");  
 city = Console.ReadLine();  
 if (city == "Kochi")  
 {  
   Console.WriteLine("Industrial Capital of Kerala");  
 }  
 else if (city == "Trichur")  
 {  
   Console.WriteLine("Cultural Capital of India");  
 }  
 else if (city == "Trivandrum")  
 {  
   Console.WriteLine("Capital of Kerala");  
 }  
 else  
 {  
   Console.WriteLine("I don't know");  
 }  

Wednesday, October 14, 2009

Simple Contact Management System In C# and VB .Net

create database ContactManagement

use ContactManagement

create table ContactGroups(GroupId int primary key, GroupName varchar(40))

select * from ContactGroups

insert into ContactGroups values (1, 'Students')
insert into ContactGroups values (2, 'Relatives')

create table Contacts (ContactId int primary key, GroupId int references ContactGroups(GroupId), ContactName varchar(40), Phone varchar(15), Email varchar(40))

insert into Contacts values (1, 1, 'Sumesh S', '9961321010', 'mail4sumo@yahoo.co.in')

insert into Contacts values (2, 1, 'Nithin T M', '9446737393', 'nithintm@gmail.com')

insert into Contacts values (3, 2, 'Shalvin', '998765778', 'shalvin@gmail.com')

select * from Contacts

select G.GroupName, C.ContactName, C.Phone, C.Email from
ContactGroups G, Contacts C where G.GroupId = C.GroupId













































I am adding a class called DbConnect which is to contain Database Connectivity and retrieval code.

using System.Data;
using System.Data.SqlClient;
namespace ContactManagementSystem
{

class DbConnect
{
public SqlConnection cnn;
public void Open()
{
cnn = new SqlConnection("Integrated Security=sspi;Initial Catalog=ContactManagement");
cnn.Open();
}

public DataTable GetGroups()
{
Open();
DataSet ds = new DataSet();
SqlDataAdapter da = new SqlDataAdapter("select * from ContactGroups", cnn);
da.Fill(ds, "Grp");
return ds.Tables["Grp"];
}
}

frmGroups
























Please visit my blog Windows Forms Input Validation if your are not familiar with Validation event and ErrorProvider Control.


using System.Data.SqlClient;
DbConnect dbc = new DbConnect();
Boolean b = false;
int intMax = 0;
SqlCommand cmd;

private void frmGroups_Load(object sender, EventArgs e)
{
dbc.Open();
cmd = new SqlCommand("select Max(GroupId) from ContactGroups", dbc.cnn);
b = Int32.TryParse(cmd.ExecuteScalar().ToString(), out intMax);
intMax += 1;

ShowData();
}

private void ShowData()
{
dgvGroups.DataSource = dbc.GetGroups();

}


private void btnAdd_Click(object sender, EventArgs e)
{
cmd = new SqlCommand("insert into ContactGroups values (" + intMax.ToString() + ", '" + txtContactGroup.Text + "')", dbc.cnn);
cmd.ExecuteNonQuery();
MessageBox.Show("Record Saved");
ShowData();
}



private void txtContactGroup_Validating(object sender, CancelEventArgs e)
{
if (txtContactGroup.Text == "")

{
errorProvider1.SetError(txtContactGroup, "Group Name cannot be blank");
txtContactGroup.Focus();
}
else
{
errorProvider1.SetError(txtContactGroup, "");
}

}

Obviously creating an sql statement for passing to SqlCommand is not the right approach. But let me keep it simple and short and not end up in feature creep. I will take up the better approach in a later blog.

frmContact
























Now let's come to the child table data insertion.

using System.Data.SqlClient;

DbConnect dbc = new DbConnect();
SqlCommand cmd;
Boolean b = false;
int intMax = 0;

private void frmContacts_Load(object sender, EventArgs e)
{
dbc.Open();
cboGroup.DataSource = dbc.GetGroups();
cboGroup.DisplayMember = "GroupName";
cboGroup.ValueMember = "GroupId";
}


private void btnSave_Click(object sender, EventArgs e)
{
dbc.Open();
cmd = new SqlCommand("select Max(ContactId) from Contacts", dbc.cnn);
b = Int32.TryParse(cmd.ExecuteScalar().ToString(), out intMax);
intMax += 1;

cmd = new SqlCommand("insert into Contacts values (" + intMax.ToString() + ", " + cboGroup.SelectedValue.ToString() + ", '" + txtContact.Text + "', '" + txtPhone.Text + "', '" + txtEmail.Text + "')", dbc.cnn);
cmd.ExecuteNonQuery();
MessageBox.Show("Record Saved");
}


VB .Net Code

'DbConnect - Class Module

Imports System.Data.SqlClient
Public Class DbConnect
Public cnn As SqlConnection

Public Sub Open()
cnn = New SqlConnection("Integrated Security=sspi;Initial Catalog=ContactManagement")
cnn.Open()
End Sub

Public Function GetGroups() As DataTable
Open()
Dim da As New SqlDataAdapter("select * from ContactGroups", cnn)
Dim ds As New DataSet
da.Fill(ds, "Grp")
Return ds.Tables("Grp")
End Function

Public Function GetContacts() As DataTable
Open()
Dim strSql As String
strSql = "select G.GroupName, C.ContactName, C.Phone, C.Email " strSql += "from ContactGroups G, Contacts C where G.GroupId = C.GroupId"
Dim da As New SqlDataAdapter(strSql, cnn)
Dim ds As New DataSet
da.Fill(ds, "Grp")
Return ds.Tables("Grp")
End Function

End Class

'frmMain

Private Sub ExitToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ExitToolStripMenuItem.Click
Close()
End Sub

Private Sub GroupsToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles GroupsToolStripMenuItem.Click
Dim fg As New frmGroups
fg.MdiParent = Me fg.Show()
End Sub

Private Sub ContactsToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ContactsToolStripMenuItem.Click
Dim fc As New frmContacts
fc.MdiParent = Me fc.Show()
End Sub


'frmContactGroups

Imports System.Data.SqlClient

Public Class frmGroups

Dim dbc As New DbConnect
Dim cmd As SqlCommand
Dim intMax As Integer
Dim b As Boolean
Dim be As Boolean = False
Private Sub frmGroups_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load dbc.Open()
IncrementId()
FillGroups()
End Sub

Private Sub IncrementId()
cmd = New SqlCommand("select Max(GroupId) from ContactGroups", dbc.cnn)
b = Int32.TryParse(cmd.ExecuteScalar().ToString(), intMax)
intMax += 1
End Sub

Private Sub FillGroups()
lstGroups.DataSource = dbc.GetGroups
lstGroups.DisplayMember = "GroupName"
End Sub

Private Sub btnAdd_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnAdd.Click
If be = True Then IncrementId()
End If
cmd = New SqlCommand("insert into ContactGroups values (" + intMax.ToString + ", '" + txtGroup.Text + "')", dbc.cnn)
cmd.ExecuteNonQuery()
MessageBox.Show("Record Saved")
FillGroups()
BlankControls()
be = True
End Sub

Private Sub BlankControls()
txtGroup.Text = "" txtGroup.Focus()
End Sub
End Class


'frmContacts
Imports System.Data.SqlClient

Public Class frmContacts

Dim dbc As New DbConnect
Dim cmd As SqlCommand
Dim intMax As Integer
Dim b As Boolean
Dim be As Boolean = False

Private Sub frmContacts_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
FillGroupsCombo()
IncrementId()
FillContactsGrid()
End Sub

Private Sub FillGroupsCombo()
cboGroups.DataSource = dbc.GetGroups
cboGroups.DisplayMember = "GroupName"
cboGroups.ValueMember = "GroupId"
End Sub

Private Sub IncrementId()
cmd = New SqlCommand("select Max(ContactId) from Contacts", dbc.cnn)
b = Int32.TryParse(cmd.ExecuteScalar().ToString(), intMax)
intMax += 1
End Sub

Private Sub btnAdd_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnAdd.Click
If be = True Then IncrementId()
End If
cmd = New SqlCommand("insert into Contacts values (" + intMax.ToString() + ", " + cboGroups.SelectedValue.ToString + ", '" + txtContact.Text + "', '" + txtPhone.Text + "', '" + txtEmail.Text + "')", dbc.cnn)
cmd.ExecuteNonQuery()
MessageBox.Show("Record Saved")
FillContactsGrid()
be = True
End Sub

Private Sub FillContactsGrid()
DataGridView1.DataSource = dbc.GetContacts
End Sub

Related Blog
Contact Management System VB .Net Windows Generated Code

Wednesday, July 29, 2009

String Formatting Resources

http://blog.stevex.net/index.php/string-formatting-in-csharp/

Query Analyser with C# Beta

































I am not basically a fan of Sql Server 2005 Management Studio mainly because of its compatibility issues and high overhead.


So I thought of creating a simple query tool. Here is the code.




using System.Data.SqlClient;
namespace TreeView_in_Split_Container
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
SqlConnection cnn, cnn2;
SqlCommand cmd;
SqlDataReader dr, dr2;
List<string> glsdb = new List<string>();
string strDbCnn;
private void Form1_Load(object sender, EventArgs e)
{
cnn = new SqlConnection(@"integrated Security=sspi;Initial Catalog=master;Data Source=.\sqlexpress");
cnn.Open();
cmd = new SqlCommand("sp_helpdb",cnn);
dr = cmd.ExecuteReader();
treeView1.Nodes.Add("Database");
while (dr.Read())
{
glsdb.Add(dr["Name"].ToString());
treeView1.TopNode.Nodes.Add(dr["Name"].ToString());
comboBox1.Items.Add(dr["Name"].ToString());
}
dr.Close();
}





Database Combo Selection
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
cnn = new SqlConnection(@"integrated Security=sspi;Data Source=.\sqlexpress;Initial Catalog=" + comboBox1.Text );
cnn.Open();
}


Object Browser


The project make use of two Context Menu dataContext and contextMenuStrip1. First for database related options like Create Database whose functionality is yet to be implemented. second for table related options like Show Table Data.






private void treeView1_NodeMouseClick(object sender, TreeNodeMouseClickEventArgs e)
{
try
{
TreeNode tempNode = treeView1.GetNodeAt(e.X, e.Y);
treeView1.SelectedNode = tempNode;
if (treeView1.SelectedNode.Level == 1)
{
treeView1.ContextMenuStrip = null;
strDbCnn = (@"integrated Security=sspi;Data Source=.\sqlexpress;Initial Catalog=" + tempNode.Text);
cnn2 = new SqlConnection(strDbCnn);
cnn2.Open();
cmd = new SqlCommand("select * from sysobjects where xtype = 'u'", cnn2);
dr2 = cmd.ExecuteReader();
treeView1.SelectedNode.Nodes.Clear();
while (dr2.Read())
{
treeView1.SelectedNode.Nodes.Add(dr2[0].ToString());
}
cnn2.Close();
dr2.Close();
}
else if (treeView1.SelectedNode.Level == 0)
{
treeView1.ContextMenuStrip =DataContext;
}
else if (treeView1.SelectedNode.Level == 2)
{
treeView1.ContextMenuStrip = contextMenuStrip1;
}
}
catch (Exception exp)
{
MessageBox.Show(exp.Message);
}
}



Execute Button Click Code
private void button1_Click(object sender, EventArgs e)
{
try
{
string strSql = "";
if (textBox1.SelectedText != "")
strSql = textBox1.SelectedText;
else
strSql = textBox1.Text;

string strtmp = strSql;
string[] ss = strSql.Split(new char[]{' '});

if(ss[0].Equals("Use"))
{
richTextBox1.Text = "Database context changed to" + ss[1];
return;
}


cmd = new SqlCommand(strSql, cnn);
dr = cmd.ExecuteReader();
richTextBox1.Text = "";
int irf = dr.RecordsAffected;
while (dr.Read())
{

for (int i = 0; i < dr.FieldCount; i++)
{

richTextBox1.Text += dr[i].ToString() + "\t";

}

richTextBox1.Text += "\n";


}
if (irf > 0)
{
richTextBox1.Text += irf + " records affected";
}
dr.Close();
}
catch (Exception ex)
{
richTextBox1.Text += ex.Message.ToString();
}
}



Showing the SELECT result in Grid View


private void showDataToolStripMenuItem_Click(object sender, EventArgs e)
{

DataGrid d1 = new DataGrid();
d1.Dock = DockStyle.Fill;
cnn2 = new SqlConnection(strDbCnn);
cnn2.Open();
SqlDataAdapter adp;
adp = new SqlDataAdapter("select * from " + treeView1.SelectedNode.Text, cnn2);
DataSet ds=new DataSet();
adp.Fill(ds,"T1");
d1.DataSource = ds.Tables["T1"];
cnn2.Close();

splitContainer2.Panel2.Controls.Add(d1);
d1.BringToFront();
}




Windows Generated Code



private void InitializeComponent()
{
this.panel1 = new System.Windows.Forms.Panel();
this.splitContainer1 = new System.Windows.Forms.SplitContainer();
this.splitContainer2 = new System.Windows.Forms.SplitContainer();
this.textBox1 = new System.Windows.Forms.TextBox();
this.richTextBox1 = new System.Windows.Forms.RichTextBox();
this.btnExecute = new System.Windows.Forms.Button();
this.treeView1 = new System.Windows.Forms.TreeView();
this.label1 = new System.Windows.Forms.Label();
this.comboBox1 = new System.Windows.Forms.ComboBox();
this.DataContext = new System.Windows.Forms.ContextMenuStrip();
this.contextMenuStrip1 = new System.Windows.Forms.ContextMenuStrip();
this.createDatabaseToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.showDataToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.panel1.SuspendLayout();
this.splitContainer1.Panel1.SuspendLayout();
this.splitContainer1.Panel2.SuspendLayout();
this.splitContainer1.SuspendLayout();
this.splitContainer2.Panel1.SuspendLayout();
this.splitContainer2.Panel2.SuspendLayout();
this.splitContainer2.SuspendLayout();
this.DataContext.SuspendLayout();
this.contextMenuStrip1.SuspendLayout();
this.SuspendLayout();
//
// panel1
//
this.panel1.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D;
this.panel1.Controls.Add(this.comboBox1);
this.panel1.Controls.Add(this.label1);
this.panel1.Controls.Add(this.btnExecute);
this.panel1.Dock = System.Windows.Forms.DockStyle.Top;
this.panel1.Location = new System.Drawing.Point(0, 0);
this.panel1.Name = "panel1";
this.panel1.Size = new System.Drawing.Size(529, 77);
this.panel1.TabIndex = 0;
//
// splitContainer1
//
this.splitContainer1.Dock = System.Windows.Forms.DockStyle.Fill;
this.splitContainer1.Location = new System.Drawing.Point(0, 77);
this.splitContainer1.Name = "splitContainer1";
//
// splitContainer1.Panel1
//
this.splitContainer1.Panel1.Controls.Add(this.treeView1);
//
// splitContainer1.Panel2
//
this.splitContainer1.Panel2.Controls.Add(this.splitContainer2);
this.splitContainer1.Size = new System.Drawing.Size(529, 286);
this.splitContainer1.SplitterDistance = 176;
this.splitContainer1.TabIndex = 1;
//
// splitContainer2
//
this.splitContainer2.Dock = System.Windows.Forms.DockStyle.Fill;
this.splitContainer2.Location = new System.Drawing.Point(0, 0);
this.splitContainer2.Name = "splitContainer2";
this.splitContainer2.Orientation = System.Windows.Forms.Orientation.Horizontal;
//
// splitContainer2.Panel1
//
this.splitContainer2.Panel1.Controls.Add(this.textBox1);
//
// splitContainer2.Panel2
//
this.splitContainer2.Panel2.Controls.Add(this.richTextBox1);
this.splitContainer2.Size = new System.Drawing.Size(349, 286);
this.splitContainer2.SplitterDistance = 95;
this.splitContainer2.TabIndex = 0;
//
// textBox1
//
this.textBox1.Dock = System.Windows.Forms.DockStyle.Fill;
this.textBox1.Location = new System.Drawing.Point(0, 0);
this.textBox1.Multiline = true;
this.textBox1.Name = "textBox1";
this.textBox1.Size = new System.Drawing.Size(349, 95);
this.textBox1.TabIndex = 0;
//
// richTextBox1
//
this.richTextBox1.Dock = System.Windows.Forms.DockStyle.Fill;
this.richTextBox1.Location = new System.Drawing.Point(0, 0);
this.richTextBox1.Name = "richTextBox1";
this.richTextBox1.Size = new System.Drawing.Size(349, 187);
this.richTextBox1.TabIndex = 0;
this.richTextBox1.Text = "";
//
// btnExecute
//
this.btnExecute.Location = new System.Drawing.Point(80, 10);
this.btnExecute.Name = "btnExecute";
this.btnExecute.Size = new System.Drawing.Size(75, 23);
this.btnExecute.TabIndex = 1;
this.btnExecute.Text = "&Execute";
this.btnExecute.UseVisualStyleBackColor = true;
this.btnExecute.Click += new System.EventHandler(this.btnExecute_Click);
//
// treeView1
//
this.treeView1.Dock = System.Windows.Forms.DockStyle.Fill;
this.treeView1.Location = new System.Drawing.Point(0, 0);
this.treeView1.Name = "treeView1";
this.treeView1.Size = new System.Drawing.Size(176, 286);
this.treeView1.TabIndex = 0;
this.treeView1.NodeMouseClick += new System.Windows.Forms.TreeNodeMouseClickEventHandler(this.treeView1_NodeMouseClick);
//
// label1
//
this.label1.AutoSize = true;
this.label1.Location = new System.Drawing.Point(185, 20);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(86, 13);
this.label1.TabIndex = 2;
this.label1.Text = "Select Database";
//
// comboBox1
//
this.comboBox1.FormattingEnabled = true;
this.comboBox1.Location = new System.Drawing.Point(277, 10);
this.comboBox1.Name = "comboBox1";
this.comboBox1.Size = new System.Drawing.Size(121, 21);
this.comboBox1.TabIndex = 3;
this.comboBox1.SelectedIndexChanged += new System.EventHandler(this.comboBox1_SelectedIndexChanged);
//
// DataContext
//
this.DataContext.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.createDatabaseToolStripMenuItem});
this.DataContext.Name = "DataContext";
this.DataContext.Size = new System.Drawing.Size(157, 26);
//
// contextMenuStrip1
//
this.contextMenuStrip1.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.showDataToolStripMenuItem});
this.contextMenuStrip1.Name = "contextMenuStrip1";
this.contextMenuStrip1.Size = new System.Drawing.Size(153, 48);
//
// createDatabaseToolStripMenuItem
//
this.createDatabaseToolStripMenuItem.Name = "createDatabaseToolStripMenuItem";
this.createDatabaseToolStripMenuItem.Size = new System.Drawing.Size(156, 22);
this.createDatabaseToolStripMenuItem.Text = "Create Database";
//
// showDataToolStripMenuItem
//
this.showDataToolStripMenuItem.Name = "showDataToolStripMenuItem";
this.showDataToolStripMenuItem.Size = new System.Drawing.Size(152, 22);
this.showDataToolStripMenuItem.Text = "Show Data";
this.showDataToolStripMenuItem.Click += new System.EventHandler(this.showDataToolStripMenuItem_Click);
//
// Form1
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(529, 363);
this.Controls.Add(this.splitContainer1);
this.Controls.Add(this.panel1);
this.Name = "Form1";
this.Text = "Shalvin Sql Server Management Studio";
this.WindowState = System.Windows.Forms.FormWindowState.Maximized;
this.Load += new System.EventHandler(this.Form1_Load);
this.panel1.ResumeLayout(false);
this.panel1.PerformLayout();
this.splitContainer1.Panel1.ResumeLayout(false);
this.splitContainer1.Panel2.ResumeLayout(false);
this.splitContainer1.ResumeLayout(false);
this.splitContainer2.Panel1.ResumeLayout(false);
this.splitContainer2.Panel1.PerformLayout();
this.splitContainer2.Panel2.ResumeLayout(false);
this.splitContainer2.ResumeLayout(false);
this.DataContext.ResumeLayout(false);
this.contextMenuStrip1.ResumeLayout(false);
this.ResumeLayout(false);
}
private System.Windows.Forms.Panel panel1;
private System.Windows.Forms.SplitContainer splitContainer1;
private System.Windows.Forms.SplitContainer splitContainer2;
private System.Windows.Forms.Button btnExecute;
private System.Windows.Forms.TextBox textBox1;
private System.Windows.Forms.RichTextBox richTextBox1;
private System.Windows.Forms.TreeView treeView1;
private System.Windows.Forms.ComboBox comboBox1;
private System.Windows.Forms.Label label1;
private System.Windows.Forms.ContextMenuStrip DataContext;
private System.Windows.Forms.ContextMenuStrip contextMenuStrip1;
private System.Windows.Forms.ToolStripMenuItem createDatabaseToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem showDataToolStripMenuItem;

Tuesday, July 28, 2009

WPF (Windows Presentation Foundation)

This is a beginner level blog on WPF.


Nesting Controls
Styles
Exploring WPF the Code Way

Majority of examples presented in this blog will work with Silverlight also.
Windows Presentation Foundation (WPF) is the Microsoft's presentation technology for creating compelling user interface including graphics and media.
It is based on Vector Graphics
Create a new project in Visual Studio 2008 by selecting File, New Project.
Starting a WPF Application Project

















The WPF editor contains two view the visual representation of the form as well as the XAML implementation of the window.

A WPF Form is in fact a class that inherits from System.Windows.Window. The Window class which in turn inherits from ContentControl class.A ContentControl class can have only a single element as its Content Property.
Inside the Windows is a Grid Control that can hold multiple child controls.









As you set the propeties of an element both the windows designer as well as the xaml gets updated.







Here I am settting the Title for the form.






























You can also edit the xaml and the changes will be immediately apparent in the windows designer.





















Setting the window title at Runtime

private void Window_Loaded(object sender, RoutedEventArgs e)
{
this.Title = "shalvinpd.blogspot.com";
}




WPF do have a collection of common control which you would expect in a presentation technology.

















Button

Drag and drop a button on to the windows design surface.




























On clicking the button you will be taken to the event handler.


private void button1_Click(object sender, RoutedEventArgs e)
{
MessageBox.Show("Hello welcome to WPF", "Shalvin.com");
}

Run the application. Click on the button and you will receice a welcome message.


















MessageBox.Show Method's Overloads

MessageBox's Show method has 21 overloads, following are a few examples.

private void btnHello_Click(object sender, RoutedEventArgs e)
{
MessageBox.Show("Hello");
}

private void btnHelloCaption_Click(object sender, RoutedEventArgs e)
{
MessageBox.Show("Hello", "shalvin");
}

private void btnYesNo_Click(object sender, RoutedEventArgs e)
{
MessageBox.Show("Hello", "Shalvin", MessageBoxButton.YesNo);
}

private void btnExclamation_Click(object sender, RoutedEventArgs e)
{
MessageBox.Show("Hello", "Shalvin", MessageBoxButton.YesNo, MessageBoxImage.Exclamation);
}

MessageBoxResult
private void btnClose_Click(object sender, RoutedEventArgs e)
{
if (MessageBox.Show("Do you want to quit ?", "Shalvin", MessageBoxButton.YesNo) == MessageBoxResult.Yes)
Close();
}

String Memory Variable

private void btnMemoryVariable_Click(object sender, RoutedEventArgs e)
{
string strName = "Shalvin";
MessageBox.Show("Hello " + strName);
strName = "Shalvin P D";
MessageBox.Show("Hello " + strName);
}


String Concatenation
In this example instread of simply displaying a Hello message the user will be greated with the name entered in text box.













private void button1_Click(object sender, RoutedEventArgs e)

{
MessageBox.Show("Hello " + txtName.Text);
}




















Integer Memory Variable and Simple Calculator




















int i, j, res;
private void btnAdd_Click(object sender, RoutedEventArgs e)
{
i = Int32.Parse(txtInt1.Text);
j = Int32.Parse(txtInt2.Text);
res = i + j;
lblResult.Content = res.ToString();
}

Here I am defining three integer memory variables i, j and res. Int32.Parse() method is used to convert the textbox data to integer.

<Window x:Class="WpfApplication1.Calc"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="Calc" Height="300" Width="300" Loaded="Window_Loaded">
    <Grid>
        <Label Content="Integer 1" Height="28" HorizontalAlignment="Left" Margin="44,33,0,0" Name="label1" VerticalAlignment="Top" />
        <TextBox Height="23" HorizontalAlignment="Left" Margin="120,33,0,0" Name="txtInt1" VerticalAlignment="Top" Width="120" />
        <Label Content="Integer 2" Height="28" HorizontalAlignment="Left" Margin="53,88,0,0" Name="label2" VerticalAlignment="Top" />
        <TextBox Height="23" HorizontalAlignment="Left" Margin="120,80,0,0" Name="txtInt2" VerticalAlignment="Top" Width="120" />
        <Label Content="Result" Height="28" HorizontalAlignment="Left" Margin="63,132,0,0" Name="label3" VerticalAlignment="Top" />
        <Label Height="28" HorizontalAlignment="Left" Margin="120,132,0,0" Name="lblResult" VerticalAlignment="Top" Width="112" BorderBrush="Black" BorderThickness="1" />
        <Button Content="+" Height="23" HorizontalAlignment="Left" Margin="98,196,0,0" Name="btnAdd" VerticalAlignment="Top" Width="75" Click="btnAdd_Click" />
    </Grid>
</Window>

ListBox

ListBox is used for displaying a number of items at the same time. Place a ListBox on to the form and select the Items collection from the properties window. The Collection Editor dialog will appear. You can add additional items to the ListBox by clicking the Add button and specifying a Content.






Behing the scene it will create ListBoxItems tags inside the ListBox tag.







It is possible to add items to ListBox at runtime. Double click on the title of the form and you will be taken to the Loaded event of the Window.
private void Window_Loaded(object sender, RoutedEventArgs e)
{
lstInterests.Items.Add("Guitar");
}





ComboBox
ComboBox contains similar functionality that of ListBox. Above mentioned functionality also works with ComboBox

RadioButton and If else











private void btnGender_Click(object sender, RoutedEventArgs e)
{
if (rbMale.IsChecked == true)
MessageBox.Show("Male candidate");
else
MessageBox.Show("Female candidate");
}













DatePicker Control
private void btnDate_Click(object sender, RoutedEventArgs e)
{
DateTime dt = DateTime.Parse(datePicker1.SelectedDate.ToString());
MessageBox.Show(dt.ToString());
MessageBox.Show(dt.ToString("d"));
MessageBox.Show(dt.ToString("D"));
}

Nesting Controls

































As usual you can have event handlers of the controls. In this case I am extracting the value of Inner TextBox, concatenating it with a Hello and MessageBoxing it.

private void btnHello_Click(object sender, RoutedEventArgs e)
{
MessageBox.Show("Hello " + txtName.Text);
}























































Styles
Styles as WPF equivalent of CSS in Html.


















Working with Styles at Runtime




private void btnBold_Click(object sender, RoutedEventArgs e)
{
btnBold .Style = (Style)FindResource("BoldStyle");
}








Filling Wpf ComboBox with the Contents of a SqlDataReader
using System.Data.SqlClient;
SqlConnection cnn = new SqlConnection(@"Integrated Security=sspi;Initial Catalog=Shalvin;Data Source=.\sqlexpress");
SqlCommand cmd;
SqlDataReader dr;
private void Window_Loaded(object sender, RoutedEventArgs e)
{
cnn.Open();
cmd = new SqlCommand("select * from Categories", cnn);
dr = cmd.ExecuteReader();
while (dr.Read())
{
cboCategories.Items.Add(dr["CategoryName"]);
}
}























Exploring WPF the Code Way
Having seen the fundamentals of working with IDE. Let's turn out attention to the internals of WPF in coded way, means without XAML.

using System;
using System.Windows;
using System.Windows.Controls;
namespace WpfApplication1
{
class Class1 : Window
{
[STAThread]
public static void Main()
{
Application app = new Application();
app.Run(new Class1{Title = "shalvin"});
}
public Class1()
{
Grid LayoutRoot = new Grid();
this.Content = LayoutRoot;
Button btn = new Button();
btn.Width = 75;
btn.Height = 50;
btn.Content = "Hello";
LayoutRoot.Children.Add(btn);
}
}
}

Saturday, July 25, 2009

BackgroundWorker Component

BackgroundWorker Component can be used in situations where long running operations is likely to affect the responsiveness of the UI.

Here I am writing a method within an intention to simulate a delay using Thread Sleep. If I am directly calling the method from button click, the UI will freeze till the operation is complete.
Instead I am using DoWork event of BackgroundWorker Component in conjunction with RunWorkerAsync method.




















using System.Threading
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
int arg = (int)e.Argument;
e.Result = Add(arg);
}

private int Add(int ct)
{
int o, j;
o = 0;
j = 1;
int sum = 0;
for(int i = 0 ;i < ct; i++)
{
sum += o + j;
o = j;
j = sum;
Thread.Sleep(1000);
}

return sum;
}

private void btnAdd_Click(object sender, EventArgs e)
{
//int sum = Add(4);
//MessageBox.Show(sum.ToString());
int arg = 4;
backgroundWorker1.RunWorkerAsync(arg);
}

private void btnBlog_Click(object sender, EventArgs e)
{
MessageBox.Show("ShalvinPD.blogspot.com");
}

private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
MessageBox.Show(e.Result.ToString());
}

Monday, January 12, 2009

Hashtable and DictionaryEntry

HashTable Class of System.Collections namespace represents a collection of key/value pairs that are organized based on the hash code of the key.


using System.Collections;

Hashtable ht = new Hashtable();
private void Form1_Load(object sender, EventArgs e)
{
	ht.Add("Am", "Ambily");
	ht.Add("Di", "Divya");
	foreach (DictionaryEntry de in ht)
	{
		listBox1.Items.Add(de.Key);
		listBox2.Items.Add(de.Value);
	}
}

private void button1_Click(object sender, EventArgs e)
{
	ht.Add(textBox1.Text, textBox2.Text);
	ShowHashTable();
}

private void ShowHashTable()
{
	listBox1.Items.Clear();
	listBox2.Items.Clear();
	foreach (DictionaryEntry de in ht)
	{
		listBox1.Items.Add(de.Key);
		listBox2.Items.Add(de.Value);
	}
}

VB .Net







Dim ht As New Hashtable
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
	ht.Add("Am", "Ambily")
	ht.Add("Di", "Divya")
	ShowHT()
End Sub
Private Sub ShowHT()
	ListBox1.Items.Clear()
	ListBox2.Items.Clear()
	For Each de As DictionaryEntry In ht
		ListBox1.Items.Add(de.Key)
		ListBox2.Items.Add(de.Value)
	Next
End Sub
Private Sub btnAdd_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnAdd.Click
	ht.Add(txtKey.Text, txtValue.Text)
	ShowHT()
End Sub
Related Blog ReadOnlyCollectionBase Class Generics and Collection Initializer in .Net

Friday, December 12, 2008

Isolated Storage (Code Snippets)

using System.IO;
using System.IO.IsolatedStorage;

private void button1_Click(object sender, EventArgs e)
{
this.Text = textBox1.Text;
IsolatedStorageFile f = IsolatedStorageFile.GetMachineStoreForDomain();
IsolatedStorageFileStream i = new IsolatedStorageFileStream("co.col", System.IO.FileMode.Create, f);
StreamWriter sw = new StreamWriter(i);
sw.Write(this.Text);
sw.Flush();
sw.Close();
}


private void Form1_Load(object sender, EventArgs e)
{
IsolatedStorageFile f1 = IsolatedStorageFile.GetMachineStoreForDomain();
IsolatedStorageFileStream i1 = new IsolatedStorageFileStream("co.col", FileMode.Open, f1);
StreamReader sr = new StreamReader(i1);
this.Text = sr.ReadToEnd();
sr.Close();
}

Courtesy : Saji P Babu, IndiaOptions, Kochi.

Related Blog
System.IO Namespace in .Net

Monday, October 27, 2008

FileSystemWatcher Component and Class in WPF and Windows Forms

FileSystemWatcher Component (Class) can be used to monitor file system directories for changes. FileSystemWatcher Class in WPF FileSystemWatcher Class in found in System.IO namespace using System.IO is not added by default in WPF. using System.IO; private void Window_Loaded(object sender, RoutedEventArgs e) { FileSystemWatcher fsw = new FileSystemWatcher(); fsw.Path = @"c:\"; fsw.IncludeSubdirectories = true; fsw.EnableRaisingEvents = true; fsw.Created +=new FileSystemEventHandler(fsw_Created); } private void fsw_Created(object sender, FileSystemEventArgs e) { MessageBox.Show(e.FullPath + " created"); } FileSystemWatcher Component in Windows Forms Add a FileSystemWatcher to the form. Since it is a component it will appear in the component tray. Support if you want to monitor c: and its sub directories for changes, then set the Path property to C:, IncludeSubdirectories to True and EnableRaisingEvents to true. Now you can write event handlers for the FileSystemWatcher Component as follows: private void fileSystemWatcher1_Created(object sender, System.IO.FileSystemEventArgs e) { MessageBox.Show(e.FullPath + " created"); } private void fileSystemWatcher1_Deleted(object sender, System.IO.FileSystemEventArgs e) { MessageBox.Show(e.FullPath + " deleted"); } A better approach would be writing to an event log or a text file. Related blog: DataTable DataColumn and DataRow (Asp.Net)

Tuesday, June 10, 2008

.Net C# Multi Tier Application

The 3-Tier architecture has the following three tiers:

Data Tier
This tier consists of Database Servers. Here information is stored and retrieved. This tier keeps data neutral and independent from application servers or business logic. Giving data its own tier also improves scalability and performance.
Application Tier (Business Logic/Logic Tier)
The logic tier is pulled out from the presentation tier and, as its own layer, it controls an application’s functionality by performing detailed processing.
Presentation Tier
This is the topmost level of the application. The presentation tier displays information related to such services as browsing merchandise, purchasing, and shopping cart contents. It communicates with other tiers by outputting results to the browser/client tier and all other tiers in the network.
Lets take up creating a very simple multi tier application.

First we will see the Data Tier. Here I am using Sql Server 2005 as data store.



















Now we will create the Application Tier or the Business Tier. For this I am creating a Class Library Project.

using System.Data;
using System.Data.SqlClient;
using System.Configuration;

namespace ShalvinBusinessObject
{
public class BusinessObject
{
public DataTable GetCategories()
{
SqlConnection cnn;
SqlDataAdapter da;
DataSet ds = new DataSet();
cnn = new SqlConnection(@"Integrated Security=sspi;Initial Catalog=ShalvinPDBlog;Data Source=.\sqlexpress");
cnn.Open();
da = new SqlDataAdapter("spAllCategories", cnn);
da.Fill(ds, "Cat");
return ds.Tables["Cat"];
}
}

Goto Build, Build Solution for building the dll.

Creating the User Tier

Start a Windows Application Project.
Go to project, Add Reference, Select Browse and Navigate to the bin, release folder of the previously creating class library project. Select the dll.

Now you can access the dll from your project.



















using ShalvinBusinessObject;


BusinessObject bo;
private void Form1_Load(object sender, EventArgs e)
{
bo = new BusinessObject();
dataGridView1.DataSource = bo.GetCategories();
}

Here I am creating an Object of the Class in the previous dll and binding an dataGridView to the GetCategories method.

Sunday, June 8, 2008

C# Interface

An interface is a class with only signatures of methods properties and events without any implementation.
It is up to implementing class to add functionality . Your can't create an instance of interface.
Interface is an contract between an interface and implementing class that the implementing class should implements all the members of the interface.
It is possible to have multiple interface inheritance.

Start a new Windows Forms application or Wpf Application.

Add a new Interface by selecting Project, Add New Item and Interface from the Add NewItem Dialog.




















interface ISpecialization
{
string Specialization { get; set; }
}

Likewise create another Interface called IHobby.

interface IHobby
{
string Hobby { get; set; }
}


Now create a class which implements both ISpecailization and IHobby.

class Person : ISpecialization, IHobby
{
public string Hobby { get; set; }
public string Specialization { get; set; }
}

Now in Wpf Form you can instantiate Person class and use it.

Person Shalvin;
private void Window_Loaded(object sender, RoutedEventArgs e)
{
Shalvin = new Person();
Shalvin.Specialization = ".Net";
Shalvin.Hobby = "Blogging";
}

private void btnHobby_Click(object sender, RoutedEventArgs e)
{
MessageBox.Show(Shalvin.Hobby);
}

private void btnSpecialization_Click(object sender, RoutedEventArgs e)
{
MessageBox.Show(Shalvin.Specialization);
}




















Though we are using inheritance operator (:) behind the scene it is doing an implementation as is evident form the IL code below.
















If your are not conversant with Intermediate Language visi my blog : http://shalvinpd.blogspot.com/2008/02/intermediate-language.html

C# Express Edition : Creating Windows Forms User Control

Though there is no project template for User Control in C# Express Edition, it is possible to create User Controls with C# Express edition.

Start C# Express Edition. Start a new Class Library Project by selecting to File, New Project and Class Library from the New Project dialog.



















Go to Solution Explorer and delete the Class1.




























Go to Project menu and Select Add User Control give a good name.





















I am going to have a user control, which on clicking opens by blog in Internet explorer.

An User control is a border canvas. Place a Button Control give appropriate Text and Name to the Button.

In the click event of Button write the following code:





















You can't test an User Control in Express Edition at this point, thought such a feature is provided in Visual Studio.

You have to build the project first, make sure you save the project in an appropriate folder.















Now your control is ready for use.


For Consuming the User control start a new Windows Forms Application Project.
Lets create a new tab in tool box for our controls and give an appropriate name.


























Right click the newly created tab and select Choose Items.
























Choose Toolbox Items dialog will appear. Select Browse. In the Open Dialog navigate to the bin folder of the previously created project, go to debug directory (at the time of deployment the mode should be release) and select the dll.


















The control will appear in the toolbox and you can use the control by adding the control to the form just like ordinary Windows Forms Controls.

Friday, May 16, 2008

.Net : Introduction to Multi threading

The basic concept behind multi threading is to perform multiple tasks simultaneously. The success of an application depends on reducing the downtime. For example if the application is performing a lengthy printing task, the application should be in a position to perform other tasks also.

Listing Threads in a Process
using System.Diagnostics;
Process p;
private void Form1_Load(object sender, EventArgs e)
{
p = Process.GetProcessById(5944);
ProcessThreadCollection theTrheads = p.Threads;
foreach (ProcessThread pt in theTrheads)
listBox1.Items.Add(String.Format("{0} {1} {2}", pt.Id, pt.StartTime, pt.PriorityLevel ));
}

A Process is a running application. The above example lists all the threads found in a process whose Process Id is 5944.


The namespace used for creating multi threaded application is System.Threading. The Thread class is used for working with threads.

You create a thread by passing the method to ThreadStart delegate.

Here is a very simple multi threading example which simultaneously shows two messageboxes.

using System.Threading;

Thread t;
Thread t1;
private void Form1_Load(object sender, EventArgs e)
{
t = new Thread(new ThreadStart(Hello));
t.Start();

t1 = new Thread(new ThreadStart(Shalvin));
t1.Start();

}
private void Hello()
{
for (int i = 0; i < 10;i++)
{
MessageBox.Show("Hello");
}
}

private void Shalvin()
{
for (int i = 0; i <10;i++)
{
MessageBox.Show("Shalvin");
}
}
}

Multithreaded Ellipse Application
(Courtesy Saji P Babu)

This example demonstrates Sleep method, suspending and resuming threads. The example simultaneously draws two ellipses in Panel controls.


using System.Threading;

Thread thread;
Thread thread1;
private void Form1_Load(object sender, EventArgs e)
{
ThreadStart threadStart = new ThreadStart(DrawEllipse);
thread = new Thread(threadStart);
thread.Start();

ThreadStart threadStart1 = new ThreadStart(DrawEllipse1);
thread1 = new Thread(threadStart1);
thread1.Start();
}
private void DrawEllipse()
{
Graphics g = panel1.CreateGraphics();
Random rnd = new Random();
for (int i = 0; i < 500;i++)
{
g.DrawEllipse(Pens.Blue, 0, 0, rnd.Next(this.Width), rnd.Next(this.Height));
Thread.Sleep(100);
}
}

private void DrawEllipse1()
{
Graphics g = panel2.CreateGraphics();
Random rnd = new Random();
for (int i = 0; i < 500; i++)
{
g.DrawEllipse(Pens.Blue, 0, 0, rnd.Next(this.Width), rnd.Next(this.Height));
Thread.Sleep(100);
}
}
}