Wednesday, June 20, 2012

Session Manager - Singleton

Class IDISessionManager
{
Private IDISessionManager()
{
}

public static IDISessionManager ActiveSessionMgr
{

get
{
HttpContext context = HttpContext.current;
IDISessionManager manager = context.Session["SSSS"]  as IDISessionManager;
if(manager = null)
{

manager = new IDISessionManager();
context.Session["SSSS"] = manager;
}
return manager;
}
}


}

Monday, June 18, 2012

Send Email

Send Email

http://webdevel.blogspot.com/2007/07/sending-emails-with-c.html
http://w3mentor.com/learn/asp-dot-net-c-sharp/c-asp-net-mail/send-email-to-multiple-recipients-in-c/
http://www.systemwebmail.com/faq/2.6.aspx

Write to ConfigFile

Private Sub WriteToConfig(ByVal AnalysisID As String)
        Dim myConfiguration As System.Configuration.Configuration = System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration("~")
        myConfiguration.AppSettings.Settings.Item("AnalysisID").Value = AnalysisID
        myConfiguration.Save()

ShowModelDialog






Reading Config File

Imports System.Windows
Imports System.Collections.Generic
Imports System.Windows.Resources
Imports System.IO
Imports System.Xml.Linq
Imports System.Reflection

'''

''' Access appSettings from a configuration file
'''

''' Your appConfig file must be in the root of your applcation
Public NotInheritable Class ConfigurationManager

    Shared Sub New()
        AppSettings = New Dictionary(Of String, String)()
        ReadSettings()
    End Sub

    Public Shared Property AppSettings() As Dictionary(Of String, String)
        Get
            Return m_AppSettings
        End Get
        Set(ByVal value As Dictionary(Of String, String))
            m_AppSettings = value
        End Set
    End Property
    Private Shared m_AppSettings As Dictionary(Of String, String)

    Private Shared Sub ReadSettings()

        Try
            ' Get the name of the executing assemby - we are going to be looking in the root folder for
            ' a file called app.config
            Dim assemblyName As String = Assembly.GetExecutingAssembly().FullName
            assemblyName = assemblyName.Substring(0, assemblyName.IndexOf(","c))
            '  Dim url As String = [String].Format("{0};component/Configuration/app.config", assemblyName)
            Dim url As String = [String].Format("{0};component/ServiceReferences.ClientConfig", assemblyName)
            Dim configFile As StreamResourceInfo = Application.GetResourceStream(New Uri(url, UriKind.Relative))
            If configFile IsNot Nothing AndAlso configFile.Stream IsNot Nothing Then
                Dim stream As Stream = configFile.Stream
                Dim document As XDocument = XDocument.Load(stream)
                For Each element As XElement In document.Descendants("appSettings").DescendantNodes()
                    AppSettings.Add(element.Attribute("key").Value, element.Attribute("value").Value)
                Next
            End If
        Catch ex As Exception

        End Try

    End Sub
End Class

DataAccess Layer

DataAccess Layer

using System;
using System.Text;
using System.Data;
using System.Data.SqlClient;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Web.UI.WebControls;
using .PurchaseOrder.BusinessLogicLayer;

namespace .PurchaseOrder.DataAccessLayer
{
    public class OrdersDataAccess : DataAccess
    {
        //TextHeader.iId,cPrefix+cOrder as OrderNo,dWindowStart,TextFile.dUpload,TextProductionZone.cProductionZone,cName,dWindowEnd,cStatus
        private const string SP_ORDERS_GET = "TextGetOrders";
        private const string SP_ORDERS_GET2 = "TextGetOrdersSort";

        private void TGenerateOrderItemListFromReader(SqlDataReader returnData, ref List userInfoList)
        {
            while (returnData.Read())
            {
                OrderItem orderItem = new OrderItem();

                orderItem.OrderID = (int)returnData["iId"];
                orderItem.OrderNo = (string)returnData["OrderNo"];
                orderItem.OrderDate = (DateTime)returnData["dWindowStart"];
                orderItem.DateUploaded = (DateTime)returnData["dUpload"];
                orderItem.ProductionZone = (string)returnData["cProductionZone"];
                orderItem.Manufacturer = (string)returnData["cName"];
                orderItem.PrintDate = (DateTime)returnData["dWindowEnd"];
                orderItem.Status = (string)returnData["cStatus"];

                userInfoList.Add(orderItem);
            }
        }

        public List GetOrdersByID(int TextId,int UserType)
        {
            SqlCommand sqlCmd = new SqlCommand();

            AddParamToSQLCmd(sqlCmd, "@TextID", SqlDbType.Int, 0, ParameterDirection.Input, TextId);
            AddParamToSQLCmd(sqlCmd, "@UserType", SqlDbType.Int, 0, ParameterDirection.Input, UserType);

            SetCommandType(sqlCmd, CommandType.StoredProcedure, SP_ORDERS_GET);

            List orderItemList = new List();

            TExecuteReaderCmd(sqlCmd, TGenerateOrderItemListFromReader, ref orderItemList);

            return orderItemList;
        }
        public List GetOrdersByID(int TextId, int UserType,string sortParameter)
        {
            SqlCommand sqlCmd = new SqlCommand();

            AddParamToSQLCmd(sqlCmd, "@TextID", SqlDbType.Int, 0, ParameterDirection.Input, TextId);
            AddParamToSQLCmd(sqlCmd, "@UserType", SqlDbType.Int, 0, ParameterDirection.Input, UserType);
            AddParamToSQLCmd(sqlCmd, "@ColumnName", SqlDbType.Char, 50, ParameterDirection.Input, sortParameter);

            SetCommandType(sqlCmd, CommandType.StoredProcedure, SP_ORDERS_GET2);

            List orderItemList = new List();

            TExecuteReaderCmd(sqlCmd, TGenerateOrderItemListFromReader, ref orderItemList);

            return orderItemList;
        }
    }
}

using System;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
using .AIA.Common;
using System.Collections;
using System.Collections.Specialized;
using System.Collections.Generic;

namespace .AIA.DataAccessLayer
{
    public class DataAccess
    {
        protected string ConnectionString = Settings.ConnectionString;
       
        /*** DELEGATE ***/
        protected delegate void TGenerateListFromReader(SqlDataReader returnData, ref List tempList);

        /*****************************  BASE CLASS IMPLEMENTATION *****************************/

        /*****************************  SQL HELPER METHODS *****************************/
        protected void AddParamToSQLCmd(SqlCommand sqlCmd,
                                      string paramId,
                                      SqlDbType sqlType,
                                      int paramSize,
                                      ParameterDirection paramDirection,
                                      object paramvalue)
        {

            if (sqlCmd == null)
                throw (new ArgumentNullException("sqlCmd"));
            if (paramId == string.Empty)
                throw (new ArgumentOutOfRangeException("paramId"));

            SqlParameter newSqlParam = new SqlParameter();
            newSqlParam.ParameterName = paramId;
            newSqlParam.SqlDbType = sqlType;
            newSqlParam.Direction = paramDirection;

            if (paramSize > 0)
                newSqlParam.Size = paramSize;

            if (paramvalue != null)
                newSqlParam.Value = paramvalue;

            sqlCmd.Parameters.Add(newSqlParam);
        }

        protected int ExecuteScalarCmd(SqlCommand sqlCmd)
        {
            int strOuput = 0;
            if (ConnectionString == string.Empty)
                throw (new ArgumentOutOfRangeException("ConnectionString"));

            if (sqlCmd == null)
                throw (new ArgumentNullException("sqlCmd"));

            using (SqlConnection cn = new SqlConnection(this.ConnectionString))
            {
                sqlCmd.Connection = cn;
                cn.Open();
                sqlCmd.ExecuteScalar();
                strOuput = (int)sqlCmd.Parameters["@ArtWorkId"].Value;
            }
            return strOuput;
        }

        protected void SetCommandType(SqlCommand sqlCmd, CommandType cmdType, string cmdText)
        {
            sqlCmd.CommandType = cmdType;
            sqlCmd.CommandText = cmdText;
        }

        protected void TExecuteReaderCmd(SqlCommand sqlCmd, TGenerateListFromReader gcfr, ref List List)
        {
            if (ConnectionString == string.Empty)
                throw (new ArgumentOutOfRangeException("ConnectionString"));

            if (sqlCmd == null)
                throw (new ArgumentNullException("sqlCmd"));

            using (SqlConnection cn = new SqlConnection(this.ConnectionString))
            {
                sqlCmd.Connection = cn;

                cn.Open();

                gcfr(sqlCmd.ExecuteReader(), ref List);
            }
        }

        /*****************************  GENARATE List HELPER METHODS  *****************************/
    }
}

ErrorLogger

ErrorLogging
Try
          
        Catch ex As Exception
            Dim path As String = HostingEnvironment.ApplicationPhysicalPath
            ErrorLogger.CreateInstance().WriteToErrorLog(path, ex.Message, ex.StackTrace, Convert.ToString(ex.InnerException), "Error in ExecuteInitDatabasePackage")
            Throw New FaultException("Error thrown in ExecuteInitDatabasePackage")
        End Try



Imports System.IO
Imports System.Web

Public Class ErrorLogger
    Implements IDisposable

    Private Sub New()

    End Sub
    'Shared dataOpertaion As New DataOperations()
    'Shared readCnfg As New ReadConfig()
    Private Shared log As ErrorLogger

    Public Shared Function CreateInstance() As ErrorLogger
        If (log Is Nothing) Then
            log = New ErrorLogger
        End If

        Return log
    End Function

    Public Sub WriteToErrorLog(ByVal path As String, ByVal msg As String, _
       ByVal stkTrace As String, ByVal innerException As String, ByVal title As String)
        path = path + "ErrorLog\"

        If Not System.IO.Directory.Exists(path) Then
            System.IO.Directory.CreateDirectory(path)
        End If

        'check the file
        Dim fs As FileStream = New FileStream(path + "errlog.txt", FileMode.OpenOrCreate, FileAccess.ReadWrite)
        Dim s As StreamWriter = New StreamWriter(fs)
        s.Close()
        fs.Close()

        'log it
        Dim fs1 As FileStream = New FileStream(path + "errlog.txt", FileMode.Append, FileAccess.Write)
        Dim s1 As StreamWriter = New StreamWriter(fs1)
        s1.Write("Title: " & title & vbCrLf)
        s1.Write("Message: " & msg & vbCrLf)
        s1.Write("StackTrace: " & stkTrace & vbCrLf)
        s1.Write("InnerException: " & innerException & vbCrLf)
        s1.Write("Date/Time: " & DateTime.Now.ToString() & vbCrLf)
        s1.Write("================================================" & vbCrLf)
        s1.Close()
        fs1.Close()

    End Sub

#Region "IDisposable Support"
    Private disposedValue As Boolean ' To detect redundant calls

    ' IDisposable
    Protected Overridable Sub Dispose(ByVal disposing As Boolean)
        If Not Me.disposedValue Then
            If disposing Then
                ' TODO: dispose managed state (managed objects).
            End If

            ' TODO: free unmanaged resources (unmanaged objects) and override Finalize() below.
            ' TODO: set large fields to null.
        End If
        Me.disposedValue = True
    End Sub

    ' TODO: override Finalize() only if Dispose(ByVal disposing As Boolean) above has code to free unmanaged resources.
    'Protected Overrides Sub Finalize()
    '    ' Do not change this code.  Put cleanup code in Dispose(ByVal disposing As Boolean) above.
    '    Dispose(False)
    '    MyBase.Finalize()
    'End Sub

    ' This code added by Visual Basic to correctly implement the disposable pattern.
    Public Sub Dispose() Implements IDisposable.Dispose
        ' Do not change this code.  Put cleanup code in Dispose(ByVal disposing As Boolean) above.
        Dispose(True)
        GC.SuppressFinalize(Me)
    End Sub
#End Region

End Class

Saturday, June 16, 2012

More on Design Patterns

http://www.oodesign.com/

Factory Pattern

using System;
using System.Collections.Generic;
using System.Reflection;
using Factory2.Autos;

namespace Factory2
{
    ///

    /// A simple auto factory that creates various types of automobiles
    /// based on a key for Type lookup
    ///

    public class AutoFactory
    {
        Dictionary autos;

        public AutoFactory()
        {
            LoadTypesICanReturn();
        }

        public IAuto CreateInstance(string carName)
        {
            Type t = GetTypeToCreate(carName);

            if(t == null)
                return new NullAuto();

            return Activator.CreateInstance(t) as IAuto;
        }

        Type GetTypeToCreate(string carName)
        {
            foreach (var auto in autos)
            {
                if (auto.Key.Contains(carName))
                {
                    return autos[auto.Key];
                }
            }

            return null;
        }

        void LoadTypesICanReturn()
        {
            autos = new Dictionary();

            Type[] typesInThisAssembly = Assembly.GetExecutingAssembly().GetTypes();

            foreach (Type type in typesInThisAssembly)
            {
                if (type.GetInterface(typeof(IAuto).ToString()) != null)
                {
                    autos.Add(type.Name.ToLower(), type);
                }
            }
        }
    }
}

using Factory2.Autos;

namespace Factory2
{
    ///

    /// simple factory
    ///

    class Program
    {
        static void Main(string[] args)
        {
            string carName = args[0];

            AutoFactory factory = new AutoFactory();

            IAuto car = factory.CreateInstance(carName);

            car.TurnOn();
            car.TurnOff();
        }
    }
}


namespace Factory2.Autos
{
    public interface IAuto
    {
        void TurnOn();
        void TurnOff();
    }
}

using System;

namespace Factory2.Autos
{
    public class MiniCooper : IAuto
    {
        public void TurnOn()
        {
            Console.WriteLine("The Mini Cooper is on! 1.6 Liters of brutal force is churning.");
        }

        public void TurnOff()
        {
            Console.WriteLine("The Mini Cooper is has turned off.");
        }
    }
}

namespace Factory2.Autos
{
    public class NullAuto : IAuto
    {
        public void TurnOn()
        {
           
        }

        public void TurnOff()
        {
           
        }
    }
}