Friday, May 23, 2008

WebParts in Asp .Net

Before speaking about WebParts in Asp .Net let me speak a bit about iGoogle. Following is my iGoogle page.



















Here I can decide on what to appear on my page. I can add new Gadgets, remove Gadgets and change the location of gadgets.

Similar service are provided by Microsoft in my.msn.com as show in the figure.



















Web Parts
is Microsoft technology for creating personalized pages as seen in iGoogle. This is a part of Microsoft Portal Framework.

Start a new Asp .Net Project. Add a Table with 4 columns and 1 row.
Add a WebPartManager to the form.

Add a WebPartZone to each Table Data.

Into the first WebPart Zone add a Calendar.
Since the calendar is place inside a WebPart zone you will get an extender property called Title. Set an appropriate title.

If you run the application you will see extra menu options for Calendar contol as shown in the exhibit.
























Now you are in Browser Display Mode.

If you select the minimize option the the calendar will be minimized and next time you open the page the minimized state will be persisted.













WebParts Design Display Mode
WebParts supports multiple display mode. In Design Display Mode you can drag a control from one webpart zone to another.

Place a Command Button on the existing form. Change its text to Design. On clicking the Design Button you want to change the display mode to Design Display Mode.
Here is the code

protected void btnDesign_Click(object sender, EventArgs e)
{
WebPartManager1.DisplayMode = WebPartManager.DesignDisplayMode;
}

Now you can drag a control from one WebPartZone to another as shown in the figure below.

















CatalogDispalyMode for Adding Controls to WebPartZone

If you close the Calendar by select Close menu from the control there is no way the have the control back. Also you might want to add new Control (widgets) to a zone as Add Stuff option in iGoogle. For doing that you can use the CatalogZone and DeclarativeCatalogPart controls and setting the Display mode to Catalog Display mode.

So add a CatalogZone to the page. Add a DeclarativeCatalogPart to the CatalogZone. Select Edit Template from the Smart tag of DeclarativeCatalogPart.














Cut and past the calender control into the DeclarativeCatalogPart.

Add a Command Button give a text Catalog. On clicking the button you have change the Display mode to CatalogDisplay Mode.

Here is the code:
protected void btnCatalog_Click(object sender, EventArgs e)
{
WebPartManager1.DisplayMode = WebPartManager.CatalogDisplayMode;
}

Now when you click the button you will see the Catalog zone. From the catalog zone you can select the control and the WebPartZone to which you want to add the control.
















Now we can implement the BrowseDisplayMode which is the mode for end user browsing.
So Place another TextBox. Set the Text Propterty to Browser and write the following code:

protected void btnBrowse_Click(object sender, EventArgs e)
{
WebPartManager1.DisplayMode = WebPartManager.BrowseDisplayMode;
}

WebParts and ASPNETDB Database
You might be wondering the the data is getting persisted. It is in the ASPNETDB.MDF file system database that is getting created inside App_Data folder of the project. The information is stored in aspnet_PersonalizationPerUser table as shown in the figure below.
















ASPNETDB Database is used in Membership, Profile and WebParts services of Asp .Net 2.0.

Asp.Net 2.0 Master Page and TreeView
Themes in Asp .Net
shalvinpd.blogspot.com

Ajax .Net I : Extension Controls in Visual Studio 2008

In this blog we are going see Script Manager, UpdatePanel and Timer in Action. I will demnostrate creating an Digital clock in the site.

Start a new ASP .Net Website.

Visual Studio comes with 5 Ajax Extension controls as shown below.












Drag a ScriptManager to the form.
Below the ScriptManager add an UpdatePanel.
ScriptManager is responsible for delivering scripts to the Browser
In Ajax .Net Partial Page update is made possible using UpdatePanel.
Add a Label and an Ajax Timer Control Ajax Controls into the UpdatePanel. Set the Enabled property to True and Interval to 1000 (milliseconds) for the Timer Control.

Double click on the Timer control you will be taken to Tick Event of Timer.
Write the code to display the current time as shown below:

protected void Timer1_Tick(object sender, EventArgs e)
{
lblTime.Text = System.DateTime.Now.ToString("T");
}

Run the application you will see that the time is getting updated without the web page making a postback to the server.











Related Blog

Ajax .Net II : Setting up Ajax Control Toolkit controls

Ajax .Net III : CalendarExtender Control

Ajax .Net IV : TextBoxWaterMarkExtender

Ajax .Net V : FilteredTextBoxExtender

Ajax .Net VI : ConfirmButtonExtender

Thursday, May 22, 2008

Microsoft Innovation Days: Cochin - May 30, 2008

Learn about building reliable, high performance applications with a super-rich user interactivity using Microsoft technologies, such as the Visual Studio 2008, SQL Server 2008, Windows Server 2008, Silverlight 2 beta 1 and Expression Studio.

For registration click here

Monday, May 19, 2008

.Net Globalization

Globalization is the process of designing and developing applications that function for multiple cultures.

Lets begin our discussion on .Net Globalization with an ASP .Net example. Start an asp. Net project. Go to web.config and type the following:






Place a Calendar control on the form. When you run the application you will see an Arabic calendar with the Hijri year.


















Displaying All Cultures

Here I am creating an array of CultureInfo class. CultureInfo class contains information about a culture like its name, Calendar, Day Names, Month Names, Currency Format, etc.

SpecificCulture is a culture type where there is language code as well as country code. Examples are ar-SA, ml-IN, fr-FR. Here the first portion represents the Language Code and the second portion represents the Country Code.
using System.Globalization;

private void Form1_Load(object sender, EventArgs e)
{
CultureInfo[] cis = CultureInfo.GetCultures(CultureTypes.SpecificCultures);
foreach (CultureInfo ci in cis)
listBox1.Items.Add(String.Format( ci.ToString()));
}

Displaying DisplayName and NativeName and Day Names of a Selected Culture

























using System.Globalization;
private void Form1_Load(object sender, EventArgs e)
{
CultureInfo[] cis = CultureInfo.GetCultures(CultureTypes.SpecificCultures);
foreach (CultureInfo ci in cis)
comboBox1.Items.Add(String.Format( ci.ToString()));
}

private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
lstDetails.Items.Clear();
CultureInfo ci = new CultureInfo(comboBox1.Text);
lstDetails.Items.Add(ci.DisplayName.ToString());
lstDetails.Items.Add(ci.NativeName.ToString());
lstDetails.Items.Add("");
lstDetails.Items.Add("Day names");
string[] strDayNames = ci.DateTimeFormat.DayNames;
foreach (string strDay in strDayNames)
lstDetails.Items.Add(strDay);

lstDetails.Items.Add("");
lstDetails.Items.Add("Month Names");
string[] strMonthNames = ci.DateTimeFormat.MonthNames;
foreach(string strMonth in strMonthNames)
lstDetails.Items.Add(strMonth);
}



Related Blog
Globalization in Windows Forms - Application with multi language support


Happy Programming
shalvin.com

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);
}
}
}

Thursday, May 15, 2008

.Net Windows Forms Database Connectivity with Ado .Net

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

 Two important Managed Providers are SqlClient and OleDb.

SqlClient namespace contains classes required for interacting with Sql Server 7 and above.

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

But it is not recommended using OleDb 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 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"); <!-- #InsertTextBox 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());
}