Progs

  • November 2019
  • PDF

This document was uploaded by user and they confirmed that they have the permission to share it. If you are author or own the copyright of this book, please report to us by using this DMCA report form. Report DMCA


Overview

Download & View Progs as PDF for free.

More details

  • Words: 4,894
  • Pages: 51
Page Directives Page directives specify optional settings used by the page compiler when processing ASP.NET files. The Web Forms page framework supports the following directives: · @ Page · @ Control · @ Import · @ Register · @ Assembly · @ OutputCache The @ Page Directive The @ Page directive defines page-specific attributes used by the ASP.NET page parser and compiler. <%@ page Trace="true" %> The @ Control Directive In addition to HTML and Web server controls, you also can create your own custom, reusable controls by using the same techniques you have learned to develop Web Forms pages. These controls are called user controls. The @ Import Directive The @ Import directive explicitly imports a namespace into a page, making all classes and interfaces of the imported namespace available to the page. The @ Register Directive The @ Register directive associates aliases with namespaces and class names for short description in custom server control syntax.

1

The @ Assembly Directive The @ Assembly directive declaratively links an assembly to the current page, making all of the assembly’s classes and interfaces available for use on the page. <%@ Assembly Name="myassembly.dll" %> The @ OutputCache Directive The @ OutputCache directive declaratively controls the output caching policies of a page. <%@ OutputCache Duration="10" %> USE OF APPLICATION OBJECTS

private void Button1_Click(object sender, System.EventArgs e) { Response.Write(Application["test"].ToString()); Response.Write("

"+"Hello friends"); 2

}

TextBox1.Text="Hello friends";

private void Button2_Click(object sender, System.EventArgs e) { Response.Redirect("Webform2.aspx"); } private void Button3_Click(object sender, System.EventArgs e) { ListBox1.Items.Clear(); for(Application["test2"]=1;(Int32)Application["test2"]<=10;) { ListBox1.Items.Add(Application["test2"].ToString()); Application["test2"]=(Int32)Application["test2"]+1; } string[] arr2 = new string[3]; arr2 = (string[])Application["arr"]; for(int k=0;k<arr2.Length;k++) { ListBox2.Items.Add(arr2[k].ToString()); } } private void Button4_Click(object sender, System.EventArgs e) { TextBox2.Text=Application["test2"].ToString(); }

3

USE OF VALIDATION CONTROLS

USE OF CUSTOM CONTROL

4

<script language="JavaScript"> function check(objSource, objArgs) { var num=objArgs.Value var valid=true if(num % 2 == 0) { valid=true } else { valid=false } 5

objArgs.IsValid = valid; //return objArgs; } SERVER OBJECTS

private void RadioButtonList1_SelectedIndexChanged(object sender, System.EventArgs e) { if (RadioButtonList1.SelectedIndex==0) { Label1.Text=Server.MachineName.ToString(); } else if(RadioButtonList1.SelectedIndex==1) { 6

Label1.Text=Server.UrlDecode("http://localhost/chaitanyaweb/WebF orm3.aspx"); } else if(RadioButtonList1.SelectedIndex==2) { Label1.Text=Server.UrlEncode("http://localhost/chaitanyaweb/WebF orm3.aspx"); } else if(RadioButtonList1.SelectedIndex==3) { Label1.Text=Server.HtmlEncode("

"+"hi..friends"+"

"); } else if(RadioButtonList1.SelectedIndex==4) { Label1.Text=Server.HtmlDecode("

"+"hi..friends"+"

"); } else if(RadioButtonList1.SelectedIndex==5) { Server.Transfer("WebForm1.aspx"); } else if(RadioButtonList1.SelectedIndex==6) { Label1.Text="Server.Execute works in page load event"; } } private void Button1_Click(object sender, System.EventArgs e) { string str="images//flower45.jpg"; Image1.ImageUrl=Server.MapPath(str); }

7

COOKIES

private void Page_Load(object sender, System.EventArgs e) { HttpCookie ck = new HttpCookie("userinfo"); ck.Values.Add("uid",TextBox1.Text); ck.Values.Add("pwd",TextBox2.Text); DateTime dt = DateTime.Now; TimeSpan ts = new TimeSpan(0,0,2,0,0); ck.Expires = dt.Add(ts); Response.Cookies.Add(ck); Session["first"]=TextBox1.Text.ToString(); } private void Button2_Click(object sender,System.EventArgs e) { 8

}

Response.Redirect("WebForm5.aspx");

private void Page_Load(object sender, System.EventArgs e) { Response.Write("

"+Session.SessionID.ToString()+"

"); Label1.Text="Hi.. " + Session["first"].ToString(); Response.Write("

"+"COOKIES DETAILS"+"

"); HttpCookie ck1 = Request.Cookies["userinfo"]; Response.Write("User id is: " + ck1.Values["uid"].ToString()); Response.Write("Password is: " + ck1.Values["pwd"].ToString()); } SESSION PROPERTIES

9

private void RadioButtonList1_SelectedIndexChanged(object sender, System.EventArgs e) { if(RadioButtonList1.SelectedIndex==0) { Label1.Text=Session.SessionID.ToString(); } else if(RadioButtonList1.SelectedIndex==1) { Label1.Text=Session.Timeout.ToString(); } else if(RadioButtonList1.SelectedIndex==2) { Label1.Text=Session.LCID.ToString(); } else if(RadioButtonList1.SelectedIndex==3) { 10

Label1.Text=Session.IsNewSession.ToString(); } else if(RadioButtonList1.SelectedIndex==5) { Label1.Text=Session.Count.ToString(); } } DATABASE PROGRAMS USING ADO.NET

USING SQLDATAADAPTER

private void Page_Load(object sender, System.EventArgs e) {

11

SqlConnection cn = new SqlConnection("server=localhost;uid=sa;database=muser"); cn.Open(); SqlDataAdapter adp = new SqlDataAdapter("select * from uaccount",cn); DataSet ds = new DataSet(); adp.Fill(ds,"uaccount"); DataGrid1.DataSource=ds.Tables["uaccount"]; DataGrid1.DataBind(); } USING OLEDB

private void Page_Load(object sender, System.EventArgs e) { OleDbConnection cn = new OleDbConnection("provider=sqloledb;uid=sa;initial catalog=muser"); cn.Open(); OleDbCommand cmd = new OleDbCommand("select * from uaccount",cn); //DataGrid1.DataSource=cmd.ExecuteReader(); OleDbDataReader dr; dr = cmd.ExecuteReader(); DataGrid1.DataSource=dr; DataGrid1.DataBind(); } USING DATAADAPTER,DATASET AND COMMAND

private void Page_Load(object sender, System.EventArgs e) { OleDbConnection cn = new OleDbConnection("provider=sqloledb;uid=sa;database=muser"); cn.Open(); string str="select * from uaccount"; OleDbCommand cmd = new OleDbCommand(); cmd.CommandText=str; cmd.Connection=cn; OleDbDataAdapter adp = new OleDbDataAdapter(); 12

adp.SelectCommand=cmd; DataSet ds = new DataSet(); adp.Fill(ds); DataGrid1.DataSource=ds.Tables[0]; DataGrid1.DataBind(); }

USING DATAVIEWS i.e. rowfilter and sort

private void Page_Load(object sender, System.EventArgs e) { OleDbConnection cn = new OleDbConnection("provider=microsoft.jet.oledb.4.0;data source="+Server.MapPath("MUSER.mdb")); cn.Open(); OleDbDataAdapter adp = new OleDbDataAdapter("select * from uaccount",cn); DataSet ds = new DataSet(); adp.Fill(ds,"uaccount"); DataView dv; dv = new DataView(ds.Tables[0]); dv.Sort="name"; dv.RowFilter="slno > 3 and slno <=7"; DataGrid1.DataSource=dv; DataGrid1.DataBind(); } SEARCHING RECORDS

13

OleDbConnection cn = new OleDbConnection("provider=sqloledb;uid=sa;database=muser"); private void Page_Load(object sender, System.EventArgs e) { if(!IsPostBack) { OleDbDataAdapter adp = new OleDbDataAdapter("select * from uaccount",cn); DataSet ds = new DataSet(); adp.Fill(ds,"uaccount"); DataGrid1.DataSource=ds.Tables[0]; DataGrid1.DataBind(); DropDownList1.DataTextField="slno"; DropDownList1.DataSource=ds.Tables[0]; DropDownList1.DataBind(); } } private void Button1_Click(object sender, System.EventArgs e) 14

{ OleDbCommand cmd = new OleDbCommand(); cmd.CommandText="select * from uaccount where slno = " + DropDownList1.SelectedItem; cmd.Connection=cn; cn.Open(); DataGrid1.DataSource=cmd.ExecuteReader(); DataGrid1.DataBind(); cn.Close(); } INSERTING, UPDATING, DELETING AND SEARCHING USING ADO.NET

OdbcConnection cn = new OdbcConnection("dsn=test;uid=sa"); private void Page_Load(object sender, System.EventArgs e) { if (!IsPostBack) { 15

OdbcDataAdapter adp = new OdbcDataAdapter("select * from dept",cn); OdbcDataAdapter adp1 = new OdbcDataAdapter("select * from emp",cn); DataSet ds = new DataSet(); DataSet ds1 = new DataSet(); adp.Fill(ds); adp1.Fill(ds1); DropDownList1.DataTextField="deptno"; DropDownList1.DataSource=ds.Tables[0]; DropDownList1.DataBind(); DropDownList2.DataTextField="ENO"; DropDownList2.DataSource=ds1.Tables[0]; DropDownList2.DataBind(); display(); } } protected void display() { OdbcDataAdapter adp = new OdbcDataAdapter("select * from emp",cn); DataSet ds = new DataSet(); adp.Fill(ds); DataGrid1.DataSource=ds.Tables[0]; DataGrid1.DataBind(); } private void Button1_Click(object sender, System.EventArgs e) { OdbcCommand cmd = new OdbcCommand("insert into emp values('" + TextBox1.Text + "', '" + TextBox2.Text + "','" + TextBox3.Text + "','" + TextBox4.Text + "','" + DropDownList1.SelectedItem.ToString() + "','" + TextBox5.Text + "','" + TextBox6.Text + "')",cn); cn.Open(); cmd.ExecuteNonQuery(); 16

cn.Close(); display(); } private void Button4_Click(object sender, System.EventArgs e) { OdbcCommand cmd = new OdbcCommand ("select * from emp where eno = '" + DropDownList2.SelectedItem + "' ",cn); OdbcDataReader dr; cn.Open(); dr=cmd.ExecuteReader(); dr.Read(); TextBox1.Text=dr[0].ToString(); TextBox2.Text=dr[1].ToString(); TextBox3.Text=dr[2].ToString(); TextBox4.Text=dr[3].ToString(); DropDownList1.SelectedValue=dr[4].ToString(); TextBox5.Text=dr[5].ToString(); TextBox6.Text=dr[6].ToString(); cn.Close(); } private void Button2_Click(object sender, System.EventArgs e) { string str; str="update emp set ename = '" + TextBox2.Text +"',addr = '" + TextBox3.Text +"',desig='" + TextBox4.Text +"',deptno = '"+ DropDownList1.SelectedItem +"',exp= " + TextBox5.Text +",salary =" + TextBox6.Text +" where eno = '"+ TextBox1.Text + "' "; OdbcCommand cmd = new OdbcCommand(); cmd.CommandText=str; cmd.Connection=cn; cn.Open(); cmd.ExecuteNonQuery(); cn.Close(); 17

display(); } private void Button3_Click(object sender, System.EventArgs e) { OdbcCommand cmd = new OdbcCommand(); cmd.CommandText="delete from emp where eno = '" + DropDownList2.SelectedItem.ToString() + "' "; cmd.Connection=cn; cn.Open(); cmd.ExecuteNonQuery(); cn.Close(); display(); } PROGRAM TO DISPLAY SUM OF MARKS AND TOTAL MARKS IN A DATAGRID

18

<%@ Page CodeBehind="WebForm22.aspx.cs" Language="c#" AutoEventWireup="false" Inherits="Webtrial.WebForm22" %> <%@ Register Tagprefix="uc1" tagname="myctrl" src="WebUserControl1.ascx" %>

SqlConnection cn = new SqlConnection("server=localhost;uid=sa;database=student_det ails"); double sum; private void Page_Load(object sender, System.EventArgs e) { cn.Open(); databind(); 19

} void databind() { SqlDataAdapter adp = new SqlDataAdapter("select * from marks1",cn); DataSet ds = new DataSet(); adp.Fill(ds,"marks"); DataColumn dc; dc = new DataColumn("Total", Type.GetType("System.Double")); dc.Expression="math+sci+sst"; ds.Tables[0].Columns.Add(dc); DataGrid1.DataSource=ds; DataGrid1.DataBind(); } protected void gtot(double s) { sum += s; } private void DataGrid1_ItemDataBound(object sender, System.Web.UI.WebControls.DataGridItemEventArgs e) { if ((e.Item.ItemType == ListItemType.Item) || ( e.Item.ItemType == ListItemType.AlternatingItem)) { gtot(Double.Parse( e.Item.Cells[5].Text )); } else if (e.Item.ItemType ==ListItemType.Footer ) { e.Item.Cells [4].Text =" Total "; e.Item.Cells[5].Text =sum.ToString(); } } USE OF DATA REPEATERS

20

<%@ Import Namespace="System.Data.SqlClient" %> <%@ Import Namespace="System.Data" %> <script language="C#" runat="server"> private void Page_Load(object sender, System.EventArgs e) { SqlConnection cn = new SqlConnection("server=localhost;uid=sa;database=railway"); SqlDataAdapter adp = new SqlDataAdapter("select * from emp",cn); DataSet ds = new DataSet(); adp.Fill(ds); Repeater1.DataSource=ds.Tables[0]; Repeater1.DataBind(); }
21

<SeparatorTemplate>

Details on Employee's

<%# DataBinder.Eval(Container.DataItem,"eno") %> <%# DataBinder.Eval(Container.DataItem,"ename") %> <%# DataBinder.Eval(Container.DataItem,"addr") %> <%# DataBinder.Eval(Container.DataItem,"desig") %> <%# DataBinder.Eval(Container.DataItem,"deptno") %> <%# DataBinder.Eval(Container.DataItem,"exp") %> <%# DataBinder.Eval(Container.DataItem,"salary") %>

<%# DataBinder.Eval(Container.DataItem,"eno") %> <%# DataBinder.Eval(Container.DataItem,"ename") %> 22

<%# DataBinder.Eval(Container.DataItem,"addr") %> <%# DataBinder.Eval(Container.DataItem,"desig") %> <%# DataBinder.Eval(Container.DataItem,"deptno") %> <%# DataBinder.Eval(Container.DataItem,"exp") %> <%# DataBinder.Eval(Container.DataItem,"salary") %>
<% =System.DateTime.Now %>
USE OF DATA LIST CONTROL

23

<%@ Import Namespace="System.Data" %> <%@ Import Namespace="System.Data.SqlClient" %> <script language="C#" runat="server"> private void Page_Load(object sender, System.EventArgs e) { SqlConnection cn = new SqlConnection("server=localhost;uid=sa;database=student_details"); SqlDataAdapter adp = new SqlDataAdapter("select * from student",cn); DataSet ds = new DataSet(); adp.Fill(ds); DataList1.DataSource=ds.Tables[0]; DataList1.DataBind(); } 24

Details of employees

<%# DataBinder.Eval(Container.DataItem,"sno") %> <%# DataBinder.Eval(Container.DataItem,"name") %> <%# DataBinder.Eval(Container.DataItem,"addr") %> <SeparatorTemplate>
<%# DataBinder.Eval(Container.DataItem,"sno") %> <%# DataBinder.Eval(Container.DataItem,"name") %> <%# DataBinder.Eval(Container.DataItem,"addr") %>
EXAMPLE ON DATALIST CONTROL i.e. updating and deleting records

25

<%@ Import Namespace = System.Data %> <%@ Import Namespace = System.Data.SqlClient %> WebForm19 <script language="C#" runat="server"> SqlConnection cn = new SqlConnection("server=ecas;uid=sa;database=test"); SqlDataAdapter adp = new SqlDataAdapter(); public void Page_Load(object sender, System.EventArgs e) { if(!IsPostBack ) { bindList(); 26

} } void bindList() { DataSet ds = new DataSet(); adp = new SqlDataAdapter("SELECT * FROM customer",cn); adp.Fill(ds, "customer"); DataList1.DataSource=ds; DataList1.DataBind(); } void Edit_cmd(Object src, DataListCommandEventArgs e) { DataList1.EditItemIndex = e.Item.ItemIndex; bindList(); } void Cancel_cmd(Object src, DataListCommandEventArgs e) { DataList1.EditItemIndex = -1; bindList(); } void Delete_cmd(Object src, DataListCommandEventArgs e) { //DataList1.EditItemIndex = -1; object cno; cno=DataList1.DataKeys[(int)e.Item.ItemIndex]; Label1.Text=e.Item.ItemIndex.ToString(); //cno.ToString(); string deleteCmd = "DELETE from customer where custno = " + cno; SqlConnection conn = new SqlConnection("server=ecas;uid =sa;database=test"); SqlCommand myCommand = new SqlCommand(deleteCmd,conn); //myCommand.Parameters.Add(new SqlParameter("@cno", SqlDbType.Int)); //myCommand.Parameters["@cno"].Value = DataList1.DataKeys[(int)e.Item.ItemIndex]; //myCommand.Connection.Open(); conn.Open(); try { myCommand.ExecuteNonQuery(); 27

} catch (SqlException e1) { Label1.Text = "ERROR: Could not delete record"; } //myCommand.Connection.Close(); conn.Close(); bindList(); } void Update_cmd(Object src, DataListCommandEventArgs e) { object cno; cno=DataList1.DataKeys[(int)e.Item.ItemIndex]; string cname =((TextBox)e.Item.FindControl("cname")).Text; string caddr =((TextBox)e.Item.FindControl("caddr")).Text; string cage = ((TextBox)e.Item.FindControl("cage")).Text; string str = "UPDATE customer SET custname='"+ cname + "', custaddr='" + caddr + "', age ='"+ cage +"' WHERE custno='" + cno+ "' "; SqlConnection conn = new SqlConnection("server=ecas;uid =sa;database=test"); SqlCommand comm = new SqlCommand(str,conn); conn.Open(); comm.ExecuteNonQuery(); conn.Close(); DataList1.EditItemIndex = -1; bindList(); }
28

Titles
Serial no : <%# DataBinder.Eval(Container.DataItem, "custno") %>
Customer Name : <%# DataBinder.Eval(Container.DataItem, "custname") %>
Customer Address : <%# DataBinder.Eval(Container.DataItem, "custaddr") %>
Customer Age : <%# DataBinder.Eval(Container.DataItem, "age") %>
<EditItemTemplate> 29

Serial no : <%# DataBinder.Eval(Container.DataItem, "custno") %>
Customer Name :
Customer Address :
Customer Age :
<SelectedItemStyle Font-Bold="True" ForeColor="White" BackColor="#738A9C"> 30

Label
EXAMPLE ON DATALIST CONTROL i.e. selecteditemtemplate

31

<%@ Import Namespace = System.Data %> <%@ Import Namespace = System.Data.SqlClient %> <script language="C#" runat="server"> SqlConnection cn = new SqlConnection("server=ecas;uid=sa;database=test"); public void Page_Load(object sender, System.EventArgs e) { cn.Open(); SqlDataAdapter adp = new SqlDataAdapter("select * from customer",cn); DataSet ds = new DataSet(); adp.Fill(ds,"customer"); DataList1.DataSource=ds.Tables["customer"].DefaultView; DataList1.DataBind(); } /*void showItem( Object src, DataListCommandEventArgs e ) { SqlDataAdapter adp = new SqlDataAdapter("select * from customer",cn); DataSet ds = new DataSet(); adp.Fill(ds,"customer"); DataList1.SelectedIndex = e.Item.ItemIndex; DataList1.DataSource = ds.Tables["customer"].DefaultView; DataList1.DataBind(); }*/ void populateList() { SqlDataAdapter adp = new SqlDataAdapter("select * from customer where custno like '%' ",cn); DataSet ds = new DataSet(); adp.Fill(ds,"customer"); DataList1.DataSource = ds.Tables["customer"].DefaultView; DataList1.DataBind(); } void getSelected(Object src, DataListCommandEventArgs e) { DataList1.SelectedIndex = e.Item.ItemIndex; populateList();

32

//msg.Text = "The item selected is "+((HtmlGenericControl)DataList1.SelectedItem.FindControl("custno")).InnerText + ""; } void chBackcolor(Object src, EventArgs e) { if(DataList1.SelectedItem != null ) DataList1.SelectedItem.BackColor = System.Drawing.Color.Pink; }

A REPORT ON CUSTOMER

<SeparatorTemplate>
33

<%# DataBinder.Eval(Container.DataItem,"custno") %>
<%# DataBinder.Eval(Container.DataItem,"custname") %> <%# DataBinder.Eval(Container.DataItem,"custaddr") %>
<SelectedItemTemplate> <%# DataBinder.Eval(Container.DataItem,"custno") %> <%# DataBinder.Eval(Container.DataItem,"custname") %> <%# DataBinder.Eval(Container.DataItem,"custaddr") %>

HI FRIENDS

 

EXAMPLE ON ADO.NET USING XML FILE IN DATAGRID CREATE XML FILE i..e passenger1.xml <demo1> <passenger pnrno="1" seatno="1" pname="sam" paddr="" age="23" phno="11111" country="INDIA"/> <passenger pnrno="2" seatno="3" pname="pavan" paddr="visakhapatnam" age="20" phno="22222" country="INDIA"/> <passenger pnrno="3" seatno="4" pname="salil" paddr="visakhapatnam" age="25" phno="33333" country="INDIA"/>

34

<passenger pnrno="4" seatno="5" pname="ramee" paddr="visakhapatnam" age="35" phno="44444" country="INDIA"/> <passenger pnrno="5" seatno="9" pname="raghu" paddr="delhi" age="30" phno="55555" country="INDIA"/> <passenger pnrno="6" seatno="10" pname="sandhya" paddr="kolkata" age="15" phno="66666" country="INDIA"/> <passenger pnrno="7" seatno="12" pname="salu" paddr="visakhapatnam" age="16" phno="7777" country="INDIA"/> <passenger pnrno="8" seatno="13" pname="rahul" paddr="goa" age="44" phno="98765" country="INDIA"/> <passenger pnrno="9" seatno="14" pname="raghu" paddr="vizag" age="77" phno="87876" country="INDIA"/>

35

using System.IO; using System.Xml; private void Page_Load(object sender, System.EventArgs e) { FileStream fs = new FileStream(Server.MapPath("passenger1.xml"), FileMode.Open, FileAccess.Read); StreamReader sr = new StreamReader(fs); DataSet ds = new DataSet(); ds.ReadXml(sr); DataView Source = new DataView(ds.Tables[0]); Source.Sort="pnrno desc"; Source.RowFilter = "pnrno >=3 and pnrno<=6"; DataGrid1.DataSource=Source; DataGrid1.DataBind(); } NOTES ON USER CONTROL AND WEB SERVICES TagPrefix— This is the namespace to which the user control belongs. This is used to differentiate the user controls from those written by other people. TagName— This is the name by which the user control is recognized in this aspx page. Any name can be used, irrespective of the physical filename in which the user control is stored. Src— Specifies the virtual path to the source code file of user control. You can use user controls to provide a consistent user interface throughout the web site by encapsulating your web site banners, sidebars, headers, and footers in the user controls. This not only increases consistency, but if later you are requested to change the UI or code inside a header, you need only to change it at one place and it is immediately reflected everywhere. WEB SERVICES A web service is a mechanism for making components available across the Internet using open standards, including HTTP (Hypertext Transfer Protocol) and XML (Extensible Markup Language). The idea is to create 'black box' components that can communicate with each other, regardless of the operating system or programming language. A little more precisely, a web service is a component, or module, of executable code with a special interface that makes its methods available for use (also called 'consumption') by other programs using an HTTPbased request. 36

Web Services Description Language (WSDL) Web Services Description Language (WSDL) describes the methods supported by a web service, the parameters the methods take, and what the web service returns. Generally, creators of ASP.NET web services do not have to worry themselves about WSDL; a WSDL document is automatically generated at runtime by the ASP.NET runtime using a process called reflection. Universal Description, Discovery, and Integration (UDDI) Universal Description, Discovery, and Integration (UDDI) is a more general, cross-industry effort at creating a repository for publishing and finding web services. The UDDI project (www.uddi.org) consists of a registry and a set of APIs for accessing the registry. IBM and Microsoft maintain cross-synchronized UDDI registries that can be browsed. The Microsoft registry can also be accessed from the Visual Studio Start page,

37

IN SERVER1.ASMX PAGE WRITE FOLLOWING CODE: [WebMethod] public double servicetax(double amt) { return (amt*12.36)/100; }

38

IN NORMAL ASPX PAGE WRITE FOLLOWING CODE: private void Button1_Click(object sender, System.EventArgs e) { double a,b,c; webanilreddy.Service1 s = new webanilreddy.Service1(); a=Convert.ToDouble(TextBox1.Text); b=s.servicetax(a); c=a+b; TextBox2.Text=b.ToString(); TextBox3.Text=c.ToString(); } Tracing When developing an application, we execute the page at different levels of development, and for effective debugging, we always need to see the values assigned to variables and the state of different conditional constructs at different stages of execution. In ASP, developers used the Response.Write statement to display this information. The downside of this is that while completing the application development, the developer had to go to every page and either comment or remove the Response.Write statements they created for testing purposes. ASP.NET provides a new feature to bypass all of this. It is the Trace capability. The Trace feature provides a range of information about the page, including request time, performance data, server variables, and most importantly, any message added by the developers. It is disabled by default. Like the debug mode, tracing can be either enabled or disabled at either the page (or the application) level. SETTINGS AND CONFIGURATIONS Request Details: This section contains information pertaining to the page request, such as the Session ID for the current session, the request type (whether it is GET or POST), the time at which the request was made, the encoding type of the request among others. Trace Information: This is the section in which the actual trace information is displayed along with the messages written by developers. This section displays the category, the message, the time since the first message, and the most recent message displayed. Control Tree: This section displays details about the different controls used in the page. The details include the ID provided for the control, the type of control used, and its position among 39

other controls. Cookies Collection: This section displays all cookies used in the page. It shows only the SessionID because it is the only member of the cookies collection used in our page. Headers Collection: This section displays the various HTTP headers sent by the client to the server, along with the request. Writing to the Trace Log Each ASP.NET page provides a Trace object that can be used to write messages to the trace log. You can use two methods to write messages to the trace log: - Trace.Write() - Trace.Warn() The messages are only displayed when tracing is enabled. Both methods are used to write messages to the trace log, but when using the Trace.Warn() method, the messages are displayed in red. You may want to use Trace.Warn() for writing (and highlighting) unexpected results or incorrect values for variables in a program. In ASP.NET, configuration information is stored in an XML-based configuration file. This means that it is user-viewable and editable. Because of this, administrators and developers can update web application and site configuration settings with ease. It is no longer necessary for developers to wait for an administrator to change Internet Information Services (IIS) settings and reboot the web server for the settings to take effect. This under-standably improves a developer’s productivity. The configuration system is fully extensible because you can store your own custom configuration settings for a web application. This is achieved through a hierarchical configuration infrastructure that enables extensible configuration data to be defined and used throughout ASP.NET applications. At the same time, ASP.NET provides a rich set of system-provided configuration settings. a web.config file is placed in the \WebRoot directory. Any ASP.NET code processed in that directory or any subdirectories therein use the settings in the web.config file. The Structure of the web.config File Section This section of the web.config file is used to specify

40

handlers, which are functions used to interpret the XML used in a web.config section and to return information to the user of the section. This section should only be used if you are adding your own custom configuration file handlers. <system.web> Section The <system.web> configuration section is the main area of the web.config file. This is where you can configure almost any aspect of an ASP.NET application’s environment. Many configuration subsections exist inside the system.web section. Development Configuration The sections outlined here control settings, which alter the development environment of ASP.NET when a page is compiled. The sections covered here are · · <customErrors> · The Section This section is used to define the language in which to compile a web page and whether or not a page should be compiled with debug information included. The section attributes are as follows: · debug— This attribute, if set to true, tells ASP.NET to include debug information in a compiled web page. · defaultLanguage— This attribute sets the default language to be used in a web page’s script blocks by default. A few of the languages supported are the following: - vb (Visual Basic. NET) - c# (C#) - jscript (JScript) You can also specify multiple default languages by using a semicolon-separated list of language names. An Example of the Section <system.web>

41

The <customErrors> Configuration Section The <customErrors> configuration section is used to do two things—the first is enabling or disabling custom errors and the second is re-directing a URL to a user if a specific error occurs. The <customErrors> section has the following two attributes: · defaultRedirect— This is the default URL used to redirect the user if an error occurs. · mode— The mode attribute, when set to On, means that the custom errors are enabled; when it is set to Off, they are disabled. There is one other setting for the mode and that is RemoteOnly. When RemoteOnly is used, the custom errors are shown only to remote users. The <customErrors> section also contains a subelement, which is used to define custom error pages for specific HTTP status codes. This element is the <error /> element, and it has the following two attributes: · StatusCode— This is the HTTP error status code to trap for a custom error handler page. · redirect— This is the URL that redirects the user when the defined error occurs. An Example of the <customErrors> Section <system.web> <customErrors defaultRedirect="defaultError.aspx" <error statusCode="500" redirect="Error500.aspx"/> <error statusCode="504"redirect="Error504.aspx"/>

mode="RemoteOnly">

The Configuration Section This section is used to enable or disable the application trace functionality in ASP.NET. enabled

This attribute, if set to true, will enable application-level trace functionality; otherwise, it will be disabled.

requestLimit Used to specify the total number of trace requests to store on the server.

42

pageOutput This defines whether or not trace information will be displayed at the end of each web page; if set to true, the trace information for that web page will be displayed; if set to false, it will not be displayed. traceMode - This attribute defines the sort order of the trace information when it is displayed. Possible values are · SortByTime · SortByCategory localOnly - This attribute is used to set the application trace viewer to work only on the web server (local only) if its value is set to true; otherwise, the trace viewer can be used by any client. An Example of the Section <system.web> Security Configuration ASP.NET has a very comprehensive security system, which is used to authenticate and authorize access to web resources. This configuration section has three main sections, which are · · · Authentication is the process of identifying and verifying who the client accessing the server is. The Section Attributes The section has one attribute and two subsections. The mode attribute is used to control the authentication mode for an ASP.NET web application and supports the following values:

43

· Windows— Used to specify Windows authentication as the authentication mode. This is used when using any form of IIS authentication. · Forms— Used to specify ASP.NET forms-based authentication as the authentication mode. · Passport— Used to specify Microsoft Passport as the authentication mode.Centralized authentication service provided by Microsoft that offers a single logon and core profile services for member sites. · None— Used to specify no authentication support. The section is a subsection of the configuration section and is used when forms-based authentication is being used. This tag has five attributes and one subsection tag. name -

This attribute is used to specify the HTTP cookie used for authentication.

loginUrl - This attribute is used to specify a URL to redirect the user when an invalid authentication cookie is found. Protection This attribute is used to specify that the web application uses both data validation and encryption to protect the authentication cookie. Possible values for this attribute are · None— Used to specify that both encryption and validation are disabled for sites that are using cookies only for personalization and have weaker security requirements. · Encryption— Used to specify that the cookie is encrypted. · Validation— Used to specify a validation scheme, which verifies that the contents of an encrypted cookie have not been altered in transit. · All— This setting enables both encryption- and validationbased protection. timeout cookie

This attribute is used to specify the time (in minutes) when the authentication expires.

path - This attribute is used to specify the path for cookies created by the web application. The passwordFormat attribute is used to specify the encryption format used when storing passwords; it can have any of the following values: · Clear— Used to specify that passwords are not encrypted and are stored in a clear-text format. · MD5— Used to specify that passwords are encrypted using the MD5 hash algorithm. · SHA1— Used to specify that passwords are encrypted using the SHA1 hash algorithm. 44

An Example of the Section <system.web> The Configuration Section The section is used to define authorization settings for ASP.NET web applications. Authorization is the process of determining whether an authenticated user has access to run a particular page within an ASP.NET web application. Specifically, as an application author decide to grant or deny the authenticated user access to the admin.aspx page. The section has two subsections; these are · · <deny> The subsection is used to enable access to a resource, the three attributes for this section are · users— Used to grant users access to resources. This attribute’s value is a comma-separated list of users. A question mark (?) allows anonymous users and an asterisk (*) allows all users. · roles— A comma-separated list of roles that are granted access to the resource. The <deny> subsection is used to deny access to a resource. The three attributes for this section are · users— Used to deny user access to resources. This attribute’s value is a comma-separated list of users. A question mark (?) denies anonymous users and an asterisk (*) denies all users. · roles— A comma-separated list of roles that are denied access to the resource An Example of the Section <system.web> <deny users="*" /> 45

State Management Configuration The <sessionState> Configuration Section The <sessionState> section is used to configure the state management features of ASP.NET applications. The <sessionState> section has the following attributes. mode This attribute is used to specify where the session state is stored; it has the following possible values: · Off— Used to disable session state management. · Inproc— Used to enable in-process session state management. · StateServer— Used to enable the state serverbased state management. (State is stored on a remote server.) · SqlServer— Used to enable SQL Server-based state management. cookieless - This attribute is used to specify whether or not cookieless sessions should be used to identify client sessions. If the attribute value is true, then cookieless sessions are enabled. timeout This attribute is used to specify the total number of minutes a session can be idle before it is abandoned. connectionString - This attribute is used to specify the server name and port where session state is stored remotely. This is used in conjunction with the “StateServer” mode otherwise, it is not required. sqlConnectionString - This attribute is used to specify the connection string for SQL Server-based state management. This is used in conjunction with the “SQLServer” mode, otherwise, it is not required. An Example of the <sessionState> Section <system.web> <sessionState mode="SQLState" sqlConnectionString="data source=localhost;user id=sa; password="" cookieless="true" timeout="25" /> 46



47

SqlConnection myConnection; public static int i=1; private void Page_Load(object sender, System.EventArgs e) { if(!IsPostBack) { LinkButton1.Enabled=false; LinkButton1.Visible=false; } } 48

private void Button1_Click(object sender, System.EventArgs e) { if(Page.IsValid) { HttpCookie cookie1 = new HttpCookie("username"); cookie1.Values.Add("uid", userid.Text); cookie1.Values.Add ("pwd", password1.Text); /*DateTime dt = DateTime.Now; TimeSpan ts = new TimeSpan(0,0,1,0,0); cookie1.Expires = dt.Add(ts);*/ Response.Cookies.Add(cookie1); try { myConnection = new SqlConnection("server=ecas;uid=sa;database=logid"); myConnection.Open(); } catch (Exception e1) { msg.Text = "Connection failed to open successfully.
"; msg4.Text=e1.Message; } string insertCmd = "SELECT pwd FROM login WHERE usrnm='" + userid.Text + "'"; SqlCommand myCommand = new SqlCommand(insertCmd, myConnection); SqlDataReader dr; dr = myCommand.ExecuteReader(); if(i>2) { msg4.Text="YOU HAVE NO CHANCE TO ENTER....."; 49

LinkButton1.Enabled=true; LinkButton1.Visible=true; } else { if(dr.Read()) { if(dr["pwd"].ToString()==password1.Text) { Response.Redirect("WebForm4.aspx"); } else { msg.Text="Invalid password"; i++; } } else { msg.Text="userid Not Found"; i++; } } } } private void LinkButton1_Click(object sender, System.EventArgs e) { if(i>2) { i=1; Response.Redirect("WebForm3.aspx"); LinkButton1.Visible=false; } } } 50

IN THE SECOND PAGE’S PAGELOAD EVENT WRITE FOLLOWING CODE: private void Page_Load(object sender, System.EventArgs e) { HttpCookie ck1 = Request.Cookies["username"]; Response.Write("UserName : " +ck1.Values["uid"]); Label1.Text = "WELCOME " +ck1.Values["uid"]; } IN WEB.CONFIG WRITE FOLLOWING CODE: <system.web> <deny users=" ">

51

Related Documents

Progs
November 2019 5
Progs
November 2019 7
Progs
November 2019 8
Bailout Progs
April 2020 23