.Net Web development 3 XML

The DataTable object represents tabular data as rows, columns, and constraints. Use the DataTable object to hold data in memory while performing disconnected data operations.

//Create the DataTable named "Children"
DataTable childTime = new DataTable("Children" );
//Add the DataColumn using all properties
DataColumn cid = new DataColumn("CID");
cid.DataType = typeof(string);
cid.MaxLength = 10;
cid.Unique = true;
cid.AllowDBNull = false;
cid.Caption = "CID";
childTime.Columns.Add(cid);



DataColumn properties

DataType
MaxLength
Unique
AllowDBNull
Caption


childs.Rows.Add("21", "a", "b");
//Load DataRow, replacing existing contents, if existing
childs.LoadDataRow(
new object[] { "21", "v", "u"},
LoadOption.OverwriteChanges);


finally..
anydataboundcontrol.datasource = mydatatable;
anydataboundcontrol.Databind();




A DiffGram is an XML document that contains all of the data from your DataSet object, including the original DataRow object information. To save as a DiffGram, use the XmlWriteMode.DiffGram enumeration
value when serializing a DataSet object.
When the user is not connected to the database, the DataSet object is stored locally as a DiffGram to ensure that you still have the original data, because the original data is needed when it’s time to send your changes back to the database.

Deserializing a DataSet from XML:


DataSet childList = new DataSet();
childList.ReadXmlSchema(MapPath("childListListSch.xsd"));
childList.ReadXml(MapPath("children.xml"));

mygrid1.DataSource = childList ;
mygrid1.DataMember = "ParentName";
mygrid2.DataSource = childList ;
mygrid2.DataMember = "ChildName";
mygrid1.DataBind();
mygrid2.DataBind();


When reading an XML file, you can optionally pass an XmlReadMode enumeration value.

Auto
DiffGram
Fragment
IgnoreSchema
InferSchema
InferTypedSchema
ReadSchema


Serializing the DataSet Object as Binary Data :
ofcourse on network, binary transfer is faster.

childList.RemotingFormat = SerializationFormat.Binary;

using (FileStream fs = new FileStream(MapPath("childList.bin"), FileMode.Create))
{
BinaryFormatter fmt = new BinaryFormatter();
fmt.Serialize(fs, childList);
}
Connection pooling is the process of reusing existing active connections instead of creating
new connections when a request is made to the database. It involves the use of a connection manager that is responsible for maintaining a list, or pool, of available connections.
Connection Timeout T
Min Pool Size
Max Pool Size
Pooling
Connection Reset
Load Balancing
Enlist

ExecuteNonQuery
ExecuteScalar
ExecuteReader

Multiple Active Result Sets (MARS)


SqlBulkCopy Object
overloads of the WriteToServer method, which can accept an array of DataRow objects, an object that implements the IDbDataReader interface, a DataTable object, or a DataTable and DataRowState


transaction is an atomic unit of work

Atomicity
Consistency
Isolation
Durability
Custom web controls

user control
A user control is a template control
custom Web control
A custom Web control is a control that inherits from a Web control, where you either write all of the code to render the control
composite control
A composite control is a custom Web control that can contain constituent controls; the constituent controls are added to the composite control
via code to the class file that defines the control. The class file can be compiled
to a .dll
user control
1.
Remove the <html>,<body> and <form> tags.
2. Change the @Page to @Control directive.
3.Change file extension from .aspx to.ascx.
4.In the @Control directive, change Inherits="System.Web.UI.Page" to Inherits="
System.Web.UI.UserControl".


In other webpage add
1. <%@ Register Src="MyControl.ascx" TagName="MyControl" TagPrefix="uc1" %>


2. in body add
<uc1:MyControl ID="MyControl1" runat="server" />
a custom web control
public class LabeledTextBox : TextBox
{
public string LabelText
{
get { return _labelText; }
set { _labelText = value; }
}
private string _labelText;
public int LabelWidth
{
get { return _labelWidth; }
set { _labelWidth = value; }
}
private int _labelWidth;
protected override void Render(HtmlTextWriter writer)
{
writer.Write(
@"<span style=""display:inline-block;width:{0}px"">{1} &nbsp;</span>",LabelWidth, LabelText);
base.Render(writer);
}
}
public class LogoControl : WebControl
{
public LogoControl()
{
}
public string LogoUrl = """;
private string _logoUrl = "";
private string _companyName = "";
protected override void Render(HtmlTextWriter writer)
{
writer.WriteFullBeginTag("div");
writer.Write(@"<img src=""{0}"" /><br />", LogoUrl);
writer.Write(CompanyName + "<br />");
writer.WriteEndTag("div");
}
}
This is for Beating stateless HTML

Many ways to save state
View state
Control state
Hidden fields
Cookies
Query strings
Better scalability -- no load on server
Supports multiple browsers -- Caching is supported by all browsers
Better security -- no secure data is transfered on network
Reduced bandwidth - No extra load on server


Viewstate

<configuration> <system.web> <pages viewStateEncryptionMode="Always"/> </system.web> </configuration>

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" ViewStateEncryptionMode="Always"%>

If you want to disable viewstate ...
EnableViewState property="false"


reading and writing viewstate:

if (ViewState["earlier"] != null)
Label1.Text = (string)ViewState["earlier"];
else
Label1.Text = "lastVisit ViewState not defined.";
// update it
ViewState.Add("earlier",DateTime.Now.ToString());
Cookies are also like viewstates . But you can control the expiry datetime -- cookies are disabled in some web browsers by user. So be careful.
if (Request.Cookies["lastVisit"] != null)

Label1.Text = Server.HtmlEncode(Request.Cookies["lastVisit"].Value);
else Label1.Text = "No value defined";

Response.Cookies["lastVisit"].Value = DateTime.Now.ToString();
Response.Cookies["lastVisit"].Expires = DateTime.Now.AddDays(1);

HttpCookie class and HttpCookieCollection will come very handy.

you can scope down a cookie to a folder level in asp.net website
Response.Cookies["lastVisit"].Path = "/Application1";

you can scope up your cookie
Response.Cookies["lastVisit"].Domain = "janaganamana.net";

Browsers have 2083-character limits on URLs, so from query strings, you can get that much data.

Label1.Text = "User: " + Server.HtmlEncode(Request.QueryString("user"))
Server side caching
Session
Application

Application_Start
Application_End
Application_Error


you can disable session as below in web.config
<configuration>
<system.web>
<sessionState mode="off"/>
</system.web>
</configuration>

to disable for a page do it this way
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs"
Inherits="_Default" EnableSessionState = "False"%>



Where does the session data live?
InProc -- in memory on the Web server.
So restart IIS -- memory is Gone can you afford? - this is default
StateServer --Stores in a service called the ASP.NET State Service. set the startup type to Automatic on this service.
SQLServer -- Stores in a SQL Server database.
Custom -- your own way -- you need to provide a way.
Off -- disabled



<configuration>
<system.web>
<sessionState mode="SQLServer"
cookieless="true "
regenerateExpiredSessionId="true "
timeout="30"
sqlConnectionString="Data Source=MyServer;"
stateNetworkTimeout="30"/>
</system.web>
</configuration>

AuthenticationSection section = (AuthenticationSection) WebConfigurationManager.GetSection("system.web/authentication");

AuthenticationSection <system.web><authentication>
AnonymousIdentificationSection <system.web><anonymousIdentification>
AuthorizationSection <system.web><authorization>
CacheSection <system.web><cache>
CompilationSection <system.web><compilation>
CustomErrorsSection<system.web><customErrors>
DeploymentSection<system.web><deployment>
GlobalizationSection <system.web><globalization>
HealthMonitoringSection <system.web><healthMonitoring>
HostingEnvironmentSection <system.web><hostingEnvironment>
HttpCookiesSection <system.web><httpCookies>
HttpHandlersSection <system.web><httpHandlers>
HttpRuntimeSection <system.web><httpRuntime>
IdentitySection <system.web><identity>
MachineKeySection <system.web><machineKey>
MembershipSection <system.web><membership>
OutputCacheSection <system.web><outputCache>
PagesSection <system.web><pages>
ProcessModeSection <system.web><processMode>
ProfileSection <system.web><profile>
RolesManagerSection <system.web><rolesManager>
SecurityPolicySection <system.web><securityPolicy>
SessionPageStateSection <system.web><sessionPageState>
SessionStateSection <system.web><sessionState>
SiteMapSection <system.web><siteMap>
SqlCacheDependencySection <system.web><sqlCacheDependency>
TraceSection <system.web><trace>
TrustSection <system.web><trust>
WebControlsSection <system.web><webControls>
WebPartsSection <system.web><webParts>
XhtmlConformanceSection <system.web><xhtmlConformance>
Asynchronous Web Page
Add the Async="true" attribute to the @ Page directive

<%@ Page Language="C#" Async="true" AutoEventWireup="true" %>


in .cs file
IAsyncResult BeginGetAsyncData(Object src, EventArgs args, AsyncCallback cb, Objectstate) { }
void EndGetAsyncData(IAsyncResult ar)
{ }
Request.Browser can tell about browser

ActiveXControls whether the browser supports ActiveX controls.
AOL whether the client is an America Online (AOL) browser.
BackgroundSounds whether the browser supports playing background sounds using the <bgsounds> HTML element.
Browser
ClrVersion the version of the .NET Framework that is
installed on the client.
Cookies whether the browser supports cookies.
Crawler whether the browser is a search engine Web crawler.
Frames whether the browser supports HTML frames.
IsColor whether the browser has a color display.
IsMobileDevice whether the browser is a recognized mobile device.
JavaApplets whether the browser supports Java
JavaScript whether the browser supports JavaScript.
JScriptVersion Jscript version that the browser supports.
MobileDeviceManufacturer
Returns the name of the manufacturer of a mobile device, if known.
MobileDeviceModel model name of a mobile device, if known.
MSDomVersion version of Microsoft HTML (MSHTML)
Tables value indicating whether the browser supports HTML <table> elements.
VBScript value indicating whether the browser supports Visual Basic Scripting edition (VBScript).
Version full version number (integer and decimal)
of the browser as a string.
W3CDomVersion Gets the version of the World Wide Web Consortium
Win16 Gets a value indicating whether the client is a Win16-based computer.
Win32 Gets a value indicating whether the client is a Win32-based computer.
Context Classes
Response
Provides access to the HTTP response sent from the server to the client after receiving an incoming Web request.

Request
Provides access to information that is part of the current page request as sent from the Web browser, including the request headers, cookies, client certificate, and query string.

Server
Exposes utility methods that you can use to transfer control between pages, get information about the most recent error, encode and decode HTML text, and more. Most of the useful Server methods are static.

Context
Provides access to the entire current context (including the Request object). Most of the methods and properties provided by Context are also provided by other more frequently used objects, such as Request and Server.

Session
Provides information to the current user session. Also provides access to a session-wide cache you can use to store information, along with the means to control how the session is managed. For detailed information about the Session object, read Chapter 7.

Application
Provides access to application-wide methods and events for all sessions. Also provides access to an application-wide cache you can use to store information. For detailed information about the Application object, read Chapter 7.

Trace
Provides a way to display both system and custom trace diagnostic
messages in the HTTP page output.