ASP
ASP
ASP
Creating the web service Creating a proxy Consuming the web service
Take the following steps to create the web service: Step (1): Select File--> New --> Web Site in Visual Studio, and then select ASP.Net Web Service. Step (2): A web service file called Service.asmx and its code behind file, Service.cs is created in the App_Code directory of the project. Step (3): Change the names of the files to StockService.asmx and StockService.cs. Step (4): The .asmx file has simply a WebService directive on it:
using System; using System.Collections; using System.ComponentModel; using System.Data; using System.Linq; using System.Web; using System.Web.Services; using System.Web.Services.Protocols; using System.Xml.Linq; namespace StockService { /// <summary> /// Summary description for Service1 /// <summary> [WebService(Namespace = "http://tempuri.org/")] [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)] [ToolboxItem(false)] // To allow this Web Service to be called from script, // using ASP.NET AJAX, uncomment the following line. // [System.Web.Script.Services.ScriptService] public class Service1 : System.Web.Services.WebService { [WebMethod]
2 de 17
public string HelloWorld() { return "Hello World"; } } }
Step (6): Change the code behind file to add the two dimensional array of strings for stock symbol, name and price and two web methods for getting the stock information.
[WebService(Namespace = "http://tempuri.org/")] [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)] // To allow this Web Service to be called from script, // using ASP.NET AJAX, uncomment the following line. // [System.Web.Script.Services.ScriptService] public class StockService : System.Web.Services.WebService { public StockService () { //Uncomment the following if using designed components //InitializeComponent(); } string[,] stocks = { {"RELIND", "Reliance Industries", "1060.15"}, {"ICICI", "ICICI Bank", "911.55"}, {"JSW", "JSW Steel", "1201.25"}, {"WIPRO", "Wipro Limited", "1194.65"}, {"SATYAM", "Satyam Computers", "91.10"} }; [WebMethod] public string HelloWorld() { return "Hello World"; } [WebMethod] public double GetPrice(string symbol) { //it takes the symbol as parameter and returns price for (int i = 0; i < stocks.GetLength(0); i++) { if (String.Compare(symbol, stocks[i, 0], true) == 0) return Convert.ToDouble(stocks[i, 2]); } return 0; } [WebMethod] public string GetName(string symbol) { // It takes the symbol as parameter and // returns name of the stock for (int i = 0; i < stocks.GetLength(0); i++) { if (String.Compare(symbol, stocks[i, 0], true) == 0) return stocks[i, 1]; } return "Stock Not Found"; } }
Step (7) : Running the web service application gives a web service test page, which allows testing the service methods.
3 de 17
Step (8) : Click on a method name, and check whether it runs properly.
Step (9): For testing the GetName method, provide one of the stock symbols, which are hard coded, it returns the name of the stock
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="wsclient._Default" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" > <head runat="server"> <title>Untitled Page</title> </head> <body> <form id="form1" runat="server"> <div> <h3>Using the Stock Service</h3> <br /> <br /> <asp:Label ID="lblmessage" runat="server"></asp:Label> <br />
4 de 17
<br /> <asp:Button ID="btnpostback" runat="server" onclick="Button1_Click" Text="Post Back" Width="132px" /> <asp:Button ID="btnservice" runat="server" onclick="btnservice_Click" Text="Get Stock" Width="99px" /> </div> </form> </body> </html>
The code behind file for the web application is as follows:
using using using using using using using using using using using using
System; System.Collections; System.Configuration; System.Data; System.Linq; System.Web; System.Web.Security; System.Web.UI; System.Web.UI.HtmlControls; System.Web.UI.WebControls; System.Web.UI.WebControls.WebParts; System.Xml.Linq;
//this is the proxy using localhost; namespace wsclient { public partial class _Default : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) lblmessage.Text = "First Loading Time: " + DateTime.Now.ToLongTimeString(); else lblmessage.Text = "PostBack at: " + DateTime.Now.ToLongTimeString(); } protected void btnservice_Click(object sender, EventArgs e) { StockService proxy = new StockService(); lblmessage.Text = String.Format("Current SATYAM Price:{0}", proxy.GetPrice("SATYAM").ToString()); } } }
5 de 17
protected void btnservice_Click(object sender, EventArgs e) { StockService proxy = new StockService(); lblmessage.Text = String.Format("Current SATYAM Price: {0}", proxy.GetPrice("SATYAM").ToString()); }
Take the following steps for creating the proxy: Step (1): Right click on the web application entry in the Solution Explorer and click on 'Add Web Reference'.
Step (2): Select 'Web Services in this solution'. It returns the StockService reference.
Step (3): Clicking on the service opens the test web page. By default the proxy created is called 'localhost', you can rename it. Click on 'Add Reference' to add the proxy to the client application.
using localhost;
6 de 17
Creating Thread:
A thread is created by creating a Thread object, giving its constructor a ThreadStart reference.
The Unstarted State: it is the situation when the instance of the thread is created but the Start method has not been called. The Ready State: it is the situation when the thread is ready to run and waiting CPU cycle. The Not Runnable State: a thread is not runnable, when: o Sleep method has been called o Wait method has been called o Blocked by I/O operations The Dead State: it is the situation when the thread has completed execution or has been aborted.
Once a thread is created its priority is set using the Priority property of the thread class.
NewThread.Priority = ThreadPriority.Highest;
7 de 17
The Thread class has the following important properties: Property CurrentContext CurrentCulture CurrentPrinciple CurrentThread CurrentUICulture ExecutionContext IsAlive IsBackground IsThreadPoolThread ManagedThreadId Name Priority ThreadState Description Gets the current context in which the thread is executing. Gets or sets the culture for the current thread. Gets or sets the thread's current principal (for role-based security). Gets the currently running thread. Gets or sets the current culture used by the Resource Manager to look up culture-specific resources at run time. Gets an ExecutionContext object that contains information about the various contexts of the current thread. Gets a value indicating the execution status of the current thread. Gets or sets a value indicating whether or not a thread is a background thread. Gets a value indicating whether or not a thread belongs to the managed thread pool. Gets a unique identifier for the current managed thread. Gets or sets the name of the thread. Gets or sets a value indicating the scheduling priority of a thread. Gets a value containing the states of the current thread.
The Thread class has the following important methods: Methods Abort AllocateDataSlot AllocateNamedDataSlot BeginCriticalRegion BeginThreadAffinity EndCriticalRegion EndThreadAffinity FreeNamedDataSlot Description Raises a ThreadAbortException in the thread on which it is invoked, to begin the process of terminating the thread. Calling this method usually terminates the thread. Allocates an unnamed data slot on all the threads. For better performance, use fields that are marked with the ThreadStaticAttribute attribute instead. Allocates a named data slot on all threads. For better performance, use fields that are marked with the ThreadStaticAttribute attribute instead. Notifies a host that execution is about to enter a region of code in which the effects of a thread abort or unhandled exception might jeopardize other tasks in the application domain. Notifies a host that managed code is about to execute instructions that depend on the identity of the current physical operating system thread. Notifies a host that execution is about to enter a region of code in which the effects of a thread abort or unhandled exception are limited to the current task. Notifies a host that managed code has finished executing instructions that depend on the identity of the current physical operating system thread. Eliminates the association between a name and a slot, for all threads in the process. For better performance, use fields that are marked with the ThreadStaticAttribute attribute instead. Retrieves the value from the specified slot on the current thread, within the current thread's current domain. For better performance, use fields that are marked with the ThreadStaticAttribute attribute instead. Returns the current domain in which the current thread is running. Returns a unique application domain identifier. Looks up a named data slot. For better performance, use fields that are marked with the ThreadStaticAttribute attribute instead. Interrupts a thread that is in the WaitSleepJoin thread state. Blocks the calling thread until a thread terminates, while continuing to perform standard COM and SendMessage pumping. This method has different overloaded forms. Synchronizes memory access as follows: The processor executing the current thread cannot
GetData
8 de 17
reorder instructions in such a way that memory accesses prior to the call to MemoryBarrier execute after memory accesses that follow the call to MemoryBarrier. ResetAbort SetData Cancels an Abort requested for the current thread. Sets the data in the specified slot on the currently running thread, for that thread's current domain. For better performance, use fields marked with the ThreadStaticAttribute attribute instead. Starts a thread. Makes the thread pause for a period of time. Causes a thread to wait the number of times defined by the iterations parameter Reads the value of a field. The value is the latest written by any processor in a computer, regardless of the number of processors or the state of processor cache. This method has different overloaded forms. Writes a value to a field immediately, so that the value is visible to all processors in the computer. This method has different overloaded forms. Causes the calling thread to yield execution to another thread that is ready to run on the current processor. The operating system selects the thread to yield to.
VolatileWrite() Yield
Example:
The following example illustrates the uses of the Thread class. The page has a label control for displaying messages from the child thread. The messages from the main program is directly displayed using the Response.Write() method. So it appears on the top of the page. The source file is as follows:
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="threaddemo._Default" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" > <head runat="server"> <title>Untitled Page</title> </head> <body> <form id="form1" runat="server"> <div> <h3>Thread Example</h3> </div> <asp:Label ID="lblmessage" runat="server" Text="Label"> </asp:Label> </form> </body> </html>
The code behind file is as follows:
using using using using using using using using using using
System; System.Collections; System.Configuration; System.Data; System.Linq; System.Web; System.Web.Security; System.Web.UI; System.Web.UI.HtmlControls; System.Web.UI.WebControls;
9 de 17
using System.Web.UI.WebControls.WebParts; using System.Xml.Linq; using System.Threading; namespace threaddemo { public partial class _Default : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { ThreadStart childthreat = new ThreadStart(childthreadcall); Response.Write("Child Thread Started <br/>"); Thread child = new Thread(childthreat); child.Start(); Response.Write( "Main sleeping for 2 seconds.......<br/>"); Thread.Sleep(2000); Response.Write( "<br/>Main aborting child thread<br/>"); child.Abort(); } public void childthreadcall() { try{ lblmessage.Text = "<br />Child thread started <br/>"; lblmessage.Text += "Child Thread: Coiunting to 10"; for( int i =0; i<10; i++) { Thread.Sleep(500); lblmessage.Text += "<br/> in Child thread </br>"; } lblmessage.Text += "<br/> child thread finished"; } catch(ThreadAbortException e) { lblmessage.Text += "<br /> child thread - exception"; } finally{ lblmessage.Text += "<br /> child thread - unable to catch the exception"; } } } }
Observe the following:
When the page is loaded, a new thread is started with the reference of the method childthreadcall(). The main thread activities are displayed directly on the web page. The second thread runs and sends messages to the label control. The main thread sleeps for 2000 ms, during which the child thread runs. The child thread runs till it is aborted by the main thread. It raises the ThreadAbortException and is terminated. Control returns to the main thread.
10 de 17
The behavior of an ASP.Net application is affected by different settings in the configuration files:
machine.config web.config
The machine.config file contains default and the machine-specific value for all supported settings. The machine settings are controlled by the system administrator and applications are generally not given access to this file. An application however, can override the default values by creating web.config files in its roots folder. The web.config file is a subset of the machine.config file. If the application contains child directories, it can define a web.config file for each folder. Scope of each configuration file is determined in a hierarchical top-down manner. Any web.config file can locally extend, restrict or override any settings defined on the upper level. Visual Studio generates a default web.config file for each project. An application can run without a web.config file, however, you cannot debug an application without a web.config file. The following figure shows the Solution Explorer for the sample example used in the web services tutorial:
In this application there are two web.config files for two projects i.e., the web service and the web site calling the web service. The web.config file has the configuration element as the root node. Information inside this element is grouped into two main areas: the configuration section-handler declaration area, and the configuration section settings area. The following code snippet shows the basic syntax of a configuration file:
<configuration> <!-- Configuration section-handler declaration area. --> <configSections> <section name="section1" type="section1Handler" /> <section name="section2" type="section2Handler" />
11 de 17
</configSections> <!-- Configuration section settings area. --> <section1> <s1Setting1 attribute1="attr1" /> </section1> <section2> <s2Setting1 attribute1="attr1" /> </section2> <system.web> <authentication mode="Windows" /> </system.web> </configuration>
Clear - it removes all references to inherited sections and section groups. Remove - it removes a reference to an inherited section and section group. Section - it defines an association between a configuration section handler and a configuration element. Section group - it defines an association between a configuration section handler and a configuration section.
<configuration> <appSettings> <add key="appISBN" value="0-273-68726-3" /> <add key="appBook" value="Corporate Finance" /> </appSettings> </configuration>
12 de 17
datacaching\App_Data\ASPDotNetStepByStep.mdb" providerName="System.Data.OleDb" /> <add name="booksConnectionString" connectionString="Provider=Microsoft.Jet.OLEDB.4.0; Data Source=C:\ \databinding\App_Data\books.mdb" providerName="System.Data.OleDb" /> </connectionStrings>
<system.web> <anonymousIdentification> <authentication> <authorization> <browserCaps> <caching> <clientTarget> <compilation> <customErrors> <deployment> <deviceFilters> <globalization> <healthMonitoring> <hostingEnvironment> <httpCookies> <httpHandlers> <httpModules> <httpRuntime> <identity> <machineKey> <membership> <mobileControls> <pages> <processModel> <profile> <roleManager> <securityPolicy> <sessionPageState> <sessionState> <siteMap> <trace> <trust> <urlMappings> <webControls> <webParts> <webServices> <xhtmlConformance> </system.web>
The following table provides brief description of some of common sub elements of the system.web element:
anonymousIdentification:
This is required to identify users who are not authenticated when authorization is required.
authentication:
It configures the authentication support. Basic syntax:
13 de 17
<authentication mode="[Windows|Forms|Passport|None]"> <forms>...</forms> <passport/> </authentication>
authorization
It configures the authorization support.Basic syntax:
caching:
Configures the cache settings.Basic syntax:
customErrors:
Defines custom error messages. Basic syntax:
deployment:
Defines configuration settings used for deployment. Basic syntax:
hostingEnvironment:
Defines configuration settings for hosting environment.Basic syntax:
identity:
Configures the identity of the application. Basic syntax:
14 de 17
machineKey:
Configures keys to use for encryption and decryption of Forms authentication cookie data. It also allows configuring a validation key that performs message authentication checks on view-state data and Forms authentication tickets. Basic syntax:
<machineKey validationKey="AutoGenerate,IsolateApps" [String] decryptionKey="AutoGenerate,IsolateApps" [String] validation="HMACSHA256" [SHA1 | MD5 | 3DES | AES | HMACSHA256 | HMACSHA384 | HMACSHA512 | alg:algorithm_name] decryption="Auto" [Auto | DES | 3DES | AES | alg:algorithm_name] />
membership:
This configures parameters of managing and authenticating user accounts.Basic syntax:
pages:
Provides page-specific configurations. Basic syntax:
<pages asyncTimeout="number" autoEventWireup="[True|False]" buffer="[True|False]" clientIDMode="[AutoID|Predictable|Static]" compilationMode="[Always|Auto|Never]" controlRenderingCompatibilityVersion="[3.5|4.0]" enableEventValidation="[True|False]" enableSessionState="[True|False|ReadOnly]" enableViewState="[True|False]" enableViewStateMac="[True|False]" maintainScrollPositionOnPostBack="[True|False]" masterPageFile="file path" maxPageStateFieldLength="number" pageBaseType="typename, assembly" pageParserFilterType="string" smartNavigation="[True|False]" styleSheetTheme="string" theme="string" userControlBaseType="typename" validateRequest="[True|False]" viewStateEncryptionMode="[Always|Auto|Never]" > <controls>...</controls> <namespaces>...</namespaces> <tagMapping>...</tagMapping> <ignoreDeviceFilters>...</ignoreDeviceFilters> </pages>
profile:
Configures user profile parameters. Basic syntax:
15 de 17
<profile enabled="true|false" inherits="fully qualified type reference" automaticSaveEnabled="true|false" defaultProvider="provider name"> <properties>...</properties> <providers>...</providers> </profile>
roleManager:
Configures settings for user roles. Basic syntax:
<roleManager cacheRolesInCookie="true|false" cookieName="name" cookiePath="/" cookieProtection="All|Encryption|Validation|None" cookieRequireSSL="true|false " cookieSlidingExpiration="true|false " cookieTimeout="number of minutes" createPersistentCookie="true|false" defaultProvider="provider name" domain="cookie domain"> enabled="true|false" maxCachedResults="maximum number of role names cached" <providers>...</providers> </roleManager>
securityPolicy:
Configures the security policy. Basic syntax:
urlMappings:
Defines the mappings for hiding the actual URL and providing a more user friendly URL. Basic syntax:
webControls:
It provides the name of shared location for client scipts. Basic syntax:
webServices:
This configures the web services.
16 de 17
Local deployment in this case the entire application is contained within a virtual directory and all the contents and assemblies are contained within it and available to the application. Global deployment in this case, assemblies are available to every application running on the server.
There are different techniques used for deployment, however, we will discuss the following most common and easiest ways of deployment:
XCOPY Deployment:
XCOPY deployment means making recursive copies of all the files to the target folder on the target machine. You can use any of the commonly used techniques:
FTP transfer Using Server Management tools providing replication on a remote site MSI installer application
XCOPY deployment simply copies the application file to the production server and set a virtual directory there. You need to set a virtual directory using the Internet Information Manager Microsoft Management Consol (MMC snap-in).
Copying a Website:
The Copy Web Site option is available in Visual Studio. It is available from the Website --> Copy Web Site menu option. This menu items allows copying the current web site to another local or remote location. It is a sort of integrated FTP tool. Using this option, you connect to the target destination, select the desired copy mode:
Then proceed with copying the files physically. Unlike the XCOPY deployment, this process of deployment is done from Visual Studio environment. However, there are the following problems with both the above deployment methods:
You pass on your source code There is no pre-compilation and related error checking for the files The initail page load will be slow
Step (3): Choosing the default location ensures that the set up project will be located in its own folder under the root directory of the site. Click on okay to get the first splash screen of the wizard.
17 de 17
Step (4): The second screen asks to choose a project type. Select 'Create a setup for a web application'.
Step (8): The Set up project is added to the Solution Explorer and the main design window shows a file system editor
Step (5): Next, the third screen asks to choose project outputs from all the projects in the solution. Check the check box next to 'Content Files from...'
Step (9): Next step is to build the setup project. Rightclick on the project name in the Solution Explorer and select Build.
Step (6): The fourth screen allows including other files like ReadMe. However, in our case there is no such file. Click on finish.
Step (10): When build is completed, you get the following message in the Output window:
Step (7): The final screen displays a summary of settings for the set up project.
Setup.exe Setup-databinding.msi
You need to copy these files to the server and double-clicking the setup file will cause the content of the .msi file to be installed on the local machine.