Incandescent Blur

September 1, 2009

XMl in .Net

Filed under: C#, XML — admin @ 3:36 pm

In Many cases we may need to send information across services in XML form.
Some common practice is to create a class as a model and serialize it to XML after assigning values.

Or you can use from a variety of ways in which .Net support XML data, such as Xpath, xdocument, xpathnavigator yada, yada

And then there is Linq XML. namespace System.Linq.Xml;

With Linq to XMl, we can create Xml fragments easily.
The code below shows how to create an Xml fragment from a Dictionary.
assuming resultPair is a Dictionary with values.



XDocument doc = new XDocument(
new XElement("Results",
from myListItem in resultPair
select
new XElement("Pair",
new XElement("Key", myListItem.Key),
new XElement("Value", myListItem.Value)
)
)
);


Now You’ve seen the big chunk, lets break it down!

Now to break it down we can start with the XElement

XElement myVar = new XElement("elementName", "any xml data");

myVar will have the value of “<elementName>any xml data</elementName>”

likewise

XElement myVar = new XElement("elementName1",
new XElement("elementName2", "any xml data")
);

myVar will have the value of “<elementName1>
<elementName2>
any xml data
</elementName2>
</elementName1>”

I’ll Continue on this topic on my next blog.

August 28, 2009

Unit Testing with Cache

Filed under: Code Testing — admin @ 12:36 pm

One time I was working on a TEST-project for one of my web projects, I basically needed to test a UserControl. However, one of the function I need to test is referring to the HttpContext.Current.Cache. .

Running the test without a running web application will cause an error because HttpContext.Current.Cache is null.

So the solution was to create a sort of a dummy HttpContext.Current.

and heres how to do it.



TextWriter txtw = new StringWriter();
HttpWorkerRequest hwr= new SimpleWorkerRequest("/webapp", "c:\\inetpub\\wwwroot\\webapp\\", "default.aspx", "", txtw );
HttpContext.Current = new HttpContext(hwr);


after this HttpContext.Current.Cache is now accessible.

or even simpler



HttpContext.Current = new HttpContext(new HttpRequest(null, "http://tempuri.org", null), new HttpResponse(null));


However if you want to access HttpContext.Current.Session
then I suggest you check this Website for more options
Unit Test Web Code

You can also download the code files for simulating HTTP stuff. It Should be easy to find in the link above.

Powered by WordPress