Posts Tagged ‘C#’

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];
else
{
XslCompiledTransform xslt = new XslCompiledTransform();
xslt.Load(transformationName);
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);

TransformationHelper.Transform(container);

outputXML = container.DestinationXML;
XElement.Parse(outputXML).Save(Server.MapPath(@”XML\output.xml”));

Response.Write(outputXML);

 

Download the complete source XML-XSLT-TransformationSample.zip

 

Cheers!!

Advertisements

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.

Logging asp.net

 

Logging.cs:

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

 

Web.config:

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

<configSections>

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

</configSections>

Now add the below section after the config sections:

<ErrorHandling>

<!–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”/>

</ErrorHandling>

 

Global.asax:

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)

{

GetData(123);

}

}

public void GetData(int userID)

{

try

{

//{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 :

Loggingadmin asp.net

 

Download the complete source here LoggingSample.zip

 

Cheers!!

Another useful feature of delegates is the ability to execute a method asynchronously. That is, through a delegate, you can begin invocation of a method and then return immediately while the delegate executes its method in a separate thread. Your page execution does not need to wait for that method to complete.

The following example demonstrates the use of delegates for asynchronous method invocation. To see this in action we need a method that simulates a lengthy operation, such as writing data to db logs, record page hits that can be asynchronous, and do not affect the end client response.

public delegate void LongTimeTask_Delegate(string s);

protected void Page_Load(object sender, System.EventArgs e)
{
if (!Page.IsPostBack)
{

// databind of all the controls

LongTimeTask_Delegate d = null;
d = new LongTimeTask_Delegate(LongTimeTask);

IAsyncResult R = null;
R = d.BeginInvoke(“TestString”, null, null); //invoking the method
}
}

In the above load event of the page after binding all the UI controls we need to perform a lengthy operation to record something in DB or any IO operation file.
We are initializing the deligate with the LongTimeTask method, and delegate.BeginInvoke will call the method below asynchronously. Later we will see how to know if the method invokation completed successfully or not.

public void LongTimeTask(string s)
{
// Write your time consuming task here
}

Now, if we would want to perform an another operation after the above method is completed, That is called callback approach, add the async call back event in beginInvoke:

//using callback approach
R = d.BeginInvoke(“TestString”, new AsyncCallback(TaskCompleted), null);

public void TaskCompleted(IAsyncResult R)
{
// Write here code to handle the completion of
// your asynchronous method
}
The above method will execute on completion of LongTimeTask method.

We can also wait untill the LongTimeTask is execution is completed or not, but then that will not serve the purpose of calling it asynchronously, but still you would need it somewhere:

//this will block until the asynchronous operation is complete
d.EndInvoke(R);

Try it out at your end, I have just given you the skeleton that I have tried, It works fine, but just be careful, as this works on a separate thread, which might sometimes consumes a lot of memory / CPU usage.

I was developing an application to post xml data to a URL (REST call) using asp.net 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 asp.net 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”));

try
{
myWriter = new StreamWriter(objRequest.GetRequestStream());
myWriter.Write(strPost);
}
catch (Exception e)
{
//
}
finally
{
myWriter.Close();
}

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

// Close and clean up the StreamReader
sr.Close();
}

return result;
}

In one of the module I came across to the situation where a physician needs to input their DEA number on a form and we have to validate the DEA Number, either using javascript or C#. I was provided with the algorithm from client and we had to write a javascript / c# function for the same. First I tried searching it on Google for some ready made stuff, but I could not found any, so written my own function to validate a DEA number. Here is the code snippet in both Javascript and C#:

C#
private bool DEAValidation(string DEANumber)
{
if (DEANumber != null && DEANumber != “” && DEANumber.Length == 9)
{
string strDEAFirstLetter = DEANumber.Substring(0, 1).ToUpper();
Response.Write(“strDEAFirstLetter: ” + strDEAFirstLetter);

if (strDEAFirstLetter != “A” && strDEAFirstLetter != “B” && strDEAFirstLetter != “M” && strDEAFirstLetter != “F”)
{
return false;
}

string strDEASecondLetter = DEANumber.Substring(1, 1).ToUpper();
string strValidChars = “ABCDEFGHIJKLMNOPQRSTUVWXYZ”;
string strValidNums = “0123456789”;
if (strValidChars.IndexOf(strDEASecondLetter) < 0 && strValidNums.IndexOf(strDEASecondLetter) < 0)
{
return false;
}

int iThirdDigit = int.Parse(DEANumber.Substring(2, 1));
int iForthDigit = int.Parse(DEANumber.Substring(3, 1));
int iFifthDigit = int.Parse(DEANumber.Substring(4, 1));
int iSixthDigit = int.Parse(DEANumber.Substring(5, 1));
int iSeventhDigit = int.Parse(DEANumber.Substring(6, 1));
int iEightDigit = int.Parse(DEANumber.Substring(7, 1));
int iNinthDigit = int.Parse(DEANumber.Substring(8, 1));

int Total_3_5_7 = iThirdDigit + iFifthDigit + iSeventhDigit;
int Total_4_6_8 = iForthDigit + iSixthDigit + iEightDigit;

int FinalTotal = Total_3_5_7 + (2 * Total_4_6_8);

Response.Write(“FinalTotal: ” + FinalTotal.ToString());

if (iNinthDigit.ToString() != FinalTotal.ToString().Substring(FinalTotal.ToString().Length – 1, 1))
{
return false;
}

return true;
}
else
{
return false;
}
}

Javascript:


function DEAValidation(DEANumber)
{
try
{
if (DEANumber != null && DEANumber != “” && DEANumber.length == 9)
{

var strDEAFirstLetter = DEANumber.substr(0, 1).toUpperCase();

if (strDEAFirstLetter != “A” && strDEAFirstLetter != “B” && strDEAFirstLetter != “M” && strDEAFirstLetter != “F”)
{
return false;
}

var strDEASecondLetter = DEANumber.substr(1, 1).toUpperCase();

var strValidChars = “ABCDEFGHIJKLMNOPQRSTUVWXYZ”;
var strValidNums = “0123456789”;

if (strValidChars.indexOf(strDEASecondLetter) < 0 && strValidNums.indexOf(strDEASecondLetter) < 0)
{
return false;
}

var iThirdDigit = parseInt(DEANumber.substr(2, 1));
var iForthDigit = parseInt(DEANumber.substr(3, 1));
var iFifthDigit = parseInt(DEANumber.substr(4, 1));
var iSixthDigit = parseInt(DEANumber.substr(5, 1));
var iSeventhDigit = parseInt(DEANumber.substr(6, 1));
var iEightDigit = parseInt(DEANumber.substr(7, 1));
var iNinthDigit = parseInt(DEANumber.substr(8, 1));

var Total_3_5_7 = iThirdDigit + iFifthDigit + iSeventhDigit;
var Total_4_6_8 = iForthDigit + iSixthDigit + iEightDigit;

var FinalTotal = Total_3_5_7 + (2 * Total_4_6_8);

if (iNinthDigit != FinalTotal.toString().substr(parseInt(FinalTotal.toString().length) – 1,1))
{
return false;
}

return true;

}
else
{
return false;
}
}
catch(err)
{
return false;
}
}

Ever got fed up with creating all the code behind parameters for your stored procedures? I have. So, I wrote this stored proc to generate the C# code for me. This has been written for use with “Microsoft Data Application Block” (SQLHelper.cs), however it could be hacked around to write the code without using the MDAB or even to write the code in VB. The script handles both input and output parameters, setting the size of text types, and you could even use it for direct access to a view or table.

Using the code

To implement, just copy the code into Query Analyzer and run. This will create a SPROC called “usp_getCode”.

To use, just execute the SPROC passing the name of the SPROC you want the code for (see below). Note: don’t include any owner prefix, e.g.: (dbo.).

EXEC usp_getCode ‘mySprocsNameHere’

The message window in the Query Analyzer will write out all the code required for your class or code behind. There is a variable in “usp_getCode” called “@connName” which you can set to the name of your connection instance. By default, it’s set to “conn.Connection” – just alter this for your own project’s naming convention.

The code

CREATE PROCEDURE usp_getCode
(
@objName nvarchar(100)
)
AS
/*
___________________________________________________________________
Name: CS SPROC Builder
Version: 1
Date: 07/30/2010
Author: Shabbir
Description: Call this stored procedue passing the name of your
database object that you wish to insert/update
from .NET (C#) and the code returns code to copy
and paste into your application. This version is
for use with “Microsoft Data Application Block”.

Version: 1.1
Date: 07/30/2010
Author: Shabbir
Description: a) Updated to include ‘UniqueIdentifier’ Data Type
b) Support for ‘ParameterDirection.Output’

*/
SET NOCOUNT ON
DECLARE @parameterCount int
DECLARE @errMsg varchar(100)
DECLARE @parameterAt varchar(1)
DECLARE @connName varchar(100)
DECLARE @outputValues varchar(100)
–Change the following variable to the name of your connection instance
SET @connName=’conn.Connection’
SET @parameterAt=”
SET @outputValues=”
SELECT
dbo.sysobjects.name AS ObjName,
dbo.sysobjects.xtype AS ObjType,
dbo.syscolumns.name AS ColName,
dbo.syscolumns.colorder AS ColOrder,
dbo.syscolumns.length AS ColLen,
dbo.syscolumns.colstat AS ColKey,
dbo.syscolumns.isoutparam AS ColIsOut,
dbo.systypes.xtype
INTO #t_obj
FROM
dbo.syscolumns INNER JOIN
dbo.sysobjects ON dbo.syscolumns.id = dbo.sysobjects.id INNER JOIN
dbo.systypes ON dbo.syscolumns.xtype = dbo.systypes.xtype
WHERE
(dbo.sysobjects.name = @objName)
AND
(dbo.systypes.status <> 1)
ORDER BY
dbo.sysobjects.name,
dbo.syscolumns.colorder

SET @parameterCount=(SELECT count(*) FROM #t_obj)
IF(@parameterCount<1) SET @errMsg=’No Parameters/Fields found for ‘ + @objName
IF(@errMsg is null)
BEGIN
PRINT ‘try’
PRINT ‘ {‘
PRINT ‘ SqlParameter[] paramsToStore = new SqlParameter[‘ + cast(@parameterCount as varchar) + ‘];’
PRINT ”

DECLARE @source_name nvarchar,@source_type varchar,
@col_name nvarchar(100),@col_order int,@col_type varchar(20),
@col_len int,@col_key int,@col_xtype int,@col_redef varchar(20), @col_isout tinyint

DECLARE cur CURSOR FOR
SELECT * FROM #t_obj
OPEN cur
— Perform the first fetch.
FETCH NEXT FROM cur INTO @source_name,@source_type,@col_name,@col_order,@col_len,@col_key,@col_isout,@col_xtype

if(@source_type=N’U’) SET @parameterAt=’@’
— Check @@FETCH_STATUS to see if there are any more rows to fetch.
WHILE @@FETCH_STATUS = 0
BEGIN
SET @col_redef=(SELECT CASE @col_xtype
WHEN 34 THEN ‘Image’
WHEN 35 THEN ‘Text’
WHEN 36 THEN ‘UniqueIdentifier’
WHEN 48 THEN ‘TinyInt’
WHEN 52 THEN ‘SmallInt’
WHEN 56 THEN ‘Int’
WHEN 58 THEN ‘SmallDateTime’
WHEN 59 THEN ‘Real’
WHEN 60 THEN ‘Money’
WHEN 61 THEN ‘DateTime’
WHEN 62 THEN ‘Float’
WHEN 99 THEN ‘NText’
WHEN 104 THEN ‘Bit’
WHEN 106 THEN ‘Decimal’
WHEN 122 THEN ‘SmallMoney’
WHEN 127 THEN ‘BigInt’
WHEN 165 THEN ‘VarBinary’
WHEN 167 THEN ‘VarChar’
WHEN 173 THEN ‘Binary’
WHEN 175 THEN ‘Char’
WHEN 231 THEN ‘NVarChar’
WHEN 239 THEN ‘NChar’
ELSE ‘!MISSING’
END AS C)

–Write out the parameter
PRINT ‘ paramsToStore[‘ + cast(@col_order-1 as varchar)
+ ‘] = new SqlParameter(“‘ + @parameterAt + @col_name
+ ‘”, SqlDbType.’ + @col_redef
+ ‘);’

–Write out the parameter direction it is output
IF(@col_isout=1)
BEGIN
PRINT ‘ paramsToStore[‘+ cast(@col_order-1 as varchar) +’].Direction=ParameterDirection.Output;’
SET @outputValues=@outputValues+’ ‘ +REPLACE(@col_name,’@’,”) +’=paramsToStore[‘+ cast(@col_order-1 as varchar) +’].Value;’
END
ELSE
BEGIN
–Write out the parameter value line
PRINT ‘ paramsToStore[‘+ cast(@col_order-1 as varchar) + ‘].Value = ‘+ REPLACE(@col_name,’@’,”) +’;’
END
–If the type is a string then output the size declaration
— IF(@col_xtype=231)OR(@col_xtype=167)OR(@col_xtype=175)OR(@col_xtype=99)OR(@col_xtype=35)
— BEGIN
— PRINT ‘ paramsToStore[‘ + cast(@col_order-1 as varchar) + ‘].Size=’ + cast(@col_len as varchar) + ‘;’
— END

— This is executed as long as the previous fetch succeeds.
FETCH NEXT FROM cur INTO @source_name,@source_type,@col_name,@col_order, @col_len,@col_key,@col_isout,@col_xtype
END
PRINT ”
PRINT ‘ SqlHelper.ExecuteNonQuery(‘ + @connName + ‘, CommandType.StoredProcedure,”‘ + @objName + ‘”, paramsToStore);’
PRINT @outputValues
PRINT ‘ }’
PRINT ‘catch(Exception excp)’
PRINT ‘ {‘
PRINT ‘ }’
PRINT ‘finally’
PRINT ‘ {‘
PRINT ‘ ‘ + @connName + ‘.Dispose();’
PRINT ‘ ‘ + @connName + ‘.Close();’
PRINT ‘ }’
CLOSE cur
DEALLOCATE cur
END
if(LEN(@errMsg)>0) PRINT @errMsg
DROP TABLE #t_obj
SET NOCOUNT ON

All you then have to do is copy-paste and fill in the values you want to pass and catch any exceptions… (Yes you do have to write some code!).

ENJOY……

Cheers!!!!!