Sunday, September 11, 2016

authentication in wcf

Authentication in wcf rest service

Steps.

  1. Create Authenticate method which authenticates an user and also returns a token which can be used for next subsequent requests.
  2. Create a login class in business layer which has business logic to validate the user credential against database and generate the token if the credentials are valid
  3. Create a method to validate the token which would come in next subsequent requests



  • Create Authenticate method in *SVC.cs file which takes userId and password as a parameter

//Below method authenticates the user and sends a token for authenticated user which can be used for //next subsequent requests.

public stream Authenticate(string userID, string password) {
 Stream strJSONResponse = null;
 Login Obj = new + 6(); // This is your login class in business layer explained in point #2 below
 //string deviceId = string.Empty   //Optional if you are coding for mobile devices then can be used
 WebHeaderCollection headers = WebOperationContext.Current.IncomingRequest.Headers;
 //WebHeaderCollection  - Namespace | System.net.WebHeaderCollection
 //WebOperationContext - Namespace | System.serviceModel.web.WebOperationContext
 try {
  foreach(string headerName in headers.Allkeys) {
   //If you want retrieve device ID from header
   if (headerName == 'desiredDeviceId') {
    deviceId = headers[headername];
   }
   strJSONResponse = obj.Authenticate(userID, password, deviceId)
   return strJSONResponse;
  }
 }
}



  • Login class in business layer having implementation of Authenticate method


public class Login {
 public stream Authenticate(string usersId, string password, string deviceId) {
   outAuthentication objOutAuthentication = new outAuthentication();
   try {
    objOutAuthenticaton.successFlag = Decimal.One.ToString();
    if (deviceId == String.Empty) {
     objOutAuthenticaton.successMessage = "Device Id Absent";
    } else {
     objOutAuthenticaton.successMessage = "Success";
     bool bIsAuthenticatedUser = false;
     bool bIsActiveUser = false;
     DataTable dtUser = objDAL.GetUserCredentials(usersId);
     if (dtUser != null && dtUser.Rows.count > 0) {
      Decrypt objDecrypt = new clsUtilities.Decrypt();
      if `(userID.ToUpper() == convert.ToString((dtUser.Rows[0][0]).Trim().ToUpper && password == objDecrypt.DecryptString(Convert.ToString(dtUser.Rows[0][1])))
{
bIsAuthenticatedUser = true;
}
bIsAtctiveUser = Convert.ToBoolean(dtUser.Rows[0][2]);
}
}
objOutAuthenticaton.status = bIsAuthenticatedUser == true? Decimal.One.ToString() : Decimal.Zero.ToString();

if(bIsActiveUser)
{
if(bIsAuthenticatedUser)
{
Datatable dt = new DataTable();
dt = objDAL.GetUserDetail(userId)
if ( dt!= null && dt.Rows.count>0)
{
//Below code to send Authenticate key to the calling application so that it can be used for subsequent //request by authorized user. User won't have to provide ID and pwd again and again
objOutAuthenticaton.authKey = GenerateToken(usersId, "AnyStringKey", deviceId, DateTime.UtcNow.Ticks);

//Insert autorization token in session token table
InsertAuthToken(objOutAuthenticaton.authKey,DateTimeUtcNow);
}
}
}
}
}


//Database layer

  • 3. Get user credentials saved in database

public DataTable GetUserCredentials(string strUserId) {
 DataTable dt = new DataTable();
 ConnectionClass objConnection = new ConnectionClass();
 try {
  SqlParameter[] objParams = {
   new SqlParameters("UsersID", SqlDbType.Nvarchar) {
    Value = strUserId
   }
  };
  dt = ExecuteReaderDataTableSP("Login_usp_GetUserCredentials, objParams);
  }
 }

}


  • 4. Generate Token

public static string GenerateToken(string userName, string password, string deviceID, long ticks) {
 string hash = string.Join(":", new string[] {
  userName,
  deviceID,
  ticks,
  ToString()
 });
 string hashLeft = string.Empty;
 string hashRight = string.Empty

 using(HMAC hmac = HMACHA256.Create("HmacSHA256")) {
  hmac.key = Encoding.UTF8.GetBytes(GetHashedPassword(password));
  hmac.computeHash(Encoding.UTF8.GetBytes(hash));
  hashLeft = Convert.ToBase64String(hmac.Hash);
  hashRight = string.Join(":", new string[] {
   userName,
   deviceID,
   ticks.ToString()
  });
 }
 return Convert.ToBase64String(Encoding.UTF8.GetBytes(string.Join(":", hashLeft, hashRight)));
}



5. Insert GeneratedToken into database
public bool InsertAuthToken(string token, DateTime currentDate) {
  ConnectionClass objConnection = new ConnectionClass();
  try {
   SqlParameter[] objParams = {
    new SqlParameters("token", SqlDbType.Nvarchar) {
     Value = token
    } {
     new SqlParameters("currentDate", SqlDbType.Nvarchar) {
      Value = currentDate
     }
    };
    int iCount = objConnection.ExecuteNonQuerySP("usp_InsertAuthToken", objParams);
    return icount > 0 ? true : false;
   }
  }

  • 6. IsTokenValid

Call below method in subsequent requests to verify the token sent by client is valid or not

public static string IsTokenValid(string token, string userId, string dvcId) {
 string message = String.Empty;
 try {
  string key = Encoding.UTF8.GetString(Convert.FromBase64String(token));
  int _expirationMinutes = Convert.ToInt32("20").ToString();
  // Split the parts,
  string[] parts = key.Splt(new char[] {
   ':'
  });
  if (parts.Lenth == 4) {
   string hash = parts[0];
   string username = parts[1];
   string deviceId = parts[2];
   long ticks = parts[3];
   string servicePassword = "AnyStringKey";
   string computedToken = GenerateToken(username, servicePassword, deviceId, ticks);

   if (token == computedToken) {
    string modifiedTime = GetModifiedDts(token); //check expiry date of token
    if (!string.IsNullOrEmpty(modifiedTime)) {
     boll expired = Math.Abs((DateTime.UtcNow - Convert.ToDateTime(modifiedTime)).TotalMinutes) > 20;

     if (expired) {
      message = "Auth Key Expired, please login again";
      //Delete token from session table of database
     } else {
      //update the latest timestamp in database against that token so that session time keep on extending if //attempt is valid
      DateTim currentDate = DateTime.UtcNow;
      //UpdateAuthToken(token,CurrentDate)
      message = "Authentication Key is valid";
     } |


    }
   }

   //Check whether the user name is proper from header
   if (username == userId && deviceId == dvcId) {}
  }
 }
}



Stored Procedures :

1. usp_GetUserCredentials

CREATE PROCEDURE [dbo].[usp_GetUserCredentials] @usersId nVarchar(50)
AS
BEGIN
SELECT U.UsersId,U.Password, U.isActive
FROM [DBO].[users] U
Where U.usersId = @usersId
AND @usersId IS NOT NULL;
END

2. usp_InsertAuthToken

CREATE PROCEDURE [dbo].[usp_InsertAuthToken]
@token nvarchar(max),
@curentDate DateTime
As
BEGIN
Insert INTO [DBO].SESSIONTOKENS] VALUES (ltrim(rtrim(@token, @currentDate)
END

Thursday, August 18, 2016

Log4Net


log4net step by step


1. Install Log4Net either by adding log4Net.dll or by running below command,
  • PM> Install-Package log4net

2. Create XML file inside web application project as below

<? xml version = " 1.0 " ?>
< log4net >
< appender name = " FileAppender " type = " log4net.Appender.RollingFileAppender " >
< param name = " File " value = " D:\LogFile.log " />
< param name = " DatePattern " value = " yyyy.MM.dd " />
< param name = " RollingStyle " value = " Size " />
< param name = " maxSizeRollBackups " value = " 10 " />
< param name = " maximumFileSize " value = " 100KB " />
< layout type = " log4net.Layout.PatternLayout " >
< param name = " ConversionPattern " value = " %date{yyyy-MM-dd HH:mm:ss ffff} [%-3t] %-5p %logger{1}.%method: %message%newline " />
</ layout >
</ appender >
< root >
<!-- OFF, FATAL, ERROR, WARN, DEBUG, INFO, ALL -->
< level value = " ALL " />
< appender-ref ref = " FileAppender " />
</ root >
</ log4net >

Assume that "log4net.xml" is the file name of the above created xml file

3.  Configure above created xml file in web.config
  • In <appsettings> section add below entry
  • <add key = "log4net.config" value = "log4net.xml" />
4. Create Logger.cs in project and add reference of log4net.dll in the project. Mostly this would be in the utility project as we can refer utility project in any of the layer/project.

Using System;

namespace yournamespacename;
public class logger
{
private static log4net.ILog Log {get; set;}
static Logger
{
Log = log4net.LogManager.GetLogger(typeof(Logger));
}

public static void Error (Object message)
{
Log.Error(message);
}

public static void Error (Object message, Exception Ex)
{
Log.Error(message, Ex);
}

public static void Error (Exception Ex)
{
Log.Error(Ex);
bool x = Log.IsErrorEnabled;
}

public static void Info (Object message)
{
Log.Info(message);
}

}

5. Make sure the user (generally Iuser) configured in IIS to access the website has read write access to the Log file. This can be done by right click -> properties -> Security -> Edit -> Add -> select the user and give the permissions.

6. Below is the sample which can be used in catch block
  • Add reference of above project where log4net has to be used
  • Catch block can be as below
Catch (exception ex)
{
Logger.Error(ex);
}

 ====================================================================
If it is not working, follow below changes,

1. Add below line in AssemblyInfo.cs file,
[assembly: log4net.Config.XmlConfigurator(Watch = true)]

2. Add below section in App.config file,

<configSections>

<section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net" />

</configSections>

<log4net>

<appender name="FileAppender" type="log4net.Appender.RollingFileAppender">

<param name="File" value="D:\\PUDLog.log" />

<AppendToFile value="true" />

<param name="DatePattern" value="yyyy.MM.dd" />

<param name="RollingStyle" value="Size" />

<param name="maxSizeRollBackups" value="10" />

<param name="maximumFileSize" value="100KB" />

<layout type="log4net.Layout.PatternLayout">

<param name="ConversionPattern" value="%date{yyyy-MM-dd HH:mm:ss ffff} [%-3t] %-5p %logger{1}.%method: %message%newline" />

</layout>

</appender>

<root>

<!-- OFF, FATAL, ERROR, WARN, DEBUG, INFO, ALL -->

<level value="DEBUG" />

<appender-ref ref="FileAppender" />

</root>

</log4net>

Wednesday, August 3, 2016

Anonymous method in c#

Anonymous method


When to use anonymous methods

  • If we want to use the delegate only inside the same function
  • Reduce overhead of instantiating delegate i.e. performance improvement
E.g.

class program
{
delegate int pointToAddFunction(int n1,int n2);

static void Main (string[] args)
{
//Anonymous method is below
pointToAddFunction ptrObj = delegate
(int n1,int n2)
{
return n1 +n2;
};     //Note semicolon
//Anonymous method ended

int x = ptrObje.Invoice(2,2);
console.writeline(x);
}
}
 

Design patterns c# examples

Singleton Pattern

When we want only one instance of the object to be created and shared between clients (global variables of project)

To achieved/implement Singleton pattern
1. Define the constructor as private. So no instance/object can be created
2. Define instance (variables) & methods as static. This will cause one global instance to be created and shared across.

E.g.

public class clsSingleton
{
public static int intCounter;
private clsSingleTon()
{
//This is private constructor
}
private static void Hits()
{
intCounter++;
}
public static int getTotalHits()
{
return intCounter;
}
}

Client code

clsSingleTon.Hit();  // Everytime counter increments tag by 1

=========================================================================

Factory Pattern

public class clsFactoryInvoice
{
public static IInvoice getInvoice(int intInvoiceType)
{
IInvoice objinv;
if(intInvoiceType == 1)
{
objinv = new clsInvoiceWithHeaders();
}
else if (intInvoiceType == 2)
{
objinv = new clsInvoiceWithoutHeaders();
}
else
{
return null;
}
return objinv;
}
}

public Interface IInvoice
{
void print();
}

public class clsInvoiceWithHeader : IInvoice
{
public void print()
{
console.writeline("Invoice will be printed with Header");
}
}

public class clsInvoiceWithoutHeader : IInvoice
{
public void print()
{
console.writeline("Invoice will be printed without Header");
}
}

client code

class program
{
static void Main (string [] args)
{
int intInvoiceType = 0;
IInvoice objInvoice;
console.writeline("Enter Invoice Type");
intInvoiceType = console.readline();
objInvoice = clsFactoryInvoice.getInvoice(intInvoiceType );
objInvoice .print();
console.Readline();
}
}

Benefits : Client no need to know which all concrete classes available (loosely coupling) client will have object created just by passing parameter
 

Wednesday, July 20, 2016

Shadowing in c#

Shadowing in c#


new keyword explicitly hides member that is inherited from the base class (base class method is hidden or we can say derived class replaces/hides the base method) 

When you hide an inherited member, the derived version of the member replaces the base class version.


* It is an error to use both new and override on the same member, because the two modifier have mutually exclusive meanings. The new modifier creates a new member with the same name and causes the original member to become hidden. The override modifier extends the implementation for an inherited member.

public class BaseC
{
public int x;
public void invoke()
{
}
}

public class DerivedC : BaseC
{
   nenw public void Invoke()
   {
    }
}

Design patterns c#

Design patterns c#

Singleton pattern

When we want only one instance of the object to be created and shared between clients (global variables of project)

To achieve/implement singleton pattern

1. Define the constructor as private, so no instance/object can be created
2. Define instance (variables) and methods as static. This will cause one global instance to be created and shared across.

E.g.

Public class clsSingleton
{
  public static int intCounter;
  private clsSingleton()
    {
       //This is a private constructor
     }

   public static void Hits()
    {
         intCounter++;
     }
    public static int getTotalHits()
     {
        return intCounter;
      }
}

Client Code
clsSingleton.Hit();                 //Everytime counter increments by 1


Factory Pattern

public class clsFactoryInvoice
{
  public static IInvoice getInvoice(int intInvoiceType)
  {
    IInvoice objInv;
    if(intInvoiceType == 1)
    {
      objInv = new clsInvoiceWithHeader();
    }
    else if (intInvoiceType ==2)
    {
        objInv = new clsInvoiceWithoutHeader();
     }
     else
      { return null;}
    return objInv;
  }
}

public interface IInvoice
{
  public void print();
}

public class clsInvoiceWithHeader : IInvoice
{
  public void print()
  {
     console.writelinne("Invoice will be printed with header");
   }
}

public class clsInvoiceWithoutHeader : IInvoice
{
  public void print()
  {
     console.writelinne("Invoice will be printed without header");
   }
}


Benefits : Client no need to know which all concrete classes available (loosely coupled) client will have object created just by passing parameter.

Sunday, July 17, 2016

Assembly

Assembly

Assembly form the fundamental unit of deployment, version control, reuse.
Assembly take the form of an executable (.exe) file or dynamic link library (.dll) file. They provide the CLR with information it needs to be aware of type implementation.
You can think of an assembly as a collection of types and resources that forms a logical unit of functionality and are built to work together.



Assembly Contents
1. Assembly manifest which contains metadata
2. Type metadata
3. MSIL code that implements the type
4. Set of resources

Assemblies have the following properties

  • Assemblies are implementated as .exe or .dll files
  • You can share an assembly between applications by putting in the GAC. Assembly must be strong-named before they can included in GAC
  • Assemblies are only loaded in the memory if they are required. if they are not required they are not loaded
  • You can problematically obtain information about an assembly by using reflection.

Assembly Manifest

Within every assembly is an assembly manifest.
Assembly manifest contains the following

  • The assembly identity (its name & version) make up the assembly for e.g. any other  assemblies you created that your .exe or .dll relies on
  • An assembly reference list - External dependency such as GAC or somewhat like system 32 directory.

Assembly Contents

In general, a static assembly can consists of four elements.
  • The assembly manifest, which contains assembly metadata
  • Type metadata
  • Microsoft Intermediate Language (MSIL) code that implements types
  • A set of resources

Metadata

Metadata is a binary information describing your program that is stored either in a common language runtime portable executable (PE) file or in memory. When you compile your code into PE file, metadata is inserted into one portion of the file and your code is converted to Microsoft  intermediate language (MSIL) and inserted into another portion of the file.
Every type and member that is referential in a module or assembly is described within metadata. When code is executed, the runtime loads metadata into memory and references it to discover information about you code's classes, members , instances and so on.

Language interoperability : Metadata provides all the information required about compiled code for you inherit a class from a PE file written in different language you can created an instance of any class written in any managed language (any language that targets the common language runtime) without worrying about explicit marshaling or using custom interoperabilty code.

MSIL
When compiling to managed code, the compiler translates your source code into MSIL, which is CPU independent set of instruction that can be efficiently converted to native code. Before code can be run, MSIL must be converted to native code, usually by a Just-In-Time (JIT) compiler


Wednesday, July 6, 2016

Types of constructors

Types of constructors

1. Instance Constructor
2. Static Constructor (gets called only once)
3. Private Constructor


Static Constructor

 A static constructor is used to initialize any static data or to perform a particular action that needs to be performed once automatically before the first instance is created or any static members are referenced.

E.G.

Class SimpleClass
{
static readonly long x;
//static constructor is called at most one time
//before any constructor is invoked or member is accessed

Static SimpleClass()
{
x = DateTime.Now.Ticks;
}
}

Important points to note

  • A static constructor does not take access modifier or have parameters
  • A static constructor cannot be called directly
  • Users have no control only when the static constructor is executed in the program
  • A typical use of static constructor is when the class is using a log file and constructor is used to write entries
  • We can have both static constructor and instance constructor in same class

Private Constructor

If a class has one or more private constructor *and no public constructor* other class cannot create instance of this class (expect nested class).
We can have both private & public constructor in same class if parameters are different.

By default constructor is private. If we try to create instance of a class having private constructor, you will get constructor is inaccessible due to its protection level


========================================================================

Unless a class is static, class without constructor are given a public default by c# compiler in order to enable class instantiation.


Moral : A class must have public constructor for creating its object


========================================================================

Copy constructor : c# doesn't provide constructor  for objects, but we can create


E.g.

class Person
{
//Copy constructor
public Person (Person prevPerson)
{
Name = prevPerson.Name;
Age = prevPerson.Age
}


//Below is parameterized constructor public Person (string name, int age)
{
Person P1 = new Person("George", 40);
Person P2 = new Person (P1);
}
}

Sunday, July 3, 2016

Try-Catch

Try-Catch

  1. Generalized exception catch block should be at the end in case of multiple catch block. If we declare generalized catch block at starting then it will give compile time error. Error :                  Already declared in super class
  2. We can have return statement in catch block
  3. We can have break statement in catch block if loop is present inside catch
  4. Finally block can't have return statement
  5. Finally block can have other try-catch block.
  6. Finally block can have break statement inside the loop
  7. If exception occurs in finally, execution will break/stop
  8. Try block should at least  have finally block if catch block is not provided


Nested Try Catch scenario


i. If divide by zero exception encounters in outer try block then outer try block will execute
ii. In case of inner try block exception, inner catch block will execute
iii. If divide by zero exception encounters in inner try block and if we don't have inner catch block specific for divide by zero and if we have outer catch block which specifically handles divide by zero then outer catch block will be executed.

Ref and Out parameters in c#


ref out param in c#


REF OUT
REF must be initialized before it passes to method OUT its not necessary, but after method call it should get initialized
Extra performance cost Faster
The called method can read argument at anytime The called method must initialize the parameter before using it
ref parameters are used to get a value and return a change to that value Out parameters are useed whe you just need to get a secondary return value


==================================================================

REF



Class tryref
{
  public void (ref int i, ref int j)
  {
     j = i*j;

  }
 }


Calling program

Class Program
{
static void main (string[] args)
{
tryref tf = new tryref();
int i = 5;
int j = 10;
console.writeline("The value of i and j before the call : "+i","+j);
tf.mul(ref i, ref j);
console.writeline("The value of i and j after the call : "+i","+j);
}

}

=======================================================================

OUT



class tryout
{
public int mul (int a, out int b)
{
b = a*a;
return b;
}

}

Calling Program

Class Program
{
static void Main(string [] args)
{
tryout to = new tryout();
// passing out parameter j and getting returning value
to.mul(5, out j);
console.writeline("The value of  j is :"+j);
}

}

========================================================================

Why we use ref and out parameters in C#.



Lets say  we call some method and value of variable changes in that method. However as per method functioning we only receive whatever returned by method i.e. for e.g. method returns integer we get integer value.
When we want to capture the changed value which happened in "called" method we use ref/out parameter irrespective of what method is returning.

Constant, Readonly and Static readonly

Constant, Readonly and Static readonly

Constant Readonly Static readonly
cant be changed runtime. Run time constant Global value for all instances of the class. Can be changed only once at runtime.
cant be changed runtime. you can initialize value of variable only once at runtime in a constructor Can be changed only once at runtime.

Wednesday, June 29, 2016

Abstract class VS Interface

abstract class vs interface c#

How to decide in which scenario Abstract class or Interface to be used?

-> When we are sure that design is not going to be changed then we should use interface. Otherwise we should use abstract class wherein we provide some functionality and anticipate multiple versions of your component

For e.g. When we know that there are going to be only 4 gears/Wheels to the care and not 5th one would be added then we choose to have an interface.
In case if there are changes to be done in interface then all the classes implementing it must be changed. Same is not with abstract class till the time we add non-abstract methods.

Static class

Static class

Below are some important point to consider for static classes.
  • Contains only static member (properties also)
  • Can not be instantiated
  • Static class is sealed
  • Can not contain Instance constructor (can contain static constructior)
* Instance constructor used to create & initialize any instance member when we use new to create object hence static class can not have  Instance constructor.

* Difference between sealed and static class is instance creation (sealed can contain static as well as non static)

Abstract class


Abstract class


  • Abstract classes are solely for inheritance
  • We can not create object of abstract class
  • Abstract can not be sealed or static
  • Abstract methods can not be private
  • Abstract methods can not have the body
  • Abstract method can not have the modifier virtual (By default it is virtual)
  • Access modifier of the abstract method should be same in both abstract and derived class
  • Abstract member can not be static
Overview in short
Private (No)
Static (No)
Sealed (No)
Virtual (No, by default virtual)



abstract class c# example



abstract class clsSave
{
    abstract public void Save();
}
class DerivedClass: clsSave
{
    // Area method is required to avoid
    // a compile-time error.
    public override void save()
    {
        //write code to save
    }
    static void Main()
    {
        DerivedClass objD= new DerivedClass();
        Console.WriteLine("Performing Save operation", objD.save());
    }
}

if condition in sql server 2008



if condition in sql

CREATE FUNCTION [dbo.[fnc_ValidateMilageReadings]
(
   @round_id INT,
   @depot_id INT,
)
RETURNS BIT

AS
BEGIN

DECLARE @openMilage NVARCHAR
DECLARE @firstStopMilage NVARCHAR
DECLARE @lastStopMilage NVARCHAR
DECLARE @closeMilage NVARCHAR
DECLARE @returnValue BIT

SET @returnValue = 0

SELECT @openMilage  = openMilage, @firstStopMilage = firstStopMilage, @lastStopMilage = lastStopMilage
FROM Transaction
WHERE roundId = @round_id AND depotId = @depot_id

IF (@closeMilage IS NULL) BEGIN SET @returnValue  = 0 END
ELSE IF (@closeMilage  = 0)  BEGIN SET @returnValue  = 0 END
ELSE IF @openMilage  < firstStopMilage BEGIN SET @returnValue  = 0 END
ELSE IF @firstStopMilage  < @lastStopMilage  BEGIN SET @returnValue  = 0 END
ELSE IF @lastStopMilage  < @closeMilage BEGIN SET @returnValue  = 0 END
ELSE @returnValue  = 1

RETURN @returnValue

END


Tuesday, June 28, 2016

Interfaces


  • We can only have internal access modifier for an interface (if we don't define also by default access modifier is internal for interface)
  • Interface can contain only signature of methods, properties, events or indexers

Decoupling can be Achieved through Interface



Lets say we have accounts class and invoice class. 
Now rather than communicating directly classes to classes (concrete classes), we can put a interface in between and both of these classes communicate via the interfaces

Example

interface IDBInterface
{
   void Update
}

class SQL : IDBInterface
{
  public void Update()
   {
     MessageBox.show("Updating SQL server.....");
   }
}

class Oracle : IDBInterface
 {
   Public void Update()
   {
     MessageBox.show("Updating oracle server...");
   }
}

class CommunicationChannel
{
  public void Update(IDBInterface idb)
  {
    idb.Update();
  }
}

=====================================================================
//Calling class
Class Myclass
{
  public void XYZ()
  {
    IDBInterface idb = new Oracle();
    CommunicationChannel cmc = new CommunicationChannel();
    cmc.Update(idb);
  }

Communication channel class is not directly communicating with concrete classes, it is communicating via interface. We can inject any class to communication channel class and the communication channel class will call the method.


======================================================================



Explicit Interface calling



interface Icontrol

{
  void paint();
}

interface Isurface
{
  void paint();

}

Way1 to call interface

class SampleClass : Icontrol,Isurface
{
  public void paint()
   {
      console.writeline("Hi");

   }
}

Explicit Calling (Way 2) 

class SampleClass : Icontrol,Isurface
{
   void Icontrol.paint()
    {
      console.writeline("IControl.paint");
     }
   void Isurface.paint()
    {
      console.writeline("Isurface.paint");

     }
}

Sunday, June 26, 2016

Four basic principles of OOP

Four major principles of Object-Oriented Programming (OOP)

  1. Data Abstraction
  2. Encapsulation
  3. Inheritance
  4. Polymorphysm


Data Abstraction

  • Any representation of data in which implementation details are hidden. (Showing only what is necessary)
  • Abstraction is a thought process (for e.g. we write design document with high level details such as method name and its return type i.e. we just say CalculateTax() without mentioning the rest of the details)



Encapsulation


  • Ability to provide users a well defined interface to a set of functions which hides internal working (Hide complexity)
  • Encapsulation is implementation side i.e. for e.g. while implementation all things are taken care such as IncomeAmount > 0 etc. which hides complexity while calling/using the method 


Inheritance

:
Inheritance enables you to create new classes that reuse, extend, and modify the behavior that is defined in other classes. The class whose members are inherited is called the base class, and the class that inherits those members is called the derived class. A derived class can have only one direct base class. However, inheritance is transitive. If ClassC is derived from ClassB, and ClassB is derived from ClassA, ClassC inherits the members declared in ClassB and ClassA.
 

Polymorphysm
: Polymorphysm is of two types
    Static and dynamic polymorphysm
  • Static
  • Dynamic

Saturday, June 25, 2016

Value and References types in C#


Value Type and References types in C#





Value Types

All numeric data types. For e.g. int x = 10
Boolean, character and Date
All structures even if their members are reference type
Enums


Reference Types

String (Internally the text is stored as a sequential read-only collection of character objects)
All arrays, even if their elements are value type
Class types such as Form
Delegates
*You must use New operator keyword when you initialize reference type.

Elements that are not Types
Namespaces
Modules
Events
Properties and Procedures
Variables, constants and fields.

In Depth
1. Value Type: A value type stores its contents in a Memory allocated on the stack. When you create a value type, a single space in memory is allocated to store the value and that variable directly holds a value. If you assign it to another variable, the value is copied directly and both the variables work independently. 
*Value type can be created compile time and stored in stack memory, because of this Garbage Collector can’t access Stack
2. Reference Type: Reference Type are used by a reference which holds a reference to a object itself. Because reference types represents the address of the variable rather than data itself, assigning a reference variable to another variable doesn’t copy the data, insteadit creates a second copy of the reference, which refers to the same location of the heap as the original value (Can be marked for garbage collection)

Value type and reference type