Saturday, June 21, 2008

Creating Asp .Net Custom Controls

Custom Controls are reusable dlls.
Start out by creating a class library in C#. Add reference to System.Web. We are overriding the Render method of System.Web.UI.Control class and using HtmlTextWriterClass we are outputing Text to the browser.

using System.Web;
using System.Web.UI;

namespace HelloCustomCtl
{
 public class HelloCtl : Control 
 {
  protected override void Render(HtmlTextWriter writer)
  {
   writer.Write("Shalvin");
  }
 }
}

Build the project.

Testing the Custom Control

Start ASP .Net, preferably add a new tab to the toolbox. Right click the tab and select Choose Item. Click on the browse button navigate to the bin folder of previously created class library and select the dll.
Now the control will appear in the toolbox and you can use it in your project.

WebControl With Properties
Since WebControl class provides the properties, methods, and events that are common to all Web server controls, this control eventually will have a set of common properties found in common controls.
Along the way we are implementing two properties Text and Location that can be set from propeties window while using the control.

using System.Web.UI;
using System.Web.UI.WebControls;

public class MultiTdCtl : WebControl
{

private string mText;
public string Text
{
get { return mText ; }
set { mText = value; }
}

private string mLocation;
public string Location
{
get
{
return mLocation;
}
set
{
mLocation = value;
}
}

protected override void RenderContents(HtmlTextWriter writer)
{
writer.AddAttribute(HtmlTextWriterAttribute.Border, "1");
writer.RenderBeginTag(HtmlTextWriterTag.Table);
writer.RenderBeginTag(HtmlTextWriterTag.Tr);
writer.RenderBeginTag(HtmlTextWriterTag.Td);
writer.Write(mText); writer.RenderEndTag ();
writer.RenderBeginTag(HtmlTextWriterTag.Td);
writer.WriteLine(mLocation);
writer.RenderEndTag();
writer.RenderEndTag();
writer.RenderEndTag();
}
}

With C# 3.0 the lengthy getter and setter code is not required in fact you replace the code with the following :

public string Text
{
get;
set;
}
public string Location
{
get;
set;
}

..writer.RenderBeginTag(HtmlTextWriterTag.Td);
writer.Write(Text); writer.RenderEndTag ();
writer.RenderBeginTag(HtmlTextWriterTag.Td);
writer.WriteLine(Location);

Creating Composite Control

using System.Web;
using System.Web.UI.WebControls;

namespace CompositeCtl
{
public class CompositeCtl : CompositeControl
{
    Label lbl;
    TextBox txt;

   protected override void CreateChildControls()
    {
        lbl = new Label { Text = "Name" };
        this.Controls.Add(lbl);


        txt = new TextBox();
        this.Controls.Add(txt);
    }
}
}
Composite Control 2
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace CompositeCtlEg
{
   public class ShalvinCompositeCtl : CompositeControl
    {
       Label lbl, lblMessage;
       TextBox txt;
        Button btn;
        protected override void CreateChildControls()
        {
            lblMessage = new Label { Text = "" };
            this.Controls.Add(lblMessage);
            lbl = new Label { Text = "Name" };
            this.Controls.Add(lbl);

            txt = new TextBox();
            this.Controls.Add(txt);

            btn = new Button { Text = "Shalvin" };
            btn.Click +=new EventHandler(btn_Click);
            this.Controls.Add(btn);
        }

        void btn_Click(object sender, EventArgs e)
        {
            lblMessage.Text = "Hello " + txt.Text;
        }

        protected override void RenderContents(System.Web.UI.HtmlTextWriter writer)
        {
           
            writer.RenderBeginTag(HtmlTextWriterTag.Table);

            writer.RenderBeginTag(HtmlTextWriterTag.Tr);
            writer.AddAttribute(HtmlTextWriterAttribute.Colspan, "2");
            writer.RenderBeginTag(HtmlTextWriterTag.Td);
           lblMessage.RenderControl(writer);
            writer.RenderEndTag();
            writer.RenderEndTag();

            writer.RenderBeginTag(HtmlTextWriterTag.Tr);
            writer.RenderBeginTag(HtmlTextWriterTag.Td);
            lbl.RenderControl(writer);
            writer.RenderEndTag();
            writer.RenderBeginTag(HtmlTextWriterTag.Td);
            txt.RenderControl(writer);
            writer.RenderEndTag();
            writer.RenderEndTag();

            writer.RenderBeginTag(HtmlTextWriterTag.Tr);
            writer.RenderBeginTag(HtmlTextWriterTag.Td);
            btn.RenderControl(writer);
            writer.RenderEndTag();
            writer.RenderEndTag();
            
            writer.RenderEndTag();
        }
    }
}

Wednesday, June 18, 2008

Session Asp .Net : Storing DataSet

This blog is an add on to my youtube vide ASP.Net (VB.Net) Session Variable ArrayList - Shalvin
Session state allows values to be stored in one page and accessed through out the site. Session state allows complex data to be stored whereas Query String supports only string value.
The session data is stored in the memory of Web Server.

Asp .Net uses an unique 120 bit identifier for tracking sessions. This ID is the only piece of information that is transmitted between the web server and the client. When the client presents the session ID, ASP.NET looks up the corresponding session, retrieves the serialized data from the state server, converts it to live objects, and places these objects into a special collection so they can be accessed in code. This process takes place automatically.
It is possible to store large amounts of data in a Session Variable. In this example I am constructing a dataset and assigning the contents to a Session variable and passing the showing the data of session variable on another page.

This example makes use of appSettings section of web.config to store connectionstring information. If you are not familiar with appSettings visit my blog Web.config's appSettings section to avoid hard coded memory variable

//web.config




//Default.aspx


using System.Configuration;
using System.Data.SqlClient;
public partial class _Default : System.Web.UI.Page
{
 SqlConnection cnn;
 SqlDataAdapter da;
 DataSet ds = new DataSet();
 protected void Page_Load(object sender, EventArgs e)
 {
  cnn = new SqlConnection(ConfigurationManager.AppSettings.Get	("Cnn"));
cnn.Open(); da = new SqlDataAdapter("select ProductName, UnitPrice from Products", cnn); da.Fill(ds, "Prod");
Session["Prod"] = ds.Tables["Prod"];
} protected void btnShowCart_Click(object sender, EventArgs e) { Response.Redirect("ShoppingCart.aspx");
} }

protected void Page_Load(object sender, EventArgs e)
{
 GridView1.DataSource = (DataTable)Session["Prod"];
 DataBind();
}

Related Blogs
Query String Asp .Net : Working with multiple values

ASP.Net 2.0 Profile

Query String Asp .Net : Working with multiple values

Query string is the part of URL that can be used to send data as parameters. Let's first analyze the query string generated by Google on making a search for 'Shalvin'

http://www.google.co.in/search?hl=en&q=Shalvin.Here two values are passed as query string.

Create a Web site with two web pages.
In the button click of Default.aspx write the following code:

protected void sumButton_Click(object sender, EventArgs e)
{ Response.Redirect("Sum.aspx?Val1=" + txtVal1.Text + "&Val2=" + txtVal2.Text); }

Here is the code for extracting the value in the second page.
protected void Page_Load(object sender, EventArgs e)
{
	Response.Write("Hello " + Request.QueryString["Name"] + " your blog is " + Request.QueryString["Blog"]);
}
 Calculator

<body>
    <form id="form1" runat="server">
    <div>
    
        Value 1<asp:TextBox ID="txtVal1" runat="server"></asp:TextBox>
        <asp:CompareValidator ID="CompareValidator1" runat="server" 
            ControlToValidate="txtVal1" ErrorMessage="Value cannot be string" 
            Operator="DataTypeCheck" Type="Integer"></asp:CompareValidator>
        <br />
        <br />
        Value 2<asp:TextBox ID="txtVal2" runat="server"></asp:TextBox>
        <asp:CompareValidator ID="CompareValidator2" runat="server" 
            ControlToValidate="txtVal2" ErrorMessage="Value cannot be string " 
            Operator="DataTypeCheck" Type="Integer"></asp:CompareValidator>
        <br />
        <br />
        <asp:Button ID="sumButton" runat="server" onclick="Button1_Click" Text="Button" />
    
    </div>
    </form>
</body>


Default.aspx

protected void Button1_Click(object sender, EventArgs e)
{ Response.Redirect("Sum.aspx?Val1=" + txtVal1.Text + "&Val2=" + txtVal2.Text); }

Sum.aspx
int i, j, res;
protected void Page_Load(object sender, EventArgs e)
{
    i = Int32.Parse(Request.QueryString["Val1"]);
    j = Int32.Parse(Request.QueryString["Val2"]);
    res = i + j;
    Response.Write(res.ToString());
}


Related Blog

ASP.Net 2.0 Profile

Session Asp .Net : Storing DataSet

Saturday, June 14, 2008

Ajax ASP .Net VII : Accordion Control and CollapsiblePanelExtender

First let's see Ajax in action.

The page is displaying Shalvin's content by default. Only headers of Site and Contact Info are visible.








When you click on Site and Blog header, it will show its contents and other contents are invisible as shown in the figure below.













Having seen the functionality lets try to implement it.
Working with Accordion is a bit tough in comparison to the controls I have already explained because you won't get a visual interface for working with Accordion and you have to work this control in source view.

If you are not familiar working with Asp .Net is source view visit my blog Asp .Net Introduction : Notepad way



















Inside the Accordion tag place a Panes tag. Inside Panes you can have AccodionPane. AccordionPane inturn have Header and Content. I have added a b tag for Header. In real time you have to use CSS for better look and feel.


Accordion Databinding


Accordion control would most likely be used in conjunction with database data.



Here I am creating an SqlDataSource Control that point to Northwind database's Suppliers table.



I am setting the DataSourceId property of Accordion to the SqlDataSource id and creating HeaderTemplate and ContentTemplate as shown below.



If you are not comfortable working with templated controls visit my blog Asp .net DataList.


















Result

























Here I have made the header Bold and Underline. When you click on a header you can see the contents.










Adding CSS















CollapsiblePanelExtender

<asp:ScriptManager ID="ScriptManager1" runat="server">
</asp:ScriptManager>

<asp:CollapsiblePanelExtender ID="CollapsiblePanelExtender1" runat="server"
CollapseControlID="Header"
ExpandControlID= "Header"
TargetControlID="Content">
</asp:CollapsiblePanelExtender>
</div>

<asp:Panel ID="Header" runat="server" Height="16px" Width="293px">
<u>Shalvin P D </u></asp:Panel>

<asp:Panel ID="Content" runat="server">
.Net Consultant and Corporate trainer<br /> Blog :shalvinpd.blogspot.com
</asp:Panel>


Related Blogs




Ajax .Net I : Extension Controls in Visual Studio 2008


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

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.

sqlcmd and Sql Server

sqlcmd is a command line tool for interacting with Sql Server.

Invoke the command prompt.














If your's is a low configuration machine sqlcmd is best tool since Sql Server Management studio is resource hungry.





sqlcmd -S .\sqlexpress
>create database ShalvinPDBlog
>go
>use ShalvinPDBlog
>create table Categories (
CategoryId int primary key identity(1,1), 
CategoryName varchar(20), Description varchar(60))
>go



Here -S points to the server name.



Related Blog
Transact Sql





For more information : http://msdn.microsoft.com/en-us/library/ms162773.aspx

SQL Server Authentication >sqlcmd -S .\sqlexpress -U sa -P s

Monday, June 9, 2008

Ajax .Net V : FilteredTextBoxExtender and MaskTextEditor

My initial intention of this series of blogs in to give an overview of 40 odd newly added controls. Later on I will editing these blogs and add extra information about each controls.

FilteredTextBoxExtender can be used as an aid to user preventing them from entering invalid data. For example you can allow only numeric, lower case, upper case or certain characters to be enetered into a textbox.


Add an Ajax Web Form, so that ScriptManager will be present on the form. Other wise just add a ScriptManager to the form.

Add an Asp .Net TextBox meant for entering Age. Add a FilteredTextBoxExtender set its TargetControlId property to the TextBox Id. Set the FilterType property to Numbers.




















Now it will allow only numeric input to the control.

As evident from the figure above you can set other filter types also.

Lets take up another another example similar to that demonstrated on http://www.asp.net/AJAX/AjaxControlToolkit/Samples/
where the input expected to be arithmetic operators.

Set the FilterType to Custom and ValidChars property to +-/*.

Don't rely entirely on FilteredTextBoxExtender because on disabling JavaScript on browser the user can bypass the filter. So it should be used more as an aid to the user.


MasktTextEditor

Land Phone
<asp:TextBox ID="txtLandPhone" runat="server"></asp:TextBox>
<asp:MaskedEditExtender ID="MaskedEditExtender1" runat="server"
Mask="9999-9999999" TargetControlID="txtLandPhone">
</asp:MaskedEditExtender>

Related Blog

Ajax .Net I : Extension Controls in Visual Studio 2008

Ajax .Net II : Setting up Ajax Control Toolkit controls

Ajax .Net III : CalendarExtender Control

Ajax .Net IV : TextBoxWaterMarkExtender

Ajax .Net VI : ConfirmButtonExtender

Ajax ASP .Net VII : Accordion Control

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