Translate

Monday, September 30, 2013

C# Primitive Type Definition



Predefined types (also called built in types) are types specially supported by the C# compiler.

For example int is a predefined tpe. (Note there are other types such as DateTime which are defined in the System Namespace but are not predefined by the C# compiler)



Primitive types are types that are directly supported by the CLR. All the value types excluding decimal are primitive types. You can determine whether a type is primitive using type.isPrimitive

For example

Console.WriteLine(typeof(int).IsPrimitive);//True
Console.WriteLine(typeof(string).IsPrimitive);//False


Monday, September 23, 2013

Create linked server (SQL server) (A very simple way to create linked server)

    EXEC sp_addlinkedserver  
    @server='destinationServerName',
    @srvproduct='',
    @provider='SQLNCLI',
    @datasrc='tcp:destinationServerIpAddress,1433'

EXEC sp_addlinkedsrvlogin
    @useself='FALSE',
    @rmtsrvname=''destinationServerName',
    @rmtuser='username',

    @rmtpassword='password'

Sunday, September 22, 2013

Repository Pattern C# (Simple introduction to repository pattern in C#)

In this article I will present a very simple repository pattern. I am not applying unit of work pattern here to keep the example simple. (In most real world scenarios you would be using unit of work along with Repository pattern).

What is the problem we are trying to solve?

The primary aim of the repository pattern is make your code in the business layer totally independent of the way you access data. It shouldn't matter to the business logic whether the underlying datastore is in SQL server or coming from a webservice. In the business layer I should be purely concerned about implementing the business rules.

In other words, repository pattern is meant for separation of concerns. We want to separate out the business logic and the data access code. This makes the code easier to test and maintain.

How is this done?
We have a class in between the business layer and the database that acts like a collection. The business layer acts on this repository as if its an in memory collection. For example suppose you are writing the business layer and I am writing the repository class. All you would do to add a person to the database is do something like

var priyanka = new Person {Age = 26, Id = 9, Name = "Priyanka"};
var personRepository = new PersonRepository();

personRepository.Add(priyanka);


Notice here that you are acting upon a PersonRepository object. Even if we move from SQL to XML, only the code in the PersonRepository class will change. The code in your business layer remains unchanged.

C# code that implements repository pattern

using System;
using System.Collections.Generic;
using System.Linq;

namespace RepositoryPattern
{
    internal class Program
    {
        private static void Main(string[] args)
        {
            var priyanka = new Person {Age = 26, Id = 9, Name = "Priyanka"};
            var tim = new Person {Age = 40, Id = 10, Name = "Tim"};
            
            var personRepository = new PersonRepository( );

            //Add
            personRepository.Add(priyanka);
            personRepository.Add(tim);

            //Update
            Person victor = personRepository.Find(p => p.Id == 5).Single();
            victor.Age = 66;

            //Remove
            personRepository.Remove(tim);

            foreach (Person person in personRepository.Find(p => p.Id > 0))
            {
                Console.WriteLine("Name:{0} ,Age:{1}", person.Name, person.Age);
            }
        }
    }

    public class Person
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public int Age { get; set; }
    }


    internal interface IPersonRepository
    {
        void Add(Person person);
        void Remove(Person person);
        IEnumerable<Person> Find(Func<Person, bool> predicate);
    }

    public class PersonRepository : IPersonRepository
    {
        private readonly List<Person> _people;

        public PersonRepository()
        {
            _people = FakeDatabase.GetAllPeople();
        }

        public void Add(Person person)
        {
            _people.Add(person);
        }

        public void Remove(Person person)
        {
            _people.Remove(person);
        }


        public IEnumerable<Person> Find(Func<Person, bool> predicate)
        {
            return _people.Where(predicate);
        }
    }

    public class FakeDatabase
    {
        public static List<Person> GetAllPeople()
        {
            var people = new List<Person>
                {
                    new Person {Id = 1, Age = 28, Name = "Tom"},
                    new Person {Id = 2, Age = 32, Name = "Jane"},
                    new Person {Id = 3, Age = 26, Name = "Frieda"},
                    new Person {Id = 4, Age = 54, Name = "John"},
                    new Person {Id = 5, Age = 52, Name = "Victor"},
                };

            return people;
        }
    }
}


Thursday, September 19, 2013

Some Useful Wireshark filters

Wire shark filter to show only the traffic between your computer and the ip address  204.2.196.138 (cnn.com)
ip.addr==204.2.196.138

Show only outgoing traffic to ip address 204.2.196.138
ip.dst==204.2.196.138

Show only incoming traffic from 204.2.196.138
ip.src==204.2.196.138

Show only http traffic
tcp.port==80

Show only outgoing http traffic
tcp.dstport==80

Show only incoming http traffic
tcp.srcport==80

Show only https traffic
tcp.port==443

Show only SQL traffic
tcp.port==1433

Wednesday, September 18, 2013

strategy pattern c# example

What are we trying to solve?
Suppose you have an application where a customer gets a free car wash with every servicing. The kind of car wash he gets is based on how often he comes to the business. First time customers get a bronze wash and regular customers get a silver wash. Maybe in future we might even add a gold wash for extra loyal customers. The aim here is that the CarService class should not have to do switch statements. The reason for that is if we add a switch statement, such as this
switch (carwash)
            {
                case "bronze":
                    Console.WriteLine("bronze wash");
                    break;
                case "silver":
                    Console.WriteLine("silver wash");
                    break;
            }


everytime you add a new type of car wash, you violate the open close principle.

How to solve this?
Have the service class accept an implementation of an interface that perfoms the necessary action, into its constructor. This will be passed into the constructor at runtime.

Strategy Pattern is used when you want to switch algorithm at runtime. In the example below its the method Wash( ). In a real world example, obviously the algorithm would be a lot more complex than a simple Console.WriteLine( ).

The C# Code


using System;

namespace StrategyPattern
{
    internal class Program
    {
        private static void Main(string[] args)
        {
            var newCustomerService = new CarService(new BronzeWash()) {CustomerName = "Bob"};
            var regularCustomerService = new CarService(new SilverWash()) {CustomerName = "Ted"};

            newCustomerService.PerformMaintenance();
            regularCustomerService.PerformMaintenance();
        }
    }

    public class CarService
    {
        private readonly ICarwash _carwash;

        public CarService(ICarwash carwash)
        {
            _carwash = carwash;
        }

        public string CustomerName { get; set; }


        public void PerformMaintenance()
        {
            Console.WriteLine("*******************************");
            Console.WriteLine("Servicing {0}", CustomerName);
            Console.WriteLine("Oil Change");
            Console.WriteLine("Tire Pressure check");
            _carwash.Wash();
            Console.WriteLine("*******************************");
        }
    }

    public interface ICarwash
    {
        void Wash();
    }

    public class BronzeWash : ICarwash
    {
        public void Wash()
        {
            Console.WriteLine("Bronze wash");
        }
    }

    public class SilverWash : ICarwash
    {
        public void Wash()
        {
            Console.WriteLine("Silver wash");
        }
    }
}


Output:

visual studio location in file system

The file devenv.exe (which launches Visual Studio) can be found at

VS 2008:
c:\Program Files (x86)\Microsoft Visual Studio 9.0\Common7\IDE\devenv.exe

VS 2010:
c:\Program Files (x86)\Microsoft Visual Studio 10.0\Common7\IDE\devenv.exe

VS 2012:
c:\Program Files (x86)\Microsoft Visual Studio 11.0\Common7\IDE\devenv.exe

Tuesday, September 17, 2013

composite pattern c# simple example

What are we trying to solve?
Suppose that there is an email group, and there are groups underneath it that have their own groups (as shown below). If you are given a group, You should be able to traverse through the tree and find all the people in it and send them emails.  



This is an ideal case for composite pattern. Composite pattern is applied where you want to treat every node in the tree in the same way. If a group of Super People is handed to you, you should be able to do something like groupOfSuperPeople.SendMail() and emails should go out to all people in that group.

How do we solve this?
The idea here is to have the "leaf" of the tree and the node both implement the same interface. The implementation in the node will call the implementation of the nodes beneath it. This will continue until the leaf is reached. The leaf's implementation of this interface will actually send out the email.  

The C# code that applies composite pattern to solve this problem
using System;
using System.Collections.Generic;

namespace ConsoleApplication1
{
internal class Program
{
    private static void Main(string[] args)
    {
        var adam = new Person
            {
                Name = "Adam",
                EmailAddress = "Adam@dotnetanalysis.com"
            };
        var eve = new Person
            {
                Name = "Eve",
                EmailAddress = "Eve@dotnetanalysis.com"
            };
        var joker = new Person
            {
                Name = "Joker",
                EmailAddress = "Joker@dotnetanalysis.com"
            };
        var skeletor = new Person
            {
                Name = "Skeletor",
                EmailAddress = "Skeletor@dotnetanalysis.com"
            };
        var batMan = new Person
            {
                Name = "BatMan",
                EmailAddress = "BatMan@dotnetanalysis.com"
            };
        var ironMan = new Person
            {
                Name = "IronMan",
                EmailAddress = "IronMan@dotnetanalysis.com"
            };

        var parentGroup = new Group {Name = "Parent"};
        var groupPeople = new Group {Name = "People"};
        var groupSuper = new Group {Name = "Super"};
        var groupSuperHeros = new Group {Name = "SuperHeroes"};
        var groupSuperVillians = new Group {Name = "SuperVillians"};

        groupPeople.Add(adam);
        groupPeople.Add(eve);

        groupSuperHeros.Add(batMan);
        groupSuperHeros.Add(ironMan);

        groupSuperVillians.Add(joker);
        groupSuperVillians.Add(skeletor);

        groupSuper.Add(groupSuperHeros);
        groupSuper.Add(groupSuperVillians);

           
        parentGroup.Add(groupPeople);
        parentGroup.Add(groupSuper);

        parentGroup.SendMail();
    }
}

public interface ISendMail
{
    void SendMail();
}

public class Person : ISendMail
{
    public string Name { get; set; }
    public string EmailAddress { get; set; }

    public void SendMail()
    {
        Console.WriteLine("Sending email to {0}", EmailAddress);
    }
}


public class Group : ISendMail
{
    private readonly List<ISendMail> sendMailImplementations;

    public Group()
    {
        sendMailImplementations = new List<ISendMail>();
    }

    public string Name { get; set; }

    public void SendMail()
    {
        Console.WriteLine("Processing Group " + Name);
        foreach (ISendMail sendMailImplementation in sendMailImplementations)
        {
            sendMailImplementation.SendMail();
        }
    }

    public void Add(ISendMail sendMail)
    {
        sendMailImplementations.Add(sendMail);
    }

    public void Remove(ISendMail sendMail)
    {
        sendMailImplementations.Remove(sendMail);
    }
}
}


Output:


Thursday, September 12, 2013

Dynamic sql output variable

DECLARE @ParmDefinition NVARCHAR(500) 
DECLARE @count INT 

SET @ParmDefinition='@count int output' 

EXECUTE sp_executesql 
  N'select @count=count(*) from persons', 
  @ParmDefinition, 
  @count=@count output 

SELECT @count 

Wednesday, September 11, 2013

c# create excel file (Simple beginner's example)

In this example I will read from a table in SQL server and write that into an Excel 2007 file. I will use EPPlus version 3.1 library to create and write into the Excel file.  To follow this example, add a reference to EPPlus.dll that comes with the download of  EPPlus version 3.1.

Create a table called ExcelUsers in your sql database which has three columns

CREATE TABLE [dbo].[ExcelUsers](
      [FirstName] [varchar](50) NULL,
      [LastName] [varchar](50) NULL,
      [Age] [int] NULL

) 

and add some data into that table



















using System.Collections.Generic;
using System.Data.SqlClient;
using System.IO;
using OfficeOpenXml;

namespace CreateExcelFromDataTable
{
    public class ExcelUser
    {
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public int Age { get; set; }
    }

    internal class Program
    {
        private static void Main(string[] args)
        {
            string fileLocation = @"C:\Play\newExcelFile.xlsx";
            var users = new List<ExcelUser>();

            /*Read data from Database*/
            var conn =
                new SqlConnection(
                    @"data source=MyServer;initial catalog=MyDatabase;persist security info=True;Integrated Security=SSPI;");
            var cmd = new SqlCommand(@"SELECT * FROM [MyDatabase].[dbo].[ExcelUsers]", conn);
            using (conn)
            {
                conn.Open();
                SqlDataReader reader = cmd.ExecuteReader();

                while (reader.Read())
                {
                    users.Add(new ExcelUser
                        {
                            FirstName = reader["FirstName"].ToString(),
                            LastName = reader["LastName"].ToString(),
                            Age = int.Parse(reader["Age"].ToString())
                        });
                }
                reader.Close();
            }


            /*Write to excel*/
            var excelFile = new FileInfo(fileLocation);

            using (var package = new ExcelPackage(excelFile))
            {
                //Add a worksheet
                ExcelWorksheet ws = package.Workbook.Worksheets.Add("Users");

                ExcelWorkbook workBook = package.Workbook;

                //Headers
                ws.Cells["B1"].Value = "First Name";
                ws.Cells["C1"].Value = "Last Name";
                ws.Cells["D1"].Value = "Age";
                ws.Cells["B1:D1"].Style.Font.Bold = true;

                int i = 2;
                foreach (ExcelUser excelUser in users)
                {
                    ws.Cells["B" + i.ToString()].Value = excelUser.FirstName;
                    ws.Cells["C" + i.ToString()].Value = excelUser.LastName;
                    ws.Cells["D" + i.ToString()].Value = excelUser.Age;
                    i++;
                }
                package.Save();
            }
        }
    }

}

When you run this code a new excel file gets created at C:\Play.