Saturday, December 10, 2011

XML Deserializer

XML Deserializing is great! Basically you can define any class structure, use the XML Deserializer to convert any XML to the object you defined, so long as the structures match, of course. This makes it way easy to parse XML. I just used it yesterday for the first time. Here's a great resource below:

http://msdn.microsoft.com/en-us/library/tz8csy73.aspx

In the msdn sample above, it uses an xml file, but if you want to read from an xml string, simply use the following syntax to populate your XmlReader object and the rest is the same:

XmlReader reader = XmlReader.Create(new System.IO.StringReader(xmlSTRING));

Thursday, December 8, 2011

Generic Handlers in .NET and AJAX

If you've ever come across an instance where you don't want to use UpdatePanels but you need some ajax functionality (i.e. you need to do ajax manually), generic handlers are the way to go. I could probably write an entire post on why UpdatePanels are not always a great idea but here is one alternative.

To start with, create a generic handler. This should be easy enough. In the ProcessRequest(HttpContext context) method, you want to grab your parameters from the context. Here's an example:

string url = context.Request.QueryString["url"];

Once you've done that, take your parameters, do whatever functionality you need, and the .ashx should return the value via context.Response.Write().

On the client side, use the following javascript to read the response:

function createXMLHttpRequest() {
try { return new XMLHttpRequest(); } catch(e) {}
try { return new ActiveXObject("Msxml2.XMLHTTP"); } catch (e) {}
try { return new ActiveXObject("Microsoft.XMLHTTP"); } catch (e) {}
alert("XMLHttpRequest not supported");
return null;
}

var xmlHttpReq= createXMLHttpRequest();
xmlHttpReq.open("GET", "your.ashx?v1=1&v2=2&etc", false);
xmlHttpReq.send(null);
var yourJSString = xmlHttpReq.responseText;

Then, take that response value and use JQuery or javascript to make whatever change you need on the front end. It's that simple! Now you are making AJAX calls from scratch, and you can feel like you know something.