Franc Stratton's .NET (TM) Web Application, OOP, and SOA Architecture & Programming Site

A site devoted to ASP.NET (TM), SilverLight (TM) and Browser-Based WPF (TM) Applications, IIS Services, and OOP Architectures

Home     Architecture Overview     WF/WCF/WPF     Data Store     Standards     .NET Security     Resources     jQuery     Silverlight     Developer Tips     Blog     Site Map      
N-Tier Architecture
Service Oriented Architecture
SOA Virtualization
Base Classes
BLL
DAL
Base Page
DALFactory
IDAL
Email
Application
Business Logic Layer
 
The BLL is the parent Model Business Layer Logic for specific domain BLLs (specific business section areas). The BLL works in conjuction with other model business objects such as Business Entities (classes or generics) that are business layer properties passed as parameters between n-tier layers. The BLL contains encryption/decryption and validation methods used by an application.
 

The abstract base class Business Logic Layer should contain those properties and methods that many domain business classes need across the application. This should not be a huge class that contains too many properties and behaviors, but, instead, the scope should be limited to the most useful. A similar rule-of-thumb for the domain business layer is to keep it simple. Many ASP.NET web forms have enough business rules and validation needs that they justify having their own domain BLL and DAL.

 

 

 
 
Method Name: CleanStringRegex
Validates the input text using a Regular Expression and replaces any input expression
characters with empty string.Removes any characters not in [a-z A-Z 0-9_].
 
Method Name: Decrypt3DES
Description: Decrypts values using triple DES encrypting.
 
Method Name: Encrypt3DES
Description: Encrypts values using triple DES encrypting.
 
Method Names: IsValid Methods
Description: These methods are used to validate a field from server side.
It will return true if input parameter is valid. The MVC model herein recommends
client-side and server-side validation to prevent cross-side and other scripting attacks.
 
Method Name: ReplaceRegex
Removes designated characters from an input string input text using a Regular Expression.
For a good reference on Regular Expressions, please see
 
Method Name: ValidateItem
Description: Pass in strings to validate with regex for comparison true or false.
 

namespace AppBase

{

#region Class Using References

using System;

using System.Security.Permissions;

using System.IO.IsolatedStorage;

using System.IO;

using System.Data;

using System.Configuration;

using System.Web;

using System.Web.Security;

using System.Web.UI;

using System.Web.UI.WebControls;

using System.Web.UI.WebControls.WebParts;

using System.Web.UI.HtmlControls;

using System.Security.Cryptography;

using System.Text;

using System.Text.RegularExpressions;

using Microsoft.CSharp;

#endregion

//---------------------------------------------------------------------------

/// Namespace: AppBase

/// Authors: OUR Team

/// Date: 4/22/2006 Finished properties and methods

/// Updated: 4/23/2006 Added comments and header in XML

/// 10/22/2006 Made abstract class so could not be instantiaed,

/// only inherited by derived class

/// 12/24/2006 Added DHS.AppBase Namespace

/// 5/23/2007 Added Unit Tests

/// <summary>

/// Purpose: Parent Model Business Layer Logic for specific domain blls.

/// Works in conjuction with other model business objects such as

/// Business Entities (typed datasets or generics) that can replace business layer

/// fields and properties where they are passed between n-tier layers.

/// Also contains encryption/decryption methods used by an application.

/// </summary>

//---------------------------------------------------------------------------

// Notify the CLR to grant this assembly the IsolatedStorageFilePermission.

// This allows the assembly to work with storage files that are isolated

// by user and assembly.

//[assembly: IsolatedStorageFilePermission(SecurityAction.RequestMinimum, UsageAllowed = IsolatedStorageContainment.AssemblyIsolationByUser)]

[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1705:LongAcronymsShouldBePascalCased")]

public abstract class BLL : System.IDisposable

{

#region Class Constructors

//All base class contstuctors should be protectd per VSTS code analysis

protected BLL()

{

//

// TODO: Add constructor logic here

//

}//protected BLL()

#endregion

#region Class Destructor

//Implement IDisposable.

public void Dispose()

{

Dispose(true);

GC.SuppressFinalize(this);

}

protected virtual void Dispose(bool disposing)

{

if (disposing)

{

// Free other state (managed objects).

}

// Free your own state (unmanaged objects).

// Set large fields to null.

}

// Use C# destructor syntax for finalization code.

~BLL()

{

// Simply call Dispose(false).

Dispose (false);

}

#endregion

#region Private and Public Fields and Properties

//fields and properties for error messages

private string user_Message = string.Empty;

[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Globalization", "CA1303:DoNotPassLiteralsAsLocalizedParameters", MessageId = "System.ArgumentException.#ctor(System.String)")]

public string UserMessage //property for user Error Message

{

get { return user_Message; }

set

{

if (value != null && value.Length != 0)

{

user_Message = value.Trim();

}

else

{

//Get error message from a resource file

throw new ArgumentException("Parameter value may not be set to null or empty.");

}

}

}

#endregion

#region Instance Methods And Functions

#region Encryption/Decryption Methods

///---------------------------------------------------------------------------

/// <summary>

/// Method Name: Encrypt3DES

/// Description: Encrypts values using triple DES encrypting.

/// </summary>

///

/// <param name="toEncrypt">string to encrypt</param>

/// <param name="useHashing">denotes encryption to involve hashing</param>

///---------------------------------------------------------------------------

public static string Encrypt3DES(string toEncrypt, bool useHashing)

{

byte[] keyArray;

byte[] toEncryptArray = UTF8Encoding.UTF8.GetBytes(toEncrypt);

System.Configuration.AppSettingsReader settingsReader = new AppSettingsReader();

//string key = (string)settingsReader.GetValue("SecurityKey", typeof(String));

string key = "ADD Your Key Here";

if (useHashing)

{

MD5CryptoServiceProvider hashmd5 = new MD5CryptoServiceProvider();

keyArray = hashmd5.ComputeHash(UTF8Encoding.UTF8.GetBytes(key));

hashmd5.Clear();

}

else

keyArray = UTF8Encoding.UTF8.GetBytes(key);

TripleDESCryptoServiceProvider tdes = new TripleDESCryptoServiceProvider();

tdes.Key = keyArray;

tdes.Mode = CipherMode.ECB;

tdes.Padding = PaddingMode.PKCS7;

ICryptoTransform cTransform = tdes.CreateEncryptor();

byte[] resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length);

tdes.Clear();

return Convert.ToBase64String(resultArray, 0, resultArray.Length);

}

///---------------------------------------------------------------------------

/// <summary>

/// Method Name: Decrypt3DES

/// Description: Decrypts values using triple DES encrypting.

/// </summary>

///

/// <param name="cipherString">string to decipher</param>

/// <param name="useHashing">denotes encryption to involve hashing</param>

///---------------------------------------------------------------------------

public static string Decrypt3DES(string cipherString, bool useHashing)

{

byte[] keyArray;

byte[] toEncryptArray = Convert.FromBase64String(cipherString);

System.Configuration.AppSettingsReader settingsReader = new AppSettingsReader();

//string key = (string)settingsReader.GetValue("SecurityKey", typeof(String));

string key = "31A822F3E97E0100463955FC0E354804C3F188D2CB86AD26E2B0A5C1DA8148B8";

if (useHashing)

{

MD5CryptoServiceProvider hashmd5 = new MD5CryptoServiceProvider();

keyArray = hashmd5.ComputeHash(UTF8Encoding.UTF8.GetBytes(key));

hashmd5.Clear();

}

else

{

keyArray = UTF8Encoding.UTF8.GetBytes(key);

}

TripleDESCryptoServiceProvider tdes = new TripleDESCryptoServiceProvider();

tdes.Key = keyArray;

tdes.Mode = CipherMode.ECB;

tdes.Padding = PaddingMode.PKCS7;

ICryptoTransform cTransform = tdes.CreateDecryptor();

byte[] resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length);

tdes.Clear();

return UTF8Encoding.UTF8.GetString(resultArray);

}

#endregion

#region Methods for Validating User Input Fields

//---------------------------------------------------------------------------

/// <summary>

/// Method Name: IsValidDate

/// Description: This method is used to validate an alphanumeric from server side.

/// It will return true if text parameter holds a valid alphanumeric.

/// </summary>

/// <param name="text">The text from an input field that holds an alphanumeric</param>

/// <returns>True(if valid alphanumeric) or false</returns>

///---------------------------------------------------------------------------

[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Globalization", "CA1303:DoNotPassLiteralsAsLocalizedParameters", MessageId = "System.ArgumentException.#ctor(System.String)")]

public static bool IsValidAlphaNumeric(string text)

{

string regex = @"^[a-zA-Z0-9\s]+$";

if (text != null && text.Trim().Length != 0)

{

Regex rx = new Regex(regex);

return rx.IsMatch(text);

}

else

{

throw new ArgumentException("Parameter may not be null or empty.");

}

}

//---------------------------------------------------------------------------

/// <summary>

/// Method Name: IsValidAlphaSyntax

/// Description: Validates for Alpha Syntax

/// </summary>

/// <param name="text">string</param>

///

/// <returns>bool</returns>

//---------------------------------------------------------------------------

public static bool IsValidAlphaSyntax(string text)

{

string commentsSyntax = @"^[a-zA-Z\s]+$";

if (commentsSyntax != null && commentsSyntax.Trim().Length != 0)

{

return Regex.IsMatch(text, commentsSyntax);

}

else

{

throw new ArgumentException("Parameter may not be null or empty.");

}

}

 

 

//---------------------------------------------------------------------------

/// <summary>

/// Method Name: IsValidEmail

/// Description: This method is used to validate an email from server side.

/// It will return true if text parameter holds a valid email.

/// </summary>

/// <param name="email">The text from an input field that holds an email</param>

/// <returns>True(if valid email) or false</returns>

///---------------------------------------------------------------------------

[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Globalization", "CA1303:DoNotPassLiteralsAsLocalizedParameters", MessageId = "System.ArgumentException.#ctor(System.String)")]

public static bool IsValidEmail(string email)

{

string regex = @"^[a-zA-Z][\w\.-]*[a-zA-Z0-9]@[a-zA-Z0-9][\w\.-]*[a-zA-Z0-9]\.[a-zA-Z][a-zA-Z\.]*[a-zA-Z]$";

if (email != null && email.Trim().Length != 0)

{

Regex rx = new Regex(regex);

return rx.IsMatch(email);

}

else

{

throw new ArgumentException("Parameter may not be null or empty.");

}

}

//---------------------------------------------------------------------------

/// <summary>

/// Method Name: IsValidURL

/// Description: This method is used to validate a url from server side.

/// It will return true if text parameter holds a valid url.

/// </summary>

/// <param name="url">The text from an input field that holds a url</param>

/// <returns>True(if valid url) or false</returns>

///---------------------------------------------------------------------------

[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Globalization", "CA1303:DoNotPassLiteralsAsLocalizedParameters", MessageId = "System.ArgumentException.#ctor(System.String)")]

public static bool IsValidURL(string url)

{

string regex = @"((ht|f)tp(s?)\:\/\/|~/|/)?([\w]+:\w+@)?(([a-zA-Z]{1}([\w\-]+\.)+([\w]{2,6})))((:[\d]{1,5})?)?((/?\w+/)+|/?)([\w\-]+\.[\w]{3,4})?([,]\w+)*((\?\w+=\w+)?(&\w+=\w+)*([,]\w*)*)?";

if (url != null && url.Trim().Length != 0)

{

Regex rx = new Regex(regex);

return rx.IsMatch(url);

}

else

{

throw new ArgumentException("Parameter may not be null or empty.");

}

}

//---------------------------------------------------------------------------

/// <summary>

/// Method Name: IsValidDate

/// Description: This method is used to validate a date field from server side.

/// It will return true if txtDate parameter holds a valid date.

/// </summary>

/// <param name="txtDate">The text from an input field that holds a date</param>

/// <returns>True(if valid date) or false</returns>

///---------------------------------------------------------------------------

[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Globalization", "CA1303:DoNotPassLiteralsAsLocalizedParameters", MessageId = "System.ArgumentException.#ctor(System.String)")]

public static bool IsValidDate(string txtDate)

{

string regex = @"^(((0?[1-9]|1[012])/(0?[1-9]|1\d|2[0-8])|(0?[13456789]|1[012])/(29|30)|(0?[13578]|1[02])/31)/(19|[2-9]\d)\d{2}|0?2/29/((19|[2-9]\d)(0[48]|[2468][048]|[13579][26])|(([2468][048]|[3579][26])00)))$";

if (txtDate != null && txtDate.Trim().Length != 0)

{

Regex rx = new Regex(regex);

return rx.IsMatch(txtDate);

}

else

{

throw new ArgumentException("Parameter may not be null or empty.");

}

}

//---------------------------------------------------------------------------

/// <summary>

/// Method Name: ValidateItem

/// Description: Pass in strings to validate with regex for comparison

/// true or false. This is a generic comparison method.

/// </summary>

/// <param name="regex">Regular expression</param>

/// <param name="value">string to validate against regex</param>

/// <returns>true or false</returns>

///---------------------------------------------------------------------------

[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Globalization", "CA1303:DoNotPassLiteralsAsLocalizedParameters", MessageId = "System.ArgumentException.#ctor(System.String)")]

public static bool ValidateItem(string regex, string value)

{

if (regex != null && value != null && regex.Trim().Length != 0 && value.Trim().Length != 0)

{

Regex rx = new Regex(regex);

return rx.IsMatch(value);

}

else

{

throw new ArgumentException("Parameters may not be null or empty.");

}

}

 

//*********************************************************************

//

/// <summary>

/// Method Name: CleanStringRegex

/// Validates the input text using a Regular Expression and replaces any input expression

/// characters with empty string.Removes any characters not in [a-z A-Z 0-9_].

/// </summary>

/// <param name="inputText">The text to validate.</param>

/// <returns>Sanitized string</returns>

//

//*********************************************************************

[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Globalization", "CA1303:DoNotPassLiteralsAsLocalizedParameters", MessageId = "System.ArgumentException.#ctor(System.String)")]

public static string CleanStringRegex(string inputText)

{

if (inputText != null && inputText.Trim().Length != 0)

{

RegexOptions options = RegexOptions.IgnoreCase;

return DHS.AppBase.BLL.ReplaceRegex(inputText, @"[^\\.!?""',\-\w\s@]", options);

}

else

{

throw new ArgumentException("Parameter may not be null or empty.");

}

}

//*********************************************************************

//

/// <summary>

/// Method Name: ReplaceRegex

/// Removes designated characters from an input string input text using a Regular Expression.

/// </summary>

/// <remarks>

/// For a good reference on Regular Expressions, please see

/// - http://regexlib.com

/// - http://py-howto.sourceforge.net/regex/regex.html

/// </remarks>

/// <param name="inputText">The text to clean.</param>

/// <param name="regularExpression">The regular expression</param>

/// <returns>Sanitized string.</returns>

//

//*********************************************************************

private static string ReplaceRegex(string inputText, string regularExpression, RegexOptions options)

{

if (inputText != null && inputText.Trim().Length != 0)

{

Regex regex = new Regex(regularExpression, options);

return regex.Replace(inputText, "");

}

else

{

throw new ArgumentException("Parameters may not be null or empty.");

}

}

 

#endregion

#endregion

} //public abstract class bll

} //namespace AppBase