Translate

Monday, 22 December 2014

what is the difference between loose coupling and tight coupling in object oriented paradigm?

Tight coupling is when a group of classes are highly dependent on one another.

This scenario arises when a class assumes too many responsibilities, or when one concern is spread over many classes rather than having its own class.

Loose coupling is achieved by means of a design that promotes single-responsibility and separation of concerns.

A loosely-coupled class can be consumed and tested independently of other (concrete) classes.

Interfaces are a powerful tool to use for decoupling. Classes can communicate through interfaces rather than other concrete classes, and any class can be on the other end of that communication simply by implementing the interface.

Example of tight coupling:

class CustomerRepository
{
    private readonly Database database;

    public CustomerRepository(Database database)
    {
        this.database = database;
    }

    public void Add(string CustomerName)
    {
        database.AddRow("Customer", CustomerName);
    }
}

class Database
{
    public void AddRow(string Table, string Value)
    {
    }
}

Example of loose coupling:

class CustomerRepository
{
    private readonly IDatabase database;

    public CustomerRepository(IDatabase database)
    {
        this.database = database;
    }

    public void Add(string CustomerName)
    {
        database.AddRow("Customer", CustomerName);
    }
}

interface IDatabase
{
    void AddRow(string Table, string Value);
}

class Database : IDatabase
{
    public void AddRow(string Table, string Value)
    {
    }
}

Wednesday, 17 December 2014

Class Properties example in C#

Create a reference type called Person.  Populate the Person class with the following properties to store the following information:
  1. First name
  2. Last name
  3. Email address
  4. Date of birth
Add constructors that accept the following parameter lists:
  1. All four parameters
  2. First, Last, Email
  3. First, Last, Date of birth
Add read-only properties that return the following computed information:
  1. Adult - whether or not the person is over 18
  2. Sun sign - the traditional western sun sign of this person
  3. Birthday - whether or not today is the person's birthday

using System;
using System.Collections.Generic;
using System.Text;


namespace TestProperties
{
   class Person
    {
        private String FirstName;
        private string LastName;
        private string Email;
        private DateTime Dob;

        public string SetfirstName
        {
            get
            {
                return FirstName;
            }
            set
            {
                FirstName = value;
            }
        }
        public string SetLastName
        {
            get
            {
                return LastName;
            }
            set
            {
                LastName = value;
            }
        }


        public string SetEmail
        {
            set
            {
                Email = value;
            }
        }
        public DateTime SetDob
        {
            set
            {
                Dob = value;
            }
        }
        public Person(String First, String Last, String email, DateTime DOfB)
        {
            FirstName = First;
            LastName = Last;
            Email = email;
            Dob = DOfB;
        }

        public Person(String First, String Last, String email)
        {
            FirstName = First;
            LastName = Last;
            Email = email;
        }

        public Person(String First, String Last, DateTime DOfB)
        {
            FirstName = First;
            LastName = Last;
            Dob = DOfB;
        }

        public int age(DateTime dtDOB)
        {
            TimeSpan ts = DateTime.Now.Subtract(dtDOB);
            int years = ts.Days / 365;
            return years;

        }

        public string ZodiacSign(DateTime DateOfBirth)
        {
            string returnString = string.Empty;
            string[] dateAndMonth = DateOfBirth.ToLongDateString().Split(new char[] { ',' });
            string[] ckhString = dateAndMonth[1].ToString().Split(new char[] { ' ' });
            if (ckhString[1].ToString() == "March")
            {
                if (Convert.ToInt32(ckhString[2]) <= 20)
                {
                    returnString = "Pisces";
                }
                else
                {
                    returnString = "Aries";
                }
            }
            else if (ckhString[1].ToString() == "April")
            {
                if (Convert.ToInt32(ckhString[2]) <= 19)
                {
                    returnString = "Aries";
                }
                else
                {
                    returnString = "Taurus";
                }
            }
            return returnString;
        }

        public bool IsAdult
        {
            get
            {
                if (age(this.Dob) >= 18)
                {
                    return true;
                }
                else
                {
                    return false;
                }
            }
        }

        public bool isBirthdayToday
        {
            get
            {
                if ((this.Dob.Day == DateTime.Now.Day) && (this.Dob.Month == DateTime.Now.Month))
                {
                    return true;
                }
                else
                {
                    return false;
                }
            }
        }
        public string GetSunSign
        {
            get
            {
                return (ZodiacSign(this.Dob));
            }
        }
    }
    class Program
    {
        private String getAdultString(Person obj)
        {
            if (obj.IsAdult)
            {
                return obj.SetfirstName + " Is Adult";
            }
            else
            {
                return obj.SetfirstName + " Is not Adult";
            }
        }
        private String getBdayString(Person obj)
        {
            if (obj.isBirthdayToday)
            {
                return "Today Is " + obj.SetfirstName + "'s B'day";
            }
            else
            {
                return "Today Is not " + obj.SetfirstName + "'s B'day";
            }
        }

        private String getSunSignString(Person obj)
        {
            return obj.SetfirstName + "'s Sun sign is " + obj.GetSunSign;
        }

        static void Main(string[] args)
        {
            Person p = new Person("Test1", "Test1", new DateTime(1984, 10, 30));
            Person p1 = new Person("Test2", "Test2", new DateTime(2010, 4, 30));
            Program objProgram = new Program();

            Console.WriteLine(objProgram.getAdultString(p));
            Console.WriteLine(objProgram.getBdayString(p));
            Console.WriteLine(objProgram.getSunSignString(p));
            Console.WriteLine();
            Console.WriteLine(objProgram.getAdultString(p1));
            Console.WriteLine(objProgram.getBdayString(p1));
            Console.WriteLine(objProgram.getSunSignString(p1));
            Console.ReadLine();
        }
    }
}



Tuesday, 16 December 2014

Difference between Const and ReadOnly

Difference between Const and ReadOnly



const in c#

  • You have to initialize const variables while declaration.
  • You cannot reassign a const variable.
  • Compiler evaluates the const variables.
  • The static modifier is not allowed in a constant declaration.
  • A const field of a reference type other than string can only be initialized with null.

Example for const in c#.net


using System;
using System.Text;

namespace ProgramCAll
{

    class ProgramCall
    {
        /*A const field of a reference type other than string
        can only be initialized with null*/
        private const StringBuilder myName = null;

        public static void Main()
        {
            //You have to initilize Const varabiles while declartion
            const int myEmpId = 173524;

            //Valid scenario
            const int myNumber = 10 + 16;

            const string myName = "John";

            // Reassigning a const variable is not allowed.
            //Comment out below code to run the program
            myEmpId = 23456;

            Console.WriteLine(myEmpId);

            Console.Read();
        }
    }
}

readonly in c#

  • readonly fields can be initialized only while declaration or in the constructor. (We can initialize different value or change the value using constructor at runtime)
  • Once  you initialize a readonly field, you cannot reassign it.
  • You can use static modifier for readonly fields
  • readonly modifier can be used with reference types
  • readonly modifier can be used only for instance or static fields, you cannot use readonly keyword for variables in the methods.


Example for readonly modifier in c#.net


using System;
using System.Text;

namespace ProgramCall
{
    class MyClass
    {
        //readonly can only be used with instance or static variables
        public readonly int mynumber = 10;
        public readonly int addnumber = 10 + 15;

        //readonly modifier can be used with static varaibles       
        public static string myEmployer = "ProgramCall.Com";

        //readonly can be used with reference types
        public readonly StringBuilder name = new StringBuilder("John");

        /*  readonly varaible can be intilized in constructor but
             cannot be declared in constructor    */
        public readonly string myName;

        //readonly fields can be initlized in constructor
        public MyClass(string name)
        {
            myName = name;

        }

        private void myMethod()
        {
            /* readonly modifier cannot be used in method level variables
           the below line throws a error. */
            //  readonly int num = 5;
        }

    }

    //main class
    class ProgramCall
    {

        public static void Main()
        {
            MyClass obj = new MyClass("Bill");

            Console.Read();
        }
    }
}

Difference between const and readonly

  • const fields has to be initialized while declaration only, while readonly fields can be initialized at declaration or in the constructor.
  • const variables can declared in methods ,while readonly fields cannot be declared in methods.
  • const fields cannot be used with static modifier, while readonly fields can be used with static modifier.
  • A const field is a compile-time constant, the readonly field can be used for run time constants.

what is the use of static variable in c#?When to use it?why cant i declare the static variable inside Method?


static variable is used to shared the value of it among all instances of the class.

Example:

public  class Variable
{
    public int i = 5;    // public static int i=5;
    public void test()
    {
        i=i+5;
        Console.WriteLine(i);
    }
}


public class Exercise
{
    static void Main()
    {
        Variable var = new Variable();
        var.test();
        Variable var1 = new Variable();
        var1.test();
        Console.ReadKey();
    }
}

Output:  10  10

if declare the varaible as static, Then the output is 10 15

Monday, 15 December 2014

Fault Exception and Fault Contract in WCF Services

Handling wcf service exceptions using fault contracts and data contracts.

WCF gives you enough flexibility to handle exceptions and send required detail to clients. By default WCF sends exception details to clients using SOAP FaultContract. The default FaultContract will allow you to set Message, Reason properties and throw it to clients.

We can easily customize the FaultContract with generic version FaultContract<T> which helps you to provide more appropriate and meaningful details to client with custom error messages and also the flexibility to log or take actions on critical errors.
Why we should use the FaultContract rather than using. Net exceptions?
Exceptions has limitations and security risks.
  1. .Net exception can be used by only CLR supported languages so loosing great WCF feature of interoperability.
  2. Throwing exceptions can provide service implementation and private details to clients.
  3. Exceptions are tightly coupled between clients and service.
1. Service Implementation

namespace FaultContractSampleWCF
{
    // NOTE: You can use the "Rename" command on the
    // "Refactor" menu to change the interface name
    // "IService" in both code and config file together.
    [ServiceContract]
    public interface IService1
    {
        [OperationContract]
        [FaultContract(typeof(ServiceData))]
        ServiceData TestConnection(string strConnectionString);
    }

    // Use a data contract as illustrated in the sample
    // below to add composite types to service operations.
    [DataContract]
    public class ServiceData
    {
        [DataMember]
        public bool Result { get; set; }
        [DataMember]
        public string ErrorMessage { get; set; }
        [DataMember]
        public string ErrorDetails { get; set; }
    }
}

namespace FaultContractSampleWCF
{
    // NOTE: You can use the "Rename" command on the "Refactor"
    // menu to change the class name "Service1" in code, svc and config file together.
    public class Service1 : IService1
    {
        /// <summary>
        /// Implement the TestConnection method.
        /// </summary>
        /// <returns></returns>
        public ServiceData TestConnection(string StrConnectionString)
        {
            ServiceData myServiceData = new ServiceData();
            try
            {
                SqlConnection con = new SqlConnection(StrConnectionString);
                con.Open();
                myServiceData.Result = true;
                con.Close();
                return myServiceData;
            }
            catch (SqlException sqlEx)
            {
                myServiceData.Result = true;
                myServiceData.ErrorMessage = "Connection can not open this " + 
                   "time either connection string is wrong or Sever is down. Try later";
                myServiceData.ErrorDetails = sqlEx.ToString();
                throw new FaultException<ServiceData>(myServiceData, sqlEx.ToString());
            }
            catch (Exception ex)
            {
                myServiceData.Result = false;
                myServiceData.ErrorMessage = "unforeseen error occurred. Please try later.";
                myServiceData.ErrorDetails = ex.ToString();
                throw new FaultException<ServiceData>(myServiceData, ex.ToString());
            }
        }
    }
}

The following endpoint details are automatically added to web.cofig when you create a WCF Service Project.
<services>
  <service name="FaultContractSampleWCF.Service1" 
      behaviorConfiguration="FaultContractSampleWCF.Service1Behavior">
    <!-- Service Endpoints -->
    <endpoint address="" binding="wsHttpBinding" contract="FaultContractSampleWCF.IService1">         
      <identity>
        <dns value="localhost"/>
      </identity>
    </endpoint>
    <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange"/>
  </service>
</services>


<system.serviceModel>
    <behaviors>
      <serviceBehaviors>
        <behavior>
          <!-- To avoid disclosing metadata information, set the value below to false before deployment -->
          <serviceMetadata httpGetEnabled="true"/>
          <!-- To receive exception details in faults for debugging purposes, set the value below to true.
  Set to false before deployment to avoid disclosing exception information -->
          <serviceDebug includeExceptionDetailInFaults="true"/>
        </behavior>
      </serviceBehaviors>
    </behaviors>
    <serviceHostingEnvironment multipleSiteBindingsEnabled="true" />
  </system.serviceModel>

Consuming the Services:

namespace Client_FaultContractSampleWCF
{
    class Program
    {
        static void Main(string[] args)
        {
            try
            {
                Service1Client objServiceClient = new Service1Client();
                //Pass the connection string to the TestConnection Method.
                ServiceData objSeviceData = objServiceClient.TestConnection(
                  @"integrated security=true;data source=localhost;initial catalog=master");
                if (objSeviceData.Result == true)
                    Console.WriteLine("Connection Succeeded");
                Console.ReadLine();
            }
            catch (FaultException<ServiceData> Fex)
            {
                Console.WriteLine("ErrorMessage::" + Fex.Detail.ErrorMessage + Environment.NewLine);
                Console.WriteLine("ErrorDetails::" + Environment.NewLine + Fex.Detail.ErrorDetails);
                Console.ReadLine();
            }
        }
    }
}