Code 39 Mod 43 barcode checkdigit function

Have to find the original code, the code is wrong.

    //pass in a string and returns string with check digit
    public string getCode39Mod43(string s)
    {
        int sum = 0;
        string temps = s.ToUpper();
        for (int i = 0; i < s.Length; i++)
        {
            sum += AsciiToCharTable(temps[i]);
        }

        int mod = sum % 43;
        return temps + CharTableToString(mod);
    }

    public int AsciiToCharTable(char c)
    {
        if (c == 48)//0
        {
            return 0;
        }
        else if (c == 49)//1
        {
            return 1;
        }
        else if (c == 50)//2
        {
            return 2;
        }
        else if (c == 51)//3
        {
            return 3;
        }
        else if (c == 52)//4
        {
            return 4;
        }
        else if (c == 53)//5
        {
            return 5;
        }
        else if (c == 54)//6
        {
            return 6;
        }
        else if (c == 55)//7
        {
            return 7;
        }
        else if (c == 56)//8
        {
            return 8;
        }
        else if (c == 57)//9
        {
            return 9;
        }
        else if (c == 65)//A
        {
            return 10;
        }
        else if (c == 66)//B
        {
            return 11;
        }
        else if (c == 67)//C
        {
            return 12;
        }
        else if (c == 68)//D
        {
            return 13;
        }
        else if (c == 69)//E
        {
            return 14;
        }
        else if (c == 70)//F
        {
            return 15;
        }
        else if (c == 71)//G
        {
            return 16;
        }
        else if (c == 72)//H
        {
            return 17;
        }
        else if (c == 73)//I
        {
            return 18;
        }
        else if (c == 74)//J
        {
            return 19;
        }
        else if (c == 75)//K
        {
            return 20;
        }
        else if (c == 76)//L
        {
            return 21;
        }
        else if (c == 77)//M
        {
            return 22;
        }
        else if (c == 78)//N
        {
            return 23;
        }
        else if (c == 79)//O
        {
            return 24;
        }
        else if (c == 80)//P
        {
            return 25;
        }
        else if (c == 81)//Q
        {
            return 26;
        }
        else if (c == 82)//R
        {
            return 27;
        }
        else if (c == 83)//S
        {
            return 28;
        }
        else if (c == 84)//T
        {
            return 29;
        }
        else if (c == 85)//U
        {
            return 30;
        }
        else if (c == 86)//V
        {
            return 31;
        }
        else if (c == 87)//W
        {
            return 32;
        }
        else if (c == 88)//X
        {
            return 33;
        }
        else if (c == 89)//Y
        {
            return 34;
        }
        else if (c == 90)//Z
        {
            return 35;
        }
        else if (c == 45)//-
        {
            return 36;
        }
        else if (c == 46)//.
        {
            return 37;
        }
        else if (c == 32)//sp
        {
            return 38;
        }
        else if (c == 36)//$
        {
            return 39;
        }
        else if (c == 47)///
        {
            return 40;
        }
        else if (c == 43)//+
        {
            return 41;
        }
        else if (c == 37)//%
        {
            return 42;
        }
        else
        {
            return 0;
        }
    }

    public string CharTableToString(int c)
    {
        if (c == 0)//0
        {
            return "0";
        }
        else if (c == 1)//1
        {
            return "1";
        }
        else if (c == 2)//2
        {
            return "2";
        }
        else if (c == 3)//3
        {
            return "3";
        }
        else if (c == 4)//4
        {
            return "4";
        }
        else if (c == 5)//5
        {
            return "5";
        }
        else if (c == 6)//6
        {
            return "6";
        }
        else if (c == 7)//7
        {
            return "7";
        }
        else if (c == 8)//8
        {
            return "8";
        }
        else if (c == 9)//9
        {
            return "9";
        }
        else if (c == 10)//A
        {
            return "A";
        }
        else if (c == 11)//B
        {
            return "B";
        }
        else if (c == 12)//C
        {
            return "C";
        }
        else if (c == 13)//D
        {
            return "D";
        }
        else if (c == 14)//E
        {
            return "E";
        }
        else if (c == 15)//F
        {
            return "F";
        }
        else if (c == 16)//G
        {
            return "G";
        }
        else if (c == 17)//H
        {
            return "H";
        }
        else if (c == 18)//I
        {
            return "I";
        }
        else if (c == 19)//J
        {
            return "J";
        }
        else if (c == 20)//K
        {
            return "K";
        }
        else if (c == 21)//L
        {
            return "L";
        }
        else if (c == 22)//M
        {
            return "M";
        }
        else if (c == 23)//N
        {
            return "N";
        }
        else if (c == 24)//O
        {
            return "O";
        }
        else if (c == 25)//P
        {
            return "P";
        }
        else if (c == 26)//Q
        {
            return "Q";
        }
        else if (c == 27)//R
        {
            return "R";
        }
        else if (c == 28)//S
        {
            return "S";
        }
        else if (c == 29)//T
        {
            return "T";
        }
        else if (c == 30)//U
        {
            return "U";
        }
        else if (c == 31)//V
        {
            return "V";
        }
        else if (c == 32)//W
        {
            return "W";
        }
        else if (c == 33)//X
        {
            return "X";
        }
        else if (c == 34)//Y
        {
            return "Y";
        }
        else if (c == 35)//Z
        {
            return "Z";
        }
        else if (c == 36)//-
        {
            return "-";
        }
        else if (c == 37)//.
        {
            return ".";
        }
        else if (c == 38)//sp
        {
            return " ";
        }
        else if (c == 39)//$
        {
            return "$";
        }
        else if (c == 40)///
        {
            return "/";
        }
        else if (c == 41)//+
        {
            return "+";
        }
        else if (c == 42)//%
        {
            return "%";
        }
        else
        {
            return "";
        }
    }
Advertisements
Posted in C#. Tags: . Leave a Comment »

Thread safe C# logging class using the Singleton Pattern

using System.Web;
using System.IO;
using System.Configuration;

namespace Logger
{
	/// <summary>
	/// Summary description for Logger.
	/// </summary>
	public class Logger
	{

		private static System.IO.StreamWriter _Output = null;
		private static Logger _Logger = null;
		private static Object _classLock = typeof(Logger);
		public static string _LogFile = "";
		public static int _LogLevel = 1;

		private Logger()
		{
				
		}

		public static Logger getInstance()
		{
			//lock object to make it thread safe
			lock(_classLock)
			{
				if(_Logger==null)
				{
					_Logger = new Logger();
				
				}	
			}
			return _Logger;
		}

		public static void logError(string s, int severity)
		{
			try
			{
				if(severity <=_LogLevel)
				{
					if (_Output==null)
					{
						_Output = new System.IO.StreamWriter(_LogFile, true, System.Text.UnicodeEncoding.Default);
					}
									
					_Output.WriteLine(System.DateTime.Now + " | " + severity +" | " + s,new object[0]);
									
					if (_Output != null)
					{
						_Output.Close();
						_Output = null;
					}
				}
			}
			catch(Exception ex)
			{
				Console.WriteLine(ex.Message,new object[0]);			
			}
		}

		public static void closeLog()
		{
			try
			{
				if (_Output != null)
				{
					_Output.Close();
					_Output = null;
				}
			}
			catch(Exception ex)
			{
				Console.WriteLine(ex.Message,new object[0]);
			}
		}
	}
}
Posted in C#. Tags: . 1 Comment »

Impersonation for data access with LogonUser

Using the example code from URL below and a little modification.

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/cpref/html/frlrfSystemSecurityPrincipalWindowsIdentityClassImpersonateTopic.asp

I made myself a class that would call LogonUser.
See below:


using System;
using System.Runtime.InteropServices;
using System.Security.Principal;
using System.Security.Permissions;

[assembly:SecurityPermissionAttribute(SecurityAction.RequestMinimum, UnmanagedCode=true)]
[assembly:PermissionSetAttribute(SecurityAction.RequestMinimum, Name = "FullTrust")]
namespace Impersonation
{

public class Impersonation
{
[DllImport("advapi32.dll", SetLastError=true)]
public static extern bool LogonUser(String lpszUsername, String lpszDomain, String lpszPassword,
int dwLogonType, int dwLogonProvider, ref IntPtr phToken);

[DllImport("kernel32.dll", CharSet=System.Runtime.InteropServices.CharSet.Auto)]
private unsafe static extern int FormatMessage(int dwFlags, ref IntPtr lpSource,
int dwMessageId, int dwLanguageId, ref String lpBuffer, int nSize, IntPtr *Arguments);

[DllImport("kernel32.dll", CharSet=CharSet.Auto)]
public extern static bool CloseHandle(IntPtr handle);

[DllImport("advapi32.dll", CharSet=CharSet.Auto, SetLastError=true)]
public extern static bool DuplicateToken(IntPtr ExistingTokenHandle,
int SECURITY_IMPERSONATION_LEVEL, ref IntPtr DuplicateTokenHandle);

// GetErrorMessage formats and returns an error message
// corresponding to the input errorCode.
public unsafe static string GetErrorMessage(int errorCode)
{
int FORMAT_MESSAGE_ALLOCATE_BUFFER = 0x00000100;
int FORMAT_MESSAGE_IGNORE_INSERTS = 0x00000200;
int FORMAT_MESSAGE_FROM_SYSTEM = 0x00001000;

int messageSize = 255;
String lpMsgBuf = "";
int dwFlags = FORMAT_MESSAGE_ALLOCATE_BUFFER FORMAT_MESSAGE_FROM_SYSTEM FORMAT_MESSAGE_IGNORE_INSERTS;

IntPtr ptrlpSource = IntPtr.Zero;
IntPtr prtArguments = IntPtr.Zero;

int retVal = FormatMessage(dwFlags, ref ptrlpSource, errorCode, 0, ref lpMsgBuf, messageSize, &amp;prtArguments);
if (0 == retVal)
{
throw new Exception("Failed to format message for error code " + errorCode + ". ");
}

return lpMsgBuf;
}

// Test harness.
// If you incorporate this code into a DLL, be sure to demand FullTrust.
[PermissionSetAttribute(SecurityAction.Demand, Name = "FullTrust")]
public void impersonateThis(string username, string password, string domainname)
{

IntPtr tokenHandle = new IntPtr(0);
IntPtr dupeTokenHandle = new IntPtr(0);
try
{
string userName, domainName;

domainName = domainname;

userName = username;

const int LOGON32_PROVIDER_DEFAULT = 0;
//This parameter causes LogonUser to create a primary token.
const int LOGON32_LOGON_INTERACTIVE = 2;
const int SecurityImpersonation = 2;

tokenHandle = IntPtr.Zero;
dupeTokenHandle = IntPtr.Zero;

bool returnValue = LogonUser(userName, domainName, password,
LOGON32_LOGON_INTERACTIVE, LOGON32_PROVIDER_DEFAULT,
ref tokenHandle);

if (false == returnValue)
{
int ret = Marshal.GetLastWin32Error();
Console.WriteLine("LogonUser failed with error code : {0}", ret);
Console.WriteLine("nError: [{0}] {1}n", ret, GetErrorMessage(ret));
int errorCode = 0x5; //ERROR_ACCESS_DENIED
throw new System.ComponentModel.Win32Exception(errorCode);
}

bool retVal = DuplicateToken(tokenHandle, SecurityImpersonation, ref dupeTokenHandle);
if (false == retVal)
{
CloseHandle(tokenHandle);
Console.WriteLine("Exception thrown in trying to duplicate token.");
return;
}

// The token that is passed to the following constructor must
// be a primary token in order to use it for impersonation.
WindowsIdentity newId = new WindowsIdentity(dupeTokenHandle);
WindowsImpersonationContext impersonatedUser = newId.Impersonate();

// Free the tokens.
if (tokenHandle != IntPtr.Zero)
CloseHandle(tokenHandle);
if (dupeTokenHandle != IntPtr.Zero)
CloseHandle(dupeTokenHandle);
}
catch(Exception ex)
{
}
finally
{
}
}
}
}

Once I had my class created I called the impersonateThis funtion when opening my connection inside my data access class.
See below:

public void openConnection(String connectionString)
{

try
{
Impersonation mi = new Impersonation();
mi.impersonateThis("user","password","domainname");

sqlConn = new SqlConnection(connectionString);
sqlConn.Open();

}
catch(Exception ex)
{
}
finally
{
}
}

The result of this is that when calling these classes from ASP.NET the code runs under aspnet account but when the openConnection function is called the impersonation kicks in and you are running under the impersonated account; which in my case happens to be a user setup in my SQL Server database and magic happens. When the code block is done and returns to the .aspx code behind page the impersonation is released and you are now running under the aspnet account again. To test this you can call WindowsIdentity.GetCurrent().Name to see what account you are running under when.

Posted in ASP.NET, C#. Tags: . Leave a Comment »