2005 2006 2007 2008 2009 2010 2011 2015 2016 2017 2018 aspnet azure csharp debugging docker elasticsearch exceptions firefox javascriptajax linux llblgen mongodb powershell projects python security services silverlight training videos wcf wpf xag xhtmlcss

Reflecting Graph Video Demo

For those of your who have not installed Silverlight, below is a link to a video of the demo. As you will see it works perfectly in Firefox and IE.

Links

Reflecting Graph Silverlight Demo

In one of my Ajax applications I wanted a REALLY cool interface for some of my data modeling. I was a bit stuck until I heard that Microsoft published a beta of Silverlight 1.0 (an actually working one too!) This of course opened up an entirely new planet of new design possibilities.

The design that I came up with was a tree model where each element was a node in a mesh like structure where the user can move the elements as well as the entire structure in one smooth motion and where the user can zoom in and out with their mouse scroller... something that was incredibly simple to build in Silverlight.

To demonstrate what I built, I would like to use toned-down version of the same thing to show a simple type reflector with a Silverlight interface. In this demo, simply select an assembly and select a type. The type will show up as a graph with branches for reflected members, organized by methods, properties, and events.

The mechanics of this is actually really simple. First, define a few canvases so that an inner canvas can scale and translate to give the effect of a zoom and canvas movement. Second, have a method that accepts a JSON structure containing the model for your tree. In the iteration plot the ball element, the text as as well as a line that goes from itself to its parent. The trick in this step is to get the math right to know where exactly to plot the element. I'll discuss this in a bit. Lastly, watch for mousedown, mouseup, and mousemove events on the elements and the on canvas as well as mouse scrolling events on the canvas.

Placing the elements on the screen is really just basic geometry. We know that the first element can go anywhere and that its sole purpose is to set a positioning basis for all other elements. Plotting the children is just about as easy. For perfectly symmetrical elements, you just have to plot them at equal points from each other around a 360 degree radius. For mathematical details on this, see the essential mathematics page below.

Having symmetrical elements is all well and good, but it's ugly and nasty. [See image 1] So, to take it a bit further, I played with the angle a bit. If the element was the first child, I just plotted it normally via symmetry. If not, make the angle an increment of 45. This will just make the children the same length from each other regardless of how many there are. [See image 2] After this, I scaled down the separation of the elements by how many elements there were. [See image 3]

Next, I wanted to make sure the children were pointing in the same general direction their their parents pointed in. So I subtracted the angle of the parent (minus 90) to make it go in the same general area. Remember that all the elements are grouped together, so now we are moving groups of elements, not just a single element. [See image 4]

At this point it doesn't look too bad, but the child groups don't really line up with their parents. For them to line up I needed to add 45 degrees plus half the radius of the entire child set (another 45 degrees scaled by how many children there are). [See image 5]

Now we have something that looks like it it could grow nicely... however, it would be nice if it didn't look like a robot built it. To give it a more organic feel I added a random angle to every element. No, it's not the most sophisticated method for creating a more natural look, but it does work rather nicely. [See image 6]

As far as the events are concerned. If you get a mousedown on an element, you are in dragging mode and when you get a mousemove, adjust the element, text, and line accordingly. Silverlight will automatically redraw the line based on the new X, Y endpoint of the line. If you get a mouseup, then you are no longer in dragging mode and mousemove, doesn't do anything. If you get a mousedown that's on the canvas, then you simply need to adjust the translation of the canvas. If you get a mouse scroll simply, adjust the scaling of the canvas. It's extremely important to take the scaling into effect when you work with the moveable elements as the coordinate system completely shifts. In the provided demo, I added a few adjustments for this, but it could be much better it a live version.

As a closing note, this demo can also act as an example for an asymmetrical schema Ajax service. The service I wrote here accepts an XML message, but responds with JSON data. It's important to remember that the focus of communication is on receiving, not on transmission. If a person from France and a person from German want to have a conversation and each CAN speak the other's language, but understand their own flawlessly, the one from French may speak German so as to maximize communication and the person from German may speak French to the same end. So in this example, JavaScript speaks XML to .NET, which can easily deserialize it to a usable object and .NET speaks JSON back to JavaScript for easy direct use.

Related Materials

JavaScript Repeater Data Binding

In a previous post, I wrote about a way to convert JSON to XAML. The sample I provided with that post didn't really stop with a simple conversion example, but it also demonstrated how to create an use a simple JavaScript data binding repeater. It's just something I threw together in two minutes to bind an array of objects to a div to basically do in JavaScript/XHTML what ASP.NET does with the Repeater control. I think many people will be interested in this technique to see how they can bind data to a browser in a more efficient way.

As far as my requirements, I wanted this to be like ASP.NET in that the data is bound from a data source matching the fields in the data source objects to the data fields declared in this repeater and after all is said and done, the original declarative code should disappear. As far as the data source, I wanted it to be a series of the same type of object... kind of like a generic List.

So, to start off with, I simply declared the code that I wanted to write as the client. Some people call this the 'Sellsian' method (after Chris Sells at Microsoft), though I simply call it... common sense (as I honestly suspect Chris would too!). So, here is the declarative code I wanted to write for my data binding:

<div id="rptData">
    <h2>Title</h2>
    <div id="title" class="bind"></div>

    <h2>XAML Output </h2>
    <div id="output" class="bind"></div>
</div>

In this situation the data source fields are matched to element with the bind class and the element id. This is much like <%#Bind("") %> in ASP.NET.

On the other side, I would like my data source to be in JSON format and I would like to be able to bind in a way that 'feels' like a static class. Here is what I decided on:

var dataSource = [{
        title: 'Ellipse',
        output: Xaml.CreateXamlFromJSON(jsonElement1)
    }, {
        title: 'Rectangle',
        output: Xaml.CreateXamlFromJSON(jsonElement2)
    }, {
        title: 'Canvas',
        output: Xaml.CreateXamlFromJSON(jsonElement3)
    }
];

DataBinder.BindTextRepeater(D('rptData'), dataSource);

In the sample above you can see that I have a data source with 3 objects with the object being defined with the interface of a string field named 'title' and another string field named 'output'. Furthermore, I wanted to call the method what it is: a text repeater, not a fancy object repeater (though building that shouldn't be much more difficult), so my static method is called BindTextRepeater and accepts the declarative repeater object and the data source as parameters. In my examples I use the D('id') syntax where D is simply an alias for document.getElementById. I know some people use a dollar sign for that, but that just looks really weird to me.

Now onto the code. Here is the basic shell:

var DataBinder = {
    BindTextRepeater: function(obj, ds) {

    }
}

The first thing we do in this situation is look at the data source and see what the objects look like. For this we simply need to create an array to record what fields we are looking at and iterate through the object to record it's fields. Put another way... we simply need to do simple JavaScript reflection and record the object interface, something that's incredibly simple in JavaScript.

var fields = new Array( );
for(var f in ds[0]) { fields.push(f); }

Now that we know what the object looks like, let's iterate through the datasource and bind each field to it's proper place in the repeater. This is what the rest of the method does and it should be fairly self explanatory, except for the following things:

First, I said that data is bound to fields with the 'bind' class. What if you had your own class on it? That's not a problem. JavaScript classes are a bit like .NET interfaces (where as JavaScript ids are a bit like .NET classes), so you can "apply" (or implement in .NET) a few of them. So, if you wanted the apply the class "message-log" to the bindable element, you would simply have the following:

<div class="bind message-log"></div>

In this case this is possible because I'm simply checking to see if the class STARTS with "bind", rather than simply checking to see if it IS "bind":

if(obj.childNodes[e].id && obj.childNodes[e].className && obj.childNodes[e].className.substring(0, 4) == 'bind') {
    /* ... */
}

Second, if the element if found to be bindable, the method looks through the fields array to see if that element has data for in the specified data field. If so, it binds. If not... there's not much it can do (though ideally you would throw an exception). One thing to note about this is that it replicates the element and binds the text as a child. This is seen by the following line:

var bindableObj = obj.childNodes[e].cloneNode(false);

When you clone a node, you can say true, which means to clone it's children, or you can say false, which means to clone only that particular element. In this case, we don't need the children as this is a text repeater and we are going to put our own text as a child. If we were to say true, we would have to go out of our way to remove the children.

If the element is not found to be bindable, it copies the element and it's children as can be seen as the cloneNode(true).

Third, after the data object is ready you have a duplicate of the original repeater, but now filled with data from the data source. This data object is then bound to the browser's DOM as a element immediately before the repeater template. After all data objects have been bound, the original repeater is removed. Thus, you replaced the repeater template with data bound controls and you're done.

Here is the final implementation of the BindTextRepeater method:

var DataBinder = {
    BindTextRepeater: function(obj, ds) {
        var fields = new Array( );
        for(var f in ds[0]) { fields.push(f); }
        
        for(var r in ds) {
            var outputObj = DOM.createElement('div');

            if(ds[r]) {
                var d = ds[r]
                for(var e in obj.childNodes) {
                    if(obj.childNodes[e].nodeType && obj.childNodes[e].nodeType == 1) {
                        if(obj.childNodes[e].id && obj.childNodes[e].className && obj.childNodes[e].className.substring(0, 4) == 'bind') {
                            for(var i in fields) {
                                if(obj.childNodes[e].id == fields[i]) {
                                    var bindableObj = obj.childNodes[e].cloneNode(false);
                                    bindableObj.appendChild(DOM.createTextNode(d[fields[i]]));
                                    outputObj.appendChild(bindableObj);
                                }
                            }
                        }
                        else {
                            outputObj.appendChild(obj.childNodes[e].cloneNode(true));
                        }
                    }
                }
            }
            obj.parentNode.insertBefore(outputObj, obj);
        }

        obj.parentNode.removeChild(obj);
    }
};

Using this same approach of templating XHTML elements and reflecting JavaScript JSON data sources, you could actually create a full scale data binding solution for all your client-side data binding needs. Furthermore, since we used a JSON data source we can now bind data directly from JSON services accessed via Ajax techniques. Lastly, as I hope you can see, there wasn't really much magic in this example and absolutely no proprietary technology. It's simply a usage of what we already have and have had for many, many years.

Links

Converting JSON to XAML

For reasons beyond human comprehension, the world felt like making an huge deal about Microsoft "revealing" SilverLight even even though WPF/E has been known about for some time now and even though nothing technical has changed even in the slightest with the simple change of a name. Having said that... it will probably be an awesome technology and I'm sure I'll be marinating many of my future applications in it. Editing XAML in notepad is much more appealing to me than being forced to use the overpriced and overly complicated Flash.

As cool as that is, however, since most of the work I do involves pure Ajax/JavaScript clients with almost all .NET coding at the service level, I definitely find JSON (which IS a JavaScript object) easier to manage than XML (which CAN BE a JavaScript object). So, in one of my applications I have the service that provides graphical information to Silverlight in the form of JSON serialized XAML, which will then be converted into XAML.

Here is an example of something the service would provide:

var jsonElement1 = {
        'Ellipse': {
        'Canvas.Left': '130',
        'Canvas.Top': '130',
        Height: '200',
        Width: '200',
        Stroke: 'Red',
        StrokeThickness: '10',
        Fill: 'SlateBlue'
    }
};

No, it's not human readable like XML is, but it's what JavaScript loves to see and it's what my service creates. Also, no, this is done for for efficiently purposes. This doesn't lower the service "message" size in the slightest, but it does however help to keep a consistence programming model across all my service calls. Furthermore, given that the data was in a database and not in XAML on the server, there's no real overhead. If, however, the data was in XAML on the server it would be a sign of pure stupidity for me to convert that to JSON and then back to XAML.

The parsing for something like this is actually really simple: just iterate through the JSON objects and arrays and creating an XML tree from it. As a reminder or reference, with regard to XML in a web browser, Firefox uses document.implementation.createDocument for XML while IE uses the MSXML2.DOMDocument COM object. Furthermore, Firefox is more strict in its usage of XML than the more familiar COM model that IE uses.

Here is an example of what I mean:

var doc = null;
if(DOM.implementation && DOM.implementation.createDocument) {
    doc = DOM.implementation.createDocument('', '', null);
    Xaml.ScanJSONElements(doc, data, doc);


    var xmlSerializer = new XMLSerializer( );
    return xmlSerializer.serializeToString(doc);
}
else {
    doc = new ActiveXObject("MSXML2.DOMDocument");
    Xaml.ScanJSONElements(doc, data, doc);
    return doc.xml;
}

As you look through the Xaml.js file provided, you will also see that Firefox is very explicit about it's namespaces, while the COM model figured you will take care of them. There's nothing wrong with either approach, it's just something you will want to be aware of if you ever create XML in JavaScript.

Links

Object Range Selection and Emulating Word 2007's Formatting Box

Say you're working on a text driven web application and you want to get the selected text in order to see what was selected. With JavaScript that's easy enough, but what if you wanted to know what strongly-typed text was selected in order to recreate the selection later? This would come in tremendously handy if you want to have text annotation capabilities in your application. But, why stop there? If you are going to do that, why not add a nice pop-up window over your selection to give easy access to appropriate toolbox options? That's exactly what Word 2007 gives you and you can do the same in your JavaScript applications.

Implementing these two things involves the following tasks: assign each word (or letter if you want really fine grained control) a container span with an id and then watch for hovering over an object. When an object is hovered over, start a timer counter for the time of the hover. If hovering ends, reset the timer. When a specified amount of hover time has elapsed, see if they is a selection and if the object currently hovered over is in the selection. If so, show the toolbox. The first word and he last word selected are saved in the browser's Selection object as the 'anchorNode' and 'focusNode' objects of the selection, respectively.

Here's the meat:

// Get all spans and iterate through them making sure each REALLY exists and
// making sure each as an id.
var b = document.getElementsByTagName('span');
for(var a in b) {
    if(b[a] && b[a].id) {
    
        // Only use those with an id starting with 'wid'.
        if(b[a].id.substring(0, 3) == 'wid') {
        
            // Set the event that is called at each interval.
            b[a].timercall = function(evt){
            
                // It there is a saved object (see onmouseover event below), 
                // then continue...
                if(gHoverObject) {
                
                    // Increment counter.  When there are 4 timer intervals, 
                    // then get the object information and show the hover box.
                    hoverCounter++;
                    if(hoverCounter > 3) {
                    
                        // Get the text selection
                        var selection = window.getSelection( );
                        
                        // Does the selection contain the object the cursor is currently over?
                        // false means that the object the cursor is over must be fully selected.
                        // That is, half the word being selected won't cut it.
                        if(selection && selection.containsNode(gHoverObject, false)) {
                        
                            // Save the first object id selected and the last object id selected
                            toolboxObj.start = selection.anchorNode.parentNode.id;
                            toolboxObj.end = selection.focusNode.parentNode.id;
                            toolboxObj.style.display = 'block';
                            toolboxObj.style.left = parseInt(gHoverObject.x) + 'px';
                            toolboxObj.style.top = parseInt(gHoverObject.y) + 'px';
                        }
                    }
                }
            };

            b[a].onmouseover = function(evt) {
                // When the object is hovered over, save the object.
                gHoverObject = this;
                gHoverObject.x = evt.pageX;
                gHoverObject.y = evt.pageY;
                
                this.timer = setInterval(this.timercall, 150);
                hoverCounter = 0;
            };
            
            b[a].onmouseout = function(evt) {
                // Destroy the object so the algorithm doesn't run.
                gHoverObject = null;
                clearInterval(this.timer);
                hoverCounter = 0;
            };
        }
    }
}

The provided proof-of-concept demonstration also demonstrates how to setup regular text to be strongly typed. This is simply done by splitting the text by a space and putting each word into a span, then putting each span into a parent object and finally putting that parent object before the original text and deleting the original text. You can view all this happening and see the resulting structure using Firebug for Mozilla Firefox.

The proof-of-concept demonstration provided is for Mozilla Firefox only.  Internet Explorer does NOT have the abilities to do this.

Important Disclaimer: it's not my intention to teach anyone JavaScript. This information is not for someone to simply copy/paste into their own applications. A solid understanding of the DOM, JavaScript syntax and dynamics, and XHTML is required before any true application can be built. So, please do not ask me any "how do I..." questions. When I get those I merely explain the basics and tell the person to figure it out on their own. In other words, I won't do your homework for you.

Links

XmlHttp Service Interop - Part 2 (Utilizing WCF)

Today I'm publishing the second in an article series regarding XmlHttp Service Interop. In this article, entitled "Utilizing WCF", I explain how to build WCF services, how to trace their XML messages, and how to communicate with them and other SOAP services via raw XmlHttp.

Instead of posting the entire thing on my blog, from here on out I'm going to be posting articles in their own pages to make them easier to read and easier to access. This will also make it easier for me to update and edit as well. You may access this article as well as others in the series by the links below.

.NET Slides

Back in 2005 I taught a class where I gave an overview of various parts of the .NET universe (at the time, the WinFX universe). I covered everything from C# to data binding to ASP.NET to service-oriented architecture to web standards. My goal was to give a familiarization with each of the topics so that the students can then learn the topics on their own in a way that best fits them.

My first session, however, was a presentation experiment. Instead of using really nasty verbose slides, I had just a few words on a slide and on one slide I had simply the number 42. Don Box would have loved my presentation. The point of the experiment was to make sure that people were paying attention to the topic and not simply reading a useless slide. I really think that PowerPoint is a massive hindrance to education. You can access my experimental presentation, named .NET Overview, below.

My next to last session was on web standards and in this session I simply told a story and then gave a few examples showing how web standards development is the only web development that is acceptable. You can access this presentation, named Web Standards Presentation, below.

Below is also a link to a video where Don Box talks about giving great technical presentations. I would recommend this video to anyone who gives talks on really any topic. Don't just watch it, study it. It takes practice.

English Standard Version Bible Web Service via WCF

The WCF version of this died years ago. The new versions are at https://bitbucket.org/davidbetz/esv-bible-services-for-.net

Many of the applications that I create are Bible based applications and my designs are made easier thanks to the the English Standard Version of Scripture. Long before I used it for development, I fell in love with it and made it my primary Bible version, not only because it's an incredible Bible translation with incredible accuracy and amazing readability, but also because it's so widely accessible. Their website at http://www.gnpcb.org/esv/ is by far one of my favorite websites. I can read on my screen, adjusting the font-size on a whim or click on an audio link to listen to any chapter in a variety of formats. Furthermore, they have great Firefox support and great technical articles explaining the internals of the system.

Not only that, you can also access the ESV text through e-mail and through a SOAP interface. Being someone deeply involved with interop and someone who has commited myself to the study of Scripture I am overjoyed to have the ability to directly access the ESV Bible data source. That said, now adays I'm a WCF user and the ESV Bible Web Service interface has methods and properties which, when used in WCF, are very Java-ish. Not a problem... I went ahead and got the svcutil code and modified it a bit to make the proxy follow the .NET Framework Design Guidelines. I cleaned up the svcutil output, added XML comments, added an added enumeration class and then split into different files for easier modification. Feel free to take the classes and combine them back into one proxy file as you wish. Here is a sample application using the fixed proxy:

using (var client = new ESVBibleClient( )) {
    var options = new OutputOptions( );
    options.IncludeFootnotes = true;
    options.IncludeCopyright = true;
    options.OutputFormat = OutputFormat.PlainText;

    String text = client.DoPassageQuery("TEST", "1 John 2", options);

    Console.WriteLine(text);
    Console.ReadLine( );
}

XmlHttp Service Interop - Part 1 (Simple Service Creation)

This entry is the first is a series on XmlHttp Service Interop.

In my day job I am constantly making diverse systems communicate. I make classic ASP talk to the .NET 2.0 Framework, .NET systems talk with Java systems, a Pascal-based system communicate with a custom .NET mail server, and even make .NET components access systems from the stone age. I love interop, but I'm finding that many people don't. From what I see, it seems to be a lack of understanding more so than a lack of desire. It's actually some pretty cool stuff and you can find great books on various interop topics.

While I do work a lot with COM, ES, and web service interop, my favorite communication mechanism is via straight XmlHttp calls. It's just so easy to do and support for it is just about universal. You can take JavaScript and make a call to ASP.NET, go to a VBS WScript and make a call to a web service, or force the oldest, nastiest product in your company to communicate with WS-* services. In this part of the series, we are going to discuss XmlHttp in general and see a call from JavaScript to a manually created service endpoint.

To start off with lets make it clear what we are and are not talking about. We are not talking about sockets or direct TCP calls nor are we talking about a service framework. XmlHttp is a way to transfer XML over HTTP. However, even though we talk about XML, in your using XmlHttp you'll find that this isn't a requirement at all, so, at root what we are doing is making simple HTTP calls.

To see what we're talking about in action, lets create a simple XML service endpoint that accepts a well-defined XML format to allow the sending of e-mail. Then, lets access the service via JavaScript. This is very similar to something I recently created to allow a very old system to send e-mails using the .NET Framework. Of course, in that situation I used the programming language of the system in question (Pascal), not JavaScript.

To begin with lets create the client. I know it seems a bit backwards, but lets look at this from the standpoint of a framework designer: look at how it will be used first, then implement mechanics. Now, the first thing we need to do this is a simple "htm" document. I want the page to be "htm" for the sake of this demonstration, simply to show that there is no server-side processing at all in this page.

Next, we need a way to access our endpoint. I'm not going to get into severe detail about how to do this in every single browser in the world, but, rather, I'm only going to show the standardized way. You can quickly do a search online to see how to extent this behavior to IE5 and IE6.

Skipping the lame setup and stuff many 6th graders can do, let's get right to the core of what we are going to do. The full implementation of everything seen here is in an accompanying VS2005 solution. It would probably be a good idea to have that open as you go through this.

To send a request to a server, simply use syntax similar to the following:

var xmlhttp = new XMLHttpRequest( ); xmlhttp.open('POST', ' Service.aspx', true); xmlhttp.onreadystatechange = function ( ) { if(xmlhttp.readyState == 4) { alert(xmlhttp.responseText); } }; xmlhttp.send(data);

This syntax works in any version of Firefox, the newer versions of Opera, and IE7 (or what I like to call " IE6.5"). Basically, what's happening here is this: you are creating a new instance of an HTTP requestor, giving it some connection information, setting a callback function, and sending some data to the service.

The part that you should look at closely is the XMLHttpRequest::open (note: my double colon syntax is from C++ and simply means Class::Member)function. This obviously takes three parameters: the HTTP method, the HTTP endpoint, and a boolean stating asynchronous communication. I want this to be an asynchronous call, so I'm setting the third parameter to true. I'll come back to the HTTP method in a moment and the HTTP endpoint is just the service address.

After that we see that the property XMLHttpRequest::onreadystatechange is being assigned a JavaScript anonymous function. If you are unfamiliar with these, just think of them as anonymous delegates in C# 2.0. This is the function that's going to be called when the state of the XmlHttp call changed. When inside this function, there are a few parameters you can look at when this function gets calls, but here I'm only testing one: readyState. This property basically states the status of the call. Notice the XMLHttpRequest property is called "onreadystatechange", not "oncomplete". This function is actually called when the state of the HTTP request changes. When I test for readyState == 4 I'm looking for round trip completion. Frankly, you probably never touch the values 1, 2, and 3 though you could check for 0, which means that the XMLHttpRequest::open function has not yet been called. In this situation, if the readyState is 4, then I want to display a message box showing the response content, which is accessible via XMLHttpRequest::responseText. One other very important property you will definately be using a lot is the XMLHttpRequest::status. This property gives values like 404, 415, 500, and so on. If the request did a successful round trip the status will be 200, so that's something you'll probably be testing for quite a bit.

Finally we see the XMLHttpRequest::send method. This simply sends a set of data to the service... well, kind of. In the XMLHttpRequest::open, the first parameter, the HTTP method, is very important. Depending on what you want to do you will either set it to GET or POST. If you are calling a pre-existing page that has no idea what a HTTP stream is, but knows about querystrings, then you will want to use GET. In this situation, you will want to put parameters in the querystring in the HTTP end point, that is, in the second parameter of XMLHttpRequest::open. However, if you are creating your own service, you may want to use POST instead as using POST makes the development on both the client and service simplier. On the client, you don't pack stuff in the querystring (though you still could) and on the server, you can access the data via a stream rather than via parsing the URL or doing any iteration. As that last sentence implies, by using the POST method you send the data you want to submit to the HTTP endpoint as a parameter of the XMLHttpRequest::send function. For those of you who understand WCF terminology, you can think of the HTTP method as being analogous to the WCF binding and the HTTP endpoint as being analogous to the WCF address. The only thing analogous to the WCF contract is the XML schema you use to create your data stream.

Now, since we are sending the information in the data variable to the service, we need to put something in it. For this service, I'm using the following XML, though it doesn't have to be XML at all.

var data = ''; data += '<Mail>'; data += '<ToAddresses>'; data += '<ToAddress>johndoe@tempuri.org</ToAddress>'; data += '</ToAddresses>'; data += '<CcAddresses>'; data += '</CcAddresses>'; data += '<BccAddresses>'; data += '</BccAddresses>'; data += '<FromAddress>no-reply@tempuri.org</FromAddress>'; data += '<Subject>XmlHttp Service Interop - Part 1</Subject>'; data += '<DateTime>03-08-07 2:26PM'; data += '</DateTime>'; data += '<Body>This is the message body.</Body>'; data += '</Mail>';

Given proper event management in JavaScript, you have everything you need to have a fully functional client. Now onto the server.

As we saw when we looked at the client code, the service endpoint is Service.aspx . To help us focus on the task at hand, we aren't going to do anything fancy like using URL aliasing (aka URL rewriting) to make it look cooler, though in reality you would probably do that.

In the code behind for the Service.aspx, we have code that starts like this:

XmlDocument doc = new XmlDocument( ); doc.Load(Request.InputStream); XmlNode documentRoot = doc.DocumentElement; XmlNode mailRoot = documentRoot.SelectSingleNode("//Mail");

Here what we're doing is creating a new XmlDocument and loading the data streamed from the client into it. Then we are getting the root of the document via XPath. The rest of the code is in the accompanying project and simply consists of a bunch of XPath queries to get the information from the document.

After we found all the values we needed in the XML document, either via XPath or another mechanism, we can do whatever we want with what we found. The important point is this: all we have to do is a simple Response.Write ("") to send data sent back to the client, which in turn changes the readyState in the previously seen JavaScript to 4, thus allowing the client to display the output in the alert window. It's really just as simple as this: the client sends stuff to the service, the service does something and sends stuff back.

Now, we could beef this up a bit by adding some HTTP headers. This is something you may find yourself doing often. To do this, use XMLHttpRequest::setRequestHeader to set a key/value pair on the connection. Here's an example.

xmlhttp.setRequestHeader('X-App-Source', 'My Client');

That 'X-App-Source' was completely made up. You could use 'My Awesome Service Caller' if you wanted. That doesn't matter, what does matter however is that you put this after the call to XMLHttpRequest::open or else you will seriously want to throw something across the room, because it's a painfully subtle error that will cause the call will fail every time.

On the server side, to access a header, simply do this:

String xAppSource = Request.Headers["X-App-Source"];

I know. You were expecting something a bit more profound. Okay, I can satisfy that need. If you have many headers and you want them all, here's what you can do.

foreach (String header in Request.Headers) { // Do whatever you want... }

Whatever you do, try to fight the temptation to do this:

Dictionary<String, String> headers = new Dictionary<String, String>( );
foreach (String header in Request.Headers) {
    headers.Add(header, Request.Headers [header]);
}

As nice as that looks, if you really want to have a headers key/value pair collection, you can just do this:

NameValueCollection headers = Request.Headers;

Regardless of what you do with the headers, remember that they are there for a reason and if you do a lot of service calls, you will find yourself using HTTP headers a lot. This is something you will see in the next part of the series.

So, that's a quick overview of XmlHttp. Please see the solution provided with this post for the full code. The next part of the series discusses making manual XmlHttp calls to WCF.

Materials

Comments Fixed

A few weeks ago I started to flood my public blog with parts of the next CTP of Minima. Then I took a break for a week or so, but in my flooding I carelessly broke comments and didn't find out about it until today. Oops!

So, if you left a comment anywhere you'll have to resubmit the comment.

Sorry!