Net Remoting Versus Web Services

  • 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 Net Remoting Versus Web Services as PDF for free.

More details

  • Words: 4,823
  • Pages: 13
1 NET Remoting Versus Web Services With the advent of .NET and the .NET Framework, Microsoft introduced a set of new technologies in the form of Web services and .NET remoting. .NET remoting and ASP.NET Web services are powerful technologies that provide a suitable framework for developing distributed applications. It is important to understand how both technologies work and then choose the one that is right for your application. The Web services technology enables cross-platform integration by using HTTP, XML and SOAP for communication thereby enabling true business-to-business application integrations across firewalls. Because Web services rely on industry standards to expose application functionality on the Internet, they are independent of programming language, platform and device. Remoting is .a technology that allows programs and software components to interact across application domains, processes, and machine boundaries. This enables your applications to take advantage of remote resources in a networked environment. Both Web services and remoting support developing distributed applications and application integration, but you need to consider how they differ before choosing one implementation over the other. In this article, I will show the differences between these two technologies. I will present samples for each type of implementation and identify when to use which technology. quote: -------------------------------------------------------------------------------DCOM If you are a real Microsoft platform developer then you have done some work on COM and interface based components. When it comes to distributing your program logic, you are almost tied to Distributed COM (DCOM). -------------------------------------------------------------------------------DCOM is a very proprietary RPC-based communication protocol for COM-based distributed component architectures. Even though DCOM allows us to create scalable and reliable architectures in the Intranet environment, there are a lot of problems with DCOM when you try to integrate with different platforms and technologies in an Internet environment. A Look at .NET Remoting .NET Remoting uses a flexible and extremely extensible architecture. Remoting uses the .NET concept of an Application Domain (AppDomain) to determine its activity. An AppDomain is an abstract construct for ensuring isolation of data and code, but not having to rely on operating system specific concepts such as processes or threads. A process can contain multiple AppDomains but one AppDomain can only exist in exactly one process. If a call from program logic crosses an AppDomain boundary then .NET Remoting will come into place. An object is considered local if it resides in the same AppDomain as the caller. If the object is not in the same appdomain as the caller, then it is considered remote. In .NET remoting, the remote object is implemented in a class that derives from System.MarshalByRefObject. The MarshalByRefObject class provides the core foundation for enabling remote access of objects across application domains. A remote object is confined to the application domain where it is created. In .NET remoting, a client doesn't call the methods directly; instead a proxy object is used to invoke methods on the remote object. Every public method that we define in the remote object class is available to be called from clients.

Different Types of Remote Objects The remoting infrastructure allows you to create two distinct types of remote objects. Client-activated objects - A client-activated object is a server-side object whose creation and destruction is controlled by the client application. An instance of the remote object is created when the client calls the new operator on the server object. This instance lives as long as the client needs it, and lives across one to many method calls. The object will be subject to garbage collection once it's determined that no other clients need it.

2

Server-activated objects - A server-activated object's lifetime is managed by the remote server, not the client that instantiates the object. This differs from the client-activated object, where the client governs when the object will be marked for finalization. It is important to understand that the server-activated objects are not created when a client calls New or Activator.GetObject. They are rather created when the client actually invokes a method on the proxy. There are two types of server activated objects. They are: Single call . Single-call objects handle one, and only one, request coming from a client. When the client calls a method on a single call object, the object constructs itself, performs whatever action the method calls for, and the object is then subject to garbage collection. No state is held between calls, and each call (no matter what client it came from) is called on a new object instance. Singleton - The difference in a singleton and single call lies in lifetime management. While single-call objects are stateless in nature, singletons are stateful objects, meaning that they can be used to retain state across multiple method calls. A singleton object instance serves multiple clients, allowing those clients to share data among themselves. A Look At ASP.NET Web Services With the arrival of .NET, creating an ASP.NET Web service is a breezy experience with the .NET framework taking away all the complexities in creating and consuming Web services. To create a Web service, all you need to do is create a Web service class that derives from the System.Web.Services.WebService class and decorate the methods (that you want to expose as Web services) with the WebMethod attribute. Once this is done, these methods can be invoked by sending HTTP requests using SOAP. Consuming a Web service is very straightforward too. You can very easily create a proxy class for your Web service using either wsdl.exe utility or the Add Web Reference option in VS.NET. The Web service proxy hides all the network and marshaling plumbing from the application code, so using the Web service looks just like using any other local object. When a client calls the remote method, the proxy receives the call, encodes the message using an appropriate formatter, then sends the call over the channel to the server process. A listening channel on the server appdomain picks up the request and forwards it to the server remoting system, which locates and invokes the methods on the requested object. Once the execution is completed, the process is reversed and the results are returned back to the client. Out of the box, the remoting framework comes with two formatters: the binary and SOAP formatters. The binary formatter is extremely fast, and encodes method calls in a proprietary, binary format. The SOAP formatter is slower, but it allows developers to encode the remote messages in a SOAP format. If neither formatter fits your needs, developers are free to write their own and plug it in as a replacement. http://www.developer.com/img/articles/2003/05/06/Thiru/Remote2.jpg[/img As you can see from the above diagram, the client proxy receives the request from the client, serializes the request into a SOAP request which is then forwarded to the remote Web service. The remote Web service receives the SOAP request, executes the method, and sends the results in the form of a SOAP response to the client proxy, which deserializes the message and forwards the actual results to the client. ASP.NET Web Services Vs .NET Remoting Now that we have understood the basic concepts of .NET remoting and Web services, let us identify the differences between these two technologies. For this, I present different factors such as performance, state management, etc and then identify which technology to use in what situations. Performance In terms of performance, the .NET remoting plumbing provides the fastest communication when you use the TCP channel and the binary formatter. In the case of Web services, the primary issue is performance. The verbosity of XML can cause SOAP serialization to be many times slower than a binary formatter. Additionally, string manipulation is very slow when compared to processing the individual bits of a binary stream. All data transported across the wire is formatted into a SOAP packet. However if your Web service performs computation intensive operations, you might want to consider using caching to increase the performance of your Web service on the server side. This will increase the scalability of the Web service, which in turn can contribute to the increase in performance of the

3 Web service consumers. A remoting component, using the TCP channel and the binary formatter, provides the greatest performance of any remoting scenario, primarily because the binary formatter is able to serialize and deserialize data much faster. If you use .NET remoting with a SOAP formatter, you will find that the performance provided by ASP.NET Web services is better than the performance provided by NET remoting endpoints that used the SOAP formatter with either the HTTP or the TCP channel. However the .NET remoting provides clear performance advantages over ASP.NET Web services only when you use TCP channels with binary communication. State Management Web services are a stateless programming model, which means each incoming request is handled independently. In addition, each time a client invokes an ASP.NET Web service, a new object is created to service the request. The object is destroyed after the method call completes. To maintain state between requests, you can either use the same techniques used by ASP.NET pages, i.e., the Session and Application objects, or you can implement your own custom solution. However it is important to remember that maintaining state can be costly with Web services as they use extensive memory resources. .NET remoting supports a range of state management options that you can choose from. As mentioned before, SingleCall objects are stateless, Singleton objects can share state for all clients, and client-activated objects maintain state on a per-client basis. Having three types of remote objects (as opposed to one with Web services) during the design phase helps us create more efficient, scalable applications. If you don't need to maintain state, use single-call objects; if you need to maintain state in a small section of code, use single call and singletons together. The ability to mix and match the various object types facilitates creation of solid architectural designs. Security .NET remoting plumbing does not provide out of the box support for securing cross-process invocations. However a .NET remoting object hosted in IIS, can leverage all the same security features provided by IIS. If you are using the TCP channel or the HTTP channel hosted in a container other than IIS, you have to implement authentication, authorization and privacy mechanisms yourself. Since ASP.NET Web services are hosted, by default, in IIS, they benefit from all the security features of IIS such as support for secure communication over the wire using SSL, authentication and authorization services. Reliability .NET remoting gives you the flexibility to host remote objects in any type of application including a Windows Form, a managed Windows Service, a console application or the ASP.NET worker process. If you host your remote objects in a windows service, or a console application, you need to make sure that you provide features such as fault tolerance within your hosting application so that the reliability of the remote object is not compromised. However if you do host remote objects in IIS, then you can take advantage of the fact that the ASP.NET worker process is both auto-starting and thread-safe. In the case of ASP.NET Web services, reliability is not a consideration as they are always hosted in IIS, making it easy for them to take advantage of the capabilities provided by IIS. Extensibility Both the ASP.NET Web services and the .NET remoting infrastructures are extensible. You can filter inbound and outbound messages, control aspects of type marshaling and metadata generation. .NET remoting takes extensibility to the next level allowing you to implement your own formatters and channels. Since ASP.NET Web services rely on the System.Xml.Serialization.XmlSerializer class to marshal data to and from SOAP messages at runtime, we can very easily customize the marshaling by adding a set of custom attributes that can be used to control the serialization process. As a result, you have very finegrained control over the shape of the XML being generated when an object is serialized. Ease of programming and deployment In this section, we will consider a simple remoting object and an ASP.NET Web service to understand the complexities involved in creating and consuming them. We will start off by creating a simple remote object. Creating a remote object Creating a remoting object is a simple process. To create a remote object, you need to inherit from

4 MarshalByRefObject class. The following code shows a remotable class. using System; namespace RemoteClassLib { public class MyRemoteObject : System.MarshalByRefObject { public MyRemoteObject() { Console.WriteLine("Constructor called"); } public string Hello(string name) { Console.WriteLine("Hello Called"); return "Hello " + name; } } } The above code is very simple and straightforward. We start off by defining a class that inherits from MarshalByRefObject. After that we add code to the constructor of the class to write out a message to the console. Then we have a method named Hello that basically takes a string argument and appends that with the string and returns the concatenated value back to the caller. Once the remote object is created, the next step is to create a host application that hosts the remote object. For the purposes of this article, we will create a console application that reads the details of the remote object from its configuration file. using System; using System.Runtime.Remoting; namespace RemoteClassLibServer { class RemoteServer { [STAThread] static void Main(string[] args) { RemotingConfiguration.Configure( "RemoteClassLibServer.exe.config"); Console.WriteLine("Press return to Exit"); Console.ReadLine(); } } } In the main method, we just read the configuration settings from the configuration file using the RemotingConfiguration.Configure method and wait for the client applications to connect to it. The configuration file used by the above hosting application looks like the following. In the configuration file, we specify that we want to expose the remote object using the TCP channel by using the channel element. Marshalling The process of packing one or more items of data into a message {buffer}, prior to transmitting that message buffer over a communication channel. The packing process not only collects together values which may be stored in non-consecutive memory locations but also converts data of different types into a standard representation agreed with the recipient of the message. (2000-06-09)

5

Use Custom HTTP Handlers in Your ASP.NET Applications By Mark Strawmyer An HTTP handler is the endpoint that responds to requests made by an ASP.NET Web application. The ASP.NET requests are mapped to HTTP handlers based on the type of file extension used. Each handler processes either an individual URL or groups of URL extensions within an application. If you have built an ASP.NET Web application, then you've already taken advantage of HTTP handlers. ASP.NET offers a few default HTTP handlers: • • • •

Page Handler (.aspx) – Handles Web pages User Control Handler (.ascx) – Handles Web user control pages Web Service Handler (.asmx) – Handles Web service pages Trace Handler (trace.axd) – Handles trace functionality

As you can probably tell from the list, these handlers are pretty important to the normal operation of your ASP.NET Web applications. Without them, the Web pages wouldn't process, user controls wouldn't display, and your Web service calls wouldn't respond. This article explores the built-in ASP.NET HTTP handlers and the value they provide. It mainly demonstrates how to create a custom HTTP handler and explains why you may want to create one. The included examples are built in Visual Studio 2005 and Microsoft .NET 2.0.

Creating a Custom HTTP Handler You may choose to create a custom HTTP handler for any number of reasons. For instance, when you want special handling within your Web applications, you could add such handling through file name extensions assigned to custom HTTP handlers. Two other relatively common solutions for which you could create handlers are the following: • •

Dynamic image creator – Use the System.Drawing classes to draw and size your own images. RSS – Create a handler that responds with RSS-formatted XML. This would allow you to add RSS feed capabilities to your sites.

As with many other areas of .NET, you override interfaces to generate HTTP custom handlers. You implement the IHttpHandler interface to create a synchronous handler and the IHttpAsyncHandler interface to create an asynchronous handler. The interfaces require you to implement the ProcessRequest method and the IsReusable property. The ProcessRequest method handles the actual processing for requests made, while the Boolean IsReusable property specifies whether your handler can be pooled for reuse (to increase performance) or whether a new handler is required for each request. The .ashx file extension is reserved for custom handlers. If you create a custom handler with a file name extension of .ashx, it will automatically be registered within

6 IIS and ASP.NET. If you choose to use an alternate file extension, then you will have to register the extension within IIS and ASP.NET. The advantage of using an extension other than .ashx is that you can assign multiple file extensions to one handler.

Custom HTTP Handler Sample Code The following example demonstrates how to create and register a custom HTTP handler to generate dynamic pie chart images using Microsoft .NET 2.0. Since I'm all about reuse, the example reuses sample code from a prior article on "Creating Simple Charts and Graphs". It pulls in the code to have a custom HTTP handler generate an image containing a pie chart. Also, it uses the file extension .piechart to indicate that it produces a piechart. Following this example, you use the query string to convey the width, height, and points to plot. First, create a new 2.0-based Web project and then add a PieChartHandler class to the App_Code ASP.NET folder. (Note that ASP.NET 2.0 made HTTP handlers even easier than before. In prior ASP.NET versions, the App_Code ASP.NET folder didn't exist. Once you created an .ashx file, you couldn't have included it in your project or debugged it.) Use the following sample code for the PieChartHandler class: using using using using using

System; System.Drawing; System.Drawing.Imaging; System.IO; System.Web;

public class PieChartHandler : IHttpHandler { public void ProcessRequest (HttpContext context) { /* Start of code reuse */ context.Response.ContentType = "image/png"; // Read chart setup information string chartType = context.Request.QueryString["chartType"]; int height = Convert.ToInt32(context.Request.QueryString["height"]); int width = Convert.ToInt32(context.Request.QueryString["width"]); Bitmap StockBitMap; Color bgColor = Color.FromArgb(255, 253, 244); MemoryStream memStream = new MemoryStream(); switch (chartType) { default: // Determine the number of points given and read // the values int numPoints = 1; while (context.Request.QueryString["P" + numPoints.ToString()] != null) numPoints++; decimal[] vals = new Decimal[numPoints]; for (int i = 0; i < numPoints; i++) vals[i] = Convert.ToInt32( context.Request.QueryString["P" + i.ToString()]); PieChart pie = new PieChart(); StockBitMap = pie.Draw(bgColor, width, height, vals);

7 break; } // Render BitMap Stream Back To Client StockBitMap.Save(memStream, ImageFormat.Png); memStream.WriteTo(context.Response.OutputStream); /* End of code reuse */ } public bool IsReusable { get { return false; } } } /* Start of code reuse */ public class PieChart { public Bitmap Draw(Color bgColor, int width, int height, decimal[] vals) { // Create a new image and erase the background Bitmap bitmap = new Bitmap(width, height, PixelFormat.Format32bppArgb); Graphics graphics = Graphics.FromImage(bitmap); SolidBrush brush = new SolidBrush(bgColor); graphics.FillRectangle(brush, 0, 0, width, height); brush.Dispose(); // Create brushes for coloring the pie chart SolidBrush[] brushes = new SolidBrush[10]; brushes[0] = new SolidBrush(Color.Yellow); brushes[1] = new SolidBrush(Color.Green); brushes[2] = new SolidBrush(Color.Blue); brushes[3] = new SolidBrush(Color.Cyan); brushes[4] = new SolidBrush(Color.Magenta); brushes[5] = new SolidBrush(Color.Red); brushes[6] = new SolidBrush(Color.Black); brushes[7] = new SolidBrush(Color.Gray); brushes[8] = new SolidBrush(Color.Maroon); brushes[9] = new SolidBrush(Color.LightBlue); // Sum the inputs to get the total decimal total = 0.0m; foreach (decimal val in vals) total += val; // Draw the pie chart float start = 0.0f; float end = 0.0f; decimal current = 0.0m; for (int i = 0; i < vals.Length; i++) { current += vals[i]; start = end; end = (float)(current / total) * 360.0f; graphics.FillPie(brushes[i % 10], 0.0f, 0.0f, width, height, start, end - start); }

8 // Clean up the brush resources foreach (SolidBrush cleanBrush in brushes) cleanBrush.Dispose(); return bitmap; } /* End of code reuse */ }

Registering a custom handler that does not use the .ashx extension is fairly straightforward. As you may have guessed, you do it through a section of the web.config file by adding an httpHandlers element. An example registration might look like the following: <system.web>

Now run the project and then use the URL http://localhost:1096/SampleSite/foo.piechart?chartType=pie&width=200&height=2 00&P1=20&P2=15&P3=55&P4=82&P5=102&P6=6 to view the results (see Figure 1). Note the ":1096" portion of the URL. Visual Studio 2005 provides a Web server for debugging Web applications, so you don't need to have a Web server on your development machine anymore. That is the configuration this example uses, which results in ":1096" being added to the URL. It will differ depending upon your personal configuration.

Click here for a larger image. Figure 1: Sample Pie Chart Output

9

Now That You've Covered the Basics Now you've explored the basic HTTP handlers that are built in to ASP.NET, and you've seen how easy it is to generate a custom HTTP handler that generates an image containing a pie chart. An advanced HTTP handler solution to consider—possibly a future column if there's interest—would be using an HTTP handler factory through the IHttpHandlerFactory interface. This would allow you extremely granular control over the processing of a request by instantiating the desired handler based on runtime conditions.

what is te difference b/w IIS 5.0 and IIS 6.0 both are Servers from Microsoft used to execute asp and asp.net pages IIS 5 Version was bit weak when it comes to security and was just for Classic Asp,but IIS 6 Version has provision for Classic asp as well as ASP.NET IIS6 is realised by microsoft to make IIS Server more secute Polymorphism means same operation may behave differently on different classes. Eg: Method Overloading is an example of Compile Time Polymorphism. Method Overriding is an example of Run Time Polymorphism

What is the difference between Asp.net Session state and Asp Session state Session specific information is collectively known as session state in web application Difference btewn Asp seesion state and asp.net session state In ASP session state1.It maintains the session state in the same process that host asp,so if asp process fails the seesion state lost 2.Each asp web server maintains it's own session state , this creates problem in web farm scenario, where users request can be dynamically routed to diff server 3.asp doesn't work with the browser that do not support cookies or the browser where user has disable cookies. Session state in asp.net 1.asp.net allows you to save session state out-of-process, in state server or in database server 2.As asp.net stores session state out-of-process in database server, this is helpfull in web farm scenario where multiple computer can share one database server 3.asp.net supports cookie less session by storing the session id in the URL itself by changing application configurtion. Viewstate information is stored In HTML Hidden fields

How to invoke server side event from JavaScript? use document.Form1.submit(); to submit page using javascript

Using Clustered Indexes A clustered index determines the physical order of data in a table. A clustered index is analogous to a telephone directory, which arranges data by last name. Because the clustered index dictates the

10 physical storage order of the data in the table, a table can contain only one clustered index. However, the index can comprise multiple columns (a composite index), like the way a telephone directory is organized by last name and first name. A clustered index is particularly efficient on columns that are often searched for ranges of values. After the row with the first value is found using the clustered index, rows with subsequent indexed values are guaranteed to be physically adjacent. For example, if an application frequently executes a query to retrieve records between a range of dates, a clustered index can quickly locate the row containing the beginning date, and then retrieve all adjacent rows in the table until the last date is reached. This can help increase the performance of this type of query. Also, if there is a column(s) that is used frequently to sort the data retrieved from a table, it can be advantageous to cluster (physically sort) the table on that column(s) to save the cost of a sort each time the column(s) is queried. Clustered indexes are also efficient for finding a specific row when the indexed value is unique. For example, the fastest way to find a particular employee using the unique employee ID column emp_id is to create a clustered index or PRIMARY KEY constraint on the emp_id column. Note PRIMARY KEY constraints create clustered indexes automatically if no clustered index already exists on the table and a nonclustered index is not specified when you create the PRIMARY KEY constraint. Alternatively, a clustered index could be created on lname, fname (last name, first name), because employee records are often grouped and queried in this way rather than by employee ID. Considerations It is important to define the clustered index key with as few columns as possible. If a large clustered index key is defined, any nonclustered indexes that are defined on the same table will be significantly larger because the nonclustered index entries contain the clustering key. The Index Tuning Wizard does not return an error when saving an SQL script to a disk with insufficient available space. For more information about how nonclustered indexes are implemented in Microsoft® SQL Server™ 2000, see Nonclustered Indexes. The Index Tuning Wizard can consume significant CPU and memory resources during analysis. It is recommended that tuning should be performed against a test version of the production server rather than the production server. Additionally, the wizard should be run on a separate computer from the computer running SQL Server. The wizard cannot be used to select or create indexes and statistics in databases on SQL Server version 6.5 or earlier. Before creating clustered indexes, understand how your data will be accessed. Consider using a clustered index for:



Columns that contain a large number of distinct values.

11 •

Queries that return a range of values using operators such as BETWEEN, >, >=, <, and <=.



Columns that are accessed sequentially.



Queries that return large result sets.



Columns that are frequently accessed by queries involving join or GROUP BY clauses; typically these are foreign key columns. An index on the column(s) specified in the ORDER BY or GROUP BY clause eliminates the need for SQL Server to sort the data because the rows are already sorted. This improves query performance.



OLTP-type applications where very fast single row lookup is required, typically by means of the primary key. Create a clustered index on the primary key.

Clustered indexes are not a good choice for:



Columns that undergo frequent changes

This results in the entire row moving (because SQL Server must keep the data values of a row in physical order). This is an important consideration in high-volume transaction processing systems where data tends to be volatile.



Wide keys

The key values from the clustered index are used by all nonclustered indexes as lookup keys and therefore are stored in each nonclustered index leaf entry.

Nonclustered Indexes Nonclustered indexes have the same B-tree structure as clustered indexes, with two significant differences:



The data rows are not sorted and stored in order based on their nonclustered keys.



The leaf layer of a nonclustered index does not consist of the data pages.

Instead, the leaf nodes contain index rows. Each index row contains the nonclustered key value and one or more row locators that point to the data row (or rows if the index is not unique) having the key value. Nonclustered indexes can be defined on a table with a clustered index, a heap, or an indexed view. In Microsoft® SQL Server™ 2000, the row locators in nonclustered index rows have two forms:

12 •

If the table is a heap (does not have a clustered index), the row locator is a pointer to the row. The pointer is built from the file identifier (ID), page number, and number of the row on the page. The entire pointer is known as a Row ID.



If the table does have a clustered index, or the index is on an indexed view, the row locator is the clustered index key for the row. If the clustered index is not a unique index, SQL Server 2000 makes duplicate keys unique by adding an internally generated value. This value is not visible to users; it is used to make the key unique for use in nonclustered indexes. SQL Server retrieves the data row by searching the clustered index using the clustered index key stored in the leaf row of the nonclustered index.

Because nonclustered indexes store clustered index keys as their row locators, it is important to keep clustered index keys as small as possible. Do not choose large columns as the keys to clustered indexes if a table also has nonclustered indexes.

13

Related Documents

Net Remoting Vs Web Services
November 2019 17
Net Remoting
August 2019 40
.net Remoting
July 2019 34
.net Web Services
November 2019 19