Monday 17 December 2012

2.1.2 Static Classes and Access Modifiers


What is Static class?
Static classes are used to create data and functions that can be accessed without creating an instance of the class. We can access any members of Static classes without creating instance of the class.
Example:
//Start
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace HowToBecomeAnArchitect.OOAD.StaticClass
{
static class Logger
{
public static int logLevel = 1;
public static void LogMessage()
{
//Write code here
Console.WriteLine("Logger:LogMessage() is executed");
}
}
class Demo
{
static void Main(string[] args)
{
Console.WriteLine("Main method is started");
Logger.LogMessage();
Console.WriteLine("Logger Level = " + Logger.logLevel);
Console.ReadKey();
}
}
}
//End
Note:
  1. Static classes contain only static members.
  2. Static classes cannot be instantiated.
  3. Static classes are sealed.
  4. Static variable is stored on the heap, regardless of whether it's declared within a reference type or a value type. There is only one slot in total no matter how many instances are created. This heap is separate from the normal garbage collected heap - it's known as a "high frequency heap", and there's one per application domain.
When to use Static classes?
  1. Static classes can be used when there is no data or behavior in the class that depends on any object.
  2. Static keyword will make your code a bit faster since no object creation is involved.
  3. Static classes used for logger and utility methods which often needed to access without creating any instances of the class to make faster and allocating with less memory.
  4. Static classes used for declaring the global constants for your project and these constants values read from config file and this is good practice for your development.
For example,
Config settings are
<appSettings>
<add key="MaxNoOfUsersAllowed" value="8" />
<add key="CachingServerName" value="au.cachingserver1.google.com" />
</appSettings>
Static class as follows
GoogleGlobal.cs
public static class GoogleGlobal
{
private static string cachingServerName = int.Parse(System.Configuration.ConfigurationManager.AppSettings["CachingServerName "].ToString());
private static int maxNoOfUsersAllowed = int.Parse(System.Configuration.ConfigurationManager.AppSettings["MaxNoOfUsersAllowed"]);
public static int CachingServerName { get { return cachingServerName; } }
public static int MaxNoOfUsersAllowed { get { return maxNoOfUsersAllowed; } }
}
Access Modifiers:
The following access modifiers are available in .NET
  1. 1.       Private – Access is limited to within class only.
  2. 2.       Protected – Access is limited to within class and to any class that inherits from the class.
  3. 3.       Public - There is no restriction for accessing the public members.
  4. 4.       Internal – Access is limited to the current project assembly.
  5. 5.       Protected Internal – Access is limited to the current project assembly and any types derived from the class.
Example:
//Start
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace HowToBecomeAnArchitect.OOAD.AccessModifiers
{
public class BaseClass
{
// For testing only
private int privateVariable = 1;
protected int protectedVariable = 2;
public int publicVariable = 3;
internal int internalVariable = 4;
protected internal int protectedInternalVariable = 5;
}
public class DrivedClass :BaseClass
{
public DrivedClass()
{
// print the BaseClass variables
//Console.WriteLine("Private Variable Value = " + privateVariable); //error on this line due to private variable
Console.WriteLine("Protected Variable Value = " + protectedVariable);
Console.WriteLine("Public Variable Value = " + publicVariable);
Console.WriteLine("Internal Variable Value = " + internalVariable);
Console.WriteLine("Internal Protected Variable Value = " + protectedInternalVariable);
}
}
class Demo
{
static void Main(string[] args)
{
Console.WriteLine("Main method is started");
DrivedClass drivedObj = new DrivedClass();
Console.ReadKey();
}
}
}
//End
Please visit the following URL to know more about how to use objects and classes.
http://msdn.microsoft.com/en-us/library/ms173109.aspx

2.1.1 OOAD Concepts


What is an Interface?
Interface is the blueprint of the system. An Interface contains only the signatures of the methods, delegates or events. i.e.) an interface does not contain any definition. The implementation of the methods is done in the class that implements the interface.
Example:
//Start
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace HowToBecomeAnArchitect.OOAD.Interface
{
interface IAccount
{
decimal GetAccountBalance();
//decimal GetTextBalance();                    
}
class PrePaid : IAccount
{
public decimal GetAccountBalance()
{
Console.WriteLine("PrePaid:GetAccountBalance is executed");
//write code here
// For testing I hardcoded the value
return 10;
}
}
class Demo
{
static void Main(string[] args)
{
Console.WriteLine("Main method is started");
IAccount accountObj = new PrePaid();
accountObj.GetAccountBalance();
Console.ReadKey();
}
}
}
//End
Note:
  1. Interfaces cannot contain constructors.
  2. Interfaces cannot contain fields.
  3. The access modifier does not allow in the interface. i.e.) by default access modifier is public.
  4. All the methods in the interface should be implemented the class which implements the interface. For example if you uncomment the //decimal GetTextBalance(); then you get the below error.
HowToBecomeAnArchitect.OOAD.Interface.PrePaid does not implement interface member HowToBecomeAnArchitect.OOAD.Interface.IAccount.GetTextBalance().
What is an Abstract class?
Abstract class is a special kind of class which cannot be instantiated. Abstract class contains one or more concrete methods.
Example:
//Start
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace HowToBecomeAnArchitect.OOAD.AbstractClass
{
abstract class Account
{
public abstract decimal GetAccountBalance();
public decimal GetTextBalance()
{
// Write code here
//For testing I hardcoded the value
return 100;
}
}
class PrePaid : Account
{
public override decimal GetAccountBalance()
{
Console.WriteLine("PrePaid:GetAccountBalance is executed");
//write code here
// For testing I hardcoded the value
return 10;
}
}
class Demo
{
static void Main(string[] args)
{
Console.WriteLine("Main method is started");
Account accountObj = new PrePaid();
accountObj.GetAccountBalance();
Console.ReadKey();
}
}
}
//End
Note:
  1. If you define the method is as an abstract method in the abstract class then you need to implement that method with override in the class which implements the abstract class.
  2. Non abstract methods should have the implementation in the abstract class.
  3. Abstract class contains the fields.
  4. An abstract method is implicitly a virtual method.
  5. Abstract class contains the access modifiers.
From the above examples, now, we can answers
  1. When to use Interface or Abstract class in our projects?
  2. What is the difference between an Interface and an Abstract class?
Please click the below link to know more about other  Static classes and access modifiers.

2. OOAD


OOAD – Object Oriented Analysis and Design. This is the software engineering approach that models the systems which interact with objects. OOA is the focuses on understanding and analyse the problem in the object oriented manner.

When we say modeling the system means definitely we need some tool to model the systems.  This tool is called UML (Unified modeling language). I will cover more about the UML in the sub sequent posts.
So OOAD convert real world problems to software solutions using Object Oriented Concepts. In this approach, everything is consists of objects.

I am not going to write much theory about OOAD here. But I do write which we need it for our day to day software development process.

The OO concepts are

1. Abstraction:  Simplifying the complexity into the simplified manner. In other words, representing the important details without including all the details.
For example, if you are working on banking domain, different types of accounts such as savings, mortgage can be treated as account only.

2. Encapsulation: It is a process of hiding all the internal details of an object from the outside world. For example, class is encapsulation. i.e.) the wrapping up of data and functions into a single unit is called as encapsulation.
Public class Prepaid
{
// Constructor
Public Prepiad(){}
Protected decimal ratePerMinute;
Protected decimal connectionCharge;
Protected int totalMinutes;
Public decimal GetChargeForPerCall(
{
return connectionCharge + (ratePerMinute  * totalMinutes);
}
}

3. Inheritance: Inheritance is the process of creating new class from already existing class. The new class called derived or child class and existing class is called base or parent or super class. The main purpose of inheritance is use existing code or behaviour of the parent class in the derived class.

For example,
Public class Account
{
//Constructor
Public Account () {}
Public decimal getSavingsAmount()
{
// code here
}
Public decimal getTodayWithDrawAmount()
{
}
}
Public class SavingsAccount:Account
{
// code here
}
Public class MortgageAccount: Account
{
// code here
}
Here Account is the base class and SavingsAccount and MortgageAccount are the derived classes.

4.  Polymorphism: Polymorphism means many forms. There are two types of polymorphism.
    1. Compile time polymorphism: Example, method overloading
// Start
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace HowToBecomeAnArchitect.OOAD.Polymorphism.OverLoading
{
class Customer
{
//Constructor
Customer()
{
Console.WriteLine("Customer class constructor is executed");
}
private string GetCustomerFirstName(int customerId)
{
//write code here to get customer first name
Console.WriteLine("Method GetCustomerFirstName is executed and method parameter is customerId");
//For testing I hardcoded the the name
return "Jayachandran";
}
private string GetCustomerFirstName(string emailAddress)
{
//write code here to get customer first name
Console.WriteLine("Method GetCustomerFirstName is executed & method parameter is emailAddress");
//For testing I hardcoded the email address
return "Jayachandran";
}
static void Main(string[] args)
{
Console.WriteLine("Main method is started");
Customer customerObj = new Customer();
Console.WriteLine(customerObj.GetCustomerFirstName(1234567890));
Console.WriteLine(customerObj.GetCustomerFirstName("Jayachandran.NET@hotmail.com"));
Console.ReadKey();
}
}
}

// End

The above program contains getCustomerFirstName method and this method is overloaded with different types of parameters. We can also overload method by using different number of parameters, different order of parameters.

Finally,

What are the different ways a method can be overloaded?
By using different parameter data types, different number of parameters, different order of parameters.

      2. Run time polymorphism: Example, method overriding
In C#, we can use either new or virtual keyword to override the base class methods.

What is the different between new & virtual?

Please try to execute the below programs on Visual Studio 2010 & see the output before answering this question.
//Program 1
// Start
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace HowToBecomeAnArchitect.OOAD.Polymorphism.Overriding
{
public class BaseAccount
{
//Constructor
public BaseAccount()
{
Console.WriteLine("BaseAccount class constructor is executed");
}
public void DisplayBalance()
{
Console.WriteLine("BaseAccount::DisplayBalance() is executed");
}
public void DisplayBPay()
{
Console.WriteLine("BaseAccount::DisplayBPay() is executed");
}
}
public class DerivedSavingsAccount : BaseAccount
{
//constructor
public DerivedSavingsAccount()
{
Console.WriteLine("DerivedSavingsAccount class constructor is executed");
}
public void DisplayBalance()
{
Console.WriteLine("DerivedSavingsAccount::DisplayBalance() is executed");
}
public new void  DisplayBPay()
{
Console.WriteLine("DerivedSavingsAccount::DisplayBPay() is executed");
}
}
class Demo
{
static void Main(string[] args)
{
Console.WriteLine("Main method is started");
BaseAccount baseAccount;
baseAccount = new DerivedSavingsAccount();
baseAccount.DisplayBalance();
baseAccount.DisplayBPay();
Console.ReadKey();
}
}
}
// End

Output:
Main method is started
BaseAccount class constructor is executed
DerivedSavingsAccount class constructor is executed
BaseAccount::DisplayBalance() is executed
BaseAccount::DisplayBPay() is executed

The above program complies and run successfully with one waring.
Warning details is  'HowToBecomeAnArchitect.OOAD.Polymorphism.Overriding.DerivedSavingsAccount.DisplayBalance()' hides inherited member 'HowToBecomeAnArchitect.OOAD.Polymorphism.Overriding.BaseAccount.DisplayBalance()'. Use the new keyword if hiding was intended and warning will not show if press F6 again until you modify the program and compile again.

//Program 2
// Start
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace HowToBecomeAnArchitect.OOAD.Polymorphism.Overriding
{
public class BaseAccount
{
//Constructor
public BaseAccount()
{
Console.WriteLine("BaseAccount class constructor is executed");
}
public virtual void DisplayBalance()
{
Console.WriteLine("BaseAccount::DisplayBalance() is executed");
}
public virtual void DisplayBPay()
{
Console.WriteLine("BaseAccount::DisplayBPay() is executed");
}
}
public class DerivedSavingsAccount : BaseAccount
{
//constructor
public DerivedSavingsAccount()
{
Console.WriteLine("DerivedSavingsAccount class constructor is executed");
}
public override void DisplayBalance()
{
Console.WriteLine("DerivedSavingsAccount::DisplayBalance() is executed");
}
public new void  DisplayBPay()
{
Console.WriteLine("DerivedSavingsAccount::DisplayBPay() is executed");
}
}
class Demo
{
static void Main(string[] args)
{
Console.WriteLine("Main method is started");
BaseAccount baseAccount;
baseAccount = new DerivedSavingsAccount();
baseAccount.DisplayBalance();
baseAccount.DisplayBPay();
Console.ReadKey();
}
}
}
// End

Output:
Main method is started
BaseAccount class constructor is executed
DerivedSavingsAccount class constructor is executed
DerivedSavingsAccount::DisplayBalance() is executed
BaseAccount::DisplayBPay() is executed

Finally, the answer is
New: If you use the new keyword instead of override, the method in the derived class doesn't override the method in the base class, it merely hides it.

Override: When a method of a base class is overridden in a derived class, the version in the derived class is used, even if the calling code didn't "know" that the object was an instance of the derived class.

Why we use OOPS’ for our development?

The major advantages of OOPs are:
1. Simplicity:
Software objects model real world objects, so the complexity is reduced and the program structure is very clear.

2. Modularity:
Each object forms a separate entity whose internal workings are decoupled from other parts of the system.

3. Modifiability:
It is easy to make minor changes in the data representation or the procedures in an OO program. Changes inside a class do not affect any other part of a program, since the only public interface that the external world has to a class is through the use of methods.

4. Extensibility:
Adding new features or responding to changing operating environments can be solved by introducing a few new objects and modifying some existing ones.

5. Maintainability:
Objects can be maintained separately, making locating and fixing problems easier.

6. Re-usability:

Objects can be reused in different programs.
If you would like to know more about OOPS please refer the following URL’s

Please click the below link to know more about other  OOAD concepts


Saturday 29 September 2012

Technical Bricks For Building Websites

What are the technical key considerations needed for building websites?
In overall, we need the following technical bricks to build the websites
  1. Software Design(including choosing the software technologies which comply with modern technologies)
  2. Development Environment Setup (including source version control, coding standards…etc.)
  3. Authentication and Authorization(for frontend and backend layers depends upon the type of websites)
  4. Security (including for preventing XSS, CSRF…etc.)
  5. Exception Handling and Logging (including custom error messages, page not found error page…etc.)
  6. Database Design (including normalization, store procedures, triggers, views…etc.)
  7. Caching (for improving the performance of the web site)
  8. Testing (including unit test, performance, Data Driven Testing (DDT)...etc.)
  9. Hosting Environment Plan
  10. Documentation (including deployment, support…etc. documentations)
Next, do we need necessarily all the above bricks for building websites?
Yes. But no. It's depends upon the type of websites.

Friday 24 August 2012

5. Security


In this topic, I am going to write more about security and how you can build your applications securely.
We can do many things in terms of security. However, I am going to write the necessary security topics which need it for our applications.

When I say “security” here, it consist of
  1. Authentication and Authorization
  2. How you can prevent your application from hackers
Most of the developers have lack of experience in security model unless working in banking domain. Because, they don’t have much experience in security or did not build/involving the security or the applications build by them did not hacked by hackers yet. That is why we did not think about security at all.
We can see day to day many changes in modern technologies and in order to protect our applications from hackers we need to follow/implement the modern security models.

Our next question is, where can follow the modern security models?

I would suggest that everyone to refer the OWASP (The Open Web Application Security Project) website
to know modern security methodologies.

If you don’t have much time then I would suggest that to visit the following URLs’ to know quickly about the security.

The broad range of companies and agencies around the globe are also using the OWASP Top Ten, including Citibank, IBM, Sun Microsystems, Symantec and many others.

Let’s say we are going to build the Greenfield (the project which we build from scratch) project then first we should consider Authentication and Authorization in the first place.

Authentication and Authorization:

What is Authentication?
Authentication is the process of identification and validation of a user's credentials. So first we should identify from our business that who is going to use the applications.
We can set the different Authentication types depends upon business requirements.

What is Authorization?
Authorization is process to determine whether that user has access to a particular resource. Simply, who can access what type of resources?

Authorization will happen after Authentication.
Authentication and Authorization are two interrelated concepts, which form the core of security for .NET applications. The authentication and authorization processes in ASP.NET are very flexible, simple and can be implemented in the code. ASP.NET is not a standalone product. It is linked with IIS and is, in fact, a layer on top of IIS.

So, any request that comes into the ASP.NET process is first authenticated and authorized by IIS. In short, the ASP.NET process is completely unaware if any user has been denied access to any page by IIS. Several security authorities interact when the user raises a request for an ASP.NET page. You must get to know how these processes work in order to fully understand the ASP.NET system.

The ASP.NET Authentication modes are
  1. None (Custom)
  2. Windows
  3. Passport
  4. Forms
Best practices to choose which types of Authentication mode:
  1. If its public site/no sensitive information and any one can access the site then you no need any type of Authentication and set to None
  2. If you need to verify the users and users are part of your networks then set up Windows Authentication. For example, for intranet site and access only available for network accounts.
  3. If you need to verify the users and users are not part of your networks then set up Forms Authentication. For example, for internet site and access only available for who has the valid user name and password.
  4. If you would like to have a centralized authentication service provided by Microsoft that offers a single logon and core profile services for member sites then go for Passport Authentication.
The ASP.NET Authorization modes are
  1. URL Authorization
  2. File Authorization
  3. Authorization based on ACLs
Authentication in IIS:
  1. Anonymous Authentication
  2. Basic Authentication
  3. Digest Authentication
  4. Integrated Windows Authentication
  5. Certificates Authentication

Please refer the below picture from Microsoft site.
Authentication and Authorization
Authentication and Authorization:

I am not going cover how to setup the above Authentication/Authorization modes practically as I don’t have much time. I may cover these if I get the time in the later my blog posts.

Please visit the following URLs’ to know more about the security

Until here, I talk about Authentication and Authorization and let’s talk about other security stuff.

How you can prevent your application from hackers:
As mention in the beginning of this post, please refer OWASP (The Open Web Application Security Project) website http://www.owasp.org

and

http://msdn.microsoft.com/en-us/library/ff648653.aspx to prevent your application from hackers.
And also refer the http://msdn.microsoft.com/en-us/library/ff649874 for preparing security checklist for your applications for your development team.

Summary:
  1. Decide which type of Authentication and Authorization need for your application.
  2. Please check necessary permissions needed on web and database servers and delete unnecessary permissions if it has.
  3. Use parameterized queries and store procedures for preventing the SQL injections.
  4. Strong validations, Encode the HTML output string and review potentially dangerous HTML tags and attributes for preventing XSS or CSS (Cross Site Scripting).
  5. Please use SSL certificates for your application for sensitive pages.
  6. Please use a single set of strong authentication and session management for preventing Broken Authentication and Session Management
  7. For direct references to restricted resources, the application needs to verify the user is authorized to access the exact resource they have requested. If they don’t have access then give the proper error message that access for this resources are not allowed. These prevent the Insecure Direct Object References.
  8. Setup and configure the customer error messages
  9. Please use unique token in the hidden field which sent with HTTP request to prevent Cross-Site Request Forgery(CSRF)
  10. Please install software patches and updates in a timely manner and configure the proper security configurations.
  11. Disable the directory listing for the web server virtual directories and set custom error 403.
  12. Setup customer error page for HTTP error code 404 and set
  13. Please put all the connection strings in the web.config file and these entries should be encrypted.
  14. Catch the exceptions and show friendly message to the customers
  15. Set <customErrors mode="RemoteOnly" xdt:Transform="Replace">
<error statusCode="404" redirect="404.htm"/>
</customErrors> in the web.config
16. Please prepare the security checklist for your team and make sure all the options should be ticked/implemented when application goes to production.