Posts Tagged ‘’

XML is a universal format for data exchange, most of the data repository owners store their data in xml format, and apply XSLT to transform the XML from one format to another when required, I came across to a similar project, where we were storing everything in XML and then while processing the data we needed to display in other format.

Have written my own small transformation utility with extension object support.


Transform method:

/// <summary>
/// perform the XSLT transformation on the input xml and provides the transformed xml
/// </summary>
/// <param name=”transformation”>contains input xml, xslt path, and output xml</param>
public static void Transform(ITransformation transformation)
string sourceXML = transformation.SourceXML;
using (XmlReader reader = XmlReader.Create(new StringReader(sourceXML)))
//instead of initializing it with a new instance every time, get the transformation from the static cache.
//it will improve the load time of transformation object
XslCompiledTransform xslt = PrepareTransformationObject(transformation.XSLTName);

XsltArgumentList args = new XsltArgumentList();
//adding extension object, it will work as a helper method from XSLT
args.AddExtensionObject(“urn:Util”, new Util(transformation.XsltParameters));

StringWriter stringWriter = new StringWriter();
XmlTextWriter writer = new XmlTextWriter(stringWriter);

//applying tranform
xslt.Transform(reader, args, writer);

//set the output xml
transformation.DestinationXML = stringWriter.ToString();


This method stores the transformation object in static cache, so next time if you are using the same XSLT it will retrieve the object from cache instead of loading it again.

static Hashtable _xsltText = new Hashtable();

/// <summary>
/// Return the tranformation object, either create new or get from static cache if already available
/// </summary>
/// <param name=”transformationName”>full path of xslt</param>
/// <returns></returns>
static XslCompiledTransform PrepareTransformationObject(string transformationName)
if (_xsltText.ContainsKey(transformationName))
return (XslCompiledTransform)_xsltText[transformationName];
XslCompiledTransform xslt = new XslCompiledTransform();
if (!_xsltText.ContainsKey(transformationName))
//you can lock the object if you face the concurrency issues
//lock (lockObj)
_xsltText.Add(transformationName, xslt);
return xslt;


Example using the above methods:

string xsltName = Server.MapPath(@”XSLT\Sample.xslt”);
string inputXML = XElement.Load(Server.MapPath(@”XML\input.xml”)).ToString();
string outputXML = string.Empty;

//passing the current date as transformation date, you can pass any object and then access it in util class.
XsltParam xsltParam = new XsltParam();
xsltParam.Params.Add(“TransactionDate”, DateTime.Now.ToShortDateString());

//prepare the tranformation container
TransformationContainer container = new TransformationContainer(xsltName, inputXML, outputXML, xsltParam);


outputXML = container.DestinationXML;



Download the complete source




There are lots of error logging providers available such as Log4Net, AnLogger, etc. they are easy to use as well, but just to keep it simple, I have written my own. I call it “Activity and Error Logger”, it stores the data in xml format, request by request and session by session, you can actually create the user behaviour maps if you properly call the activity log at while performing any major operations. It also takes care of the concurrency, two threads will not overwrite each other. It logs the errors on page in try catch block and also at global level, in Application_Error event in global.asax

1)      Include the Logging.cs class in App_Code folder of your project

2)      Configure the web.config

3)      Set the Application_Error in global.asax

4)      Create the Logs_App and logs_Error folders in your project and you are done

5)      It creates one log file on hourly basis, one for Activities and one for Errors

6)      Now to log the activity or error, you just have to call the Logging.LogInfo or Logging. LogException functions in your code wherever required.




Include the Logging.cs class from the source code attached in this article



Add the below line in <configSections> if there is no configsections tag in your config, then create one right inside the <configuration> tag:


<section name=”ErrorHandling” type=”System.Configuration.DictionarySectionHandler”/>


Now add the below section after the config sections:


<!–set true to enable the logging–>

<add key=”EnableLogging” value=”true”/>

<!– path to log folders, DO create the folder in app directory –>

<add key=”ErrorLogFilesDir” value=”Logs_Error”/>

<add key=”AppLogFilesDir” value=”Logs_App”/>




Replace the Application_Error with the below code:

void Application_Error(object sender, EventArgs e)


// Code that runs when an unhandled error occurs

Logging.LogException(Server.GetLastError(), “Global Error”);



Default.aspx where the activity log and error log is implemented:

using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

using System.Web.UI;

using System.Web.UI.WebControls;

namespace LoggingSample


public partial class _Default : System.Web.UI.Page


protected void Page_Load(object sender, EventArgs e)


if (!IsPostBack)





public void GetData(int userID)




//{get data from database by passing userid}

////to check if it logs the error throw an argument exception

//throw new ArgumentException(“generated error”);

//on success Log the activity

Logging.LogInfo(“Get successful for userid : ” + userID.ToString(), true);


catch (Exception ex)


//on error log the exception

Logging.LogException(ex, “Error in data bind”);






I have also made the admin part of the application, to create a report of activity logs, it applies the xslt on the activity log files and display them in a grid, you can extend it to create one for error log files too :



Download the complete source here



I was developing an application to post xml data to a URL (REST call) using and C#. The endpoint was hosted with a third party vendor and they had a much secured hosting environment. Their endpoints were https and they installed and generated the private client certificate (a password protected .p12 file) on their servers to prevent unwanted requests / hits.

So to access their endpoints one has to have that client certificate, basically any request to the endpoints should have the client certificate enclosed with the request data, even if you are requesting it from browser window you have to have that certificate installed in your browser.

To resolve the same first I installed that certificate on my development server, then I could able to request that URL from browser window. But when I did the same using my C# code using httpwebrequest object I got 403 forbidden error as the request was not sending the client certificate with xml data.

Ideally, if you have any .cer file you can add it with request object by using X509Certificate class but in case of private client certificate it just doesn’t work for that you have to use X509Certificate2 class, Here is the code snippet. You need to place the .p12 file in your webserver’s hard drive.

public string PostData(string DataToPost,string URL)
String result = “”;
String strPost = “RequestXML=” + DataToPost;
StreamWriter myWriter = null;

HttpWebRequest objRequest = (HttpWebRequest)WebRequest.Create(URL);
objRequest.Method = “POST“;
objRequest.ContentLength = strPost.Length;
objRequest.ContentType = “application/x-www-form-urlencoded”;

objRequest.ClientCertificates.Add(new X509Certificate2(@“E:\Certificate\clientcertificate.p12”, “password”));

myWriter = new StreamWriter(objRequest.GetRequestStream());
catch (Exception e)

HttpWebResponse objResponse = HttpWebResponse)objRequest.GetResponse();
using (StreamReader sr =
new StreamReader(objResponse.GetResponseStream()))
result = sr.ReadToEnd();

// Close and clean up the StreamReader

return result;