Wednesday, June 22, 2016

Cookies ASP.NET

Cookies are the small files that are created on the client's system or client browser memory. Cookies store information in plain text format. most common examples of using a cookie are to store user information, user preferences, password remember option

Disadvantage
  • It stores data in simple text format, so it's not secure at all.
  • There is a size limit for cookies data (4096 bytes / 4KB).
  • The maximum number of cookies allowed is also limited. Most browsers provide limits the number of cookies to 20. If new cookies come, the old ones are discarded. Some browsers support up to 300.
  • We need to configure the browser. Cookies will not work on a high security configuration of the browser.

"Response.Cookies" command is used to create cookies.
"Request.Cookies" command is used to retrieve a cookie value.

Cookie Munging in ASP.NET?
There are some specific reasons to use cookie munging in ASP.NET:
  • Some browsers do not support cookies.
  • Sometimes users disable cookies in the browser.

Impersonate

Impersonation allows the application to run as you (or any other user with different priveledges on the cmoputer), as if you were logged in to the computer running it itself.
When you have an application using forms authentication (FA) the IIS process is running under the credentials of a specific user setup in IIS. 

Example: If user called Bob logged on using FA and and IIS setup to run as Network Service. Bob accesses a page which makes a web service call to another computer, the other computer will see the IIS user and not Bob. You can use impersonation to allow Bob to access the web service as a real Windows user and not Network Service.

Impersonation is disabled. This is the default setting. 

Impersonation enabled. In this instance, ASP.NET impersonates the token passed to it by IIS, which is either an authenticated user or the anonymous Internet user account (IUSR_machinename).

Impersonation enabled for a specific identity. In this instance, ASP.NET impersonates the token generated using an identity specified in the Web.config file.

<identity impersonate="true"
          userName="domain\user" 
          password="password" />

Wednesday, June 8, 2016

String vs. StringBuilder

StringBuilder performance better , won't keep create a new string in every loop.

StringBuilder can be used where more than four or more string concatenations take place.
String to do some manipulation (remove and replace a part from the string)

String
StringBuilder
immutable
mutable
Performance slow because every time will create new instance
Performance high because it will use same instance of object to perform any action
String belongs to System namespace
Stringbuilder belongs to System.Text namespace

Memory Allocation (Heap and Stack)

Declare a variable, it allocates some memory in the RAM.
This memory has 3 thins: name of the variable, data type of the variable, and the value of the variable.


Stack is keeping track of the running memory needed in your application. (LIFO (Last In First Out) 
=
Value Types hold both data and memory on the same location.(e.g. Enum, Struct, Bool, Int , Bool, Decimal)
int i=4;
int y=i;
(Both variables have different copies)
__________________________________________

Heap does not track running memory, it’s just a pile of objects which can be reached at any moment of time. Heap is used for dynamic memory allocation.
=
Reference Type has a pointer which points to the memory location. ( e.g. String Class, Interface, delegate Object)
Class1 obj = new Class1();
Class1 obj1 = obj;
(Both point to the same memory location.)
(pointer on the stack, actual object is at heap.

value type inside object is store in heap.

Boxing - value types to reference types.
UnBoxing reference types to value types.

Thursday, June 2, 2016

OOP Concepts

Encapsulation is the process of keeping one or more items within a single package. it prevents access to implementation details. access specifiers are public, private, protected, internal etc.

E.g.
public can be accessed any code.

private can only be accessed by code in the same class or struct.

protected can only be accessed by code in the same class or struct, or in a derived class.

internal can be accessed by any code in the same assembly only.

protected internal can be accessed by any code in the same assembly, or by any derived class in another assembly.

Abstraction is the process of providing only essential information to the outside real world and hiding overall background details to present an object. It relies on the separation of interface and implementation.to hide irrelevant details 
For example, we continue with “Bike” as an example, we have no access to the piston directly, we can usestart button to run the piston. Just imagine if a bike manufacturer allows direct access to piston, it would be very difficult to control actions on the piston. That’s the reason why a bike provider separates its internal implementation from its external interface.

private string GetEngineMakeFormula(){ return formula;}

public string DisplayMakeFormula() { //"GetEngineMakeFormula()" is private but accessible and limited to this class only
return GetEngineMakeFormula();}

Polymorphism means having many forms. Generally, polymorphism occurs when there is a hierarchy of classes and they are related by inheritance. (Overloading)
Vehicle airplane = new Airplane();
A Bike can be into two forms like cell start or kick start. We can later on decide which form or method we will use to start bike to go for drive

Inherritance

Initialize Child will Run Parent Constructor 1st only Child Constructor.
Child can Run Parent Method.
Can initialize Parent Object.
Override only for virtual or abstract method.

Constructor no return value, can overloaded

Destructor use for manual cleanup to destroy the objects that we no longer want to use.
~Bike(){ //Destructor }

OOP Deisgn Principle (SOLID)

5 principles to design a class SOLID:

SRP (Single Responsibility Principle)

  • 1 Class only 1 responsibility.
  • A class should have one, and only one, reason to change.
  • E.g. Student Class only for Student, teacher Class only for Teacher.
  • e.g. We not write function in every catch there, we will write a Common Log Class and Method, and use all the class. so in future, we just change the common log method. Not 1 by 1.

OCP (Open Closed Principle)

  • be open for extension, but closed for modification.
  • E.g. different shape has different calculate area method, we cannot use if…else to calculate this, in future, it might have new shape.
  • Shape > Abstract class, calculate area > abstract method.
  • Rectangle inherit Shape and override calculate method.

http://joelabrahamsson.com/a-simple-example-of-the-openclosed-principle/

LSP (Liskov Substitution Principle)

  • Derived classes must be substitutable for their base classes.
  • object of a derived class should be able to replace an object of the base class without bringing any errors in the system or modifying the behavior of the base class.
  • New derived classes are extending the base classes without changing their behavior.
  • Not implement method in sub class (so you can loop with Parent class and call Parent Method)
  • Sub class function overrides the base class method to give it new meaning.

http://www.infragistics.com/community/blogs/dhananjay_kumar/archive/2015/06/30/simplifying-the-liskov-substitution-principle-of-solid-in-c.aspx

ISP (Interface Segregation Principle)

  • No client should be forced to depend on methods it does not use.
  • Client only want printer function print ONLY, not scan and photocopy.
  • So you can use interface control how many interface you want.

http://www.codeproject.com/Tips/766045/Interface-Segregation-Principle-ISP-of-SOLID-in-Cs

DIP (Dependency Inversion Principle)
  • High-level modules should not depend on low-level modules. They should both depend on abstractions.
  • Loose Coupling and Dependency Injection.
  • Depend on abstractions, not on concretions. 

OOP Design Pattern

Abstract Factory Pattern: Create instances of classes belonging to different families (abstract method, 1 products 2 style)
http://penyu91.blogspot.my/2016/08/abstract-factory-pattern.html

Builder Pattern: Separate representation and object construction.
http://penyu91.blogspot.my/2016/08/builder-design-pattern.html

Factory Method Pattern: Create instances of derived classes.
http://penyu91.blogspot.my/2016/08/factory-pattern.html

Prototype Pattern: Clone or copy initialized instances.
http://penyu91.blogspot.my/2016/08/prototype-pattern.html

Singleton Pattern: Class with only one single possible instance.
http://penyu91.blogspot.my/2016/03/singleton-pattern.html

Dependency Injection

  • If no Dependency Injection, customer point to DatabaseHelper now, future have XMLDatabase, you would change lot of code.
  • Dependency Injection is good; it makes the classes loose couple.
  • It achieves Dependency Inversion Principle. (High-level modules should not depend on low-level modules. Both should depend on abstractions.) [Customer is High Level, DatabaseHelper is low level, IStorage is High Level]
  • Is to pass the variable into Constructor, Default Constructor is to initialize the concrete class.
static void Main(string[] args)
{
       var customera = new Customer(new DatabaseHelper());
       customera.CustStore();

       var customerb = new Customer(new XMLHelper());
       customerb.CustStore();

       Console.ReadLine();
}

public class Customer
{
    private IStorageHelper _iStorageHelper;

    public Customer(IStorageHelper iStorageHelper)
    {
        _iStorageHelper = iStorageHelper;
    }

    public void CustStore()
    {
        _iStorageHelper.Store();
    }
}

public interface IStorageHelper
{
    void Store();
}

public class DatabaseHelper : IStorageHelper
{
    public void Store()
    {
        Console.WriteLine("DB Store");
    }
}

public class XMLHelper : IStorageHelper
{
    public void Store()
    {
        Console.WriteLine("XML Store");
    }
}

Wednesday, June 1, 2016

High Conhension(亲密度), Loose Coupling (联结)

Effect on how flexible and maintainable your software

High cohesion increases the probability that a component can be reused in more places.

  • stuck together well , clear , closely, easy understand. e.g. DAC all related to Database.
  • e.g. Low Conhension -  EmalMessage has Login

Loose coupling allows components to be used independently from other components.  e.g IPOD

  • Tight Coupling, 2 classes are tight together (Class A instantiate object Class B), e.g. motherboard need to depend RAM, Processor.
  • Tight coupling increases the maintenance cost as it is difficult and changes to one component would affect all other components that are connected to it.
  • Solution, add interface in between,
  • Lego (loose coupling) , Puzzle (high Coupling)

So, next time you are writing a class, think to yourself: Am I writing a Lego or am I writing a puzzle piece?