Posts Tagged ‘Programming’

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!!

Advertisements

Watch in 720 or 1080 px (HD) and switch to full screen:youtube.com/watch?v=uTwLf28KzEg

Better version : esnips.com/doc/c96fca47-8149-4c02-b1de-4ac48a47ee99/RegEx_In_SQL_V2

Download the source code here:RegEx-In-SqlServer.zip

Node.js (nodejs.org) is an event-driven I/O server-side JavaScript environment based on V8. It is intended for writing scalable network programs such as web servers. It was created by Ryan Dahl in 2009, and its growth is sponsored by Joyent, which employs Dahl.

Wiki : en.wikipedia.org/wiki/Nodejs

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!!!!!