Distributed Computing


It s a term that covers a whole bundle of technologies. So here s a section to match: a whole mound of secrets dedicated to the world of distributed computing. From the quick guide to using MSMQ, to the cheat s guide to XML, to the five steps to transactions with COM+, and more!

The Cheat s Guide to XML

They write entire books on it. They hold conferences dedicated to it. I know at least three caf s named after it. It s XML, it s eXtensible Markup Language, it s an excellent addition to your r sum

But just what is it, really? XML is a method of storing structured data in a pure text format. It uses a system of tags to embed its information, such as a list of customers and their orders. And, as an XML document is simply one chunk of text (no matter how in depth or complex the information it holds or the relationships among the individual chunks of information), it is still simply text, making XML an ideal cross-platform data storage mechanism.

TOP TIP  

You can learn more about the official XML specification by checking out documents from the World Wide Web Consortium at www.w3.org/XML/ .

To demonstrate this concept, here s a sample, relatively simple XML document:

 <?xml version="1.0"?>  <articles>      <article id="10">      <site>VB World</site>      <type>codesnippet</type>      <title>The Cheat's Guide to XML</title>      <shortname>xmlcheat</shortname>      <description>Need to learn XML fast? .e.t.c. </description>      <author>Karl Moore</author>      <authorEmail>karl@karlmoore.com</authorEmail>      <pages>      <page number="1">      <title>Introduction</title>      <body>Yadda ... yadda ... yadda ...</body>      </page>      <page number="2">      <title>Getting More Complicated</title>      <body>Etc ... etc ... etc ... </body>      </page>      </pages>      </article>      <article id="11">      <site>VB Square</site>      <type>review</type>      <title>Review of WebZinc .NET</title>      <shortname>webzinc</shortname>      ... and so on ..      </article>  </articles> 

Here, you can see we have a top-level < articles > tag, containing numerous < article > items. Each item contains an associated unique id attribute, plus numerous subelements that list details such as the site, author name , and a related < pages > segment, listing individual pages and the body text. See how it works? Articles, to article, to pages, to page. It s relational data, stored in a pure text format.

TOP TIP  

One simple way to demonstrate the relational style of XML document is to add an XML file (Project Add New Item) to your Visual Studio .NET project, type in something similar to the preceding XML, then click on Data. You ll be shown your data in grid format ”ready for viewing, editing, or adding to!

So, you pretty much understand what an XML document is: it looks a bit like HTML, stores relational data in tags, plus it s pure text so it can be used cross-platform. What can you use it for? Imagine it as the new, cooler , slightly younger brother of the comma-separated or tab-delimited file format. Anything they can do, XML can do better.

How can you integrate XML with your VB .NET applications? Well, there are five key techniques:

  • Create a Web service to expose data from your application. (See Chapter 4, The Lowdown on Web Services.)

  • Read an XML document in code.

  • Write an XML document in code.

  • Use XML with your DataSets.

  • Use XML with SQL Server.

The rest of this tip provides working examples of these last four techniques.

Reading an XML Document in Code

The XmlDocument class in the System.Xml namespace provides everything you need to parse XML data. To use, simply create a new instance of the class, use the .Load or .LoadXml method to get data into the object, then start parsing using the available methods and functions.

Such techniques are typically best demonstrated through sample code ”so here s a snippet that uses a common method of cycling through various nodes in the XmlDocument object, retrieving key pieces of information. It s based on the sample XML document shown earlier, and, with a little cross-referencing, should be relatively easy to follow through:

 ' Create new XmlDocument object  Dim objDoc As New System.Xml.XmlDocument()  ' Load actual XML  objDoc.Load("c:\filename.xml")  ' Create placeholders for node list and individual nodes  Dim objNodeList As System.Xml.XmlNodeList  Dim objNode, objNodeChild As System.Xml.XmlNode  ' Retrieve list of article elements  objNodeList = objDoc.GetElementsByTagName("article")  ' Cycle through all article elements  For Each objNode In objNodeList      ' Display article ID numbers      MessageBox.Show(objNode.Attributes("id").InnerText)      ' Cycle through all child node of article      For Each objNodeChild In objNode          ' Display article site names          If objNodeChild.Name = "site" Then              MessageBox.Show(objNodeChild.InnerText)          End If      Next  Next 

After a little reviewing, you can see this is really pretty simple, and this recursive-style code can be easily ported to practically any situation. No matter whether you re handling an XML file created by another application or parsing an XML stream straight from the Net (for example, www.slashdog.org/slashdot.xml ), the XmlDocument object can help you out.

TOP TIP  

When loading an XML document, you may want to check its structure, ensuring that it adheres to the expected . You do this through an XML schema. We don t cover this here, but you can learn more by looking up XML, validating XML in the help index.

Writing an XML Document in Code

The XmlTextWriter class in the System.Xml namespace can be jolly useful when it comes to outputting XML. To use it, create a new instance of the class, passing a new filename or an appropriate stream in the constructor, plus a potential encoding option.

Next, start your document with the .WriteStartDocument method and continue using others, such as .WriteStartElement , .WriteAttributeString , WriteElementString , and .WriteEndElement to create the document. When you re finished, .WriteEndDocument to close all open tags, .Flush to save changes to the file, then .Close .

This is another beast best explained by example, so here goes:

 ' Create a new XmlTextWriter object  Dim objWriter As New System.Xml.XmlTextWriter(_      "c:\mydocument.xml", System.Text.Encoding.UTF8)  With objWriter      ' Set the formatting to use neat indentations      .Formatting = Xml.Formatting.Indented      ' Write document opening      .WriteStartDocument()      ' Begin core XML      .WriteStartElement("articles")      ' First article...      .WriteStartElement("article")      .WriteAttributeString("id", "10")      .WriteElementString("site", "VB-World")      .WriteElementString("type", "codesnippet")      .WriteElementString("author", "Karl Moore")      ' Write list of associated pages      .WriteStartElement("pages")      .WriteStartElement("page")      .WriteAttributeString("number", "1")      .WriteElementString("title", "My Title")      .WriteElementString("body", "This is my body text")      .WriteEndElement()      .WriteStartElement("page")      .WriteAttributeString("number", "2")      .WriteElementString("title", "My Second Title")      .WriteElementString("body", "This is my 2nd body text")      ' Close open elements      .WriteEndElement()      .WriteEndElement()      .WriteEndElement()      .WriteEndElement()      ' ... Add any further articles here ...      ' Close document      .WriteEndDocument()      .Flush()      .Close()  End With 

Simple enough? It s a very straightforward procedural method of creating an XML file that should suit all XML developers. (See Figure 7-14 for the results of this sample, displayed in Internet Explorer.)

click to expand
Figure 7-14: Our produced XML document, viewed in Internet Explorer

But why not simply build your own XML string and write it straight to a file? Three reasons. First, there are situations in which extra XML tags need to be added to adhere to the official specification. For example, you may be storing HTML in one of your elements. HTML, of course, contains < tags > that may be misinterpreted as actual XML elements. As such, the XmlTextWriter follows the official specification and adds CDATA clauses to the statement, ensuring that any readers correctly identify this as text, not actually part of the document structure. So, firstly, it s a bit more intelligent than a quick file-write routine.

Second, it s very good at automatically handling developer cock-ups, which means, if you have any tag that you ve forgotten to close correctly, the XmlTextWriter will automatically step in and fill the gap for you. How kind.

And third ”well, it can save data in that pretty indented manner. Personally, I d prefer not to attempt implementing this with just a regular string. Way too messy.

That s it: the XmlTextWriter . Simple, elegant, procedural. An understated class that could save you hours.

Using XML and DataSets

DataSets were covered back in Chapter 4 (Working with Data). They re basically multitable Recordsets with a few extra frills ”and one of those frills is their ability to both accept and output XML with ease.

But how? You need to know about three key DataSet members .

First, there s .GetXml . This excellent function returns an XML representation of the data in your DataSet. It s simple to use and returns a string containing data from all the tables in your DataSet. For example:

 <MyDataSet xmlns="http://www.karlmoore.com/MyDataSetSchema.xsd">    <wc_vbwn_article_listing>      <id>5</id>      <tag>bettersplit</tag>      <siteListingid>1</siteListingid>      <type>3</type>      <userLevel>3</userLevel>      <title>VB: A Better Split Function</title>      <description>When using the Split function ...</description>      <authorCommunityListingid>3</authorCommunityListingid>      <added>2002-10-20T13:38:00.0000000+01:00</added>          <live>true</live>  </wc_vbwn_article_listing>    </MyDataSet> 

The second useful member is the .WriteXml method, which accepts a stream or filename and essentially writes the results of .GetXml directly to it. It saves you writing a separate file-save routine and automatically applies all the fancy indenting, too.

Well, we ve had two methods of getting XML out of the DataSet, so now here s our third handy DataSet member ”the .ReadXml function, which loads XML into the DataSet. You can use this function with practically any XML source, but I d recommend sticking to either a simple XML stream, or one that you ve previously extracted from the DataSet or have an XSD schema for. It s not required; it s simply a recommendation from experience: complex XML structures aren t as easily manipulated through a DataSet.

TOP TIP  

If you re creating a DataSet and want to read straight from an XML file, you may want to first specify an XML schema definition (XSD) so you can catch any data errors. To do this, simply use the schema equivalents of the members we ve covered here ” . GetXmlSchema , . WriteXmlSchema , and .ReadXmlSchema ”passing your XSD filename as appropriate. If you don t have an XML schema, you can create one manually in VS .NET (Project Add New Item XML Schema), or allow it to generate one for you by creating a typed DataSet. See the Quick, Editable Grid tips in Chapter 4 (Working with Data) for a demonstration of generating this XSD template. If you re completely confused and have no idea what an XML schema is, imagine it as a rulebook for the data in your XML document. Look up XML Schema, about XML Schema for more information.

The Three Words to SQL Server XML Success

Three simple words: For XML Auto . Adding these to the end of your SQL statement will result in SQL Server 2000 (and above) returning an XML representation of your data, rather than your regular table of information.

For example, a statement such as SELECT username, password FROM users FOR XML AUTO may return something like this:

 ... <users username="KarlMoore" password="TEST123"/>      <users username="SuzanneVega" password="MARLENA123"/> ... 

How can you extract and use this data? My favorite method is simply extracting the XML from the first returned field using .ExecuteScalar , then slapping it straight into an XmlDocument object. After that, I can do what I like ”save it, edit it, XSL it, whatever:

 ' Setup Command  Dim objCommand As New System.Data.SqlClient.SqlCommand(_      "SELECT field1, field2, field3, field4 " & _      "FROM table1 FOR XML AUTO", _      MyConnection)  ' Retrieve XML  Dim strXML As String = _      objCommand.ExecuteScalar  ' Load data into XmlDocument, adding root level <data> tags  Dim objDoc As New System.Xml.XmlDocument()  objDoc.LoadXml("<data>" & strXML & "</data>")  '   continue as appropriate   

The SqlCommand object actually provides its own method ” .ExecuteXmlReader ” specifically for handling XML data coming back from SQL Server. This function returns an XmlReader object, a sort of forward-only, read-only version of the XmlDocument . Here, I cycle through a few entries, then close the reader:

 ' Setup Command  Dim objCommand As New System.Data.SqlClient.SqlCommand(_      "SELECT field1, field2, field3, field4 " & _      "FROM table1 FOR XML AUTO", _      SqlConnection1)  ' Retrieve XMLReader object  Dim objReader As System.Xml.XmlReader = _      objCommand.ExecuteXmlReader  ' Loop round entries  Do While objReader.Read      MessageBox.Show(objReader.GetAttribute("field3"))  Loop  ' Close XMLReader, freeing up connection  objReader.Close 

Personally, I don t like working with the XMLReader like this ”it s relatively inflexible and ties up your connection until you close the object ”but it has certain niche uses, so is listed here for completeness.

Quick XML Review

XML is an interesting topic. Although a lot of unwarranted industry hype surrounds what is still simply a chunk of HTML-like text, there s no denying that that chunk of text is still a great idea and one that won t be fading away anytime soon.

Here, in this rather elongated tip, we ve covered the basics of working with XML. There s still much more you might want to learn, however. You may wish to take a further look at more-complex schemas and really understand how they can help you validate your XML, for example. (Look up XML Schemas, ADO. NET datasets and and XML Schemas, creating in the help index to assist in solidifying these concepts.)

Or you may wish to explore the whole bundle of extra classes in the System.Xml namespace we haven t covered here (the XmlValidatingReader class, for example) or check out the extra XML-related features of SQL Server (the XMLDATA parameter, for instance).

And that s not all. There s also the world of XSL (Extensible Style Sheet Language). You can imagine this almost like a mail merge document for your XML. It contains HTML and various XSLT (XSL Transformation) elements, and tells it how to process your XML: put this there, change that to this, cycle through these elements and display them here. It s practically a mini programming language on its own. Find out more for yourself by following a VS .NET walkthrough; look up XSL, identity transformation in the help index.

Not everyone will use XML, and fewer still will go all the way with schemas and XSL, so we re going to end this tip here. But remember: XML is a growing standard and beginning to infiltrate all areas of development. So, whether you think it concerns you or not, it might be worthwhile giving XML a peek. You might just surprise yourself.

Further reading: check out www.apress.com for the latest XML titles.

Six Steps to Basic Transactions with COM+

It took me a good few weeks to get my head around the world of transactions in .NET. I spent an absolute age trying to figure out what had happened to Microsoft Transaction Server (MTS).

If you re in the same boat, I m sorry to inform you that MTS died some time ago. It was merged into a host of services christened COM+ (We didn t communicate that very well, a Microsoft publicist told me) and is now incorporated in classes under the System.EnterpriseServices namespace. It s all done very differently from the days of yesteryear, too: transactional components in .NET require no complicated configuration nor manual registration. Transactions can be set up and performed entirely in code.

TOP TIP  

Many developers used MTS for the database connection pooling it offered . If that s all you re wanting, good news: in .NET, all the SqlConnection objects used on a machine are automatically pooled for you, regardless of whether you re using COM+ (the new MTS). Look up connection pooling, ADO. NET connections in the help index for more information.

ANOTHER TOP TIP  

If you re looking to implement transactions and are only using one database on one machine, you probably don t need the power nor overhead of COM+ transactions. Check out the SQL Server transaction sample in the Essentials section of Chapter 4 for more information.

But let s start at the beginning. What exactly is a transaction? A transaction is an operation that must be undertaken as a whole, or not at all. The age-old example of a bank still stands: if your application takes money out of one account to deposit in another, and your machine crashes halfway through, you really don t want to lose that money. You either need to do it all or nothing. If an error occurs during any part of that process, the whole thing needs to be undone.

That s what COM+ enables you to do: implement a stable, time- tested undo mechanism in your code, easily. It can automatically roll back your edits in any transaction-aware application, such as SQL Server or Microsoft Message Queue ” even if the edits are made on different machines. On the other hand, if all goes well, all edits (no matter which machine they are made upon) are committed.

How can you put all this into play? Well, you need to start with a class that inherits the ServicedComponent class, the base functionality of any transaction. You can then add attributes to your class and its methods, depending on how you want to implement your transaction. You can also work with a ContextUtil object, to commit or abort the transaction.

TOP TIP  

Looking for a walkthrough guide to creating your first transaction? Surf to the MSDN article at http://support.microsoft.com/default.aspx?scid=kb;en-us;Q315707 for a simple Northwind database sample project.

Six core steps are involved in setting up an automatically registering COM+ transactional class. Simply open your project ”Windows application, class library, or other ”and follow this to-do list:

  1. Reference the System.EnterpriseServices DLL . Click on Project Add Reference, select System.EnterpriseServices , then click on OK.

  2. Create your core transaction-aware class . Click on Project Add New Item, and select Transactional Component. Enter a name, click on Open, and then alter the TransactionOption.Supported value to TransactionOption.Required . Alternatively, click on Project Add Class and use the following neater base for your work.

     ' Automatic transaction template  Imports System.EnterpriseServices  <Transaction(TransactionOption.Required)> _      Public Class ClassName      Inherits ServicedComponent  End Class 
    TOP TIP  

    Here, we have the Transaction attribute set with the value TransactionOption.Required , the most common setting. This means that, if you are already inside a transaction and call a member of this class, it runs its code and informs the parent transaction how the operation went (and, if it failed, will likely rollback the results of parent transactions, a sort of code domino effect). On the other hand, if you are not in a transaction, this option will create one for you. Other possible options here are Disabled, NotSupported , RequriesNew , and Supported .

  3. Add your transaction-aware methods and functions . If you want to take advantage of automatic committing, which ˜saves all changes if no error occurs, or performs a rollback if an exception does occur, then use code similar to the following:

     <AutoComplete()> Public Sub MemberName()      ' Do processing here, such as accessing      ' a transaction-aware database.      ' If exception occurs, transaction fails.  End Sub 
  4. Use ContextUtil if you wish to control transactions manually. Instead of relying on an exception to be caught, you may wish to control the whole transaction manually. You do this using the ContextUtil object, with code similar to the following:

     Public Sub MemberName()      ' Do processing here, maybe with error handling      ' When youre satisfied all has worked, run...      ContextUtil.SetComplete()      ' If, however you have experienced problems or caught      ' an exception, roll everything back by running...      ContextUtil.SetAbort()  End Sub 
  5. Generate a strong name for your application . To take part in a transaction, COM+ requires your application to have a strong name. This is a random public/private key, merged with your application name, version number, and culture information (if available). To generate the strong name key pair, click on Programs Microsoft Visual Studio .NET Visual Studio .NET Tools Visual Studio .NET Command Prompt. From the DOS-style window, type sn k c:\mykeyname.snk and press Return. You should get a Key pair written success message. Open the directory (in this case, the root of the c: drive) to check the file is there ”this is your random public/private key pair file. Next, add the following line to AssemblyInfo.vb, telling the application which key pair to utilize for the strong name (for simplicity, we re using a hard coded reference to the path here; using a relative path appears to behave inconsistently between certain VS .NET builds):

     <Assembly: AssemblyKeyFileAttribute("c:\mykeyname.snk")> 
    TOP TIP  

    If you plan to use your transactional component outside of the .NET world, you ll need to do three things at this point: provide your assembly with a title in the AssemblyInfo.vb file (used for the COM+ Catalog), manually expose your .NET assembly to COM (see exposing .NET Framework components to COM), and register your component in the COM+ Catalog (see automatic transactions, .NET Framework classes , step four).

  6. Start using your transactional component! If you ve developed an internal class, simply call it directly from within your application. Or if you ve created the class inside a Class Library project, compile your assembly and then reference from another application.

And that s all there is to implementing basic cross-machine transactions in your applications. Don t get me wrong: COM+ supports many, many more features, such as object and thread pooling, nested transactions, remoting, true MSMQ integration, special security mechanisms, and more. But these simple steps at least provide a handy reference to the base method of handling transactions across multiple machines, our method of ensuring it all happens together... or not at all.

For further reading, check out Distributed .NET Programming in VB.NET from Apress (ISBN 1-59059-068-6).

TOP TIP  

You can view your COM+ transactional components by clicking on Programs Administrative Tools Component Services, and then navigating down to Component Services Computers My Computer COM+ Applications. (See Figure 7-15.) Here, you should be able to view your automatically registered transactional component, plus see any transactions in progress. (Look out for those exciting animated icons!)

click to expand
Figure 7-15: Viewing our transactional components in Component Services
ANOTHER TOP TIP  

By simply running our application like this, our COM+ transactional component is automatically registered for us the first time it is used. This isn t a bad thing, but you should be aware of a few things about it. First, your transactional component is registered as a library component, meaning you can t view success/failure statistics via the Distributed Transaction Coordinator. (In Component Services, navigate to My Computer Distributed Transaction Coordinator). You can change this manually through your application properties (in Component Services, navigate to My Computer COM+ Applications, view properties for your app, select Activation tab) ”or look up COM+ services, registering serviced components in the help index for more information. Second, if you change the type of your transaction component (that is, from RequiresNew to Supported), you ll need to reregister your assembly (see the preceding help topic), or alter the COM+ application properties. COM+ does not automatically comprehend that you ve changed the transaction attribute. Third, due to a number of interoperability issues, Windows XP and 2000 machines will not show the animated Component Services icon when a library component is involved in a transaction. It s not a huge issue, but certainly one worry to cross off your list of debugging concerns.

Quick Guide to Using MSMQ

Download supporting files at www.apress.com .

The files for this tip are in the Ch7 ”MSMQ Sample folder.

Microsoft Message Queue (MSMQ) is one of those widgets a lot of developers have heard about, but few really feel confident playing with. It s a tool for the big boys, or so many will have you believe, and not a technology that those working in companies turning over less than ten billion a year should be using.

This, as you may suspect, is balderdash.

But, just in case you haven t heard of MSMQ, let s start at the beginning. What exactly is it? MSMQ is a product now integrated into Windows 2000 and 2003. It allows your applications to send messages and for other applications to pick up those messages. The message may be sent to applications on the same computer, or on a different computer. The other computer doesn t even have to be online when the message is sent; it will be automatically delivered when a connection is made.

In other words, MSMQ is email for your code.

Here s how it works. To send a message, you set up a MessageQueue object, specifying a queue path. (If you re playing along with the email analogy, imagine this as the mail address.) You check whether the queue path exists: if not, you create it. Next, you simply send your message. It ll then wait in your analogical Outbox and send itself to that queue when possible (say, immediately, or the next time you connect to the network).

So that s how you send a message. But how about receiving one?

To receive a message, your application needs to tune in to your queue path and turn up the volume. When your application notices that a message has been received, your MessageQueue object fires off an event for you to respond to. You may look at the message and confirm payment on a customer order, add a comment to the user profile, or update existing stock levels. Your message doesn t just have to be pure text either: you can serialize objects and send those as well.

Let s look at how we can implement MSMQ technology in our applications in six easy steps:

  1. Check that Microsoft Message Queue is installed . It s likely you ve already got MSMQ on your machine, but, just in case, open up the control panel and go to Add/Remove Programs. Click on the Add/Remove Windows Components button and ensure that Message Queuing is checked. If not, check it and follow through the wizard. If you re using Windows NT 4, download the option pack from www.microsoft.com/NTServer/nts/downloads/recommended/NT4OptPk/ and select to install Microsoft Message Queue Server 1.0.

  2. Reference System.Messaging.dll . With your project open, click on Project Add Reference and select the System.Messaging.dll, then click on OK.

  3. Add a MessageQueue object to your class. Drag and drop the MessageQueue item from the Components tab on the toolbox onto your form or class in Design mode.

  4. Change the Path property. Alter the Path property to the queue you wish to use. This is a combination of the machine name and the queue (mailbox) name. On my machine, for example, I m using nemean\private$\testapp as my Path property. Nemean is the name of the other computer on the network, testapp is the name of my queue, and the private$ bit in the middle indicates that this is a private queue. (Public queues are also available, and these work in exactly the same way, but are published throughout the network, unlike private queues. They also require that your administrator first set up a special MSMQ network. A sample queue Path for a public queue might be nemean\testapp .)

    TOP TIP  

    You can browse the existing queues, either on your local machines or machines on your network, by clicking on View Server Explorer, then navigating to a machine and viewing the Message Queues node. (See Figure 7-16.)

    click to expand
    Figure 7-16: Viewing available queues through the Server Explorer

  5. In your client application, add the code to send your message. The following chunk of sample code demonstrates checking for the existing of a queue, creating it if it isn t available, and then sending a message. The message is split into two parts : the body and a label (the equivalent of an email subject line), as shown here:

     ' Check for existence of queue  If MessageQueue1.Exists(MessageQueue1.Path) = False Then     MessageQueue1.Create(MessageQueue1.Path)  End If  ' Send message - body and "label"  MessageQueue1.Send(_     "ConfirmOrderTotal: .95", _     "Customer:952") 
  6. In your server application, add code to receive your message. First, you ll need to tune in by running the .BeginReceive function of your MessageQueue object. You may do this when your application starts, say, in response to the form Load event:

     ' Run this at the beginning to  ' "listen" for new messages  MessageQueue1.BeginReceive() 

When a message drops in, the ReceiveCompleted event of the MessageQueue object kicks in, passing with it a handle to the message. You then use this to receive the whole message, process it, then once again begin listening for any new messages. Here s sample code to do just that, to be used in response to the ReceiveCompleted event:

 ' Receive message  Dim objMsg As System.Messaging.Message = _      MessageQueue1.EndReceive(e.AsyncResult)  ' Process the message - ' here, we're simply showing it to the user  MessageBox.Show(objMsg.Label & " - " & objMsg.Body)  ' Begin "listening" again  MessageQueue1.BeginReceive() 

That s it: this is literally all you need to do to send and receive messages in your application. These, of course, are just the facts. To bring them to life in the real world, you need to add imagination . Which applications would benefit from being able to communicate through messages? How can this technology help those with laptops, those who are often on the road and offline for most of the day? Where in your company is there a need to perhaps serialize and queue up Customer , Order , or Stock objects, waiting to be processed ? And that is where you come in.

For further reading, check out www.apress.com for the latest MSMQ titles.

TOP TIP  

There s more to be discovered in the world of MSMQ. To learn more about serializing objects so they can be sent through MSMQ, look up serializing messages in the help index. To peek at messages without actually removing the message from the original queue, look up peeking at messages in the help index. To find out about receiving a delivery acknowledgment for a message you sent, look up message queues, acknowledging delivery to in the help index.

Which to Choose: Web Services vs. Remoting

Web services and remoting are both methods of getting computers to communicate and share data with each other. Both techniques can work through IIS, both can pass data through firewalls, both can use HTTP for communication, and both can use SOAP-compliant data formatting. But, ever since Microsoft dropped the curtains on the .NET Framework, developers have been asking, Erm, so what s the difference between the two?

It s a good question ”and one that few Microsoft support engineers enjoy answering. However, there is a difference, and this tip will reveal all.

Web services are part of ASP.NET and hosted in IIS. With Web services, you can expose stateless functions to the world, which are typically called through HTTP and a SOAP XML-based response automatically returned.

Remoting is a technology that allows .NET applications to talk to each other, instantiating classes running on another machine. Remoting is more flexible than Web services, but it doesn t necessarily conform to any open standard. It can be thought of as the most flexible replacement for DCOM and requires a program running on the target machine as the server.

Yes, there s some overlap between the two technologies, but the decision over which to choose is relatively simple.

Do you need to expose your data to the outside world using open standards? Do you need to utilize caching easily? Are your clients working on a non-.NET platform? Do you need any of the special IIS features, such as security and logging? Are you unable to run a remoting server program on the target machine? If you answered yes to any of these questions, then you need to use Web services. Check out Chapter 5 for more information. Sample Web services include an online telephone directory or a product query service.

Do you need to use stateful objects in your development work? Do you require the use of properties and events? Do you need to use the raw binary TCP socket for faster communication? Do you need a custom server host for your program? Are 100% of your clients going to be .NET applications? Would you prefer not to use IIS, but rather peer-to-peer communication? If you answered yes to any of these questions, then you need to use .NET remoting. Try looking up remoting communication in the help index to learn more. Sample uses for .NET remoting include a proprietary instant messaging application or the excellent Terrarium project (www.gotdotnet.com/terrarium/).

If, however, you re somewhat indifferent to all of these questions, go for Web services. They re easier to get started with and, seasoned with a few custom hacks, can be expanded upon to do most things.

So there we have it: Web services are easy, they re for open standards, they re for SOAP and IIS. Remoting is for .NET-to-.NET applications, it s for complex objects, it s for speed and customization. They are different, but they do overlap. That s just the way it is.

For further reading, check out Distributed .NET Programming in VB.NET from Apress (ISBN 1-59059-068-6).




The Ultimate VB .NET and ASP.NET Code Book
The Ultimate VB .NET and ASP.NET Code Book
ISBN: 1590591062
EAN: 2147483647
Year: 2003
Pages: 76
Authors: Karl Moore

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net