Practical Demo

Practical Demonstration For Dotnet

My New Blog

Friends and my dudes.. I have altered my blog and change its address to http://www.dotnetandwp7.blogspot.com so please go to that page and refer. In that page i'm going to post Windows phone 7 application development Articles also.. Have a Nice Day....

Wednesday, August 17, 2011

DATALIST CONTROL IN ASP.NET 3.5

Datalist Control in ASP.Net
DataList is a data bound list control that displays items using certain templates defined at the design time. The content of the DataList control is manipulated by using templates sections such as AlternatingItemTemplate, EditItemTemplate, FooterTemplate, HeaderTemplate, ItemTemplate, SelectedItemTemplate and SeparatorTemplate. Each of these sections has its own characteristics to be defined but at a very minimum, the ItemTemplate needs to be defined to display the items in the DataList control. Other sections can be used to provide additional look and feel to the DataList control.



The contents of the DataList control can be manipulated by using templates. The following table lists the supported templates.
The DataList control displays data items in a repeating list, and optionally supports selecting and editing the items. The content and layout of list items in DataList is defined using templates. At a minimum, every DataList must define an ItemTemplate; however, several optional templates can be used to customize the appearance of the list.

AlternatingItemTemplate: If defined, provides the content and layout for alternating items in the DataList. If not defined, ItemTemplate is used.

EditItemTemplate: If defined, provides the content and layout for the item currently being edited in the DataList. If not defined, ItemTemplate is used.

FooterTemplate: If defined, provides the content and layout for the footer section of the DataList. If not defined, a footer section will not be displayed.

HeaderTemplate: If defined, provides the content and layout for the header section of the DataList. If not defined, a header section will not be displayed.

ItemTemplate: Required template that provides the content and layout for items in the DataList.

SelectedItemTemplate: If defined, provides the content and layout for the currently selected item in the DataList. If not defined, ItemTemplate is used.

SeparatorTemplate: If defined, provides the content and layout for the separator between items in the DataList. If not defined, a separator will not be displayed.

At the very minimum, the ItemTemplate needs to be defined to display the items in the DataList control. Additional templates can be used to provide a custom look to the DataList control.


The appearance of the DataList control may be customized by setting the style properties for the different parts of the control. The following table lists the different style properties.

AlternatingItemStyle: Specifies the style for alternating items in the DataList control.

EditItemStyle: Specifies the style for the item being edited in the DataList control.

FooterStyle: Specifies the style for the footer in the DataList control.

HeaderStyle: Specifies the style for the header in the DataList control.

ItemStyle: Specifies the style for the items in the DataList control.

SelectedItemStyle: Specifies the style for the selected item in the DataList control.

SeparatorStyle: Specifies the style for the separator between the items in the DataList control.

You can also show or hide different parts of the control. The following table lists the properties that control which parts are shown or hidden.

ShowFooter: Shows or hides the footer section of the DataList control.

ShowHeader: Shows or hides the header section of the DataList control.

The display direction of a DataList control can be vertical or horizontal. Set the RepeatDirection property to specify the display direction.
The layout of the DataList control is controlled with the RepeatLayout property. Setting this property to RepeatLayout.Table will display the DataList in a table format, while RepeatLayout.Flow displays the DataList without a table structure.

Lets we saw in detail.
To create a datalist oriented application we have to construct the templates.
That is ItemTemplate and EditItemTemplate.
ItemTemplate has been created in the following manner.

Similarly
Lets we saw an example Program..
In Default.aspx page Do the following.
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Untitled Page</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<br />
<asp:DataList runat="server"
DataKeyField="ID"
ID="DataList1"
OnEditCommand="DataList1_EditCommand"
OnCancelCommand="DataList1_CancelCommand"
OnUpdateCommand="DataList1_UpdateCommand">
<EditItemTemplate>
ID: <asp:Label ID="Label1" runat="server"
Text='<%# Eval("ID") %>'>
</asp:Label>
<br />
Name: <asp:TextBox ID="textCategoryName" runat="server"
Text='<%# Eval("name") %>'>
</asp:TextBox>
<br />
Description: <asp:TextBox ID="textDescription"
runat="server"
Text='<%# Eval("description") %>'>
</asp:TextBox>
<br />
<asp:LinkButton ID="LinkButton1" runat="server"
CommandName="update" >
Save
</asp:LinkButton>
 
<asp:LinkButton ID="LinkButton2" runat="server" CommandName="cancel" >
Cancel
</asp:LinkButton>
</EditItemTemplate>
<ItemTemplate>
ID:
<asp:Label ID="IDLabel" runat="server"
Text='<%# Eval("ID") %>'></asp:Label>
<br />
name:
<asp:Label ID="nameLabel" runat="server"
Text='<%# Eval("name") %>'></asp:Label>
<br />
description:
<asp:Label ID="descriptionLabel" runat="server"
Text='<%# Eval("description") %>'></asp:Label>
<br />
<asp:LinkButton runat="server" ID="LinkButton1"
CommandName="edit" >
Edit
</asp:LinkButton><br />
<br />
</ItemTemplate>

</asp:DataList>
</div>
</form>
</body>
</html>

Now Go to Default.aspx.cs:

using System;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Data.SqlClient;

public partial class _Default : System.Web.UI.Page
{
SqlConnection sqlcon = new SqlConnection();
SqlCommand sqlcmd = new SqlCommand();
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
//Bind data to the Data List control when page load first time
bindList();
}
}
void bindList()
{
SqlConnection sqlcon = new SqlConnection();
SqlCommand sqlcmd = new SqlCommand();
sqlcon.ConnectionString = "data source=.;Initial Catalog=datagrid;uid=sa;password=hi";
//Open Sql server Connection
sqlcon.Open();
sqlcmd = new SqlCommand("select * from employ", sqlcon);
//Execute query and fill value in data table
SqlDataAdapter da;
da = new SqlDataAdapter(sqlcmd);
DataTable dt = new DataTable();
da.Fill(dt);
if (dt.Rows.Count > 0)
{
//Bind data into the DataList control
DataList1.DataSource = dt;
DataList1.DataBind();
}
//Close SQl Server Connection
sqlcon.Close();
}
protected void DataList1_EditCommand(object source, DataListCommandEventArgs e)
{
//Get Edit Item index when user click edit button
DataList1.EditItemIndex = e.Item.ItemIndex;
bindList();

}
protected void DataList1_CancelCommand(object source, DataListCommandEventArgs e)
{

//Leave it Item in default for reload DataList
DataList1.EditItemIndex = -1;
bindList();

}
protected void DataList1_UpdateCommand(object source, DataListCommandEventArgs e)
{
//Get User entered value in the Edit mode text boxes
string name = ((TextBox)e.Item.FindControl("textCategoryName")).Text;
string description = ((TextBox)e.Item.FindControl("textDescription")).Text;

//Get the Identity Primary DataKey value when user click update button
int eno = Convert.ToInt32(DataList1.DataKeys[e.Item.ItemIndex]);
sqlcmd = new SqlCommand("update employ set name='" + name + "',description='" + description + "' where ID='" + eno + "'", sqlcon);
sqlcon.ConnectionString = "data source=.;Initial Catalog=datagrid;uid=sa;password=1soft";
sqlcon.Open();
//Execute query to perform update operation on SQL Server
sqlcmd.ExecuteNonQuery();
sqlcon.Close();
//Set datalist default index -1 for display record
DataList1.EditItemIndex = -1;
//Bind new updated data on DataList control
bindList();

}
}

Dont Forgot to create the Database Table Design..
Happy Coding..

Thursday, August 4, 2011

Data Caching in ASP.NET3.5 in DataList View..

Hai My readers,
In this post i will Give a sample program for data caching in asp.net3.5.
Finally i filled all the databound values into the Datalist.
Lets we see in details.

If you are using static data with your ASP.NET applications, such
as that from a database server like Microsoft SQL Server, you should take a
look at caching your data. Previously, this was not an easy thing to do, but the
caching in .NET makes caching your data and objects a trivial task.

In ASP.NET, every page you write extends the
System.Web.UI.Page class, which contains a member called Cache. You use the
Cache property as you would any other IEnumerable, which gives you methods and
properties to get, set, and enumerate through members. We will be looking at
getting and setting items in the cache. In the simplest example, you can
retrieve any object from the cache like so:

Object obj = (Object)Cache["key"];

What this does is look in the Cache for an item with the key "key".
If such an item exists, the object is returned. While we don't need to cast the
returned object to Object, this is just an example of how you must cast the
return to the class type you want returned. If the item is not found, null is
returned, so you will need to do some checking:

Object obj = (Object)Cache["key"];
if (obj == null) {
// Generate a new object and insert it into the cache
}
// Use your object

You can also assign object to the cache like the following code example, but
using Cache.Inset() is a much better means as you'll see later:

Cache["key"] = obj;

Lets We see in details..
Create a Page named Default.aspx and type the coding below..
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">

<head>
<title>Cache Dependency Tester</title>
<meta content="Microsoft Visual Studio 7.0" name="GENERATOR" />
<meta content="C#" name="CODE_LANGUAGE" />
<meta content="JavaScript" name="vs_defaultClientScript" />
<meta content="http://schemas.microsoft.com/intellisense/ie5" name="vs_targetSchema" />
</head>
<body ms_positioning="GridLayout">
<form id="Form1" method="post" runat="server">
<asp:DataList id="dlUsers" style="Z-INDEX: 101; LEFT: 44px; POSITION: absolute; TOP: 104px" runat="server" Height="148px" Width="343px" BorderWidth="1px" GridLines="Horizontal" CellPadding="4" BackColor="White" ForeColor="Black" BorderStyle="None" BorderColor="#CCCCCC">
<SelectedItemStyle font-bold="True" forecolor="White" backcolor="#CC3333"></SelectedItemStyle>
<FooterStyle forecolor="Black" backcolor="#CCCC99"></FooterStyle>
<HeaderStyle font-bold="True" forecolor="White" backcolor="#333333"></HeaderStyle>
<ItemTemplate>
<table bgcolor="#CCCCFF" border="Black" cellspacing="20">
<tr>
<td><b>User_ID:</b><%#DataBinder.Eval(Container.DataItem,"UserId")%><br />
<b>First_Name:</b><%#DataBinder.Eval(Container.DataItem,"FirstName")%><br />
<b>Last_Name:</b><%#DataBinder.Eval(Container.DataItem,"LastName")%><br /></td>
<td>
</td>
<td>
</td>
</tr>
</table>
</ItemTemplate>
</asp:DataList>
<asp:Label id="lblChange" style="Z-INDEX: 102; LEFT: 46px; POSITION: absolute; TOP: 63px" runat="server" Height="28px" Width="295px"></asp:Label>
</form>
</body>
</html>

In that design page i drag and drop one datalist control and added the necessary template.

Goto Default.aspx.cs and type the following Code.
protected void Page_Load(object sender, EventArgs e)
{
DataSet dsUsers;
try
{
if(Cache["Users"]==null)
{
SqlConnection cn;
dsUsers = new DataSet("new");
cn = new SqlConnection("data source=.;Initial Catalog=restaurent;uid=sa;password=1soft;");
// cn = new SqlConnection(ConfigurationSettings.AppSettings.Get("conn"));
SqlDataAdapter daUsers;
daUsers = new SqlDataAdapter("Select * from tblUsers",cn);
cn.Open();
daUsers.Fill(dsUsers,"tblUsers");
//Update the cache object
Cache.Insert("Users",dsUsers, new System.Web.Caching.CacheDependency(
Server.MapPath("Master.xml")), DateTime.Now.AddSeconds(45),TimeSpan.Zero);
HttpContext.Current.Trace.Write(DateTime.Now.AddSeconds(45).ToString() + "is expiry time..");
cn.Close();
cn.Dispose();
HttpContext.Current.Trace.Write("from Database..");
lblChange.Text ="From the database....";
}
else
{
HttpContext.Current.Trace.Write("From cache..");
lblChange.Text ="From the cache....";
dsUsers= (DataSet) Cache["Users"];
}
dlUsers.DataSource =dsUsers;
dlUsers.DataMember = dsUsers.Tables[0].TableName ;
//lblChange.Text += Server.MapPath("Master.xml");
this.DataBind();
}
catch(Exception ex)
{
lblChange.Text = ex.Message;
}
}
Now run the prgram..and u get the desired output.
Happy Coding....

Introduction to DotNet ...

.NET framework is an essential component of the windows operating system and helps create applications by integrating different programming languages, such as Visual C#, Visual Basic, Visual C++, and so on. .NET Framework consists of a virtual execution syatem called the common language runtime(CLR) and a set of class libraries. CLR is a Microsoft product of the Common Language Infrastructure(CLI), which is an industrial standard and a basis for creating execution and development environmentss in which languages and libraries work together. Microsoft introduced .NET to bridge the gap and ensure interoperability between application created in different languages. .NET framework is used to integrate the business logic of an application implemented in different programming languages and services. Consequently, it induces significant improvements in code reusability, code specialization, resource management, development of applications in multiple programming languages, security, deployment, and administration of programs developed in multiple programming languages..

Why .NET?

Why .NET? Mainly .NET is the competitor for JAVA. . Its an environment or platform. It contains collection of services for application development and application execution. It supports different type of applications development. ex: CUI, GUI, console, web based,mobile applications Main thing is .NET is network & Internet based application development.It provides a good development environment. ex: Drag and Drop design - IntelliSense features - Syntax highlighting and auto-syntax checking - Excellent debugging tools - Integration with version control software such as Visual Source Safe (VSS) - Easy project management

Evaluation of .NET:

Around 1995, Java was gaining popularity because of its platform-independent approach and Sun Microsyatem's open source policy. Later in 2002, Sun Microsystems released the enterprise edition of Java. ie., Java 2 Enterprise edition(J2EE), which is a Java Platform to develop and execute distributed Java Applications based on the N-tier architecture. The advent of J2EE eventually led to the decline of, Microsoft's Market share. Consequently, Microsoft started a project called NEXT GENERATION WINDOWS SERVICE(NGWS) to regain the market share . It tooks more than three years to develop the product, Which is Known as .NET. Microsoft released the first version of .NET with the name .NET Framework 1.0 on february 13,2002, along with the Visual studio .NET 2002 integrated development environment(IDE). .NET's Second revised version took nearly a year to release; and it was known as .NET framework 1.1 Microsoft Visual studio .NET, bettre known as Visual studio .NET2003, was also a part of the second release. The next version of .NET framework, .NET Framework 2.0, was released with Visual studio .NET 2005 on november 07,2005. .NET framework 3.0 formerly called WinFX, was released on novenber 06,2006. Finally the latest version of .NET framework, known as .NET framework 3.5, was released with Visual studio .NET2008 on november 19,2007.

Flavors of .NET:


Contrary to general belief .NET is not a single technology. Rather it is a set of
technologies that work together seamlessly to solve your business problems. The
following sections will give you insight into various flavors and tools of .NET and what kind of applications you can develop.
• What type of applications can I develop?
When you hear the name .NET, it gives a feeling that it is something to do only with internet or networked applications. Even though it is true that .NET provides
solid foundation for developing such applications it is possible to create many other types of applications. Following list will give you an idea about various
types of application that we can develop on .NET.
1. ASP.NET Web applications:
These include dynamic and data driven browser
based applications.
2. Windows Form based applications:
These refer to traditional rich client applications.
3. Console applications:
These refer to traditional DOS kind of applications like
batch scripts.
4. Component Libraries:
This refers to components that typically encapsulate
some business logic.
5. Windows Custom Controls:
As with traditional ActiveX controls, you can develop your own windows controls.
6. Web Custom Controls:
The concept of custom controls can be extended to
web applications allowing code reuse and modularization.
7. Web services:
They are “web callable” functionality available via industry standards like HTTP, XML and SOAP.
8. Windows Services:
They refer to applications that run as services in the
background. They can be configured to start automatically when the system boots up.
As you can clearly see, .NET is not just for creating web application but for almost all kinds of applications that you find under Windows.

Feature Of .NET

Features of .NET

Now that we know some basics of .NET, let us see what makes .NET a wonderful

platform for developing modern applications.

• Rich Functionality out of the box

.NET framework provides a rich set of functionality out of the box. It contains hundreds of classes that provide variety of functionality ready to use in your applications. This means that as a developer you need not go into low level details

of many operations such as file IO, network communication and so on.

Easy development of web applications

ASP.NET is a technology available on .NET platform for developing dynamic and data driven web applications. ASP.NET provides an event driven programming model (similar to Visual Basic 6 that simplify development of web

pages (now called as web forms) with complex user interface. ASP.NET server controls provide advanced user interface elements (like calendar and grids) that save lot of coding from programmer’s side.

• OOPs Support

The advantages of Object Oriented programming are well known. .NET provides a fully object oriented environment. The philosophy of .NET is – “Object is mother of all.” Languages like Visual Basic.NET now support many of the OO

features that were lacking traditionally. Even primitive types like integer and characters can be treated as objects – something not available even in OO languages like C++.

• Multi-Language Support

Generally enterprises have varying skill sets.
For example, a company might have people with skills in Visual Basic, C++, and Java etc. It is an experience that
whenever a new language or environment is invented existing skills are outdated.

This naturally increases cost of training and learning curve. .NET provides something attractive in this area. It supports multiple languages. This means that if you have skills in C++, you need not throw them but just mould them to suit
.NET environment. Currently four languages are available right out of the box namely – Visual Basic.NET, C# (pronounced as C-sharp), Jscript.NET and
Managed C++ (a dialect of Visual C++). There are many vendors that are working on developing language compilers for other languages (20+ language compilers are already available). The beauty of multi language support lies in the
fact that even though the syntax of each language is different, the basic capabilities of each language remain at par with one another.

• Multi-Device Support

Modern lift style is increasingly embracing mobile and wireless devices such as PDAs, mobiles and handheld PCs. . . .NET provides promising platform for programming such devices. .NET Compact Framework and Mobile Internet Toolkit are step ahead in this direction.

• Automatic memory management

While developing applications developers had to develop an eye on system resources like memory. Memory leaks were major reason in failure of applications. .NET takes this worry away from developer by handling memory on its own. The garbage collector takes care of freeing unused objects at appropriate intervals.

• Compatibility with COM and COM+

Before the introduction of .NET, COM was the de-facto standard for componentized software development. Companies have invested lot of money and efforts in developing COM components and controls. The good news is – you can still use COM components and ActiveX controls under .NET. This allows you to use your existing investment in .NET applications. .NET still relies on COM+ for features like transaction management and object pooling. In fact it provides enhanced declarative support for configuring COM+ application right from your source code. Your COM+ knowledge still remains as a valuable asset.

• No more DLL Hell

If you have worked with COM components, you probably are aware of “DLL hell”. DLL conflicts are a common fact in COM world. The main reason behind this was the philosophy of COM – “one version of component across machine”.

Also, COM components require registration in the system registry. .NET ends this DLL hell by allowing applications to use their own copy of dependent DLLs.

Also, .NET components do not require any kind of registration in system registry.

• Strong XML support

Now days it is hard to find a programmer who is unaware of XML. XML has gained such a strong industry support that almost all the vendors have released some kind of upgrades or patches to their existing software to make it “XML compatible”. Currently, .NET is the only platform that has built with XML right into the core framework. .NET tries to harness power of XML in every possible way. In addition to providing support for manipulating and transforming XML
documents, .NET provides XML web services that are based on standards like HTTP, XML and SOAP.

• Ease of deployment and configuration

Deploying windows applications especially that used COM components were always been a tedious task. Since .NET does not require any registration as such,
much of the deployment is simplified. This makes XCOPY deployment viable.

Configuration is another area where .NET – especially ASP.NET – shines over traditional languages. The configuration is done via special files having special
XML vocabulary. Since, most of the configuration is done via configuration files,

there is no need to sit in front of actual machine and configure the application manually. This is more important for web applications; simply FTPing new configuration file makes necessary changes.

• Security

Windows platform was always criticized for poor security mechanisms. Microsoft has taken great efforts to make .NET platform safe and secure for enterprise applications. Features such as type safety, code access security and role based
authentication make overall application more robust and secure.