Monday, May 04, 2009

Notes ASP do tNet

NotesASPdotNet


Contents
=========

Tutorial
Structure
ASP.Net Configuration
Connecting Events
HTML Control Class
Web / Server Control Class
ASP postback - eg like AJAX

ADO.Net - Accessing Data the Easy Way
ADO.Net - Example 
ADO.Net - command parameters
ADO.Net - Data Binding
ADO.Net - Data Binding - DataList
ADO.Net - Styles and Templates summary
Windows Service Applications
VS Setup Projects
Understanding ADO.Net - from AppDev video tutorial
Using MySQL in Visual Studio 
Configuring MySQL with ASP.Net
DropDownList
DataGrid - Sorting
WebService in ASP.Net
ASP.Net Custom Control


Tutorial
=========
1. Visual Studio 2005 -> Help -> Contents -> .Net Development
-> Web Applications -> ASP.Net Quickstart Tutorials


Structure
===========

System.Web.UI - Generic Page Class
    |
V
custom page class (my *.cs file, eg HelloClass.cs)
    |
V
custom aspx file (my *.aspx file, eg Hello.aspx)
    |
V
Page object


System.Web.HttpApplication 
    |
V
class GlobalApp (global.cs)
    |
V
global.asax   -> contain event handling code, each application can have one global.asax.


The classes are linked together like this:

VS2005: Global.asax no longer created automatically but can be added by:
Add new item -> Global Application Class.
Also the code behind global.asax.cs is no longer created, instead put the code inline in global.asax

Hello.aspx
-----------
<%@ Page Language="CS" Inherits="HelloClass" Src="HelloClass.cs" %> - if source is supplied
<%@ Page Language="CS" Inherits="HelloClass"  %> - if dll is supplied
<html>
<body>
<form id="Form" runat="server">
    <asp:Label id="lblTest" runat="server" />
</form>
....

HelloClass.cs
--------------
public class HelloClass : System.Web.UI.Page {
   protected System.Web.UI.WebControls.Label lblTest;

   private void Page_Load(){
      lblTest.Text = "Hello World";
   }
}

some basic event available to global.asax inherited from HttpApplication:
Application_OnStart
Application_OnEnd
Application_OnBeginRequest
Application_OnEndRequest
Application_OnError
Session_OnStart
Session_OnEnd

ASP.Net Configuration
======================
1. machine.config  - one per server, located at:
Microsoft.Net/Framework/Version/Config/

2. web.config - one per application, as well as one in each virtual sub-directory.

3. Structure and contents of web.config
+++++++++++++
<?xml version="1.0" encoding="utf-8" ?>
<configuration>

<!-- custome settings - using your own keyword -->
<appSettings>
<add key="ConnectionString" value="Data Source=localhost;Initial Catalog=Pubs;User ID=sa"/>
<add key="SelectSales" value="Select * FROM Sales"/>
</appSettings>

<system.web>
<httpRuntime />
<pages />
<compilation />
<customErrors />
<authentication />
<authorization />
<identity />
<trace />
<sessionState />
<httpHandlers />
<httpModules />
<globalization />
</system.web>

</configuration>
+++++++++++++

4. To make use of the special custom settings, eg.
++++++++++
using System;
using System.Configuration;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace Project
{
    public partial class ShowCustomConfigSettings : System.Web.UI.Page
    {
        protected Label lblTest;
        protected void Page_Load(object sender, EventArgs e)
        {
            lblTest.Text = "This app will connect with the connection string <br><br>";
            lblTest.Text += ConfigurationSettings.AppSettings["ConnectionString"];
            lblTest.Text += "<br><br> and will execute the SQL statement <br>";
            lblTest.Text += ConfigurationSettings.AppSettings["SelectSales"];
        }
    }
}
++++++++++


Connecting Events
===================
case: A button called id="Convert" on the aspx page. Functionality is in the function called
"Convert_ServerClick"

On the aspx page, have the attribute in the <%@Page .... >
AutoEventWireup="false"

To connect the function "Convert_ServerClick" to the event:
1.     protected override void OnInit(EventArgs e)        {
            InitializeComponent();
            base.OnInit(e);
        }

2.      private void InitializeComponent() { 
            Convert.ServerClick += new EventHandler(Convert_ServerClick);
        }

Note that EventHandler is a DELEGATE that connects a the function "Convert_ServerClick" 
The EventHandler delegate would have the same prototype of the function it points to, ie.:
        protected void Convert_ServerClick(Object sender, EventArgs e)

The ServerClick would be a type of the EventHandler delegate; perhaps
        public event EventHandler ServerClick
perhaps defined under the Convert's class - HtmlInputButton

HTML Control Class
=======================
System.Object
System.Web.UI.Controls
    HtmlControl   ---> System.Web.UI.HtmlControls namespace
    HtmlImage
HtmlInputControl
    HtmlInputButton
HtmlInputCheckBox
                HtmlInputFile
HtmlInputHidden
HtmlInputImage
HtmlInputRadioButton
HtmlInputText
HtmlContainerControl
                HtmlAnchor
HtmlButton
HtmlForm
HtmlGenericControl
HtmlSelect
HtmlTable
HtmlTableCell
HtmlTableRow
HtmlTextArea

Web / Server Control Class
============================
System.Object
System.Web.UI.Controls    
         Repeater         ---> System.Web.UI.WebControls
WebControl
     AdRotator
Calendar
ValidationSummary
BaseDataList (abstract)
    DataGrid
DataList
ListControl  (abstract)
    CheckBoxList
DropDownList
ListBox
RadioButtonList
     Button
CheckBox
    RadioButton
Hyperlink
Image
    ImageButton
     Label
    BaseValidator   (abstract)
    CompareValidator
CustomValidator
RangeValidator
RegularExpressionValidator
RequiredFieldValidator
LinkButton
Panel
Table
TableCell
    TableHeaderCell
     TableRow
TextBox

ASP postback - eg like AJAX
============================
1. Web control events that can use POSTBACK, when AutoPostBack property is set
to true:
Events                Web Control
=======               ===========================
Click                 Button, ImageButton
TextChange            TextBox
CheckChanged          CheckBox, RadioButton
SelectedIndexChange   DropDownList, ListBox, CheckBoxList, RadioButtonList
   
2. ASP.Net automatically adds these to the HTML page:
<input type="hidden" name="__EVENTTARGET" value=""/>
<input type="hidden" name="__EVENTARGUMENT" value=""/>
<script language="javascript">
<!--
   function __doPostBack(eventTarget, eventArgument){
      var theform = document.Form1;
  theform.__EVENTTARGET.value = eventTarget;
  theform.__EVENTARGUMENT.value = eventArgument;
  theform.submit();
   }
-->
3. Add event handlers to the InitializeComponent() method
i.e.  <button>.<Event> += new EventHandler(<functionName>)
eg    txt.TextChanged += new  EventHandler(CtrlChanged)

4. Implement using the added function:
private void CtrlChanged(Object sender, EventArgs e) {    }


ADO.Net - Accessing Data the Easy Way
=============================
To retrieve information
1. Create Connection, Command and DataReader objects
2. Use DataReader to retrieve info and display it on web
3. Close connection.
4. Send page to user.

To add or update information
1. Create new Connection and Command objects.
2. Execute the Command

ADO.Net - Example 
=========
using System.Data; 
using System.Data.SqlClient;  // for MS SQL
using System.Data.OleDb;      // for general connector

// Define the connection to Database
<x>={Sql, OleDb, ...}
<x>Connection myConn = new <x>Connection();
myConn.ConnectionString = "Provider=SQLOLEDB.1; Data Source=localhost;" + " Initial Catalog=Pubs; User ID=root";
  // the provider is need when <x>=OleDb, but not when <x>=Sql.
  // Password is not passed here if using "Integrated Windows Authentication"
myConn.ConnectionString = "Provider=SQLOLEDB.1; Data Source=localhost;" + " Initial Catalog=Pubs; Integrated Security=SSPI";

// Making the connection
try{
   myConn.Open();
   lblInfo.Text="<b>Server Version: </b>" + myConn.ServerVersion;
   lblInfo.Text+="<br><b> Connection is:</b> " + myConn.State.ToString();
} catch(Exception err) {
lblInfo.Text = "Error reading the database.";
lblInfo.Text += err.Message;
} finally {
    myConn.Close();
lblInfo.Text += "<br> Now Connection is";
lblInfo.Text += myConn.State.ToString();
}

//Alternative connection
using{
   myConn.Open();
   lblInfo.Text="<b>Server Version: </b>" + myConn.ServerVersion;
   lblInfo.Text+="<br><b> Connection is:</b> " + myConn.State.ToString();
}
lblInfo.Text += "<br> Now Connection is";
lblInfo.Text += myConn.State.ToString();

// Creating the SQL statement and assigning to Command
<x>Command myCmd = new <x>Command();
myCmd.Connection = myConn;
myCmd.CommandText = "Select * from Authors";
//Alternative
<x>Command myCmd = new <x>Command("Select * from Authors", myConn);

// Using Command with DataReader
<x>DataReader myReader;
myReader = myCmd.ExecuteReader();

// Reading objects
myReader.Read();      // reads an object at a time sequentially

// Cleanup
myReader.Close();
myConn.Close();

ADO.Net - command parameters
==============================
Instead of using this:
  insertSQL "Insert INTO authors (au_id) VALUES ('txtID.Text')"
.... where txtID is a from the GUI on the webpage.

This method can be hacked via SQL Injection. To solve this, Command Parameters are used:
  insertSQL "Insert INTO authors (au_id) VALUES (?)"
  cmd.Parameters.Add("?", txtID.Text);

where cmd is a OleDBCommand, and note that "?" is for OleDB only.
MySQL or MSSQL may have different symbols or notation for their command parameters.


ADO.Net - Data Binding
=======================
Simple Data Binding:
1) in the aspx page, have something like:
<asp:Label id="lbLabel" runat="server">
   There were <%# TransactionCount %>
</asp:Label>
2) In the code behind, have something like:
private void Page_Load(...){
   TransactionCount = 10;
   this.DataBind();

Alternative to data bind above is to do this in-code.
3) private void Page_Load(...){
      TransactionCount = 10;
      lblDynamic.Text = "There were " + TransactionCount.ToString();

Multiple Binding:
1. Form an array list from whereever:
   eg. ArrayList fruit = new ArrayList(); 
       fruit.Add("Kiwi");  
   or from database
2. Define binding for list controls; eg
   MyListBox.DataSource = fruit;
   MyDropDownListBox.DataSource = fruit;
   MyHTMLSelect.DataSource = fruit;
   MyCheckBoxList.DataSource = fruit;
   MyRadioButtonList.DataSource = fruit;
3. Activate the binding, eg.
   this.DataBind();        // this refers to the current page.


Multiple Binding with hashtables:
1. Create hashtable with key,val pair
   Hashtable fruit = new Hashtable();
   fruit.Add(1, "Kiwi");
   fruit.Add(2, "Pear");
2. Binding specific fields
   MyListBox.DataTextField = "Value"  -> put the Value of hastable into the Text of the Control
   MyListBox.DataValueField = "Key"  -> put the Key of hastable into the value of the Control
3. Define databinding and activate
   MyListBox.DataSource = fruit;
4. The result is the following HTML will be rendered:
   <select name="MyListBox" id="MyListBox">
      <option value="1">Kiwi</option>

Databinding with databases:
1. Some possible namespaces (when using OleDB):
   using System.Data;
   using System.Data.OleDb;
2. Making data using dataset example:
   DataSet ds = new DataSet();
   ds.Tables.Add("Users");
   ds.Tables["Users"].Columns.Add("Name");
   ds.Tables["Users"].Columns.Add("Country");
   DataRow dr = ds.Tables["Users"].NewRow();
   dr["Name"] = "John";
   dr["Country"] = "Uganda";
   ds.Tables["Users"].Rows.Add(rd);
3. Bind table to data source:
   lstUser.DataSource = ds.Tables["Users"];
   lstUser.DataTextField = "Name";
or Bind whole DataSet to data source:
   lstUser.DataSource = ds;
   lstUser.DataMember = "Users";
   lstUser.DataTextField = "Name";
4. Activate the Binding:
   this.DataBind();
or to bind just the list box
   lstItems.DataBind()

ADO.Net - Data Binding - DataList
=====================================
1. Code Behind:
   public class BasicAuthorList: Page
   {
protected DataList listAuthor;
// (Initialisation code omitted)
private string connectString ="Provider ......."

private void Page_Load(Object sender, EventArgs e)
{
string SQL = "SELECT * FROM AUTHORS";
OleDbConnection con = new OleDbConnection (connectString);
OleDbCommand cmd = new OleDbCommand(SQL, con);
OleDbAdapter adapt = new OleDbAdapter(cmd);
DataSet pubs = new DataSet();
con.Open();
adapter.Fill(pubs, "Authors");
con.Close();

//Bind the DataSet and activate the data bindings for the page
listAuthor.DataSource = pubs.Tables["Authors"];
this.DataBind();

2. ASPX DataList template 
   <asp:DataList id=listAuthor runat="server">
      <ItemTemplate>
      <font face="Verdana" size="2">
          <b><%# DataBinder.Eval(Container.DataItem, "au_fname") %>
  <%# DataBinder.Eval(Container.DataItem, "au_lname") %></b></font>
  <br> Address: <%# DataBinder.Eval(Container.DataItem, "address") %>
  <br> City: <%# DataBinder.Eval(Container.DataItem, "city") %>
  </font>
   </ItemTemplate>
   </asp:DataList>

3. Formating Values - for DataBinder
eg    DataBinder.Eval(Container.DataItem, "Price", "{0:C}")
{0:C}    Currency
{0:E}    Scientific (Exponential)
{0:P}    Percentage
{0:F?}   Fixed Decimal
see MSDN Help for more.

4. Adding different styles to Templates
a) Manual option - hand coding on aspx file
  <HeaderTemplate>
     <h2> title </h2>
  </HeaderTemplate>
  <ItemTemplate>
     (Item style1)
  </ItemTemplate>
  <AlternatingItemTemplate>
       (Item style2)
  </AlternatingItemTemplate>
  <SeparatorTemplate>
     <h2> title </h2>
  </SeparatorTemplate>
  <FooterTemplate>
     <h2> title </h2>
  </FooterTemplate>

b) Using VS.Net right-click DataList properties

c) AutoFormat link from the DataList properties

d) To make columns and rows, check out the RepeatDirection and RepeatColumns properties.


ADO.Net - Data Binding - DataGrid
=====================================
1) DataList may have columns and rows, but DataGrid has columns such that the columns
correspond to certain fields of the data item; eg phone - city - zip code as different
columns. 

2) Features include: automatic paging, sorting, editing, selecting.

3) Examples that show the Columns tag and the use of styles:
<asp: DataGrid id=gridauthor runat="server" AutoGenerateColumns="false"
BorderColor="#..." BorderStyle="None" CellSpacing="2"
BackColor="#..." CellPadding="3" BorderWidth="1px">

    <FooterStyle ForeColor="#..."  BackColor="#..." ></FooterStyle>
    <HeaderStyle ForeColor="#..."  BackColor="#..." ></HeaderStyle>
    <ItemStyle ForeColor="#..."  BackColor="#..." ></ItemStyle>

<Columns>
<asp:TemplateColumn HeaderText="AuthorName">
          <ItemTemplate>
              <%# DataBinder.Eval(Container.DataItem, "au_fname") %>
      <%# DataBinder.Eval(Container.DataItem, "au_lname") %>
      </ItemTemplate>
</asp:TemplateColumn>
</Columns>
</asp:DataGrid>

4) DataGrid has special columns including:
TemplateColumn - contents here include <ItemTemplate> and other stuff that can go into
                 DataList.
BoundColumn - a particular field from database
ButtonColumn
EditCommandColumn
HyperlinkColumn

All these columns should exist within <Columns> ... </Columns>


ADO.Net - Data Binding - Repeater
=====================================
Repeater has not much formatting by itself. It depends on formatting provided
in the html. Example:
<asp:Repeater id=repeatauthor runat="server">
    <HeaderTemplate> <table> </HeaderStyle>
    <ItemTemplate><tr>
          <%# DataBinder.Eval(Container.DataItem, "au_fname") %>
</ttr></ItemTemplate>
    <FooterTemplate> </table> </FooterStyle>
</asp:DataGrid>



ADO.Net - Styles and Templates summary
=======================================
Styles 
DataList             DataGrid             Repeater
-----------------------------------------------------------
AlternatingItemStyle AlternatingItemStyle None
EditItemStyle         EditItemStyle 
FooterStyle             FooterStyle 
HeaderStyle             HeaderStyle 
ItemStyle             ItemStyle 
SelectedItemStyle     SelectedItemStyle 
SeparatorStyle         PagerStyle 


Template 
DataList             DataGrid*         Repeater
-----------------------------------------------------------
AlternatingItemTemplate FooterTemplate     AlternatingItemTemplate
EditItemTemplate     HeaderTemplate     FooterTemplate
FooterTemplate         ItemTemplate     ItemTemplate
HeaderTemplate         EditItemTemplate SeparatorTemplate
ItemTemplate 
SelectedItemTemplate 
SeparatorTemplate 

* only supported by Template column

1) Do not bind the grid in the Page.Load event handler, otherwise info is
   lost about which button user clicked or item selected.

   private void Page_Load......
       if(!this.PostBack) {
          DataSet ds = GetDataSet();
  BindGrid(ds);
  .........
   }

   private DataSet GetDataSet(){
       string SQL = "...."
   OldDbConnection ...
   OldDbCommand cmd = 
   OleDbAdapter = ...
   DataSet dsPubs = ...
   adapter.Fill(dsPubs, "Authors");
   con.Close();
   return dsPubs;
    }

private void BindGrid(DataSet ds){
       gridAuthor.DataSource = ds.Table["Authors"];
       this.DataBind();
}


Windows Service Applications
=============================
1. Do not have any in/output to screen or Windows, or it will crash the app.

2. Error messages should be logged in the Windows event log rather than raised in the user interface. 

3. To control, use Services Control Manager, or Server Explorer, or the ServiceController class (use this 
to control the service from another app).

4. States of the service include: start, stop, pause, resume
   Corresponding methods in code: OnStart, OnStop, OnPause, OnContinue, OnShutdown, OnCustomCommand, OnPowerEvent.

5. Two types of services: Win32OwnProcess, Win32ShareProcess.

6. VisualStudio has installation components that can install resources, register the service and let Services Controller
Manager know. Add these installers to the app and also create a separate setup project.

7. Must inherit from System.ServiceProcess.ServiceBase class. The project must contain installation components.
   To create the Service:
      - set ServiceName property
  - create installers
  - override methods for OnStart and OnStop.

8. System.ServiceProcess.ServiceProcessInstaller and System.ServiceProcess.ServiceInstaller 
?You use these classes to install and uninstall your service. 

9. Execution Process:
  Add Installers in project
      Build
      Install: installutil yourproject.exe    / Uninstall: installutil /u yourproject.exe
  Start the Service

10. Debugging:
      Install service
  Start service
  In VS, Debug->Process
  Click Show System Processes
  Attach process
  add any break points
  use Services Control Manager to control the service.

11. To add Installers:
      -In Solution Explorer, go to Design View of the service.
  -Click on background of designer and AddInstaller.
      -A new class, ProjectInstaller, and two installation components, ServiceProcessInstaller and ServiceInstaller, 
  are added to your project, and property values for the service are copied to the components. 
      -Click the ServiceInstaller component and verify that the value of the ServiceName property is set to the 
  same value as the ServiceName property on the service itself. 
      -To determine how your service will be started, click the ServiceInstaller component and set the StartType property 
  to the appropriate value. { Manual, Automatic, Disabled }
      - To determine the security context in which your service will run, click the ServiceProcessInstaller 
  component and set the appropriate property values. For more information, see How to: Specify the Security Context for Services.
      - Override any methods for which you need to perform custom processing. For more information, see How to: Override Default Methods on Installation Components.
      - Perform steps 1 through 7 for each additional service in your project. 
        Note: For each additional service in your project, you must add an additional ServiceInstaller component 
to the project's ProjectInstaller class. The ServiceProcessInstaller component added in step 
three works with all of the individual service installers in the project. 
      - Create your setup project and custom action to deploy and install your service. 
  For more information on setup projects, see Setup Projects. 
  - After you add installers to your application, the next step is to create a setup project that will install 
  the compiled project files and run the installers needed to install your service. To create a complete 
  setup project, you must add the service project's output to the setup project and 
  then add a custom action to have your service installed. For more information on setup projects, see Setup Projects. For more information on custom actions, see Walkthrough: Creating a Custom Action.
      (see VS Setup Projects for more details)


VS Setup Projects
=====================
1. Design, code, build your project in VS Studio say project ProjA in solution SolnA.
2. Create the setup project SetupA, in SolnA: Add Project -> New Project -> Other Project Types -> Setup and Deployment.
3. Right click setupA -> Install -> Add Project Output. Select ProjA and choose "Primary Output".
4. Right click setupA -> View -> Custom Actions.
5. Right click on Custom Actions -> Add Custom Option. Select Application Folder -> Primary output from ProjA.
6. Build.
7. The msi and exe file will be created. 


Understanding ADO.Net - from AppDev video tutorial
====================================================
Object Model:
   Connected Object (Specific to DB engine or provider)
   -> .Net Data Provider (incl. MySql.Data.MySqlClient or SystemData.ODBC|OleDB|SqlClient|OracleClient)
         -> Connection: Transaction
         -> Command: Parameters (eg to execute some command)
         -> DataReader:
         -> DataAdapter:
            -> Fills DataTable: SelectComm
            -> Updates Database: InsertComm, UpdateComm, DeleteComm
   DisConnected Object (can work with data in a disconnected state)         
   -> DataSet (analogous to Database) <-> XML
         -> DataTableCollection
-> DataTable:
   -> DataRowCollection - storing the data
   -> DataColumnCollection - names and properties of columns
   -> ConstraintCollection - eg unique key or foreign key constraints.
         -> DataRelationCollection
   -> DataView
      -> Row Filter
      -> Sort
      -> Extended support for Data Binnding
   -> DataTableReader
      -> A DataReader for DataTables and DataSets
      -> Fast forward only reading
      -> resilient to adding or deleting rows while reading     
    
  
... to be continued at Data Caching Object
         
Using MySQL in Visual Studio 
=============================
1. View -> Server Explorer
2. Look for database server and connect
         
Configuring MySQL with ASP.Net
===============================
It is easy to use MySQL with ASP.Net. becasue by default the local ASP.Net enables you with FULL TRUST permission.
This section shows how to configure ASP.Net to work with MySQL where the ASP.Net is stored in a ISP's server,
which usually uses MEDIUM TRUST, not FULL TRUST.

To the SQL administrator:
1. There are two options, one is to modify the web_mediumtrust.config; the other option is to copy and rename the config file.
The web_mediumtrust.config is located typically in C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\CONFIG\ 
Add the SOCKPermission to this file.

<SecurityClass ............. 
<SecurityClass Name="SocketPermission" Description="System.Net.SocketPermission, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"/> 
... 
... 
<IPermission 
class="SocketPermission" 
version="1" 
Unrestricted="true"/> 

2. If we choose the second option in step 1. to make a new file and called web_mediumMySQLtrust.config, then we need
to register this in the C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\CONFIG\web.config with the following line:

<trustLevel name="Medium" policyFile="web_mediumtrust.config" />         .... already there
<trustLevel name="MediumMySQL" policyFile="web_mediumMySQLtrust.config" />    .... add this new one

Also in the same file, add this within the <system.web>
<trust level="Medium" originUrl="" /> 
or 
<trust level="MediumMySQL" originUrl="" /> 


To the Developer:
1. In the web application, in the web.config file, insert the line about <trust> just before </system.web>
eg.
    <system.web>
        ......
        ......
        <trust level="Medium" originUrl="" />
    </system.web>

         
DropDownList
============
To add first element, add a ListItem and the property AppendDataBoundItems set to true.
Eg.
<asp:dropdownlist id="suburbDropList"  AppendDataBoundItems="true" AutoPostBack="True" runat="server" >
    <asp:ListItem Text="(Select a Suburb)" Value="" />
</asp:dropdownlist>

DataGrid - Sorting
===================
To allow for sorting on the DataGrid, the following are needed.
1. Right click on the GUI design of the DataGrid and set "AllowSorting" to "true".
2. Add the following in the aspx code file in the DataGrid item:
   OnPageIndexChanging="PageChangeFunction" OnSorting="SortingFunction"
3. Set property AutoGenerateColumns to true, i.e.TestMenu.AutoGenerateColumns = true;   


WebService in ASP.Net
======================

*.asmx      - web service file
WSDL        - Web Service Description Language, describes the methods and parameters in a web service.
              The elements of WSDL are: definitions, types, message, portType, binding, service.
SOAP        - way to encode info to pass to web service
HTTP        - protocol through which SOAP messages are sent
DISCO       - discovery standard that contains links to web services
UDDI        - business registry that lists all info about companies and web services they provide, with
              URLs for their WSDL contracts and DISCO.

Data types: Basic / primitives, Enumerations, DataSets, XmlNode, Custom Objects, Arrays


Testing the web service
------------------------
http://<domain>/<webservice>.asmx      -> to view the web service directly
http://<domain>/<webservice>.asmx?WSDL -> to view the WSDL.
http://<domain>/<webservice>.asmx?op=<methodName>      -> to access the web service method directly



The use of web services in C# ASP.Net is illustrated with the example below:
----------------------------------
1.<%@ WebService Language="C#" Class="Util" %>
2. using System.Web.Services;
3. using System;
4. [WebService(Namespace="http://www.contoso.com/")]
5. public class Util: WebService 
6. {
7.     [ WebMethod]
8.     public long Multiply(int a, int b) 
9.     {
10.         return a * b;
11.     }
12. }
----------------------------------
or
----------------------------------
in file: Util.asmx
1.«%@ WebService Language="C#" CodeBehind="Util.asmx.cs" Class="Util" %»

in file: Util.asmx.cs
2. using System.Web.Services;
3. using System;
4. [WebService(Namespace="http://www.contoso.com/", Description="test utility")]
5. public class Util: WebService 
6. {
7.     [WebMethod(Description=" test a method "]
8.     public long Multiply(int a, int b) 
9.     {
10.         return a * b;
11.     }
12. }
----------------------------------

1. Declare the webservice using «%@ WebService....
Option 1: Place the above code inside *.asmx file with the C# code.
Option 2: Put only the <%@ WebService in the asmx class and put the C# code somewhere else.
Then the declaration would be:
     <%@ WebService Language="C#" Class="MyName.MyWebService,MyAssembly" %>
... where MyAssembly is the name of the assembly.

2. Deriving the WebService class - this is optional. Lines 2,5.

3. Apply WebService attribute and specify domain to avoid confusion with other webservices.
   see line 4.

4. Define the web service method using [ WebMethod ] - see line 7.

5. State Management for Web Services is achived by deriving from the WebService class. It provides 
   access to ASP.NET objects such as:
   Session     - client specific state information
   Application - used to store data globally and available to all clients
   Server      - utility functions
   User        - info about current client including authentication
   Context     - provides access to Request, Response and Cache

7. Storing and access state in a client session:
   Declare: [ WebMethod(EnableSession=true) ]
   Store:   Session["MyServiceUsage"] = 1;
   Access:  Session["MyServiceUsage"] = ((int) Session["MyServiceUsage"]) + 1;

8. Storing and access state in Web application hosting the Web service:
   Declare: [ WebMethod ]
   Store:   Application["appMyServiceUsage"] = 1;
   Access:  Application["appMyServiceUsage"] =  ((int) Application["appMyServiceUsage"]) + 1;


ASP.Net Custom Control
=======================
The following describes Custom Control for web applications (*.aspx). The Custom Control for console
applications are similar, but not exactly.

1. To add a user control, right click on the web application project in the Solution Explorer. Click
New Item, then choose Web User Control, and name it WUC.


2. In Visual Studio, this will auto create 3 files:
   - WUC.ascx - with Design and Code view
   - WUC.ascx.cs - the code to be edited or added.
   - WUC.ascx.designer.cs 

3. Put the collection of controls in your custom control withing the WUC.ascx file. For example,
<%@ Control Language="C#" AutoEventWireup="true" CodeBehind="WUC.ascx.cs" 
Inherits="ParentWebApp.WUC" %>
<asp:Label ID="lblFooter" runat="server" Height="87px" Text="Label" Width="214px"></asp:Label>

4. The Label control above can be also created by using the WUC.ascx design view. Just
drag the Label button from the toolbox onto the form.

5. In the code behind file WUC.ascx.cs, make the WUC class inherit from System.Web.UI.UserControl. And 
in the Page_Load, enter code for what the controls need to do. For example, 

    public partial class WebUserControlFooter : System.Web.UI.UserControl
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            lblFooter.Text = "This page was served at ";
            lblFooter.Text += DateTime.Now.ToString();
        }
    }

6. To use this custom control on any aspx web page:
a) Register the custom control on those aspx web pages, eg.
<%@ Register TagPrefix="cr" TagName="WUC" Src="~/WUC.ascx" %>
b)  Add the custom control, eg.
        <cr:WUC id=Footer1 runat="server" />

Note that the TagPrefix name is the alias for the custom control to be used in the aspx web page.

No comments: