NOTES Using C#
NOTES Using C#
NET
Around 1996 and 1997, a new platform called Active Server Pages (ASP) was
introduced to the world. ASP allowed users to execute code written in a scripting
language VB Script or Jscript on the server, which could access databases and
programmatically created web pages that could be delivered to the web browser.
ASP Versions :
ASP is not a language; it’s a platform that can host scripting languages like VBScript
and Jscript. This platform runs on a web server typically IIS or PWS, but ASP is also
available from third-party vendors for use on other web servers.
ASP : To create dynamic web pages. To create web pages on the fly. The HTML form
data is sent to ASP page, wherein we can use that data to do whatever you need.
1) The server code is mixed in with the HTML and client-side code. It’s hard to believe
that this has become an acceptable method of programming large-scale enterprise
applications.
2) Due to the HTML behavior, many of the ASP development environments required the
creation of tables, and nested tables, in order to obtain the desired position of controls
such as text boxes and buttons.
3) Another problem with traditional ASP programming is that the code is interpreted
rather than compiled, resulting in slower performance.
4) ASP exposed an object called the session object. This object was very easy to use,
but programmers often ran into problems when an additional web server was added,
thereby creating a web farm. The problem is that session state is not shareable within a
web farm environment.
5) ASP also uses late binding when making calls to compiled COM components,
resulting in slower performance.
1
Benefits of ASP.NET
It represents an exciting new platform for creating web sites with the .net framework,
using any .net language. The benefits are,
2) Layout control : Using web forms in ASP.NET and positioning controls such as
textboxes and buttons is easy, and VS.NET will create the appropriate HTML
code for the target browser that is selected. For instance, to be compatible with
most browsers, VS.NET will create tables, and nested tables to obtain the
desired positioning of the controls. If the application only needs to be compatible
with the latest version of Internet Explorer, then VS.NET will position the controls
using DHTML.
4) Early binding : ASP.NET also uses early binding when making calls to COM
components, resulting in faster performance.
8) Session State : ASP.NET has an improved session object. Session state can be
configured to be shared among all servers in a web farm.
9) .NET Framework : Since ASP.NET uses the .NET framework, ASP.NET also
inherits the features of the .NET Framework, such as:
10) Web Services : ASP.NET also provides the web service infrastructure. It is
possible to create a web service with very few lines of code.
Web Forms
2
It is an exciting part of the ASP.NET platform. It gives the developer the ability to
drag and drop the ASP.NET server controls onto the form and easily program the
events that are raised by the control. Web Forms have the following benefits:
Rendering: Web forms are automatically rendered in any browser. In addition, Web
Forms can be tweaked to work on a specific browser to take advantage of its features.
Programming: Web Forms can be programmed using any .NET language, and Win32
API calls can be made directly from ASP.NET code.
.NET Framework: Web Forms are part of the .NET framework; therefore web forms
provide the benefits of the .NET framework, such as performance, inheritance, type
safety, structured error handling, automatic garbage collection, and xcopy deployment.
Extensibility: User controls, mobile controls, and other third-party controls can be
added to extend Web Forms.
WYSIWYG: VS.NET provides the WYSIWYG editor for creating web forms by dragging
and dropping controls onto the web forms.
Code Separation: Web Forms provide a code-behind page to allow the separation of
HTML content from program code.
State Management: Provides the ability to maintain the view state of controls across
web calls.
c:\inetpub\wwwroot
Two ASP.NET Programming Models
1) Single file for each page. – In this type the server code and the client-side tags
and code are placed in the same file with an .aspx file extension.
2) Two file for each page – This model offers the ability to use an .aspx page for the
client-side presentation logic and a C# code-behind file with a .aspx.cs file
extension for the server-side code.
Server Controls
HTML Controls
These are traditional HTML controls, except they have a runat=”server” attribute. This
type of control is used when migrating older ASP pages to ASP.NET.
Common Properties :
3
Forecolor : To set foreground color.
BackColor : To set background color.
Text : To type or to get text.
Textbox
Button
Link Button
Image Button
HyperLink
To create hyperlinks.
ImageUrl : Specify image filename.
NavigateUrl : Specify the .aspx or .htm filename.
Text : Specify text to be displayed as hyper text.
CheckBox
Text:
TextAlign:- Left/ Right
AutoPostBack:- true/false : If True, it Submits Form.(Refreshes the Page)
Checked : true/false.
Text:
TextAlign:- Left/Right
GroupName:- specify common name (variable) for all the radiobuttons.
AutoPostBack:- true/false : If True, it Submits Form.(Refreshes the Page)
Response.Write(RadioButton1.Text);
string a= RadioButton1.Text;
DropDownList
5
Response.Write(DropDownList1.SelectedIndex.ToString());
Response.Write(DropDownList1.SelectedItem);
ListBox
Response.Write(ListBox1.SelectedIndex);
Response.Write(ListBox1.SelectedItem);
CheckBoxList/RadioButtonList
RepeatDirection : Horizontal/Vertical.
6
RepeatColumns : type No.
RepeatLayout : table/flow.
string b=””;
protected void button1_Click(object sender, System.EventArgs e)
{
int a;
for (a=0;a<CheckBoxList1.Items.Count;a++)
{
if (CheckBoxList1.Items[a].Selected)
{
// Response.Write(CheckBoxList1.Items[a].Text + "<br>");
b=b+ CheckBoxList1.Items[a].Text+” “;
}
}
Response.Write(“b=”+b);
}
Response.Write(RadioButtonList1.Text);
c=RadioButtonList1.Text;
Image
Image1.ImageUrl = "cyan-ball.gif";
Table
Rows: To add rows (Click on Add Button -> Click on Cells ->Add->type coloumn
data in text property (Repeat) ->OK
For second row: (Click on Add Button -> Click on Cells ->Add type coloumn data
in text property (Repeat)…….Ok.
7
We can create table also from Table Menu->Insert Table and give all the
settings(row, col….)->O.K.
We can also insert a ready-made table in the form which looks like a frame(No
Border).A hyperlink can be included. It’s target and NavigateURL properties can
be given so that the file opens in a iframe in the table.
Bulletedlist
ImageMap
It displays a image, and divides the image into various areas so that we can use that
area as a hyperlink.
HiddenField
To send data from one page to another page w/o showing it. The data will go to
subsequent page when postback event occurs. Using Request.Form[] we can read.
FileUpLoad
8
It is used to specify filename to be uploaded, or to attach.
It will display a textbox, button (Browse). Upon clicking on the button open file dialog
box will appear, from there you can select any file, that file name will appear in the
textbox.
To group components. After grouping we can hide/show all the components. Also to
specify backgroundcolor or backgroundimage to a particular portion of area.
In page_load event :
PlaceHolder
It is used as a container to store web server controls on the web page that were added
at run-time.
In page_load event :
9
TextBox t1 = new TextBox();
t1.Text = "sekhar";
t1.Style["position"] = "absolute";
t1.Style["top"] = “300px”;
t1.Style["left"] = “200px”;
PlaceHolder1.Controls.Add(t1);
AdRotator
Advertisement Rotator. It displays various images one by one just like how
advertisement appears in a TV. Upon clicking on the image the particular specified web
site is opened.
Procedure :
1) Create an .xml file (called avertisements file). Click on WebSite->Add New Item-
>XML File->Type filename->Add. (ads.xml)
2) Take Adrotator control->Set Width, Height.
3) Specify the .xml file in AdvertisementFile property.
<Advertisements>
<Ad>
<ImageUrl>Follow.jpg</ImageUrl>
<NavigateUrl>http://www.rediff.com</NavigateUrl>
<AlternateText>Rediff</AlternateText>
<Impressions>100</Impressions>
</Ad>
<Ad>
<ImageUrl>autumn.jpg</ImageUrl>
<NavigateUrl>http://www.Google.com</NavigateUrl>
<AlternateText>Google</AlternateText>
<Impressions>50</Impressions>
</Ad>
<Ad>
<ImageUrl>Ascent.jpg</ImageUrl>
<NavigateUrl>http://www.yahoo.com</NavigateUrl>
<AlternateText>yahoo</AlternateText>
<Impressions>10</Impressions>
</Ad>
</Advertisements>
Calendar control
To display calendar.
Single Date :
string a;
protected void Calendar1_SelectionChanged(object sender, EventArgs e)
{
Response.Write(Calendar1.SelectedDate.ToString());
a= Calendar1.SelectedDate.ToString();
}
Multiple Dates :
Restricting a Date :
All are basically label controls, if error occurs they will appear.
RequiredFieldValidator : It checks for the given value if it is equal it will display error
message.
InitialValue : Specify text to be compared with the textbox data. If you leave it
blank then it checks textbox data for blank or not. If blank error will be displayed.
If you type any data in this, it will compare textbox data with this data if both are
same then it gives error otherwise no error.
11
CompareValidator : It compares data of textbox with the specified value at design time.
RangeValidator : It checks whether the entered data is in between two given datas.
12
ErrorMessage : Specify error message to be displayed.
<script language=”VBScript”>
function test(source,args)
if (args.value=10) then
args.IsValid=true
else
args.IsValid=false
end if
end function
</script>
Also we can write the code in the CustomValidator_ServerValidate event. At that time
don’t set ClientValidationFunction property. For this double click on the CustomValidator
control.
Even though error occurs page will be submitted but other validation control does
not Submit page if error occurs.
Sample custom validation for checking whether textbox contains no. 10 or not :
string check;
protected void CustomValidator1_ServerValidate(object source,
ServerValidateEventArgs args)
{
string a = args.Value;
int l = a.Length,j,b,f=0;
char c;
for (j = 0; j < l; j++)
{
c = Convert.ToChar(a.Substring(j, 1));
b = (int)c;
if ((b > 64 && b < 91) || (b > 96 && b < 123))
{
13
f = 1;
}
else
{
f = 0;
break;
}
}
if (f == 1)
{
args.IsValid = true;
}
else
{
args.IsValid = false;
}
}
ValidationSummary : It displays all the errors occurred either in bulleted list, ordinary
list or in paragraph style.
DisplayMode : Bulleted/List/Paragraph.
Menu
To create menus. Click on Edit Menu Items->Add Root(set its properties Text,
Popoutimageurl, Separator image url) or click on Child->Set Navigate URL,
ImageURL, , Text, Tooltip, Target (_new/_blank to open in new browser)->Ok.
Orientation : Horizontal/Vertical.
Also we can specify SiteMap as Data Source for Menu. For this create a web.sitemap
enter all the url’s which you like to use as hyperlinks, create SiteMapDataSource using
web.sitemap then specify SiteMapDataSource as DataSource for the menu.
Treeview
Click on Edit Nodes or Nodes (from properties window)->Click on Add root node-
>Click on add child node->Type node text in text property, select image file name
for ImageUrl property, select filename for navigation in NavigateUrl property,
Select true/false from ShowCheckbox property, Select true/false from Checked
14
property, Type _blank in Target property for opening the file in new window,
Select true/false from Expanded property (for root item).
Also we can specify SiteMap as Data Source for treeview. For this create a
web.sitemap enter all the url’s which you like to use as hyperlinks, create
SiteMapDataSource using web.sitemap then specify SiteMapDataSource as
DataSource for the treeview.
TreeView1.Nodes.Add(t1);
TreeView1.Nodes[0].ChildNodes.Add(t2);
TreeView1.Nodes[0].ChildNodes.Add(t3);
TreeView1.Nodes[0].ChildNodes[0].ChildNodes.Add(t11);
15
TreeView1.Nodes[0].ChildNodes[1].ChildNodes.Add(t12);
TreeView1.Nodes[0].ChildNodes[0].ChildNodes[0].ChildNodes.Add(t13);
If (! Page.IsPostBack)
{
}
SitemapPath
It displays navigation structure of website. To use this control first of all we have to
create sitemap. Site map is a file which contains url’s, titles of the pages available in
your web site. Using this url’s, titile’s sitemap path displays navigation structure of the
web page. For this it displays the title on navigation bar containing current page title and
previous pages titles.
1) Click on website -> add new item -> select site map -> click on add.
2) Type URL name, in URL property, page title in title property in the file
created(Websitemap in step1).
3) Double click on site map datasource to create sitemapdatasource.
4) Double click on sitemappath control, it immediately displays the navigation
structure on the page.
Style 1 :
For the above structure we have to create sitemap file like below :
Style 2 :
Here main is the home page title, first and second are sub pages of main, aaaa, bbbb
are sub-sub pages of first, aaa, bbb are sub-sub pages of second.
</siteMapNode>
</siteMap>
17
Response.Buffer=true/false : If it is true the output will be saved in buffer on server.
At the end the whole output will be sent to client. We have to set it to false.
Response.ExpiresAbsolute=Date : It saves the output of the web page till the expiry
of the given date & time.
Response.Flush() : It sends all the data buffered to the client and clears it.
To set the status code write in the Page_Load() event of an empty page the below
statement :
Response.StatusCode=400;
Variable=request.UrlReferrer : Returns the url name from where client has come.
Response.Write("<br>"+Request.Url.ToString());
18
Response.Write("<br>"+Request.Url.AbsolutePath);
Response.Write("<br>"+Request.UrlReferrer);
Response.Write("<br>" + Request.UserAgent.ToString());
Response.Write("<br>" + Request.UserHostAddress.ToString());
Response.Write("<br>" + Request.UserHostName.ToString());
string[] l = Request.UserLanguages;
foreach (string i in l)
Response.Write("<br>" + i);
string[] a = Request.AcceptTypes;
foreach (string i in a)
Response.Write("<br>" + i);
Response.Write("<br>" + Request.ApplicationPath.ToString());
Response.Write("<br>" + Request.Browser.BackgroundSounds);
Response.Write("<br>" + Request.ContentLength);
Response.Write("<br>" + Request.ContentType);
Response.Write("<br>" + Request.Path);
Response.Write("<br>" + Request.PathInfo);
Response.Write("<br>" + Request.ServerVariables[0].ToString());
Response.Write("<br>" + Request.TotalBytes);
19
State Management
Maintaing or finding the state of a user is called state management. This can be done in
3 ways.
1) Application
2) Session
3) Cookies
2) Session : To create and maintain session scope variables. These are created
every time a user opens the web site and they are destroyed automatically when
user closes the browser or changes the web site. These variables are created
individually for every user.
1) While using same variable in recurring events. i.e. the variable does not hold
previous value because the variable shall die after the event execution is over
hence we should use session variable.
2) Storing a value in a variable in a page and using it in a new page.
The main use of Session object is to create and maintain session variables.
Variables created in a page will lost their values once the page execution is over.
To avoid create session variables.
int i;
protected void Page_Load(object sender, EventArgs e)
{
if (! IsPostBack)
{
Session["j"] = 0;
Application["c"] = 0;
}
20
}
protected void Button1_Click(object sender, EventArgs e)
{
‘ ordinary page scope variable
i= i + 1;
Response.Write("<Br>ordinary variable i=" + i);
Example of creating session variables & sessionid in one Page & using in another
page:
Coding of default4.aspx:
// application variable
Response.Write("<Br>application variable c=" + Application["c"]);
if (Session["b"] == null)
Response.Redirect("~/default4.aspx");
else
Response.Write("b=" + Session["b"]);
}
21
Cookie : It is small amount of info stored by web server on client machine.
Types of cookie :
a- temperary cookie (the info will be lost when user closes the browser or logout)
b- permanent cookie(persistent cookie) : the info will be stored on client machine till
the time specified)
user name
Password
d = cook.Values["currentdatetime"].ToString();
u = cook.Values["username"].ToString();
22
p = cook.Values["password"].ToString();
System.Text.StringBuilder sb = new System.Text.StringBuilder();
sb.Append("date time of creation of cookie is " + d + "<br>");
sb.Append("user name is " + u + "<br>");
sb.Append("password is " + p + "<br>");
Label1.Text = sb.ToString();
}
else
{
Label1.Text = "no cookie present";
}
}
3) Also it places the necessary tag for the above control. Here tag name is lg its
prefix is uc1.
4) Now in the code winow using tb1 object you can use all its properties, functions
etc. in the normal way.
To update the contents of web page without refreshing/round trip we can use ajax
scripting controls.
23
1. Take Label.
2. Take scriptmanager control.
3. Take UpdatePanel control.
4. Take Timer control, set 1000 in interval property.
5. Take Label control.
6. Place the Timer, Label2 in updatepanel.
Label2.Text=DateTime.Now.ToString();
if (DropDownList1.SelectedIndex==0)
{
DropDownList2.Items.Add(“Nagpur”);
DropDownList2.Items.Add(“Mumbai”);
}
Displaying Time on screen continuously without refreshing the page, the label is
in updatepanel.
1. Take Label.
2. Take scriptmanager control.
3. Take Timer control.
4. Take UpdatePanel control.
5. Place label in updatepanel.
6. Click on UpdatePanelControl->go to properties window->click on triggers->click
on add and select asynchronouspostbacktrigger->select the control id you like to
use->select its event.
Label2.Text=DateTime.Now.ToString();
24
3. Take label, type in text property Getting Data…..
4. Take UpdatePanel control.
5. Take dropdownlist1 control.
6. Take dropdownlist2 control. Place both the dropdownlist controls inside update
panel.
System.Threading.Thread.Sleep(1000);
DropDownList2.Items.Clear();
if (DropDownList1.SelectedIndex==1)
{
DropDownList2.Items.Add(“Nagpur”);
DropDownList2.Items.Add(“Mumbai”);
}
After selecting state from DropDownList1, it will display Getting Data….. for 1
second after that the cities will be displayed in DropDownList2.
Take a label->Click on its arrow which is displayed on top, right side->Add Extender-
>Always Visibile Control Extender->Set its properties like Horizontal Offset, Horizontal
Side, Vertical Side, Use Animation, Scroll Effect Duration.
Take a textbox->Click on its arrow which is displayed on top, right side->Add Extender-
>Click on Calendar Extender->Set its properties Format->type d or the required format
specifier you like. In format property d-date.
Take a textbox->Click on its arrow which is displayed on top, right side->Add Extender-
>Click on Colorpicker Extender->After selecting any color the color is displayed in the
textbox, from the textbox use the color where ever you require.
Take a textbox->Click on its arrow which is displayed on top, right side->Add Extender-
>Click on FilteredTextBoxExtender->Set its properties like FilterType (Numbers,
Lowercase alphabets, Uppercase alphabets, which ever option you select that type of
characters will be accepted). If you select FilterType custom then select
ValidChars/InvalidChars from FilterMode. If you take ValidChars type ValidChars in
25
ValidChars property, If you take InValidChars type InValidChars in InValidChars
property.
Take a textbox->Click on its arrow which is displayed on top, right side->Add Extender-
>Click on MaskType->Select Number/Date/Time/DateTime from Masktype property,
Type the format in which you want to enter nos. in Mask property (9,99,999.99). Type
the format in which you want to enter dates in Mask property (99/99/9999 or 99:99:99 or
99/99/9999 99:99:99). Also you can select the format for dates from UserDateFormat
and for times from UserTimeFormat.
Take a textbox-> ->Click on its arrow which is displayed on top, right side->Add
Extender->Click on TextboxWatermarkExtender->Set its property WaterMarkText with
your text.
ADO.NET
.NET uses ADO.NET (Activex Data Objects) as its primary data access and
manipulation protocol. It works with connected as well as disconnected databases.
Database Programming can be done using MS Access, Oracle, SQL Server or any
ODBC Complaint Database. (Open Database Connectivity).
Namespaces :
ACCESS – System.Data.Oledb
Oracle – System.Data.OracleClient
SQL Server – System.Data.SqlClient
ODBC – System.Data.ODBC
Classes :
Sequence :
Access :
Physical path:
Logical Path :
Functions :
or
DataSet : To store data retrieved using dataadapter. Also we can store data of multiple
tables.
OledbDataReader : To read data from table. The read data stored in this object. Directly
we can operate on data using this object, no need to fill the data in dataset.
oledbdatareader dr;
dr=cmd.executereader(); -> Executes only select query
Oracle Connectivity :
Windows Authentication :
29
Console.WriteLine(“a={0}b={1}”,a,b);
Console.WriteLine(“a=”+a+”b=”+b);
<ItemTemplate>
<asp:HyperLink runat="server" ID="h1" NavigateUrl='<%# Eval("link")%>'>
<%# Eval(“rno”) %>
</asp:HyperLink>
</ItemTemplate>
</asp:FormView>
Caching
In this type of caching the entire page will be cached for specified time. After the expiry
of the specified time only the page will be refreshed. For this click on source tab->type
the following tag, the duration is in seconds.
Label1.Text=DateTime.Now.ToString();
B) Data Caching :
Cache["objectname/variable"]="data"/objectname;
Cache["a"]=15;
Cache["b"]="sekhar";
Cache["c"]=TextBox1.Text;
30
Cache["d"]=ds;
int a1;
string b1;
string c1;
DataSet d1;
a1=Convert.ToInt32(Cache["a"]);
b1=Cache["b"].ToString();
c1=Cache["c"].ToString();
Response.Write(“a1=”+a1);
Response.Write(“<br>b1=”+b1);
Response.Write(“<br>c1=”+c1);
d1=new DataSet();
d1=Cache["d"];
Note : The cached data of one website. can’t be used in another website.
mydata1 will be cached for 1 minute, after expiry of 1 minute system will get data
from database table, displays it and then stores in a object called mydata1 which
is available in cache.
mydata2 will be cached for 2 minutes, after expiry of 2 minutes system will get
data from database table, displays it and then stores in a object called mydata2
which is available in cache. If anybody retrieves the same page before expiry of
2 minutes the difference time will be added to the 2 minutes, the data is stored in
the cache till the expiry.
It is called Sliding Expiration Time because the time left in the previous expiry is
added to the current expiry like that the expiration time increases. If the time to
expire is continuously increases it is called sliding, hence it is called sliding
expiration time.
31
//if (Cache["mydata3"] == null)
if (Cache["mydata1"] == null)
//if (Cache["mydata2"] == null)
{
Label1.Text = "Data retrieved from table";
sda.Fill(ds);
GridView1.DataSource = ds.Tables[0];
GridView1.DataBind();
DataView dv1 = new DataView(ds.Tables[0]);
//Cache["mydata3"] = dv1;
Cache.Insert("mydata1", dv1, null, DateTime.Now.AddMinutes(1), TimeSpan.Zero);
/// Cache.Insert("mydata2", dv1, null, DateTime.MaxValue, TimeSpan.FromMinutes(2));
}
else
{
Label1.Text = "Data retrieved from cache";
// DataView dv = (DataView)Cache["mydata3"];
DataView dv = (DataView)Cache["mydata1"];
// DataView dv = (DataView)Cache["mydata2"];
GridView1.DataSource = dv;
GridView1.DataBind();
}
}
Services available on internet are called Web Services. Normally every web service
contains various functions with or with out arguments, does some processing and
returns data to the user. For this first of all we have to add web reference to your web
site/project, then create object and call the function by sending arguments to it, display
the resultant value.
[WebMethod]
public int sum(int a, int b)
{
return a+b;
}
Use this page as a starting point to find Web services. You can click the links below, or
type a known URL into the address bar.
Browse to:
Web services in this solution
Example :
33
Label4.Text = l1.mul(Convert.ToInt32(TextBox1.Text),
Convert.ToInt32(TextBox2.Text)).ToString();
}
Example :
ServiceReference1.ServiceSoapClient l1 = new
ServiceReference1.ServiceSoapClient();
1. Machine.Config
2. Web.Config
2. Web.config : It is also xml file, that can be found in the web application directory.
It sets the configuration for one website only.
Note: The web.config file will override the settings of the machine.config file.
34
1. appSettings: The application settings allow the user to set the application
configuration details. It enables the user to store and retrive information as key-
value pairs.
<appSettings>
<add key="cs" value="Data Source=Home-1;initial catalog=pubs;uid =sa;
pwd=secret"/>
</appSettings>
<connectionStrings>
<add name="2to3ConnectionString" connectionString="Data Source=LAB-
387;Initial Catalog=2to3;Integrated Security=True"
providerName="System.Data.SqlClient" />
</connectionStrings>
string cs1 =
System.Configuration.ConfigurationManager.ConnectionStrings["2to3ConnectionString"
].ToString();
Login controls
To enter username, password for validation. We can also create new user, change
passwords, recover passwords, making log in, log out, displaying user login-names etc.
35
To use login controls first of all we have to configure a database. There are two
procedures to configure database.
Procedure 1 :
If you sql server 2005 express edition then no need to anything, automatically .net has
got provision to use the database. It creates aspnetdb.mdf in Sql Server 2005 express
edition, adds that database in your web site app_data folder, tables and uses it.
Procedure 2 :
If external database is installed on machine like Microsoft Sql Server 2000/2005 then
we have to configure it manually.
a) Create a database.
b) Go to .net command prompt (Click on Start->All Programs->Microsoft Visual
Studio 2008->Visual Studio Tools->.Net Command Prompt)
c) type aspnet_regsql->Next->Next->Type/select servername->Click on Windows
Authentication->Select previously created database->Next->Next->Finish.
d) Open Web.Config file, add connection string.
<connectionStrings>
<clear/>
<add name="localsqlserver"
connectionString="server=(local);Database=sekharlogin;Integrated
Security=True" providerName="System.Data.SqlClient"/>
</connectionStrings>
<authentication mode="Forms">
<forms loginUrl="login.aspx" name="l1" />
</authentication>
<authorization>
<deny users="?"/>
</authorization>
1) Create Page giving name login.aspx, place login control. Specify any page name in
DestinationPageUrl property for successful login display page.
36
CreateUserText : Type any text which will be used as a hyperlink.
CreateUserUrl : Specify filename to be opened if the above hyperlink is clicked
(CreateUserText).
DestinationPageUrl : Specify filename to be opened upon successful login.
FailuteText : Specify text to be displayed if login fails.
LoginButtonImageUrl : Specify image filename.
LoginButtonText : Specify text.
LoginButtonType : Select button type.
PasswordRecoveryText :
PasswordRecoveryURL :
go to property window
now in desktop
right click on mycomputer
select manage
select services and applications
expand internet information server
expand default smtp virtual server
r c on domains
select new domain
select alias
type computername.com (dc-6.com)
click on finish button
37
5) Create a page, place hyperlinks for login, changing password, forgot password,
creating user and connect with proper files.
7) Now restrict the users while accessing the admin folder pages. For this click on
asp.net configuration wizard->click on go to security tab->select create access rules-
>select admin folder->select role admin->and then select allow radio button->and then
click ok button.
8) once again click on create access rule->select all user radio button->select deny
radio button->click on ok button->close the admin site.
10) create two hyperlinks for accessing the pages created in admin folder.
11) Now log-in using username, password of admin role user, click on the hyperlinks
you will be taken to that page.
12) Now log-in using username, password of student role user, click on the hyperlinks
the hyperlinks will not work.
38
Using Resources for Localization with ASP.NET :
An effective way to create localized Web pages is to use resources for your page's
text and controls based on the user's language and culture. By using properties placed
in resource objects, ASP.NET can select the correct property at run time according to
the user's language and culture. The process is straightforward :
• In your page, you indicate that controls should use resources for their property
values.
• At run time, the controls' property values are derived from the resource file.
In this section, you will work with implicit localization. In implicit localization, you
specify that control properties should automatically be read from a resource file, but
you do not need to explicitly specify which properties are localized. Then, you create a
resource file with localized values for specific properties. At run time, ASP.NET
examines the controls on the page. If the control is marked to use implicit localization,
ASP.NET looks through the resource file for the page. If it finds property settings for
the marked control, ASP.NET substitutes the values in the resource file for those in the
control.
In this example of implicit localization, you use a combination of the designer and the
Resource Editor to generate a default resource file that you will use as a starting point
for localization in two languages. Visual Web Developer will generate a resource file
based only on the controls on your page. For this reason, it is a good idea to generate
the resource file after you have completed your page's control layout, including simple
controls such as buttons, labels, and text boxes.
Steps :
After creating the page and adding the controls, you can use a Visual Web Developer
command to generate a local resource file for this page. The local resource file will
contain the resource strings for the controls on the page. Visual Web Developer
generates a resource string for each property that is designated internally in the control
as localizable. Each control can have different properties designated as localizable,
although most text-based properties are marked that way.
39
Visual Studio creates a new folder named App_LocalResources, and within the
App_LocalResources folder, a new file named Default.aspx.resx. If you
named your page something other than Default.aspx, the .resx file will reflect
whatever name you chose. When using implicit localization, resource file names
are based on individual page names.
Visual Studio has added an attribute to your controls to retrieve their values from
your newly created resource file. For example, the Button control's markup has a
new meta:resourcekey attribute.
When a browser sends a request to Web server, the request can include information
about the current language and culture. For example, a browser might send the string
"en-us" to indicate it has been set to use United States English; another browser might
send the string "en-gb" to indicate it has been set to use British English.
The resource file is used as the default resource file for all requests. (It is the resource
file for the fallback culture.) If no culture is specified by the browser, or if the browser
request includes a language or culture that you do not support, resource values are
pulled from this default file.
Now that the resource file is created, you can place localized text within it by using the
Resource Editor.
In the Resource Editor, under Value, are the Text properties for each of the
controls that you placed onto your page. Changing the value here will change the
value for the default culture.
40
The text you provided in the Resource Editor is shown as the label for Button1.
When using implicit localization, syntax properties in resource files will override
properties specified in the page itself.
Each language and culture combination requires a unique resource file. To add other
cultures, you can use your default file as a starting point. You can create resource files
for different cultures and locales by creating new resource files in which the ISO
language codes are part of the file name (for example, en-us, fr-ca, and en-gb).
These ISO codes are placed between the page name and the .resx file name
extension, as in Sample.aspx.en-us.resx. To specify a culturally neutral language, you
would eliminate the country code, such as Sample.aspx.fr.resx for the French
language.
Note:
When using implicit localization syntax, you must create a separate series of resource
files for each page.
3. Right-click the Copy of Default.aspx.resx file, click Rename, and then type
Default.aspx.fr.resx.
4. Open Default.aspx.fr.resx.
5. For the Button, Label, and TextBox controls, set Text to French Button,
French Label, and French TextBox, respectively.
Before you can see if this new resource file is used by ASP.NET, you must alter your
browser settings to request the desired culture.
41
2. Click Languages.
3. In the Language Preference dialog box, click Add.
4. In the Add Language dialog box, under Languages, click French (France) [fr],
and then click OK.
5. Click Add and add Spanish (Mexico) [es-mx] to the list of languages.
6. Click Add and add Arabic (Egypt) [ar-eg] to the list of languages. Click Add and
add Hindi [hi] to the list of languages.
Internet Explorer is now set to pass fr as the language setting for any request. With
the culture set to auto in the Sample.aspx page, ASP.NET will attempt to locate a
resource file and its corresponding values to assemble the page according to your
language and culture preferences.
The page is refreshed with values from the localized French language file instead
of the English version.
Also you can set UICulture property of Page to required language. At that time it studies
the .resx for the equivalent values then displays accordingly in that language.
In the first part of this walkthrough, you used ASP.NET implicit localization to have
controls display localized text. You generated a resource file with property values in it,
and in the process, you added an attribute to each control that instructed it to fill its
property values, if any, from the resource file. Implicit localization works automatically,
in that you do not need to specify property by property how to read information from a
resource file.
However, at times you want to have more direct control over how properties are set.
For this, instead of using implicit localization, you can use explicit localization. With
explicit localization, you set the value of a property by using an expression pointing to
a resource file. When the page runs, the expression is evaluated, the value is read
from the specified resource file, and then the value is used to set the property.
Explicit localization is useful when you have large bodies of text or custom messages
you want to localize, in addition to controls and labels. For example, you could develop
a series of localized welcome and thank you messages for an e-commerce site, and
42
use explicit declarative expressions to place this text on your pages. Additionally,
explicit localization allows you to maintain a single set of localized resource files rather
than maintaining a separate set of files for each page.
In this section, you will create resource files manually and reference them by using
ASP.NET declarative expression syntax. You will create a resource file for a simple
thank you message. Unlike using the designer, a separate resource file is not required
for each ASP.NET page.
The base name of your resource file will be Resource1. For each language you want
to localize, you will create another file with the appropriate language code (and
optionally the culture code) as part of the file name. For example, for U.S. English you
would create a file named LocalizedText.resx. For the French language in Canada,
you would create a file named LocalizedText.fr-ca.resx. Both files would be placed
under the Resources directory of your Web application. Unlike the implicit example
previously, you do not need to maintain a resource file for each .aspx page; instead,
you can maintain a single series of files for each language or culture you support.
2. Right-click the App_GlobalResources folder, and then click Add New Item.
The Resource1.resx file will act as the resource for the fallback culture.
The string "fr" identifies the file as the resource to use if the browser's language
is set to French (regardless of culture).
The string "es-mx" identifies the file as file as the resource to use if the browser's
language is set to Spanish (Mexico).
43
11. Open the Resource1.fr.resx, create a resource string named Msg1,
assign it the value Bon jour. When you are finished, save and close the file.
Note:
To insert the letter with acute (í), type ALT+0237 on the numeric keypad with Number
Lock on.
13. You have created three values for the resource named Msg1. ASP.NET
will read the value out of the appropriate resource file based on what language
the browser is set to.
Now that your resource file is created, you can return to the page and add controls that
will reference the resource.
3. Right-click the Label control, click Properties, and then click the ellipsis (…)
button in the Expressions box.
7. Click OK.
Your label's text attribute now has an explicit expression stating the base file from
which to retrieve the resource and the key to select.
44
Copy Code
<asp:Label ID="Label2" Runat="server" Text="<%$ Resources:Resource1, Msg1
%>">
Note:
With the resource file completed, and the declarative expression added, you can test
the page. After the last test, your browser was set to report French as its language
preference. During the testing, you will change the browser's language several times.
The French-language version of the text you provided in the Resource Editor is
shown as the text for the Label control.
3. Click Languages.
4. In the Language Preference dialog box, move Spanish (Mexico) [es-mx] to the
top of the list of languages. When you are finished, click OK and close the
Internet Options dialog box.
6. Change the language to Arabic and then press F5 to refresh the page again.
This time, the text is displayed in the language you used in the fallback resource
file. Because you did not create a file LocalizedText.ar-eg.resx, ASP.NET was
not able to locate text that matched the language and culture reported by the
browser, so it used the fallback resource file.
7. When you are finished testing the page, set the language back to the language
your preferred language.
45
Profiles
They are used to store per user settings on web server. ie if we login in yahoo and
want to store some personal info on web server, so that when i login next time i can
see or retreive my personal info.
<connectionStrings>
<clear/>
</connectionStrings>
<system.web>
<anonymousIdentification enabled="true"/>
<profile>
<properties>
</properties>
</profile>
if (!Page.IsPostBack)
{
TextBox1.Text = Profile.companyname;
TextBox2.Text = Profile.companyaddress;
TextBox3.Text = Profile.favcolor;
}
Profile.companyname=TextBox1.Text;
Profile.companyaddress=TextBox2.Text;
Profile.favcolor = TextBox3.Text;
Themes
are used to change the look and feel of your web sites.
it contains
1- skin file - which contains code to change the look and feel of web server
controls.(ie label , button ,textbox etc.)
3- select theme
47
now go to default page
body
{
h1
{ background-color: #00FFFF; font-family: 'Times New Roman' , Times, serif;
font-size: xx-large;
}
similarly create another theme named conco2, now you want that user can select
the appropriate theme
go to setting page and place one dropdown list control and add items conco1,
conco2
48
protected void Page_PreInit(object sender, EventArgs e)
{
Page.Theme = Profile.mytheme;
}
and in button 1 click on setting page write
Response.Redirect(“~/default.aspx”);
}
ADO.Net Programs
Program for inserting, deleting, updating, displaying data in textboxes (single & all
records).
Adding data in combobox, tree view, selecting from combobox, treeview and showing in
textboxes.
49
// declare the below inside class
if (! Page.IsPostBack)
{
con.Open();
cmd.Connection = con;
cmd.CommandText = "select * from student";
dr = cmd.ExecuteReader();
TreeNode t1;
50
TreeNode t2=new TreeNode(“Roll No”);
TreeView1.Nodes.Add(t2);
DropDownList1.Items.Add(“Select any Roll No”);
ListBox1.Items.Add(“Select any Roll No”);
string rno;
while (dr.Read())
{
rno= dr.GetValue(0).ToString();
DropDownList1.Items.Add(rno);
ListBox1.Items.Add(rno);
t1=new TreeNode();
t1.Text =rno;
TreeView1.Nodes.Add(t1);
TreeView1.Nodes[0].ChildNodes.Add(t1);
}
con.Close();
}
try
{
r = int.Parse(DropDownList1.SelectedItem.Text);
r1 = r;
qry = "select * from student where rno=" + r;
//MessageBox.Show(qry);
con.Open();
cmd.Connection = con;
cmd.CommandText = qry;
dr = cmd.ExecuteReader();
if (dr.Read())
{
textBox1.Text = dr.GetValue(0).ToString();
textBox2.Text = dr.GetValue(1).ToString();
textBox3.Text = dr.GetValue(2).ToString();
textBox4.Text = dr.GetValue(3).ToString();
textBox5.Text = dr.GetValue(4).ToString();
fname = dr.GetValue(5).ToString();
if (File.Exists(fname))
pictureBox1.Image = Image.FromFile(fname);
}
}
con.Close();
com.Parameters.Clear();
com.Parameters.Add(sp1);
com.Parameters.Add(sp2);
com.Parameters.Add(sp3);
com.Parameters.Add(sp4);
com.Parameters.Add(sp5);
com.Parameters.Add(sp6);
52
//com.CommandText="select * from student where rno=@rno";
sda.Fill(ds, "student1");
GridView1.DataSource = ds;
GridView1.DataMember = "student1";
GridView1.DataBind();
//sda.Fill(ds, "student");
//GridView1.DataSource = ds.Tables["student"];
GridView1.DataBind();
//sda.Fill(ds);
//GridView1.DataSource = ds.Tables[0];
GridView1.DataBind();
53
Displaying multiple tables in DataGridView :
GridView1.DataSource = ds.Tables["emp"];
GridView1.DataBind();
GridView1.DataSource = ds.Tables["student"];
GridView1.DataBind();
54
Displaying data in DropDownList / Listbox / RadioButtonList :
if (! Page.IsPostBack)
{
sda = new SqlDataAdapter("select * from student", con);
sda.Fill(ds, "student");
DropDownList1.DataSource=ds.Tables[“student”];
DropDownList1.DataTextField=”rno”;
DropDownList1.DataValueField=”rno”;
DropDownList1.DataBind();
ListBox1.DataSource=ds.Tables[“student”];
ListBox1.DataTextField=”rno”;
ListBox1.DataValueField=”rno”;
ListBox1.DataBind();
RadioButtonList1.DataSource=ds.Tables[“student”];
RadioButtonList1.DataTextField=”rno”;
RadioButtonList1.DataValueField=”rno”;
RadioButtonList1.DataBind();
}
try
{
int r = int.Parse(DropDownList1.SelectedItem.ToString());
string qry = "select * from student where rno=" + r;
ds1.Clear();
sda = new SqlDataAdapter(qry, con);
sda.Fill(ds1);
Label1.Text = ds1.Tables[0].Rows[0].ItemArray[1].ToString();
Image1.ImageUrl= ds1.Tables[0].Rows[0].ItemArray[5].ToString();
}
catch (Exception e1)
{
}
try
55
{
int r = int.Parse(ListBox1.SelectedItem.ToString());
string qry = "select * from student where rno=" + r;
ds1.Clear();
sda = new SqlDataAdapter(qry, con);
sda.Fill(ds1);
Label1.Text = ds1.Tables[0].Rows[0].ItemArray[1].ToString();
Image1.ImageUrl= ds1.Tables[0].Rows[0].ItemArray[5].ToString();
}
catch (Exception e1)
{
}
try
{
int r = int.Parse(RadioButtonList1.Text);
qry = "select * from student where rno=" + r;
ds1.Clear();
sda = new SqlDataAdapter(qry, con);
sda.Fill(ds1);
Label1.Text = ds1.Tables[0].Rows[0].ItemArray[1].ToString();
Image1.ImageUrl= ds1.Tables[0].Rows[0].ItemArray[5].ToString();
}
catch (Exception e1)
{
}
if (! Page.IsPostBack)
{
sda = new SqlDataAdapter("select * from student", con);
sda.Fill(ds, "student");
CheckBoxList1.DataSource=ds.Tables[“student”];
CheckBoxList1.DataTextField=”rno”;
CheckBoxList1.DataValueField=”rno”;
CheckBoxList1.DataBind();
}
56
string s1=””,s2=””,s3;
for (int i=0;i<CheckBoxList1.Items.Count;i++)
{
if (CheckBoxList1.Items[i].Selected)
s1=s1+”’”+CheckBoxList1.Items[i].Text+”’”+”,”; // if string
s1=s1+CheckBoxList1.Items[i].Text+”,”; // if numeric
}
int l=s1.length;
s2=s1.Substring(0,l-1);
s3=”select * from student where rno in (“+s2+”)”;
Response.Write(“s1=”+s1);
Response.Write(“<br>s2=”+s2);
Response.Write(“<br>s3=”+s3);
SqlDataAdapter sda1=new SqlDataAdapter(s3,con);
DataSet ds1=new DataSet();
sda1.fill(ds1);
GridView1.DataSource = ds1.Tables[0];
GridView1.DataBind();
57
// type the below code in class
if (! Page.IsPostBack)
{
Session[“cr”] = 0;
}
sda = new SqlDataAdapter("select * from student", con);
sda.Fill(ds);
Session[“tr”] = ds.Tables[0].Rows.Count - 1;
// first
private void button1_Click(object sender, EventArgs e)
{
Session[“cr”] = 0;
display();
}
// last
private void button3_Click(object sender, EventArgs e)
{
Session[“cr”] = Session[“tr”];
display();
}
// next
private void button2_Click(object sender, EventArgs e)
{
cr=Convert.ToInt32(Session[“cr”]);
cr = cr + 1;
Session[“cr”]=cr;
tr=Convert.ToInt32(Session[“tr”]);
if (cr > tr)
Session[“cr”] = 0;
display();
}
58
// previous
private void button4_Click(object sender, EventArgs e)
{
cr=Convert.ToInt32(Session[“cr”]);
cr = cr - 1;
Session[“cr”]=cr;
if (cr < 0)
Session[“cr”] = Session[“tr”]/0;
display();
}
}
}
Calling Stored Procedures of SQL Server from .NET
-- stored procedure for counting total no. of records according to a given condition
testCMD.CommandType = CommandType.StoredProcedure;
testCMD.Parameters.Clear();
sp1.Value=Convert.ToInt32(textBox1.Text);
con.Open();
SqlDataReader myReader = testCMD.ExecuteReader();
myReader.Close();
textBox2.Text=sp2.Value.ToString();
con.Close();
XML stands for Extensible Markup Language. It is completely in tag based format like
html. It is the most widely used format for data interchange. The structure of XML file is
as below :
Group of sql statements is called Transaction. If you want to execute set of sql
statements at a time we have to implement transactions. Thru transactions we can find
out whether all the queries executed or not. If all the queries successfully execute the
transaction is said to be completed and it is committed, otherwise it is rolled back to
previous state.
62
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;
namespace transactions
{
// 1st query
cmd.CommandText = "insert into student values(1,'sekhar',55,66,77,’abc.jpg’)";
cmd.ExecuteNonQuery();
// 2nd query
cmd.CommandText = "insert into student values('sekhar',2,55,66,77,’bb.jpg’)";
cmd.ExecuteNonQuery();
st.Commit();
Response.Write("Data is inserted successfully");
}
catch (Exception e1)
{
Response.Write("Error occurred");
st.Rollback();
}
con.Close();
}
}
}
Crystal Report
crystalReportViewer1.ReportSource =
"d:\\juhi\\windowsformsapplication3\\crystalreport1.rpt";
crystalReportViewer1.Show();
65
Storing connection string in web.config file and reading :
<connectionStrings>
<add name="cs1" connectionString="data source=(local);
initial catalog=adventureworks;integrated security=true"/>
</connectionStrings>
66