#region " Copyleft "
// Copyright (C) 2000, 2003, 2004, 2005, 2007 Clive Chinery
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
#endregion
#region " Usings "
using System;
using System.Data;
using System.Data.SqlClient;
using System.Globalization;
using System.IO;
using System.Text;
using System.Xml;
#endregion
namespace CommonCS
{
/// <summary>
/// Common Data functions
/// </summary>
public sealed partial class CommonData
{
#region " Constants "
/// <summary>
/// With the GetBaseDirectory it should not be neccessary to rename this file as it
/// can be located with application.
/// </summary>
private static string CONFIG_FILE = "CONFIG.XML";
/// <summary>
/// Hold name of module
/// </summary>
private static string MODULE_NAME = "CommonData.cs";
#endregion
#region " Calc Functions "
/// <summary>
/// Calculate Percentage from Decimal Values
/// </summary>
/// <param name="decExpression1">Numerator value</param>
/// <param name="decExpression2">Divisor value</param>
/// <returns></returns>
public static decimal CalcPercent(decimal decExpression1, decimal decExpression2)
{
if (decExpression2 == 0)
return 0;
else
return ((100 * decExpression1) / decExpression2);
}
/// <summary>
/// Calculate Percentage from Integer Values
/// </summary>
/// <param name="iExpression1">Numerator value</param>
/// <param name="iExpression2">Divisor value</param>
/// <returns></returns>
public static int CalcPercent(int iExpression1, int iExpression2)
{
if (iExpression2 == 0)
return 0;
else
return ((100 * iExpression1) / iExpression2);
}
#endregion
#region " Decimal Functions "
/// <summary>
/// Adjust decimal value to a (sanitized) number of decimal places
/// </summary>
/// <param name="decIN">Decimal value</param>
/// <param name="iPlaces">Number of decimal places</param>
/// <returns>Adjusted value</returns>
public static decimal DecimalAdjust(decimal decIN, int iPlaces)
{
if (iPlaces < 0) iPlaces = 0;
if (iPlaces > 28) iPlaces = 28;
return decimal.Round(decIN, iPlaces);
}
#endregion
#region " Filter constants "
private const string FILTER_NUMERIC = "0123456789";
private const string FILTER_DECIMAL = FILTER_NUMERIC + "-.";
private const string FILTER_INTEGER = FILTER_NUMERIC + "-";
private const string FILTER_LOWER = "abcdefghijklmnopqrstuvwxyz";
private const string FILTER_POSTCODE = "ABCDEFGHIJKLMNOPQRSTUVWXYZ 0123456789";
private const string FILTER_UPPER = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
private const string FILTER_TELEPHONE = FILTER_LOWER + FILTER_INTEGER + " +()";
private const string FILTER_TIME = FILTER_NUMERIC + ":";
private const string FILTER_ALPHA = FILTER_LOWER + FILTER_UPPER;
private const string FILTER_ALPHANUMERIC = FILTER_ALPHA + FILTER_NUMERIC;
private const string FILTER_GENERAL_TEXT = FILTER_ALPHANUMERIC + " :/\\()-=+\n";
#endregion
#region " Filter Functions (see notes with FilterGeneralText) "
#region " FilterAlpha "
/// <summary>
/// Filter Alpha (upper + lower case) Values
/// </summary>
/// <param name="sIn">Input to filter</param>
/// <returns>Filtered string</returns>
public static string FilterAlpha(string sIn)
{
bool bDataDropped = false;
return FilterWorker(sIn, FILTER_ALPHA, ref bDataDropped);
}
/// <summary>
/// Filter Alpha (upper + lower case) Values
/// </summary>
/// <param name="sIn">Input to filter</param>
/// <param name="bDataDropped">Set true if data is dropped</param>
/// <returns>Filtered string</returns>
public static string FilterAlpha(string sIn, ref bool bDataDropped)
{
return FilterWorker(sIn, FILTER_ALPHA, ref bDataDropped);
}
#endregion
#region " FilterAlphaNumeric "
/// <summary>
/// Filter AlphaNumeric (upper + lower + integer case) Values
/// </summary>
/// <param name="sIn">Input to filter</param>
/// <returns>Filtered string</returns>
public static string FilterAlphaNumeric(string sIn)
{
bool bDataDropped = false;
return FilterWorker(sIn, FILTER_ALPHANUMERIC, ref bDataDropped);
}
/// <summary>
/// Filter AlphaNumeric (upper + lower + integer case) Values
/// </summary>
/// <param name="sIn">Input to filter</param>
/// <param name="bDataDropped">Set true if data is dropped</param>
/// <returns>Filtered string</returns>
public static string FilterAlphaNumeric(string sIn, ref bool bDataDropped)
{
return FilterWorker(sIn, FILTER_ALPHANUMERIC, ref bDataDropped);
}
#endregion
#region " FilterDecimal "
/// <summary>
/// Filter Decimal Values
/// </summary>
/// <param name="sIn">Input to filter</param>
/// <returns>Filtered string</returns>
public static string FilterDecimal(string sIn)
{
bool bDataDropped = false;
return FilterWorker(sIn, FILTER_DECIMAL, ref bDataDropped);
}
/// <summary>
/// Filter Decimal Values
/// </summary>
/// <param name="sIn">Input to filter</param>
/// <param name="bDataDropped">Set true if data is dropped</param>
/// <returns>Filtered string</returns>
public static string FilterDecimal(string sIn, ref bool bDataDropped)
{
return FilterWorker(sIn, FILTER_DECIMAL, ref bDataDropped);
}
#endregion
#region " FilterGeneralText (plus notes on usage) "
/// <summary>
/// Filter general text
/// </summary>
/// <param name="sIn">Input to filter</param>
/// <returns>Filtered string</returns>
/// <remarks>These filter functions are built upon the premise: "All input is evil".
/// These functions filter input to a range of permitted values controlled by
/// appropriate constants. By defining the allowed values within string constants
/// the allowed values can readily be changed.
/// Input is usually from a textbox but could also be an argument from the query string.
/// When working with non-english languages the General Text will need to be rewritten
/// on an exclude basis.
/// The filter functions filter on a permitted values basis - Thus FilterDecimal
/// would pass the second decimal point in "1.22.2".
/// </remarks>
public static string FilterGeneralText(string sIn)
{
bool bDataDropped = false;
return FilterWorker(sIn, FILTER_GENERAL_TEXT, ref bDataDropped);
}
/// <summary>
/// Filter general text
/// </summary>
/// <param name="sIn">Input to filter</param>
/// <param name="bDataDropped">Set true if data is dropped</param>
/// <returns>Filtered string</returns>
public static string FilterGeneralText(string sIn, ref bool bDataDropped)
{
return FilterWorker(sIn, FILTER_GENERAL_TEXT, ref bDataDropped);
}
#endregion
#region " FilterInteger "
/// <summary>
/// Filter Integer Values
/// </summary>
/// <param name="sIn">Input to filter</param>
/// <returns>Filtered string</returns>
public static string FilterInteger(string sIn)
{
bool bDataDropped = false;
return FilterWorker(sIn, FILTER_INTEGER, ref bDataDropped);
}
/// <summary>
/// Filter Integer Values
/// </summary>
/// <param name="sIn">Input to filter</param>
/// <param name="bDataDropped">Set true if data is dropped</param>
/// <returns>Filtered string</returns>
public static string FilterInteger(string sIn, ref bool bDataDropped)
{
return FilterWorker(sIn, FILTER_INTEGER, ref bDataDropped);
}
#endregion
#region " FilterLowerCase "
/// <summary>
/// Filter lower case
/// </summary>
/// <param name="sIn">Input to filter</param>
/// <returns>Filtered string</returns>
public static string FilterLowerCase(string sIn)
{
bool bDataDropped = false;
return FilterWorker(sIn, FILTER_LOWER, ref bDataDropped);
}
/// <summary>
/// Filter lower case
/// </summary>
/// <param name="sIn">Input to filter</param>
/// <param name="bDataDropped">Set true if data is dropped</param>
/// <returns>Filtered string</returns>
public static string FilterLowerCase(string sIn, ref bool bDataDropped)
{
return FilterWorker(sIn, FILTER_LOWER, ref bDataDropped);
}
#endregion
#region " FilterPostcode "
/// <summary>
/// Filter Postcode (text forced to upper case)
/// </summary>
/// <param name="sIn">Input to filter</param>
/// <returns>Filtered string</returns>
public static string FilterPostcode(string sIn)
{
bool bDataDropped = false;
return FilterWorker(sIn.ToUpper(), FILTER_POSTCODE, ref bDataDropped);
}
/// <summary>
/// Filter Postcode (text forced to upper case)
/// </summary>
/// <param name="sIn">Input to filter</param>
/// <param name="bDataDropped">Set true if data is dropped</param>
/// <returns>Filtered string</returns>
public static string FilterPostcode(string sIn, ref bool bDataDropped)
{
return FilterWorker(sIn.ToUpper(), FILTER_POSTCODE, ref bDataDropped);
}
#endregion
#region " FilterTelephone "
/// <summary>
/// Filter Telephone (text forced tolower case)
/// </summary>
/// <param name="sIn">Input to filter</param>
/// <returns>Filtered string</returns>
public static string FilterTelephone(string sIn)
{
bool bDataDropped = false;
return FilterWorker(sIn.ToLower(), FILTER_TELEPHONE, ref bDataDropped);
}
/// <summary>
/// Filter Telephone (text forced tolower case)
/// </summary>
/// <param name="sIn">Input to filter</param>
/// <param name="bDataDropped">Set true if data is dropped</param>
/// <returns>Filtered string</returns>
public static string FilterTelephone(string sIn, ref bool bDataDropped)
{
return FilterWorker(sIn.ToLower(), FILTER_TELEPHONE, ref bDataDropped);
}
#endregion
#region " FilterTime "
/// <summary>
/// FilterTime (00:00 or 00:00:00 format)
/// </summary>
/// <param name="sIn">Input to filter</param>
/// <returns>Filtered string</returns>
public static string FilterTime(string sIn)
{
bool bDataDropped = false;
return FilterWorker(sIn, FILTER_TIME, ref bDataDropped);
}
/// <summary>
/// FilterTime (00:00 or 00:00:00 format)
/// </summary>
/// <param name="sIn">Input to filter</param>
/// <param name="bDataDropped">Set true if data is dropped</param>
/// <returns>Filtered string</returns>
public static string FilterTime(string sIn, ref bool bDataDropped)
{
return FilterWorker(sIn, FILTER_TIME, ref bDataDropped);
}
#endregion
#region " FilterUpperCase "
/// <summary>
/// Filter upper case
/// </summary>
/// <param name="sIn">Input to filter</param>
/// <returns>Filtered string</returns>
public static string FilterUpperCase(string sIn)
{
bool bDataDropped = false;
return FilterWorker(sIn, FILTER_UPPER, ref bDataDropped);
}
/// <summary>
/// Filter upper case
/// </summary>
/// <param name="sIn">Input to filter</param>
/// <param name="bDataDropped">Set true if data is dropped</param>
/// <returns>Filtered string</returns>
public static string FilterUpperCase(string sIn, ref bool bDataDropped)
{
return FilterWorker(sIn, FILTER_UPPER, ref bDataDropped);
}
#endregion
#region " FilterWorker "
/// <summary>
/// Filter Worker
/// </summary>
/// <param name="sIn">Input to filter</param>
/// <param name="sValid">Whitelist of allowed characters</param>
/// <param name="bDataDropped">Set true if data is dropped</param>
/// <returns>Filtered string</returns>
private static string FilterWorker(string sIn, string sValid, ref bool bDataDropped)
{
try
{
bDataDropped = false;
if (sIn.Length == 0) return sIn;
StringBuilder sOutput = new StringBuilder(sIn.Length);
for (int iLoop = 0; iLoop < sIn.Length; iLoop++)
{
string sValue = sIn.Substring(iLoop, 1);
if (sValid.IndexOf(sValue) >= 0) // sValue is valid!
sOutput.Append(sValue);
else
bDataDropped = true;
}
return sOutput.ToString();
}
catch (Exception ex)
{ // System.Reflection.MethodInfo.GetCurrentMethod.Name
string sMethod = "FilterWorker";
CommonData.WriteEventError(MODULE_NAME, sMethod, ex, String.Empty);
return sIn;
}
}
#endregion
#endregion
#region " Get Functions "
#region " GetAudit"
/// <summary>
/// Return Audit Level
/// </summary>
/// <returns>0=Audit off, 1=Audit Fail, 2=Audit Fail & Success</returns>
public static int GetAuditLevel()
{
string sEventLogName; int iAuditLevel; int iLogLevel; string sConnect;
GetConfigVariables(out sEventLogName, out iAuditLevel, out iLogLevel, out sConnect);
return iAuditLevel;
}
#endregion
#region " GetBaseDirectory"
/// <summary>
/// Get location where dot net started looking for this assembly
/// </summary>
/// <remarks>Brock Allen of DevelopMentor (http://staff.develop.com/ballen) suggested this.
/// <list type="Application type v path returned">
/// <item>For WinForms, Windows Service and DosCommand
/// returns the installation directory with a trailing slash</item>
/// <item>For WebForm and Web Service
/// returns the root of the site (with trailing slash) not the exe location</item>
/// </list>
/// </remarks>
public static string GetBaseDirectory()
{
return AppDomain.CurrentDomain.BaseDirectory;
}
#endregion
#region " GetConfig.."
/// <summary>
/// Get path to Configuration File
/// </summary>
/// <returns>Returns path name to config file</returns>
public static string GetConfigPathName()
{
bool bConfigFileFound = false;
return CommonData.GetConfigPathName(ref bConfigFileFound);
}
/// <summary>
/// Get path to Configuration File
/// </summary>
/// <param name="bConfigFileFound">Set true if configuration file found</param>
/// <returns>Returns path name to config file</returns>
/// <remarks>Locating the configuration file is the trivial task that would be reasonably
/// be expected. Put the config file in the directory that GetBaseDirectory will
/// find it in. It is advisable to make the application startup check that the
/// config file is present by checking that bConfigFileFound is set true.
/// </remarks>
public static string GetConfigPathName(ref bool bConfigFileFound)
{
bConfigFileFound = false;
string sDaseDirectory = CommonData.GetBaseDirectory();
if (!sDaseDirectory.EndsWith("/"))
{
if (!sDaseDirectory.EndsWith("\\")) sDaseDirectory += "\\";
}
sDaseDirectory += CONFIG_FILE;
if (File.Exists(sDaseDirectory))
bConfigFileFound = true;
else
{
// Attempt alternative directory
//sDaseDirectory = this.GetCurrentDirectory;
//if (!sDaseDirectory.EndsWith("\\")) sDaseDirectory += "\\";
//sDaseDirectory += CONFIG_FILE;
if (File.Exists(sDaseDirectory))
bConfigFileFound = true;
else
{
System.Diagnostics.EventLog xLog = new System.Diagnostics.EventLog("Application");
xLog.Source = "Application";
xLog.WriteEntry("Could not find " + CONFIG_FILE + " in " + CommonData.GetBaseDirectory()
+ " or " + CommonData.GetCurrentDirectory());
}
}
return sDaseDirectory;
}
private static void GetConfigVariables(out string sEventLogName, out int iAuditLevel, out int iLogLevel, out string sConnect)
{
XmlDocument xXmlDocument = new XmlDocument();
try
{
string sPathName = GetConfigPathName();
if (File.Exists(sPathName))
{
xXmlDocument.Load(sPathName); // Load config file
sConnect = xXmlDocument.SelectSingleNode("/DATALAYER/CONNECT").InnerText;
sEventLogName = xXmlDocument.SelectSingleNode("/DATALAYER/EVENTLOGNAME").InnerText;
iAuditLevel = Convert.ToInt32(xXmlDocument.SelectSingleNode("/DATALAYER/AUDITLEVEL").InnerText);
iLogLevel = Convert.ToInt32(xXmlDocument.SelectSingleNode("/DATALAYER/LOGLEVEL").InnerText);
if (iAuditLevel < 0) iAuditLevel = 0;
if (iAuditLevel > 2) iAuditLevel = 2;
if (iLogLevel < 0) iLogLevel = 0;
if (iLogLevel > 3) iLogLevel = 3;
}
else
{
sConnect = "";
sEventLogName = "";
iAuditLevel = 0;
iLogLevel = 0;
}
}
catch (Exception objError)
{
throw objError;
}
finally
{
xXmlDocument = null;
}
}
#endregion
#region " GetConnect "
/// <summary>
/// Return connect string
/// </summary>
/// <returns>Return connection string from CONFIG.XML</returns>
public static string GetConnect()
{
string sEventLogName; int iAuditLevel; int iLogLevel; string sConnect;
GetConfigVariables(out sEventLogName, out iAuditLevel, out iLogLevel, out sConnect);
return sConnect;
}
#endregion
#region " GetCurrentDirectory "
/// <summary>
/// Get current directory
/// </summary>
/// <returns>Returns current directory</returns>
public static string GetCurrentDirectory()
{
return System.Environment.CurrentDirectory.ToString();
}
#endregion
#region " GetDataset "
/// <summary>
/// Run stored procedure with no arguments returning a dataset
/// </summary>
/// <param name="sProcName">Procedure Name</param>
/// <returns>Dataset</returns>
public static DataSet GetDataset(string sProcName)
{
DataSet xDataSet = new DataSet();
string sConnect = GetConnect();
SqlConnection xSqlConnection = new SqlConnection(sConnect);
try
{
SqlCommand xSqlCommand = new SqlCommand(sProcName, xSqlConnection);
xSqlCommand.CommandType = CommandType.StoredProcedure;
xSqlConnection.Open();
SqlDataAdapter xSqlDataAdapter = new SqlDataAdapter(xSqlCommand);
xSqlDataAdapter.Fill(xDataSet);
xSqlDataAdapter.Dispose();
}
catch (Exception ex)
{
string sMethod = System.Reflection.MethodInfo.GetCurrentMethod().Name;
WriteEventError(MODULE_NAME, sMethod, ex, "Running:" + sProcName);
}
finally
{
if (xSqlConnection != null) xSqlConnection.Close();
xSqlConnection.Dispose();
}
return xDataSet;
}
#endregion
#region " GetEvent.."
/// <summary>
/// Get Custom Event Log as Dataset
/// </summary>
/// <remarks>Not for users. May be consumed by data grid or web service.</remarks>
/// <returns>Dataset of event log in most recent first sequence.</returns>
public static DataSet GetEventLogDataset
{
get
{
string sMethod = System.Reflection.MethodInfo.GetCurrentMethod().Name;
DataSet xDataSet = new DataSet();
try
{
string sEventLogName = CommonData.GetEventLogName();
System.Diagnostics.EventLog xLog = new System.Diagnostics.EventLog(sEventLogName);
xLog.Source = sEventLogName;
if (xLog.Entries.Count == 0)
CommonData.WriteEventInformation(MODULE_NAME, sMethod, "Dummy entry");
DataTable xDataTable = new DataTable();
xDataTable.Columns.Add("EntryType");
xDataTable.Columns.Add("TimeGenerated");
xDataTable.Columns.Add("Message");
xDataTable.Columns.Add("Category");
for (int iLoop = xLog.Entries.Count - 1; iLoop >= 0; iLoop--)
{
string[] sRow = new string[]
{
xLog.Entries[iLoop].EntryType.ToString(),
xLog.Entries[iLoop].TimeGenerated.ToString(),
xLog.Entries[iLoop].Message,
xLog.Entries[iLoop].Category
};
xDataTable.Rows.Add(sRow);
}
xDataSet.Tables.Add(xDataTable);
}
catch (Exception ex)
{
CommonData.WriteEventError(MODULE_NAME, sMethod, ex, "");
}
return xDataSet;
}
}
/// <summary>
/// Get Event Log Name from CONFIG file
/// </summary>
/// <returns>Return name of custom event log</returns>
public static string GetEventLogName()
{
string sEventLogName; int iAuditLevel; int iLogLevel; string sConnect;
GetConfigVariables(out sEventLogName, out iAuditLevel, out iLogLevel, out sConnect);
return sEventLogName;
}
#endregion
#region " GetLogLevel "
/// <summary>
/// Returns Log Level
/// </summary>
/// <returns>0=Log off, 1=Errors only, 2=Errors+Warnings, 3=Errors+Warnings+Information</returns>
public static int GetLogLevel()
{
string sEventLogName; int iAuditLevel; int iLogLevel; string sConnect;
GetConfigVariables(out sEventLogName, out iAuditLevel, out iLogLevel, out sConnect);
return iLogLevel;
}
#endregion
#region " GetMachineName "
/// <summary>
/// Get Machine Name
/// </summary>
/// <returns>Returns machine name</returns>
public static string GetMachineName()
{
return System.Environment.MachineName.ToString();
}
#endregion
#region " GetOs..."
/// <summary>
/// Get OS Platform
/// </summary>
/// <returns></returns>
public static string GetOsVersionPlatform()
{
return System.Environment.OSVersion.Platform.ToString();
}
/// <summary>
/// Get OS Version
/// </summary>
/// <returns></returns>
public static string GetOsVersionVersion()
{
return System.Environment.OSVersion.Version.ToString();
}
#endregion
#region " GetStackTrace "
/// <summary>
/// Get stack of current calls
/// </summary>
/// <returns></returns>
public static string GetStackTrace()
{
return System.Environment.StackTrace.ToString();
}
#endregion
#region " GetSystemDirectory "
/// <summary>
/// Get Location of System Directory
/// </summary>
/// <returns></returns>
public static string GetSystemDirectory()
{
return System.Environment.SystemDirectory.ToString();
}
#endregion
#region " GetUser..."
/// <summary>
/// Get domain user is logged into
/// </summary>
/// <returns></returns>
public static string GetUserDomainName()
{
return System.Environment.UserDomainName.ToString();
}
/// <summary>
/// Get logged-in user name
/// </summary>
/// <returns></returns>
public static string GetUserName()
{
return System.Environment.UserName.ToString();
}
#endregion
#region " GetVersion..."
/// <summary>
/// Get version build number
/// </summary>
/// <returns></returns>
public static string GetVersionBuild()
{
return System.Environment.Version.Build.ToString();
}
/// <summary>
/// Get Major version number
/// </summary>
/// <returns></returns>
public static string GetVersionMajor()
{
return System.Environment.Version.Major.ToString();
}
/// <summary>
/// Get minor version number
/// </summary>
/// <returns></returns>
public static string GetVersionMinor()
{
return System.Environment.Version.Minor.ToString();
}
/// <summary>
/// Get Revision number
/// </summary>
/// <returns></returns>
public static string GetVersionRevision()
{
return System.Environment.Version.Revision.ToString();
}
#endregion
#endregion
#region " Is Functions "
/// <summary>
/// Test if supplied string is blank
/// </summary>
/// <param name="sTest">String to test</param>
/// <returns>True if input string is blank</returns>
public static bool IsBlank(string sTest)
{
return (sTest.Trim().Length == 0);
}
/// <summary>
/// Test if supplied string is not blank
/// </summary>
/// <param name="sTest">String to test</param>
/// <returns>True if input string is not blank</returns>
public static bool IsNotBlank(string sTest)
{
return (sTest.Trim().Length != 0);
}
/// <summary>
/// Test if input string is numeric - NOT WORKING
/// </summary>
/// <param name="sTest"></param>
/// <returns>True if string is numeric</returns>
private static bool IsNumeric(string sTest)
{
System.Text.RegularExpressions.Regex xRegEx
= new System.Text.RegularExpressions.Regex("^\\d*\\.{0,1}\\d+$");
return xRegEx.IsMatch(sTest);
}
#endregion
#region " Null Functions "
/// <summary>
/// Convert nullable value to boolean
/// </summary>
/// <param name="vValue"></param>
/// <returns></returns>
public static bool NullToBoolean(object vValue)
{
try
{
if (vValue != null)
return System.Convert.ToBoolean(vValue);
else
return false;
}
catch { return false; }
}
/// <summary>
/// Convert nullable value to boolean
/// </summary>
/// <param name="vValue"></param>
/// <param name="bDefault"></param>
/// <returns></returns>
public static bool NullToBoolean(object vValue, bool bDefault)
{
try
{
if (vValue != null)
return System.Convert.ToBoolean(vValue);
else
return false;
}
catch { return bDefault; }
}
/// <summary>
/// Convert nullable value to date string
/// </summary>
/// <param name="vValue"></param>
/// <returns></returns>
public static string NullToDateString(object vValue)
{
try
{
if (vValue != null)
{
System.DateTime dValue = System.Convert.ToDateTime(vValue);
return dValue.ToString("dd/MM/yyyy HH:mm", DateTimeFormatInfo.InvariantInfo);
}
else
return "";
}
catch { return ""; }
}
/// <summary>
/// Convert nullable value to date string with sepecified format
/// </summary>
/// <param name="vValue"></param>
/// <param name="sFormat"></param>
/// <returns></returns>
public static string NullToDateString(object vValue, string sFormat)
{
try
{
if (vValue != null)
{
System.DateTime dValue = System.Convert.ToDateTime(vValue);
return dValue.ToString(sFormat, DateTimeFormatInfo.InvariantInfo);
}
else
return "";
}
catch { return ""; }
}
/// <summary>
/// Convert nullable value to decimal value
/// </summary>
/// <param name="vValue"></param>
/// <returns></returns>
public static decimal NullToDecimal(object vValue)
{
try
{
if (vValue != null)
return System.Convert.ToDecimal(vValue);
else
return 0;
}
catch { return 0; }
}
/// <summary>
/// Convert nullable value to Integer
/// </summary>
/// <param name="vValue"></param>
/// <returns></returns>
public static int NullToInteger(object vValue)
{
try
{
if (vValue != null)
return System.Convert.ToInt32(vValue);
else
return 0;
}
catch { return 0; }
}
/// <summary>
/// Convert nullable value to string
/// </summary>
/// <param name="vValue"></param>
/// <returns></returns>
public static string NullToString(object vValue)
{
try
{
if (vValue != null)
return System.Convert.ToString(vValue);
else
return "";
}
catch { return ""; }
}
#endregion
#region " WriteEvent "
#region " WriteEventError "
/// <summary>
/// Write error flagged event log entry
/// </summary>
/// <param name="sPage">MODULE_NAME or FORM_NAME</param>
/// <param name="sMethod">From string sMethod = System.Reflection.MethodInfo.GetCurrentMethod().Name;</param>
/// <param name="xError">From catch (Exception ex)</param>
public static void WriteEventError(string sPage, string sMethod, Exception xError)
{
string sNote = "";
CommonData.WriteEventError(sPage, sMethod, xError, sNote);
}
/// <summary>
/// Write error flagged event log entry
/// </summary>
/// <param name="sPage">MODULE_NAME or FORM_NAME</param>
/// <param name="sMethod">From string sMethod = System.Reflection.MethodInfo.GetCurrentMethod().Name;</param>
/// <param name="xError">From catch (Exception ex)</param>
/// <param name="sNote">Optional note</param>
public static void WriteEventError(string sPage, string sMethod, Exception xError, string sNote)
{
string sEventLogName; int iAuditLevel; int iLogLevel; string sConnect;
GetConfigVariables(out sEventLogName, out iAuditLevel, out iLogLevel, out sConnect);
string sMessage = "";
if (sPage.LastIndexOf("/", 1) > 0) sPage = sPage.Substring(sPage.LastIndexOf("/", 1) + 1);
if (sMethod.Length > 0) sMessage = sMethod + ":" + sMessage;
if (sPage.Length > 0) sMessage = sPage + ":" + sMessage;
if (sMessage.Length > 0)
sMessage += "\n" + xError.Message;
else
sMessage = xError.Message;
while (xError.InnerException != null)
{
xError = xError.InnerException;
sMessage += "\n" + xError.Message;
}
sMessage += "\n" + xError.StackTrace;
sMessage += "\n" + xError.Source;
if (sNote.Length > 0) sMessage += "\n" + sNote;
if (iLogLevel > 0)
{
if (System.Diagnostics.EventLog.SourceExists(sEventLogName))
{
System.Diagnostics.EventLog xLog = new System.Diagnostics.EventLog(sEventLogName);
xLog.Source = sEventLogName;
try
{
xLog.WriteEntry(sMessage, System.Diagnostics.EventLogEntryType.Error);
}
catch { }
}
}
}
#endregion
#region " WriteEventFailureAudit "
/// <summary>
/// Write Event Log Audit Failure Message
/// </summary>
/// <param name="sPage">MODULE_NAME or FORM_NAME</param>
/// <param name="sMethod">From string sMethod = System.Reflection.MethodInfo.GetCurrentMethod().Name;</param>
/// <param name="sNote">Message to write to event log</param>
public static void WriteEventFailureAudit(string sPage, string sMethod, string sNote)
{
string sMessage = sNote;
if (sPage.LastIndexOf("/", 1) > 0) sPage = sPage.Substring(sPage.LastIndexOf("/", 1) + 1);
if (sMethod.Length > 0) sMessage = sMethod + ":" + sMessage;
if (sPage.Length > 0) sMessage = sPage + ":" + sMessage;
string sEventLogName; int iAuditLevel; int iLogLevel; string sConnect;
GetConfigVariables(out sEventLogName, out iAuditLevel, out iLogLevel, out sConnect);
if (iAuditLevel > 1)
{
if (System.Diagnostics.EventLog.SourceExists(sEventLogName))
{
System.Diagnostics.EventLog xLog = new System.Diagnostics.EventLog(sEventLogName);
xLog.Source = sEventLogName;
try
{
xLog.WriteEntry(sMessage, System.Diagnostics.EventLogEntryType.FailureAudit);
}
catch { }
}
}
}
#endregion
#region " WriteEventInformation "
/// <summary>
/// Write Event Log Information Message
/// </summary>
/// <param name="sPage">MODULE_NAME or FORM_NAME</param>
/// <param name="sMethod">From string sMethod = System.Reflection.MethodInfo.GetCurrentMethod().Name;</param>
/// <param name="sNote">Message to write to event log</param>
public static void WriteEventInformation(string sPage, string sMethod, string sNote)
{
string sMessage = sNote;
if (sPage.LastIndexOf("/", 1) > 0) sPage = sPage.Substring(sPage.LastIndexOf("/", 1) + 1);
if (sMethod.Length > 0) sMessage = sMethod + ":" + sMessage;
if (sPage.Length > 0) sMessage = sPage + ":" + sMessage;
string sEventLogName; int iAuditLevel; int iLogLevel; string sConnect;
GetConfigVariables(out sEventLogName, out iAuditLevel, out iLogLevel, out sConnect);
if (iLogLevel == 3)
{
if (System.Diagnostics.EventLog.SourceExists(sEventLogName))
{
System.Diagnostics.EventLog xLog = new System.Diagnostics.EventLog(sEventLogName);
xLog.Source = sEventLogName;
try
{
xLog.WriteEntry(sMessage, System.Diagnostics.EventLogEntryType.Information);
}
catch { }
}
}
}
#endregion
#region " WriteEventSuccessAudit "
/// <summary>
/// Write Event Log Audit Success Message
/// </summary>
/// <param name="sPage">MODULE_NAME or FORM_NAME</param>
/// <param name="sMethod">From string sMethod = System.Reflection.MethodInfo.GetCurrentMethod().Name;</param>
/// <param name="sNote">Message to write to event log</param>
public static void WriteEventSuccessAudit(string sPage, string sMethod, string sNote)
{
string sMessage = sNote;
if (sPage.LastIndexOf("/", 1) > 0) sPage = sPage.Substring(sPage.LastIndexOf("/", 1) + 1);
if (sMethod.Length > 0) sMessage = sMethod + ":" + sMessage;
if (sPage.Length > 0) sMessage = sPage + ":" + sMessage;
string sEventLogName; int iAuditLevel; int iLogLevel; string sConnect;
GetConfigVariables(out sEventLogName, out iAuditLevel, out iLogLevel, out sConnect);
if (iAuditLevel == 2)
{
if (System.Diagnostics.EventLog.SourceExists(sEventLogName))
{
System.Diagnostics.EventLog xLog = new System.Diagnostics.EventLog(sEventLogName);
xLog.Source = sEventLogName;
try
{
xLog.WriteEntry(sMessage, System.Diagnostics.EventLogEntryType.SuccessAudit);
}
catch { }
}
}
}
#endregion
#region " WriteEventWarning "
/// <summary>
/// Write Event Log Event Warning Message
/// </summary>
/// <param name="sPage">MODULE_NAME or FORM_NAME</param>
/// <param name="sMethod">From string sMethod = System.Reflection.MethodInfo.GetCurrentMethod().Name;</param>
/// <param name="sNote">Message to write to event log</param>
public static void WriteEventWarning(string sPage, string sMethod, string sNote)
{
string sMessage = sNote;
if (sPage.LastIndexOf("/", 1) > 0) sPage = sPage.Substring(sPage.LastIndexOf("/", 1) + 1);
if (sMethod.Length > 0) sMessage = sMethod + ":" + sMessage;
if (sPage.Length > 0) sMessage = sPage + ":" + sMessage;
string sEventLogName; int iAuditLevel; int iLogLevel; string sConnect;
GetConfigVariables(out sEventLogName, out iAuditLevel, out iLogLevel, out sConnect);
if (iLogLevel > 1)
{
if (System.Diagnostics.EventLog.SourceExists(sEventLogName))
{
System.Diagnostics.EventLog xLog = new System.Diagnostics.EventLog(sEventLogName);
xLog.Source = sEventLogName;
try
{
xLog.WriteEntry(sMessage, System.Diagnostics.EventLogEntryType.Warning);
}
catch { }
}
}
}
#endregion
#endregion
}
}
Click "Mark as Answer" on the post that helped you.
This earns you a point and marks your thread as Resolved so we will all know you have been helped.
FAQ on the correct forum http://forums.asp.net/p/1337412/2699239.aspx#2699239
TATWORTH
All-Star
72405 Points
14018 Posts
MVP
Re: filling the textbox,dropdownlist from the database??
Mar 08, 2008 02:57 PM|LINK
The C# library that the wrapper code follows:
#region " Copyleft "
// Copyright (C) 2000, 2003, 2004, 2005, 2007 Clive Chinery
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
#endregion
#region " Usings "
using System;
using System.Data;
using System.Data.SqlClient;
using System.Globalization;
using System.IO;
using System.Text;
using System.Xml;
#endregion
namespace CommonCS
{
/// <summary>
/// Common Data functions
/// </summary>
public sealed partial class CommonData
{
#region " Constants "
/// <summary>
/// With the GetBaseDirectory it should not be neccessary to rename this file as it
/// can be located with application.
/// </summary>
private static string CONFIG_FILE = "CONFIG.XML";
/// <summary>
/// Hold name of module
/// </summary>
private static string MODULE_NAME = "CommonData.cs";
#endregion
#region " Calc Functions "
/// <summary>
/// Calculate Percentage from Decimal Values
/// </summary>
/// <param name="decExpression1">Numerator value</param>
/// <param name="decExpression2">Divisor value</param>
/// <returns></returns>
public static decimal CalcPercent(decimal decExpression1, decimal decExpression2)
{
if (decExpression2 == 0)
return 0;
else
return ((100 * decExpression1) / decExpression2);
}
/// <summary>
/// Calculate Percentage from Integer Values
/// </summary>
/// <param name="iExpression1">Numerator value</param>
/// <param name="iExpression2">Divisor value</param>
/// <returns></returns>
public static int CalcPercent(int iExpression1, int iExpression2)
{
if (iExpression2 == 0)
return 0;
else
return ((100 * iExpression1) / iExpression2);
}
#endregion
#region " Decimal Functions "
/// <summary>
/// Adjust decimal value to a (sanitized) number of decimal places
/// </summary>
/// <param name="decIN">Decimal value</param>
/// <param name="iPlaces">Number of decimal places</param>
/// <returns>Adjusted value</returns>
public static decimal DecimalAdjust(decimal decIN, int iPlaces)
{
if (iPlaces < 0) iPlaces = 0;
if (iPlaces > 28) iPlaces = 28;
return decimal.Round(decIN, iPlaces);
}
#endregion
#region " Filter constants "
private const string FILTER_NUMERIC = "0123456789";
private const string FILTER_DECIMAL = FILTER_NUMERIC + "-.";
private const string FILTER_INTEGER = FILTER_NUMERIC + "-";
private const string FILTER_LOWER = "abcdefghijklmnopqrstuvwxyz";
private const string FILTER_POSTCODE = "ABCDEFGHIJKLMNOPQRSTUVWXYZ 0123456789";
private const string FILTER_UPPER = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
private const string FILTER_TELEPHONE = FILTER_LOWER + FILTER_INTEGER + " +()";
private const string FILTER_TIME = FILTER_NUMERIC + ":";
private const string FILTER_ALPHA = FILTER_LOWER + FILTER_UPPER;
private const string FILTER_ALPHANUMERIC = FILTER_ALPHA + FILTER_NUMERIC;
private const string FILTER_GENERAL_TEXT = FILTER_ALPHANUMERIC + " :/\\()-=+\n";
#endregion
#region " Filter Functions (see notes with FilterGeneralText) "
#region " FilterAlpha "
/// <summary>
/// Filter Alpha (upper + lower case) Values
/// </summary>
/// <param name="sIn">Input to filter</param>
/// <returns>Filtered string</returns>
public static string FilterAlpha(string sIn)
{
bool bDataDropped = false;
return FilterWorker(sIn, FILTER_ALPHA, ref bDataDropped);
}
/// <summary>
/// Filter Alpha (upper + lower case) Values
/// </summary>
/// <param name="sIn">Input to filter</param>
/// <param name="bDataDropped">Set true if data is dropped</param>
/// <returns>Filtered string</returns>
public static string FilterAlpha(string sIn, ref bool bDataDropped)
{
return FilterWorker(sIn, FILTER_ALPHA, ref bDataDropped);
}
#endregion
#region " FilterAlphaNumeric "
/// <summary>
/// Filter AlphaNumeric (upper + lower + integer case) Values
/// </summary>
/// <param name="sIn">Input to filter</param>
/// <returns>Filtered string</returns>
public static string FilterAlphaNumeric(string sIn)
{
bool bDataDropped = false;
return FilterWorker(sIn, FILTER_ALPHANUMERIC, ref bDataDropped);
}
/// <summary>
/// Filter AlphaNumeric (upper + lower + integer case) Values
/// </summary>
/// <param name="sIn">Input to filter</param>
/// <param name="bDataDropped">Set true if data is dropped</param>
/// <returns>Filtered string</returns>
public static string FilterAlphaNumeric(string sIn, ref bool bDataDropped)
{
return FilterWorker(sIn, FILTER_ALPHANUMERIC, ref bDataDropped);
}
#endregion
#region " FilterDecimal "
/// <summary>
/// Filter Decimal Values
/// </summary>
/// <param name="sIn">Input to filter</param>
/// <returns>Filtered string</returns>
public static string FilterDecimal(string sIn)
{
bool bDataDropped = false;
return FilterWorker(sIn, FILTER_DECIMAL, ref bDataDropped);
}
/// <summary>
/// Filter Decimal Values
/// </summary>
/// <param name="sIn">Input to filter</param>
/// <param name="bDataDropped">Set true if data is dropped</param>
/// <returns>Filtered string</returns>
public static string FilterDecimal(string sIn, ref bool bDataDropped)
{
return FilterWorker(sIn, FILTER_DECIMAL, ref bDataDropped);
}
#endregion
#region " FilterGeneralText (plus notes on usage) "
/// <summary>
/// Filter general text
/// </summary>
/// <param name="sIn">Input to filter</param>
/// <returns>Filtered string</returns>
/// <remarks>These filter functions are built upon the premise: "All input is evil".
/// These functions filter input to a range of permitted values controlled by
/// appropriate constants. By defining the allowed values within string constants
/// the allowed values can readily be changed.
/// Input is usually from a textbox but could also be an argument from the query string.
/// When working with non-english languages the General Text will need to be rewritten
/// on an exclude basis.
/// The filter functions filter on a permitted values basis - Thus FilterDecimal
/// would pass the second decimal point in "1.22.2".
/// </remarks>
public static string FilterGeneralText(string sIn)
{
bool bDataDropped = false;
return FilterWorker(sIn, FILTER_GENERAL_TEXT, ref bDataDropped);
}
/// <summary>
/// Filter general text
/// </summary>
/// <param name="sIn">Input to filter</param>
/// <param name="bDataDropped">Set true if data is dropped</param>
/// <returns>Filtered string</returns>
public static string FilterGeneralText(string sIn, ref bool bDataDropped)
{
return FilterWorker(sIn, FILTER_GENERAL_TEXT, ref bDataDropped);
}
#endregion
#region " FilterInteger "
/// <summary>
/// Filter Integer Values
/// </summary>
/// <param name="sIn">Input to filter</param>
/// <returns>Filtered string</returns>
public static string FilterInteger(string sIn)
{
bool bDataDropped = false;
return FilterWorker(sIn, FILTER_INTEGER, ref bDataDropped);
}
/// <summary>
/// Filter Integer Values
/// </summary>
/// <param name="sIn">Input to filter</param>
/// <param name="bDataDropped">Set true if data is dropped</param>
/// <returns>Filtered string</returns>
public static string FilterInteger(string sIn, ref bool bDataDropped)
{
return FilterWorker(sIn, FILTER_INTEGER, ref bDataDropped);
}
#endregion
#region " FilterLowerCase "
/// <summary>
/// Filter lower case
/// </summary>
/// <param name="sIn">Input to filter</param>
/// <returns>Filtered string</returns>
public static string FilterLowerCase(string sIn)
{
bool bDataDropped = false;
return FilterWorker(sIn, FILTER_LOWER, ref bDataDropped);
}
/// <summary>
/// Filter lower case
/// </summary>
/// <param name="sIn">Input to filter</param>
/// <param name="bDataDropped">Set true if data is dropped</param>
/// <returns>Filtered string</returns>
public static string FilterLowerCase(string sIn, ref bool bDataDropped)
{
return FilterWorker(sIn, FILTER_LOWER, ref bDataDropped);
}
#endregion
#region " FilterPostcode "
/// <summary>
/// Filter Postcode (text forced to upper case)
/// </summary>
/// <param name="sIn">Input to filter</param>
/// <returns>Filtered string</returns>
public static string FilterPostcode(string sIn)
{
bool bDataDropped = false;
return FilterWorker(sIn.ToUpper(), FILTER_POSTCODE, ref bDataDropped);
}
/// <summary>
/// Filter Postcode (text forced to upper case)
/// </summary>
/// <param name="sIn">Input to filter</param>
/// <param name="bDataDropped">Set true if data is dropped</param>
/// <returns>Filtered string</returns>
public static string FilterPostcode(string sIn, ref bool bDataDropped)
{
return FilterWorker(sIn.ToUpper(), FILTER_POSTCODE, ref bDataDropped);
}
#endregion
#region " FilterTelephone "
/// <summary>
/// Filter Telephone (text forced tolower case)
/// </summary>
/// <param name="sIn">Input to filter</param>
/// <returns>Filtered string</returns>
public static string FilterTelephone(string sIn)
{
bool bDataDropped = false;
return FilterWorker(sIn.ToLower(), FILTER_TELEPHONE, ref bDataDropped);
}
/// <summary>
/// Filter Telephone (text forced tolower case)
/// </summary>
/// <param name="sIn">Input to filter</param>
/// <param name="bDataDropped">Set true if data is dropped</param>
/// <returns>Filtered string</returns>
public static string FilterTelephone(string sIn, ref bool bDataDropped)
{
return FilterWorker(sIn.ToLower(), FILTER_TELEPHONE, ref bDataDropped);
}
#endregion
#region " FilterTime "
/// <summary>
/// FilterTime (00:00 or 00:00:00 format)
/// </summary>
/// <param name="sIn">Input to filter</param>
/// <returns>Filtered string</returns>
public static string FilterTime(string sIn)
{
bool bDataDropped = false;
return FilterWorker(sIn, FILTER_TIME, ref bDataDropped);
}
/// <summary>
/// FilterTime (00:00 or 00:00:00 format)
/// </summary>
/// <param name="sIn">Input to filter</param>
/// <param name="bDataDropped">Set true if data is dropped</param>
/// <returns>Filtered string</returns>
public static string FilterTime(string sIn, ref bool bDataDropped)
{
return FilterWorker(sIn, FILTER_TIME, ref bDataDropped);
}
#endregion
#region " FilterUpperCase "
/// <summary>
/// Filter upper case
/// </summary>
/// <param name="sIn">Input to filter</param>
/// <returns>Filtered string</returns>
public static string FilterUpperCase(string sIn)
{
bool bDataDropped = false;
return FilterWorker(sIn, FILTER_UPPER, ref bDataDropped);
}
/// <summary>
/// Filter upper case
/// </summary>
/// <param name="sIn">Input to filter</param>
/// <param name="bDataDropped">Set true if data is dropped</param>
/// <returns>Filtered string</returns>
public static string FilterUpperCase(string sIn, ref bool bDataDropped)
{
return FilterWorker(sIn, FILTER_UPPER, ref bDataDropped);
}
#endregion
#region " FilterWorker "
/// <summary>
/// Filter Worker
/// </summary>
/// <param name="sIn">Input to filter</param>
/// <param name="sValid">Whitelist of allowed characters</param>
/// <param name="bDataDropped">Set true if data is dropped</param>
/// <returns>Filtered string</returns>
private static string FilterWorker(string sIn, string sValid, ref bool bDataDropped)
{
try
{
bDataDropped = false;
if (sIn.Length == 0) return sIn;
StringBuilder sOutput = new StringBuilder(sIn.Length);
for (int iLoop = 0; iLoop < sIn.Length; iLoop++)
{
string sValue = sIn.Substring(iLoop, 1);
if (sValid.IndexOf(sValue) >= 0) // sValue is valid!
sOutput.Append(sValue);
else
bDataDropped = true;
}
return sOutput.ToString();
}
catch (Exception ex)
{ // System.Reflection.MethodInfo.GetCurrentMethod.Name
string sMethod = "FilterWorker";
CommonData.WriteEventError(MODULE_NAME, sMethod, ex, String.Empty);
return sIn;
}
}
#endregion
#endregion
#region " Get Functions "
#region " GetAudit"
/// <summary>
/// Return Audit Level
/// </summary>
/// <returns>0=Audit off, 1=Audit Fail, 2=Audit Fail & Success</returns>
public static int GetAuditLevel()
{
string sEventLogName; int iAuditLevel; int iLogLevel; string sConnect;
GetConfigVariables(out sEventLogName, out iAuditLevel, out iLogLevel, out sConnect);
return iAuditLevel;
}
#endregion
#region " GetBaseDirectory"
/// <summary>
/// Get location where dot net started looking for this assembly
/// </summary>
/// <remarks>Brock Allen of DevelopMentor (http://staff.develop.com/ballen) suggested this.
/// <list type="Application type v path returned">
/// <item>For WinForms, Windows Service and DosCommand
/// returns the installation directory with a trailing slash</item>
/// <item>For WebForm and Web Service
/// returns the root of the site (with trailing slash) not the exe location</item>
/// </list>
/// </remarks>
public static string GetBaseDirectory()
{
return AppDomain.CurrentDomain.BaseDirectory;
}
#endregion
#region " GetConfig.."
/// <summary>
/// Get path to Configuration File
/// </summary>
/// <returns>Returns path name to config file</returns>
public static string GetConfigPathName()
{
bool bConfigFileFound = false;
return CommonData.GetConfigPathName(ref bConfigFileFound);
}
/// <summary>
/// Get path to Configuration File
/// </summary>
/// <param name="bConfigFileFound">Set true if configuration file found</param>
/// <returns>Returns path name to config file</returns>
/// <remarks>Locating the configuration file is the trivial task that would be reasonably
/// be expected. Put the config file in the directory that GetBaseDirectory will
/// find it in. It is advisable to make the application startup check that the
/// config file is present by checking that bConfigFileFound is set true.
/// </remarks>
public static string GetConfigPathName(ref bool bConfigFileFound)
{
bConfigFileFound = false;
string sDaseDirectory = CommonData.GetBaseDirectory();
if (!sDaseDirectory.EndsWith("/"))
{
if (!sDaseDirectory.EndsWith("\\")) sDaseDirectory += "\\";
}
sDaseDirectory += CONFIG_FILE;
if (File.Exists(sDaseDirectory))
bConfigFileFound = true;
else
{
// Attempt alternative directory
//sDaseDirectory = this.GetCurrentDirectory;
//if (!sDaseDirectory.EndsWith("\\")) sDaseDirectory += "\\";
//sDaseDirectory += CONFIG_FILE;
if (File.Exists(sDaseDirectory))
bConfigFileFound = true;
else
{
System.Diagnostics.EventLog xLog = new System.Diagnostics.EventLog("Application");
xLog.Source = "Application";
xLog.WriteEntry("Could not find " + CONFIG_FILE + " in " + CommonData.GetBaseDirectory()
+ " or " + CommonData.GetCurrentDirectory());
}
}
return sDaseDirectory;
}
private static void GetConfigVariables(out string sEventLogName, out int iAuditLevel, out int iLogLevel, out string sConnect)
{
XmlDocument xXmlDocument = new XmlDocument();
try
{
string sPathName = GetConfigPathName();
if (File.Exists(sPathName))
{
xXmlDocument.Load(sPathName); // Load config file
sConnect = xXmlDocument.SelectSingleNode("/DATALAYER/CONNECT").InnerText;
sEventLogName = xXmlDocument.SelectSingleNode("/DATALAYER/EVENTLOGNAME").InnerText;
iAuditLevel = Convert.ToInt32(xXmlDocument.SelectSingleNode("/DATALAYER/AUDITLEVEL").InnerText);
iLogLevel = Convert.ToInt32(xXmlDocument.SelectSingleNode("/DATALAYER/LOGLEVEL").InnerText);
if (iAuditLevel < 0) iAuditLevel = 0;
if (iAuditLevel > 2) iAuditLevel = 2;
if (iLogLevel < 0) iLogLevel = 0;
if (iLogLevel > 3) iLogLevel = 3;
}
else
{
sConnect = "";
sEventLogName = "";
iAuditLevel = 0;
iLogLevel = 0;
}
}
catch (Exception objError)
{
throw objError;
}
finally
{
xXmlDocument = null;
}
}
#endregion
#region " GetConnect "
/// <summary>
/// Return connect string
/// </summary>
/// <returns>Return connection string from CONFIG.XML</returns>
public static string GetConnect()
{
string sEventLogName; int iAuditLevel; int iLogLevel; string sConnect;
GetConfigVariables(out sEventLogName, out iAuditLevel, out iLogLevel, out sConnect);
return sConnect;
}
#endregion
#region " GetCurrentDirectory "
/// <summary>
/// Get current directory
/// </summary>
/// <returns>Returns current directory</returns>
public static string GetCurrentDirectory()
{
return System.Environment.CurrentDirectory.ToString();
}
#endregion
#region " GetDataset "
/// <summary>
/// Run stored procedure with no arguments returning a dataset
/// </summary>
/// <param name="sProcName">Procedure Name</param>
/// <returns>Dataset</returns>
public static DataSet GetDataset(string sProcName)
{
DataSet xDataSet = new DataSet();
string sConnect = GetConnect();
SqlConnection xSqlConnection = new SqlConnection(sConnect);
try
{
SqlCommand xSqlCommand = new SqlCommand(sProcName, xSqlConnection);
xSqlCommand.CommandType = CommandType.StoredProcedure;
xSqlConnection.Open();
SqlDataAdapter xSqlDataAdapter = new SqlDataAdapter(xSqlCommand);
xSqlDataAdapter.Fill(xDataSet);
xSqlDataAdapter.Dispose();
}
catch (Exception ex)
{
string sMethod = System.Reflection.MethodInfo.GetCurrentMethod().Name;
WriteEventError(MODULE_NAME, sMethod, ex, "Running:" + sProcName);
}
finally
{
if (xSqlConnection != null) xSqlConnection.Close();
xSqlConnection.Dispose();
}
return xDataSet;
}
#endregion
#region " GetEvent.."
/// <summary>
/// Get Custom Event Log as Dataset
/// </summary>
/// <remarks>Not for users. May be consumed by data grid or web service.</remarks>
/// <returns>Dataset of event log in most recent first sequence.</returns>
public static DataSet GetEventLogDataset
{
get
{
string sMethod = System.Reflection.MethodInfo.GetCurrentMethod().Name;
DataSet xDataSet = new DataSet();
try
{
string sEventLogName = CommonData.GetEventLogName();
System.Diagnostics.EventLog xLog = new System.Diagnostics.EventLog(sEventLogName);
xLog.Source = sEventLogName;
if (xLog.Entries.Count == 0)
CommonData.WriteEventInformation(MODULE_NAME, sMethod, "Dummy entry");
DataTable xDataTable = new DataTable();
xDataTable.Columns.Add("EntryType");
xDataTable.Columns.Add("TimeGenerated");
xDataTable.Columns.Add("Message");
xDataTable.Columns.Add("Category");
for (int iLoop = xLog.Entries.Count - 1; iLoop >= 0; iLoop--)
{
string[] sRow = new string[]
{
xLog.Entries[iLoop].EntryType.ToString(),
xLog.Entries[iLoop].TimeGenerated.ToString(),
xLog.Entries[iLoop].Message,
xLog.Entries[iLoop].Category
};
xDataTable.Rows.Add(sRow);
}
xDataSet.Tables.Add(xDataTable);
}
catch (Exception ex)
{
CommonData.WriteEventError(MODULE_NAME, sMethod, ex, "");
}
return xDataSet;
}
}
/// <summary>
/// Get Event Log Name from CONFIG file
/// </summary>
/// <returns>Return name of custom event log</returns>
public static string GetEventLogName()
{
string sEventLogName; int iAuditLevel; int iLogLevel; string sConnect;
GetConfigVariables(out sEventLogName, out iAuditLevel, out iLogLevel, out sConnect);
return sEventLogName;
}
#endregion
#region " GetLogLevel "
/// <summary>
/// Returns Log Level
/// </summary>
/// <returns>0=Log off, 1=Errors only, 2=Errors+Warnings, 3=Errors+Warnings+Information</returns>
public static int GetLogLevel()
{
string sEventLogName; int iAuditLevel; int iLogLevel; string sConnect;
GetConfigVariables(out sEventLogName, out iAuditLevel, out iLogLevel, out sConnect);
return iLogLevel;
}
#endregion
#region " GetMachineName "
/// <summary>
/// Get Machine Name
/// </summary>
/// <returns>Returns machine name</returns>
public static string GetMachineName()
{
return System.Environment.MachineName.ToString();
}
#endregion
#region " GetOs..."
/// <summary>
/// Get OS Platform
/// </summary>
/// <returns></returns>
public static string GetOsVersionPlatform()
{
return System.Environment.OSVersion.Platform.ToString();
}
/// <summary>
/// Get OS Version
/// </summary>
/// <returns></returns>
public static string GetOsVersionVersion()
{
return System.Environment.OSVersion.Version.ToString();
}
#endregion
#region " GetStackTrace "
/// <summary>
/// Get stack of current calls
/// </summary>
/// <returns></returns>
public static string GetStackTrace()
{
return System.Environment.StackTrace.ToString();
}
#endregion
#region " GetSystemDirectory "
/// <summary>
/// Get Location of System Directory
/// </summary>
/// <returns></returns>
public static string GetSystemDirectory()
{
return System.Environment.SystemDirectory.ToString();
}
#endregion
#region " GetUser..."
/// <summary>
/// Get domain user is logged into
/// </summary>
/// <returns></returns>
public static string GetUserDomainName()
{
return System.Environment.UserDomainName.ToString();
}
/// <summary>
/// Get logged-in user name
/// </summary>
/// <returns></returns>
public static string GetUserName()
{
return System.Environment.UserName.ToString();
}
#endregion
#region " GetVersion..."
/// <summary>
/// Get version build number
/// </summary>
/// <returns></returns>
public static string GetVersionBuild()
{
return System.Environment.Version.Build.ToString();
}
/// <summary>
/// Get Major version number
/// </summary>
/// <returns></returns>
public static string GetVersionMajor()
{
return System.Environment.Version.Major.ToString();
}
/// <summary>
/// Get minor version number
/// </summary>
/// <returns></returns>
public static string GetVersionMinor()
{
return System.Environment.Version.Minor.ToString();
}
/// <summary>
/// Get Revision number
/// </summary>
/// <returns></returns>
public static string GetVersionRevision()
{
return System.Environment.Version.Revision.ToString();
}
#endregion
#endregion
#region " Is Functions "
/// <summary>
/// Test if supplied string is blank
/// </summary>
/// <param name="sTest">String to test</param>
/// <returns>True if input string is blank</returns>
public static bool IsBlank(string sTest)
{
return (sTest.Trim().Length == 0);
}
/// <summary>
/// Test if supplied string is not blank
/// </summary>
/// <param name="sTest">String to test</param>
/// <returns>True if input string is not blank</returns>
public static bool IsNotBlank(string sTest)
{
return (sTest.Trim().Length != 0);
}
/// <summary>
/// Test if input string is numeric - NOT WORKING
/// </summary>
/// <param name="sTest"></param>
/// <returns>True if string is numeric</returns>
private static bool IsNumeric(string sTest)
{
System.Text.RegularExpressions.Regex xRegEx
= new System.Text.RegularExpressions.Regex("^\\d*\\.{0,1}\\d+$");
return xRegEx.IsMatch(sTest);
}
#endregion
#region " Null Functions "
/// <summary>
/// Convert nullable value to boolean
/// </summary>
/// <param name="vValue"></param>
/// <returns></returns>
public static bool NullToBoolean(object vValue)
{
try
{
if (vValue != null)
return System.Convert.ToBoolean(vValue);
else
return false;
}
catch { return false; }
}
/// <summary>
/// Convert nullable value to boolean
/// </summary>
/// <param name="vValue"></param>
/// <param name="bDefault"></param>
/// <returns></returns>
public static bool NullToBoolean(object vValue, bool bDefault)
{
try
{
if (vValue != null)
return System.Convert.ToBoolean(vValue);
else
return false;
}
catch { return bDefault; }
}
/// <summary>
/// Convert nullable value to date string
/// </summary>
/// <param name="vValue"></param>
/// <returns></returns>
public static string NullToDateString(object vValue)
{
try
{
if (vValue != null)
{
System.DateTime dValue = System.Convert.ToDateTime(vValue);
return dValue.ToString("dd/MM/yyyy HH:mm", DateTimeFormatInfo.InvariantInfo);
}
else
return "";
}
catch { return ""; }
}
/// <summary>
/// Convert nullable value to date string with sepecified format
/// </summary>
/// <param name="vValue"></param>
/// <param name="sFormat"></param>
/// <returns></returns>
public static string NullToDateString(object vValue, string sFormat)
{
try
{
if (vValue != null)
{
System.DateTime dValue = System.Convert.ToDateTime(vValue);
return dValue.ToString(sFormat, DateTimeFormatInfo.InvariantInfo);
}
else
return "";
}
catch { return ""; }
}
/// <summary>
/// Convert nullable value to decimal value
/// </summary>
/// <param name="vValue"></param>
/// <returns></returns>
public static decimal NullToDecimal(object vValue)
{
try
{
if (vValue != null)
return System.Convert.ToDecimal(vValue);
else
return 0;
}
catch { return 0; }
}
/// <summary>
/// Convert nullable value to Integer
/// </summary>
/// <param name="vValue"></param>
/// <returns></returns>
public static int NullToInteger(object vValue)
{
try
{
if (vValue != null)
return System.Convert.ToInt32(vValue);
else
return 0;
}
catch { return 0; }
}
/// <summary>
/// Convert nullable value to string
/// </summary>
/// <param name="vValue"></param>
/// <returns></returns>
public static string NullToString(object vValue)
{
try
{
if (vValue != null)
return System.Convert.ToString(vValue);
else
return "";
}
catch { return ""; }
}
#endregion
#region " WriteEvent "
#region " WriteEventError "
/// <summary>
/// Write error flagged event log entry
/// </summary>
/// <param name="sPage">MODULE_NAME or FORM_NAME</param>
/// <param name="sMethod">From string sMethod = System.Reflection.MethodInfo.GetCurrentMethod().Name;</param>
/// <param name="xError">From catch (Exception ex)</param>
public static void WriteEventError(string sPage, string sMethod, Exception xError)
{
string sNote = "";
CommonData.WriteEventError(sPage, sMethod, xError, sNote);
}
/// <summary>
/// Write error flagged event log entry
/// </summary>
/// <param name="sPage">MODULE_NAME or FORM_NAME</param>
/// <param name="sMethod">From string sMethod = System.Reflection.MethodInfo.GetCurrentMethod().Name;</param>
/// <param name="xError">From catch (Exception ex)</param>
/// <param name="sNote">Optional note</param>
public static void WriteEventError(string sPage, string sMethod, Exception xError, string sNote)
{
string sEventLogName; int iAuditLevel; int iLogLevel; string sConnect;
GetConfigVariables(out sEventLogName, out iAuditLevel, out iLogLevel, out sConnect);
string sMessage = "";
if (sPage.LastIndexOf("/", 1) > 0) sPage = sPage.Substring(sPage.LastIndexOf("/", 1) + 1);
if (sMethod.Length > 0) sMessage = sMethod + ":" + sMessage;
if (sPage.Length > 0) sMessage = sPage + ":" + sMessage;
if (sMessage.Length > 0)
sMessage += "\n" + xError.Message;
else
sMessage = xError.Message;
while (xError.InnerException != null)
{
xError = xError.InnerException;
sMessage += "\n" + xError.Message;
}
sMessage += "\n" + xError.StackTrace;
sMessage += "\n" + xError.Source;
if (sNote.Length > 0) sMessage += "\n" + sNote;
if (iLogLevel > 0)
{
if (System.Diagnostics.EventLog.SourceExists(sEventLogName))
{
System.Diagnostics.EventLog xLog = new System.Diagnostics.EventLog(sEventLogName);
xLog.Source = sEventLogName;
try
{
xLog.WriteEntry(sMessage, System.Diagnostics.EventLogEntryType.Error);
}
catch { }
}
}
}
#endregion
#region " WriteEventFailureAudit "
/// <summary>
/// Write Event Log Audit Failure Message
/// </summary>
/// <param name="sPage">MODULE_NAME or FORM_NAME</param>
/// <param name="sMethod">From string sMethod = System.Reflection.MethodInfo.GetCurrentMethod().Name;</param>
/// <param name="sNote">Message to write to event log</param>
public static void WriteEventFailureAudit(string sPage, string sMethod, string sNote)
{
string sMessage = sNote;
if (sPage.LastIndexOf("/", 1) > 0) sPage = sPage.Substring(sPage.LastIndexOf("/", 1) + 1);
if (sMethod.Length > 0) sMessage = sMethod + ":" + sMessage;
if (sPage.Length > 0) sMessage = sPage + ":" + sMessage;
string sEventLogName; int iAuditLevel; int iLogLevel; string sConnect;
GetConfigVariables(out sEventLogName, out iAuditLevel, out iLogLevel, out sConnect);
if (iAuditLevel > 1)
{
if (System.Diagnostics.EventLog.SourceExists(sEventLogName))
{
System.Diagnostics.EventLog xLog = new System.Diagnostics.EventLog(sEventLogName);
xLog.Source = sEventLogName;
try
{
xLog.WriteEntry(sMessage, System.Diagnostics.EventLogEntryType.FailureAudit);
}
catch { }
}
}
}
#endregion
#region " WriteEventInformation "
/// <summary>
/// Write Event Log Information Message
/// </summary>
/// <param name="sPage">MODULE_NAME or FORM_NAME</param>
/// <param name="sMethod">From string sMethod = System.Reflection.MethodInfo.GetCurrentMethod().Name;</param>
/// <param name="sNote">Message to write to event log</param>
public static void WriteEventInformation(string sPage, string sMethod, string sNote)
{
string sMessage = sNote;
if (sPage.LastIndexOf("/", 1) > 0) sPage = sPage.Substring(sPage.LastIndexOf("/", 1) + 1);
if (sMethod.Length > 0) sMessage = sMethod + ":" + sMessage;
if (sPage.Length > 0) sMessage = sPage + ":" + sMessage;
string sEventLogName; int iAuditLevel; int iLogLevel; string sConnect;
GetConfigVariables(out sEventLogName, out iAuditLevel, out iLogLevel, out sConnect);
if (iLogLevel == 3)
{
if (System.Diagnostics.EventLog.SourceExists(sEventLogName))
{
System.Diagnostics.EventLog xLog = new System.Diagnostics.EventLog(sEventLogName);
xLog.Source = sEventLogName;
try
{
xLog.WriteEntry(sMessage, System.Diagnostics.EventLogEntryType.Information);
}
catch { }
}
}
}
#endregion
#region " WriteEventSuccessAudit "
/// <summary>
/// Write Event Log Audit Success Message
/// </summary>
/// <param name="sPage">MODULE_NAME or FORM_NAME</param>
/// <param name="sMethod">From string sMethod = System.Reflection.MethodInfo.GetCurrentMethod().Name;</param>
/// <param name="sNote">Message to write to event log</param>
public static void WriteEventSuccessAudit(string sPage, string sMethod, string sNote)
{
string sMessage = sNote;
if (sPage.LastIndexOf("/", 1) > 0) sPage = sPage.Substring(sPage.LastIndexOf("/", 1) + 1);
if (sMethod.Length > 0) sMessage = sMethod + ":" + sMessage;
if (sPage.Length > 0) sMessage = sPage + ":" + sMessage;
string sEventLogName; int iAuditLevel; int iLogLevel; string sConnect;
GetConfigVariables(out sEventLogName, out iAuditLevel, out iLogLevel, out sConnect);
if (iAuditLevel == 2)
{
if (System.Diagnostics.EventLog.SourceExists(sEventLogName))
{
System.Diagnostics.EventLog xLog = new System.Diagnostics.EventLog(sEventLogName);
xLog.Source = sEventLogName;
try
{
xLog.WriteEntry(sMessage, System.Diagnostics.EventLogEntryType.SuccessAudit);
}
catch { }
}
}
}
#endregion
#region " WriteEventWarning "
/// <summary>
/// Write Event Log Event Warning Message
/// </summary>
/// <param name="sPage">MODULE_NAME or FORM_NAME</param>
/// <param name="sMethod">From string sMethod = System.Reflection.MethodInfo.GetCurrentMethod().Name;</param>
/// <param name="sNote">Message to write to event log</param>
public static void WriteEventWarning(string sPage, string sMethod, string sNote)
{
string sMessage = sNote;
if (sPage.LastIndexOf("/", 1) > 0) sPage = sPage.Substring(sPage.LastIndexOf("/", 1) + 1);
if (sMethod.Length > 0) sMessage = sMethod + ":" + sMessage;
if (sPage.Length > 0) sMessage = sPage + ":" + sMessage;
string sEventLogName; int iAuditLevel; int iLogLevel; string sConnect;
GetConfigVariables(out sEventLogName, out iAuditLevel, out iLogLevel, out sConnect);
if (iLogLevel > 1)
{
if (System.Diagnostics.EventLog.SourceExists(sEventLogName))
{
System.Diagnostics.EventLog xLog = new System.Diagnostics.EventLog(sEventLogName);
xLog.Source = sEventLogName;
try
{
xLog.WriteEntry(sMessage, System.Diagnostics.EventLogEntryType.Warning);
}
catch { }
}
}
}
#endregion
#endregion
}
}
This earns you a point and marks your thread as Resolved so we will all know you have been helped.
FAQ on the correct forum http://forums.asp.net/p/1337412/2699239.aspx#2699239