// =====================================================================================
// Copyright � 2005 by Shahed Khan. All rights are reserved.
//
// If you like this code then feel free to go ahead and use it.
// The only thing I ask is that you don't remove or alter my copyright notice.
//
// Your use of this software is entirely at your own risk. I make no claims or
// warrantees about the reliability or fitness of this code for any particular purpose.
// If you make changes or additions to this code please mark your code as being yours.
//
// website , email shahed.khan@gmail.com
// =====================================================================================
//Originally written by Omar Al Zabir I modified according to my need
// Copyright � 2005 by Omar Al Zabir. All rights are reserved.
//
// If you like this code then feel free to go ahead and use it.
// The only thing I ask is that you don't remove or alter my copyright notice.
//
// Your use of this software is entirely at your own risk. I make no claims or
// warrantees about the reliability or fitness of this code for any particular purpose.
// If you make changes or additions to this code please mark your code as being yours.
//
// website http://www.oazabir.com, email OmarAlZabir@gmail.com, msn oazabir@hotmail.com
using System;
using Microsoft.Practices.EnterpriseLibrary.Logging;
using Microsoft.Practices.EnterpriseLibrary.ExceptionHandling;
using Microsoft.Practices.EnterpriseLibrary.Configuration;
using Microsoft.Practices.EnterpriseLibrary.Caching;
using Microsoft.Practices.EnterpriseLibrary.Security.Cryptography;
using Microsoft.Practices.EnterpriseLibrary.Security;
using System.Security.Principal;
using SmartJobManager;
namespace SmartJobManager
{
/// <summary>
/// Helper class for dealing with enterprise library
/// </summary>
public class EntLibHelper
{
#region Configuration Section Names
private const string CONFIGURATION_SECTION_NAME = "globalConfiguration";
private const string EXCEPTION_POLICY_NAME = "Exception Policy";
private const string SYMMETRIC_INSTANCE = "DPAPI Symmetric Cryptography Provider";
private const string HASH_INSTANCE = "MD5CryptoServiceProvider";
private const string GENERAL_CACHE_MANAGER = "General Cache";
private const string AUTHENTICATION_PROVIDER = "Database Provider";
private const string CACHING_STORE_PROVIDER = "Caching Store Provider";
private const string RULE_PROVIDER = "RuleProvider";
private const string PROFILE_PROVIDER = "Profile Database Provider";
private const string ROLE_PROVIDER = "Role Database Provider";
#endregion
#region Logging
private const string INFO_CATEGORY = "Info";
private const string WARN_CATEGORY = "Warn";
private const string ERROR_CATEGORY = "Error";
private const string DEBUG_CATEGORY = "Debug";
private const string JOB_INFO_CATEGORY = "JobInfo";
private const string JOB_ERROR_CATEGORY = "JobError";
private const int INFO_PRIORITY = 4;
private const int INFO_EVENTID = 0;
private const int ERROR_PRIORITY = 3;
private const int ERROR_EVENTID = 0;
private const int WARN_PRIORITY = 2;
private const int WARN_EVENTID = 0;
private const int DEBUG_PRIORITY = 1;
private const int DEBUG_EVENTID = 0;
/*
Category - used to determine the routing of the LogEntry;
Priority - used to filter Log Entries, only those above the �Minimum Priority� are processed (defaults to -1 which indicates that the Minimum Priority should be used);
EventId - a value you can use to further categorise Log Entries (defaults to 0 for a LogEntry and to 1 for a LogEntry implicitly created by Logger.Write);
Severity - indicates the severity of the Log Entry, e.g., Information, Warning, Error etc.
Title - a summary of the LogEntry.Message.
*/
private static CacheManager manager = CacheFactory.GetCacheManager(GENERAL_CACHE_MANAGER);
public static void Info( string title, object message )
{
Logger.Write( "Log message", "Debug" );
Logger.Write( message, INFO_CATEGORY, INFO_PRIORITY, INFO_EVENTID, Microsoft.Practices.EnterpriseLibrary.Logging.Severity.Information, title );
}
public static void Error( string title, object message )
{
Logger.Write( message, ERROR_CATEGORY, ERROR_PRIORITY, ERROR_EVENTID, Microsoft.Practices.EnterpriseLibrary.Logging.Severity.Error, title );
}
public static void Warn( string title, object message )
{
Logger.Write( message, WARN_CATEGORY, WARN_PRIORITY, WARN_EVENTID, Microsoft.Practices.EnterpriseLibrary.Logging.Severity.Warning, title );
}
public static void Debug( string title, object message )
{
Logger.Write( message, DEBUG_CATEGORY, DEBUG_PRIORITY, DEBUG_EVENTID, Microsoft.Practices.EnterpriseLibrary.Logging.Severity.Unspecified, title );
}
public static void JobInfo( string title, Job job)
{
string jobData = string.Format("Job: {0}{1}",job.ToString(),Environment.NewLine);
foreach(JobDetail detail in job.JobDetailCollection)
{
jobData = string.Format("{0}{1}{2}",jobData,detail.ToString(),Environment.NewLine);
}
Logger.Write( jobData, JOB_INFO_CATEGORY, INFO_PRIORITY, INFO_EVENTID, Microsoft.Practices.EnterpriseLibrary.Logging.Severity.Information, title );
}
public static void JobError( string title, Job job )
{
string jobData = string.Format("Job: {0}{1}",job.ToString(),Environment.NewLine);
foreach(JobDetail detail in job.JobDetailCollection)
{
jobData = string.Format("{0}{1}{2}",jobData,detail.ToString(),Environment.NewLine);
}
Logger.Write( jobData, JOB_ERROR_CATEGORY, ERROR_PRIORITY, ERROR_EVENTID, Microsoft.Practices.EnterpriseLibrary.Logging.Severity.Error, title );
}
#endregion
#region Exception Handling
public static bool Exception( string title, Exception x )
{
ApplicationException wrapped = new ApplicationException( title, x );
bool rethrow = ExceptionPolicy.HandleException( wrapped, EXCEPTION_POLICY_NAME );
return rethrow;
}
internal static void UnhandledException(Exception x)
{
// An unhandled exception occured somewhere in our application. Let
// the 'Global Policy' handler have a try at handling it.
try
{
bool rethrow = ExceptionPolicy.HandleException(x, "Unhandled Exception");
if (rethrow)
{
throw x;
}
}
catch
{
// Something has gone wrong during HandleException (e.g. incorrect configuration of the block).
// Exit the application
string errorMsg = "An unexpected exception occured while calling HandleException with policy 'Global Policy'. ";
errorMsg += "Please check the event log for details about the exception." + Environment.NewLine + Environment.NewLine;
throw new Exception( errorMsg );
}
}
public static bool JobException( string title, Job job, Exception x )
{
string jobData = string.Format("Job: {0}{1}",job.ToString(),Environment.NewLine);
foreach(JobDetail detail in job.JobDetailCollection)
{
jobData = string.Format("{0}{1}{2}",jobData,detail.ToString(),Environment.NewLine);
}
title = string.Format("{0}{1}{2}",title,jobData,Environment.NewLine);
ApplicationException wrapped = new ApplicationException( title, x );
bool rethrow = ExceptionPolicy.HandleException( wrapped, EXCEPTION_POLICY_NAME );
return rethrow;
}
#endregion
#region Caching
public static void StoreInCache( string key, object data )
{
if( null == data ) manager.Remove( key );
else manager.Add( key, data );
}
public static object GetCachedObject( string key )
{
if( manager.Contains( key ) )
return manager.GetData( key );
else
return null;
}
#endregion
#region Cryptography
public static string Encrypt( string data )
{
if( 0 == data.Trim().Length ) return string.Empty;
return Cryptographer.EncryptSymmetric( SYMMETRIC_INSTANCE, data );
}
public static string Decrypt( string data )
{
if( 0 == data.Trim().Length ) return string.Empty;
try
{
return Cryptographer.DecryptSymmetric( SYMMETRIC_INSTANCE, data );
}
catch
{
throw new ApplicationException( "Cannot decrypt password. Please set again." );
}
}
public static string Hash( string data )
{
if( 0 == data.Length ) return string.Empty;
return Cryptographer.CreateHash( HASH_INSTANCE, data );
}
public static byte [] HashUnicoded( string data )
{
// Initialize hash provider
ConfigurationContext context = ConfigurationManager.GetCurrentContext();
HashProviderFactory hashProviderFactory = new HashProviderFactory(context);
IHashProvider hashProvider = hashProviderFactory.CreateHashProvider( HASH_INSTANCE );
byte [] unicodeBytes = System.Text.Encoding.Unicode.GetBytes(data);
byte[] hashBytes = hashProvider.CreateHash(unicodeBytes);
return hashBytes;
}
#endregion
#region Authentication and Authorization
public static string Authenticate( string userName, string password )
{
IAuthenticationProvider authenticationProvider = AuthenticationFactory.GetAuthenticationProvider(AUTHENTICATION_PROVIDER);
IIdentity identity;
byte [] passwordBytes = System.Text.Encoding.Unicode.GetBytes( password );
NamePasswordCredential credentials = new NamePasswordCredential(userName, passwordBytes);
bool authenticated = authenticationProvider.Authenticate(credentials, out identity);
if( authenticated )
{
ISecurityCacheProvider cache = SecurityCacheFactory.GetSecurityCacheProvider(CACHING_STORE_PROVIDER);
// Cache the identity. The SecurityCache will generate a token which is then
// returned to us.
IToken token = cache.SaveIdentity(identity);
return token.Value;
}
else
{
return null;
}
}
public static bool Authenticate(string tokenValue)
{
ISecurityCacheProvider cache = SecurityCacheFactory.GetSecurityCacheProvider(CACHING_STORE_PROVIDER);
// Retrieves the identity previously saved by using the corresponding token
IToken token = new GuidToken( new Guid( tokenValue ) );
IIdentity savedIdentity = cache.GetIdentity(token);
if( null != savedIdentity )
return true;
else
return false;
}
public static void CleanSecurityToken( string tokenValue )
{
IToken token = new GuidToken( new Guid( tokenValue ) );
ISecurityCacheProvider cache = SecurityCacheFactory.GetSecurityCacheProvider(CACHING_STORE_PROVIDER);
// Expire the identity
cache.ExpireIdentity(token);
}
public static bool IsInRole(string userName, string roleName)
{
IRolesProvider rolesProvider = RolesFactory.GetRolesProvider(ROLE_PROVIDER);
IPrincipal principal = rolesProvider.GetRoles(new GenericIdentity(userName));
if (principal != null)
{
bool isInRole = principal.IsInRole(roleName);
return isInRole;
}
else
{
return false;
}
}
public static bool IsAuthorized( string userName, string task )
{
IRolesProvider roleProvider = RolesFactory.GetRolesProvider(ROLE_PROVIDER);
IIdentity identity = new GenericIdentity(userName);
IPrincipal principal = roleProvider.GetRoles(identity);
IAuthorizationProvider ruleProvider = AuthorizationFactory.GetAuthorizationProvider(RULE_PROVIDER);
// Determine if user is authorized for the rule defined e.g. "Print Document"
bool authorized = ruleProvider.Authorize(principal, task);
return authorized;
}
[Serializable]
public class MyIdentity : GenericIdentity
{
public string SecurityToken = Guid.NewGuid().ToString();
public MyIdentity( string userName, string type ) : base( userName, type )
{
}
public MyIdentity( string userName ) : base( userName )
{
}
}
#endregion
}
}