Thursday, October 1, 2009

Simple File watcher using FileSystemWatcher in C#

static void Main(string[] args)
        {
            FileSystemWatcher fs = new FileSystemWatcher();
            fs.Path = @"D:\AAS\";
            fs.NotifyFilter = NotifyFilters.FileName | NotifyFilters.DirectoryName;
            fs.Created += new FileSystemEventHandler(fs_Changed);
            fs.Changed += new FileSystemEventHandler(fs_Changed);
            fs.EnableRaisingEvents = true;
            Console.ReadKey();
        }

        static void fs_Changed(object sender, FileSystemEventArgs e)
        {
            Console.WriteLine(e.FullPath);
            File.Delete(e.FullPath);
        }

Events and Delegates using C#


Delegate, Enum and Event Arguments:


public delegate void TimeSheetRejectedDelegate(TimeSheetEventArgs e);
    public enum Status
    {
        New = 0,
        Saved = 1,
        Submitted = 2,
        Approved = 3,
        Rejected = 4
    }
    public class TimeSheetEventArgs : EventArgs
    {
        long _timesheetId = 0;
        DateTime _timesheetDate = default(DateTime);
        Status _status = 0;
        string _message = string.Empty;

        public long TimeSheetId
        {
            get { return _timesheetId; }
        }

        public DateTime TimeSheetDate
        {
            get { return TimeSheetDate; }
        }

        public Status TimeSheetStatus
        {
            get { return _status; }
        }

        public string Message
        {
            get { return _message; }
        }

        public TimeSheetEventArgs(long timesheetId, DateTime timesheetDate, Status status, string MessageText)
        {
            this._timesheetId = timesheetId;
            this._timesheetDate = timesheetDate;
            this._status = status;
            this._message = MessageText;
        }
      
    }



Business Entity with Event:


public class TimeSheet
    {
        long _timesheetId = 0;
        DateTime _timesheetDate = default(DateTime);
        Status _status = 0;
       
        public event TimeSheetRejectedDelegate TimeSheetRejected;
               
        public long TimeSheetId
        {
            get { return _timesheetId; }
        }

        public DateTime TimeSheetDate
        {
            get { return TimeSheetDate; }
        }

        public Status TimeSheetStatus
        {
            get { return _status; }
        }

        public void AddTimeSheet(long timesheetId, DateTime timesheetDate, Status status)
        {
            this._timesheetId = timesheetId;
            this._timesheetDate = timesheetDate;
            this._status = status;
            if (status == Status.Rejected)
                DispatchTimeSheetRejectedEvent("Timesheet is added with Rejected Status");
        }

        public void ChangeTimeSheetStatus(long timesheetId, Status status)
        {
            if (status == Status.Rejected)
                DispatchTimeSheetRejectedEvent("Timesheet is updated with Rejected Status");
        }

        void DispatchTimeSheetRejectedEvent(string MessageText)
        {
            if (TimeSheetRejected != null)
            {
                TimeSheetRejected(new TimeSheetEventArgs(_timesheetId, _timesheetDate, _status,
                    MessageText));
            }
        }

       
    }



Invoking Point:


TimeSheet time1 = new TimeSheet();
            time1.TimeSheetRejected += new TimeSheetRejectedDelegate(time1_TimeSheetRejected);
            time1.AddTimeSheet(1, DateTime.Now,Status.New);
            time1.ChangeTimeSheetStatus(1, Status.Rejected);
            time1.AddTimeSheet(2, DateTime.Now, Status.Rejected);
            Console.ReadKey();

Wednesday, September 30, 2009

Search a text in tables using SQL Query

CREATE PROC FindAllTables
(
    @SearchStr nvarchar(100)
)
AS
BEGIN

   

    CREATE TABLE #Results (ColumnName nvarchar(370), ColumnValue nvarchar(3630))

    SET NOCOUNT ON

    DECLARE @TableName nvarchar(256), @ColumnName nvarchar(128), @SearchStr2 nvarchar(110)
    SET  @TableName = ''
    SET @SearchStr2 = QUOTENAME('%' + @SearchStr + '%','''')

    WHILE @TableName IS NOT NULL
    BEGIN
        SET @ColumnName = ''
        SET @TableName =
        (
            SELECT MIN(QUOTENAME(TABLE_SCHEMA) + '.' + QUOTENAME(TABLE_NAME))
            FROM     INFORMATION_SCHEMA.TABLES
            WHERE         TABLE_TYPE = 'BASE TABLE'
                AND    QUOTENAME(TABLE_SCHEMA) + '.' + QUOTENAME(TABLE_NAME) > @TableName
                AND    OBJECTPROPERTY(
                        OBJECT_ID(
                            QUOTENAME(TABLE_SCHEMA) + '.' + QUOTENAME(TABLE_NAME)
                             ), 'IsMSShipped'
                               ) = 0
        )

        WHILE (@TableName IS NOT NULL) AND (@ColumnName IS NOT NULL)
        BEGIN
            SET @ColumnName =
            (
                SELECT MIN(QUOTENAME(COLUMN_NAME))
                FROM     INFORMATION_SCHEMA.COLUMNS
                WHERE         TABLE_SCHEMA    = PARSENAME(@TableName, 2)
                    AND    TABLE_NAME    = PARSENAME(@TableName, 1)
                    AND    DATA_TYPE IN ('char', 'varchar', 'nchar', 'nvarchar')
                    AND    QUOTENAME(COLUMN_NAME) > @ColumnName
            )
   
            IF @ColumnName IS NOT NULL
            BEGIN
                INSERT INTO #Results
                EXEC
                (
                    'SELECT ''' + @TableName + '.' + @ColumnName + ''', LEFT(' + @ColumnName + ', 3630)
                    FROM ' + @TableName + ' (NOLOCK) ' +
                    ' WHERE ' + @ColumnName + ' LIKE ' + @SearchStr2
                )
            END
        END   
    END

    SELECT ColumnName, ColumnValue FROM #Results
END



GO


--exec FindAllTables 'activitylog'

Sample StyleCop custom rules


Methods should not have more then 200 lines of code:


private void MethodShouldNotHaveMoreThanTwoHundredLines(CsElement element, CsElement parentElement)
        {
            if ((!element.Generated && (element.Declaration != null)) && (element.Declaration.Name != null))
            {
                switch (element.ElementType)
                {
                    case ElementType.Method:
                        //Checking 203 line as first line for method declaration and two lines for opening and closing parenthesis '{','}'
                        if (element.Location.LineSpan > 203)
                        {
                            base.AddViolation(element, "MethodShouldNotHaveMoreThanTwoHundredLines");
                        }
                        break;
                }
            }

        }



Prefix Private variables with underscore:


private void PrefixPrivateVariableNameWithUnderScore(CsElement element, CsElement parentElement)
        {
            // Flag a violation if the instance variables are not prefixed with an underscore.
            if (!element.Generated && element.ElementType == ElementType.Field && element.ActualAccess == AccessModifierType.Private &&
                 element.Declaration.Name.ToCharArray()[0] != '_')
            {
                //If field type is "const" than Pascal casing rule is applicable on it.
                if (((Field)element).Const) return;

                base.AddViolation(element, "PrefixPrivateVariableNameWithUnderScore");
            }
            else if (!element.Generated && element.ElementType == ElementType.Field && element.ActualAccess == AccessModifierType.Private
                && CheckCase(element.Declaration.Name.Substring(1), false))
            {
                base.AddViolation(element, "PrefixPrivateVariableNameWithUnderScore");
            }

        }



Avoid specifying type for Enum:


private void AvoidSpecifyingEnumType(CsElement element, CsElement parentElement)
        {
            if (element.ElementType == ElementType.Enum)
            {
                Microsoft.StyleCop.CSharp.Enum enm = (Microsoft.StyleCop.CSharp.Enum)element;
                if (enm.BaseType != null)
                {
                    base.AddViolation(element, "AvoidSpecifyingEnumType", new object[0]);
                }
            }
        }



Camel casing for local variable names and method arguments:


private void CamelCasingForMethodArgumentsAndLocalVariable(CsElement element, CsElement parentElement)
        {
            if (element.ElementType == ElementType.Method)
            {
                foreach (Variable tempVariable in element.Variables)
                {
                    //If argument type is 'EventArgs' allow non-Camel case variable name also.
                    if (!tempVariable.Type.Text.ToLower().EndsWith("EventArgs".ToLower()))
                    {
                        if (CheckFieldUnderscores(tempVariable.Name) || CheckCase(tempVariable.Name, false))
                        {
                            base.AddViolation(element, tempVariable.Location.LineNumber, "CamelCasingForMethodArgumentsAndLocalVariable");

                        }
                    }
                }
            }


        }



Avoid abbrivated character variable names, such as i, num, tmp:


private void AvoidAbbrivatedCharacterVariableNames(CsElement element, CsElement parentElement)
        {
            if (element.ElementType == ElementType.Field)
            {
                if (element.Declaration.Name.Length <= 3)
                    base.AddViolation(element, "AvoidAbbrivatedCharacterVariableNames", new object[0]);
            }
            if (element.ElementType == ElementType.Method)
            {
                foreach (Variable elem in element.Variables)
                {
                    if (!elem.Type.Text.ToLower().EndsWith("EventArgs".ToLower()))
                    {
                        if (elem.Name.Length <= 3)
                            base.AddViolation(element, elem.Location.LineNumber, "AvoidAbbrivatedCharacterVariableNames", new object[0]);
                    }
                }
            }   
        }



Using directive inside namespace:


private void UsingDirectiveOutSideOfNameSpace(CsElement element, CsElement parentElement)
        {
            if (!element.Generated && (element.ElementType == ElementType.UsingDirective))
            {
                // CsElement parentElement = element.ParentElement;
                if ((parentElement != null) && (parentElement.ElementType == ElementType.Namespace))
                {

                    AddViolation(element, "UsingDirectiveShouldOutSideOfNameSpace");

                }
            }
        }

XML Transformation using XSLT


public static XmlElement Transfomer(string xsltFilePath, XmlDocument bericht)
        {
            XslCompiledTransform transformer = new XslCompiledTransform();
            XsltSettings xsltSettings = new XsltSettings(false, true);
            transformer.Load(xsltFilePath, xsltSettings, new XmlUrlResolver());



            XmlDocument transformedMessage = new XmlDocument();

            using (MemoryStream memoryStream = new MemoryStream())
            {
                XmlWriterSettings writerSettings = new XmlWriterSettings();
                writerSettings.Indent = true;
                writerSettings.IndentChars = "\t";
                writerSettings.Encoding = System.Text.Encoding.UTF8;
                writerSettings.ConformanceLevel = ConformanceLevel.Fragment;
                writerSettings.OmitXmlDeclaration = true;

                XmlWriter writer = XmlWriter.Create(memoryStream, writerSettings);

                transformer.Transform(bericht, writer);
                writer.Flush();
                memoryStream.Position = 0;
                transformedMessage.Load(memoryStream);
            }

            return transformedMessage.DocumentElement;
        }

Structural Pattern - Facade


Definition:
Provide a unified interface to a set of interfaces in a subsystem. Façade defines a higher-level interface that makes the subsystem easier to use. 

UML Diagram:  











Sample Code:
public sealed class Facade
    {
        SubSystem1 _subSystem1 = default(SubSystem1);
        SubSystem2 _subSystem2 = default(SubSystem2);
        SubSystem3 _subSystem3 = default(SubSystem3);

        public Facade()
        {
            _subSystem1 = new SubSystem1();
            _subSystem2 = new SubSystem2();
            _subSystem3 = new SubSystem3();
        }

        public void Method1()
        {
            _subSystem3.Method1();
            _subSystem1.Action1();
            _subSystem2.Action1();
        }

        public void Method2()
        {
            _subSystem1.Action2();
            _subSystem2.Action1();
            _subSystem2.Action2();
        }
    }

    public class SubSystem1
    {
        public void Action1()
        {
            Console.WriteLine("SubSystem1 -> Action1 called");
        }

        public void Action2()
        {
            Console.WriteLine("SubSystem1 -> Action2 called");
        }
    }
    public class SubSystem2
    {
        public void Action1()
        {
            Console.WriteLine("SubSystem2 -> Action1 called");
        }

        public void Action2()
        {
            Console.WriteLine("SubSystem2 -> Action2 called");
        }
    }

    public class SubSystem3
    {
        public void Method1()
        {
            Console.WriteLine("SubSystem3 -> Action1 called");
        }
    }

Tuesday, September 29, 2009

Creational Pattern - Abstract Factory

Definition:
An abstract factory provides an interface for creating families of related objects without specifying their concrete classes. Sometimes one wants to construct an instance of one of a suite of classes, deciding between the classes at the time of instantiation. In order to avoid duplicating the decision making everywhere an instance is created, we need a mechanism for creating instances of related classes without necessarily knowing which will be instantiated.

UML Diagram:










Sample Code:


Enums & Factories:


    public enum DeviceQuality
    {
        LowQuality = 1,
        AverageQuality = 2,
        GoodQuality = 3
    }
    public enum Device
    {
        CDPlayer = 1,
        DVDPlayer = 2,
        CassettePlayer = 3
    }
    public static class AVDeviceFactory
    {
        static IAVDevice _device = default(IAVDevice);
        public static IAVDevice GetFactory(Device device)
        {
           
            switch (device)
            {
                case Device.CDPlayer:
                    _device = new CDPlayer();
                    break;
            }
            return _device;
        }
    }

    public static class AudioDeviceFactory
    {
        static IAudioDevice _audioDevice = default(IAudioDevice);
        public static IAudioDevice GetFactory(DeviceQuality quality)
        {
           
            switch (quality)
            {
                case DeviceQuality.GoodQuality:
                    _audioDevice = new GoodQualityAudioDevice();
                    break;
            }
            return _audioDevice;
        }
    }

    public static class VideoDeviceFactory
    {
        static IVideoDevice _videoDevice = default(IVideoDevice);
        public static IVideoDevice GetFactory(DeviceQuality quality)
        {
           
            switch (quality)
            {
                case DeviceQuality.GoodQuality:
                    _videoDevice =  new GoodQualityVideoDevice();
                    break;
            }
            return _videoDevice;
        }
    }



Interfaces and Classes:


    public abstract class IAVDevice
    {
        protected IAudioDevice _audioDevice = default(IAudioDevice);
        protected IVideoDevice _videoDevice = default(IVideoDevice);

        public abstract IAudioDevice AudioDevice
        {
            get;
          
        }

        public abstract IVideoDevice VideoDevice
        {
            get;
           
        }
    }

    public interface IAudioDevice
    {
        int GetSoundQuality();
    }
    public interface IVideoDevice
    {
        int GetVideoQuality();
    }

    public sealed class GoodQualityAudioDevice : IAudioDevice
    {
        public int GetSoundQuality()
        {
            return 1;
        }
    }

    public sealed class GoodQualityVideoDevice : IVideoDevice
    {
        public int GetVideoQuality()
        {
            return 1;
        }
    }

    public sealed class CDPlayer : IAVDevice
    {
        public override IAudioDevice AudioDevice
        {
            get
            {
                _audioDevice = AudioDeviceFactory.GetFactory(DeviceQuality.GoodQuality);
                return _audioDevice;
            }
        }
        public override IVideoDevice VideoDevice
        {
            get
            {
                _videoDevice = VideoDeviceFactory.GetFactory(DeviceQuality.GoodQuality);
                return _videoDevice;
            }
        }
    }
}

SQL Trigger to capture all the columns that are getting updated while UPDATE

CREATE TABLE [dbo].[Table1](
    [id] [int] NOT NULL,
    [ColumnA] [varchar](50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL,
    [namechanged] [int] NULL
) ON [PRIMARY]





ALTER TRIGGER [table1_update] ON [dbo].[Table1]
FOR  UPDATE
AS begin
DECLARE @ColID INT
DECLARE @Cols VARCHAR(8000)
SET @Cols = SPACE(0)
SET @ColID = 1
WHILE @ColID <= (SELECT COUNT(*)
                  FROM INFORMATION_SCHEMA.COLUMNS
                 WHERE TABLE_NAME = 'Table1')
BEGIN
IF (SUBSTRING(COLUMNS_UPDATED(),(@ColID - 1) / 8 + 1, 1))  &
               POWER(2, (@ColID - 1) % 8) =
               POWER(2, (@ColID - 1) % 8)
   SELECT @Cols = @Cols + COLUMN_NAME + ','
                 FROM INFORMATION_SCHEMA.COLUMNS
                 WHERE TABLE_NAME = 'Table1' AND ORDINAL_POSITION = @ColID

   SET @ColID = @ColID + 1
END
PRINT 'Updated columns are :' + @Cols
END

SQL Trigger to capture OLD and NEW values while updating in TABLE

CREATE TABLE [dbo].[Table1](
    [id] [int] NOT NULL,
    [ColumnA] [varchar](50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL,
    [namechanged] [int] NULL
) ON [PRIMARY]

GO

CREATE TRIGGER [table1_update] ON [dbo].[Table1]
FOR  UPDATE
AS begin
  update table1 set table1.namechanged = table1.namechanged + 1
  from inserted i, deleted d
  where i.[ColumnA] <> d.[ColumnA] and i.[id] = d.[id] and table1.[id] = i.[id]
end

Code to traverse TreeView and generate the possible paths using C#


Here is the sample code for traversing the TreeView control and generating the possible paths


private void btnGeneratePathsFile_Click(object sender, EventArgs e)
        {
            foreach (TreeNode _rootNode in tvPath.Nodes)
            {
                TreeNode leafNode = FindLeafNode(_rootNode);
                //Result.Add(leafNode.FullPath.Replace("\\", " "));
            }
            System.IO.StreamWriter myFile = new System.IO.StreamWriter("c:\\output.txt");
            foreach (string strVal in Result)
            {
                myFile.WriteLine(strVal);
            }
            myFile.Close();

        }



TreeNode FindLeafNode(TreeNode RootNode)
        {
            TreeNode leafNode = default(TreeNode);
            leafNode = RootNode;
            foreach (TreeNode subNode in RootNode.Nodes)
            {
                if (subNode.Nodes.Count > 0)
                    leafNode = FindLeafNode(subNode);
                else
                    Result.Add(subNode.FullPath.Replace("\\", " "));
            }
            return leafNode;
        }

Using VSTO to access the CustomXML of the word document file

Here is the code for accessing the CustomXML file of the word document file


foreach (System.IO.Packaging.PackageRelationship relationship in myPackage.GetRelationshipsByType("http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument"))
            {
                Uri documentUri = PackUriHelper.ResolvePartUri(new Uri("/", UriKind.Relative), relationship.TargetUri);
                documentPart = myPackage.GetPart(documentUri);
              
                foreach (PackageRelationship objPckRel in documentPart.GetRelationshipsByType("http://schemas.openxmlformats.org/officeDocument/2006/relationships/customXml"))
                {
                    partUri = PackUriHelper.ResolvePartUri(objPckRel.SourceUri ,objPckRel.TargetUri);
                    objPackPart = myPackage.GetPart(partUri);
                    doc = new XmlDocument();
                    doc.Load(objPackPart.GetStream());
                    try
                    {
                       objNode = doc.SelectSingleNode("/root[1]/ProjectData[1]");
                      string strXML = objNode.OuterXml;
                      break;

                    }
                    catch (Exception ex)
                    {
                        //do nothing
                    }
                }
            }   

Sunday, September 27, 2009

Simple code to convert ASPX page to ASPX User Control

Here is the simple code to convert ASPX page to ASPX user control


public class ConvertPageToUserControl
    {
        string _pageFileName = string.Empty;
        string _pagePath = string.Empty;
        StreamReader _pageRader = default(StreamReader);
        StreamWriter _ucWriter = default(StreamWriter);
       
        public string PageFileName
        {
            get
            { return _pageFileName; }
            set
            { _pageFileName = value; }
        }

        public string PageFilePath
        {
            get
            { return _pagePath; }
            set
            { _pagePath = value; }
        }

        string PageFile
        {
            get { return Path.Combine(_pagePath,_pageFileName); }
        }
        string UserControlName
        {
            get { return string.Format("{0}.ascx", _pageFileName.Split(".".ToCharArray())[0]); }
        }

        string UserControlFile
        {
            get { return Path.Combine(_pagePath, UserControlName); }
        }

        public void Convert()
        {
           
            ReadPageDoc();
            GetUCDoc();
            string _lineText = _pageRader.ReadLine();

            while (!_pageRader.EndOfStream)
            {
               
                if (_lineText.ToLower().IndexOf("<html") > -1 ||
                    (_lineText.ToLower().IndexOf("<body") > -1) ||
                    (_lineText.ToLower().IndexOf("<head") > -1) ||
                    (_lineText.ToLower().IndexOf("<title") > -1) ||
                    (_lineText.ToLower().IndexOf("<form") > -1) ||
                    _lineText.ToLower().IndexOf("</html") > -1 ||
                    (_lineText.ToLower().IndexOf("</body") > -1) ||
                    (_lineText.ToLower().IndexOf("</head") > -1) ||
                    (_lineText.ToLower().IndexOf("</title") > -1) ||
                    (_lineText.ToLower().IndexOf("</form") > -1) ||
                    (_lineText.ToUpper().IndexOf("<!DOCTYPE") > -1))
                {
                    _lineText = _pageRader.ReadLine();
                    continue;
                }
                else if (_lineText.ToLower().IndexOf("@ page") > -1)
                    _lineText = UpdatePageTag(_lineText);
                _ucWriter.WriteLine(_lineText);
                _lineText = _pageRader.ReadLine();
            }
            _ucWriter.Close();
            _pageRader.Close();
            StreamReader _pageCodeBehind = new StreamReader(PageFile + ".cs");
            StreamWriter _ucCodeBehind = new StreamWriter(UserControlFile + ".cs");
            while (!_pageCodeBehind.EndOfStream)
            {
                string LineText = string.Empty;
                LineText = _pageCodeBehind.ReadLine();
                LineText = LineText.Replace("System.Web.UI.Page", "System.Web.UI.UserControl");
                _ucCodeBehind.WriteLine(LineText);
            }
            _pageCodeBehind.Close();
            _ucCodeBehind.Close();
        }
        string UpdatePageTag(string InputLine)
        {
            string OutPutLine = "<%@ Control Language=\"C#\" AutoEventWireup=\"true\" CodeBehind=\"{0}\" Inherits=\"{1}\" %>";
            string CodeBehind = string.Empty;
            string Inherits = string.Empty;
            string TransformedText = InputLine.Replace(" ", "");
            int indexStart = 0;
       
            //getting CodeBehind
            indexStart = TransformedText.IndexOf("CodeBehind=\"");
            indexStart = indexStart + "CodeBehind=\"".Length;
            TransformedText = TransformedText.Substring(indexStart);
            CodeBehind = TransformedText.Split("\"".ToCharArray())[0];
            CodeBehind = CodeBehind.Replace("aspx", "ascx");

            TransformedText = InputLine.Replace(" ", "");
            indexStart = 0;
            //getting Inherits
            indexStart = TransformedText.IndexOf("Inherits=\"");
            indexStart = indexStart + "Inherits=\"".Length;
            TransformedText = TransformedText.Substring(indexStart);
            Inherits = TransformedText.Split("\"".ToCharArray())[0];

            return string.Format(OutPutLine,CodeBehind ,Inherits);
        }
        void GetUCDoc()
        {
            _ucWriter = new StreamWriter(UserControlFile);
        }
        void ReadPageDoc()
        {
            _pageRader = new StreamReader(PageFile);
        }
    }

Architecture - 4 + 1 View Architecture

  • 4+1 is a view model designed by Philippe Kruchten for describing the architecture of software-intensive systems, based on the use of multiple, concurrent views
  • The views are used to describe the system in the viewpoint of different stakeholders, such as end-users, developers and project managers
  • The four views of the model are 
    •  logical 
    • development
    • process and
    • physical view
  • In addition selected use cases or scenarios (CTQ) are utilized to illustrate the architecture

Code Metrics - Maintainability Index

  • This is an index from 0 to 100 indicating the overall maintainability of the member or type or program
  • This index is based on the following metrics,
    •  Halstead Volume (which factors in the number and use of operands and operators),
    • Cyclomatic Complexity
    • Lines of Code
Maintainability Index = 171 - 5.2 * log2 (Halstead Volume) - 0.23 * (Cyclomatic Complexity) - 16.2 * log2 (Lines of Code)

  • A low number indicates code that is complex and hard to maintain
 VSTS2008 has the inbuilt maintainability measuring technique.


Maintainability Definition:

Range
Level
20-100 inclusive
  High Maintainability
10-19 inclusive
  Moderate Maintainability
0-9 inclusive
  Low Maintainability