Wednesday, 17 February 2016

Creating ASP.NET Applications with N-Tier Architecture

This article describes how to build ASP.NET applications using n-tier architecture. The benefits of having n-tier architecture is that all the modules having dedicated functionality will be independent of each other. Changing one tier will not effect other tiers and there is no single point of failure even if some tier is not working.

Background


In a typical n-tier application there will be 4 Layers. The bottom most layer is the Data layer which contains the tables and stored procedures, scaler function, table values function. This Data layer is typically the database engine itself. We will be using SqlServer as the data layer in our example.

On top of Data Layer, we have a Data Access Layer (DAL). This layer is responsible for handling Database related tasks i.e. only data access. This Data access layer is created as a separate solution so that the changes in DALonly need the recompilation of DAL and not the complete website. The benefit of having this layer as a separate solution is that in case the database engine is changes we only need to change the DAL and the other areas of the website need not be changed and recompiled. Also the changes in other areas outside this solution will not demand for DAL recompilation.

On top of DAL, we have our Business Logic Layer(BLL). BLL contains all the calculations and Business Rule validations that are required in the application. It is also in a separate solution for the reason that if the Business rules change or the calculations change we only need to recompile the BLL and the other layers of the application will remain unaffected.

Finally on top of BLL we have our Presentation Layer. The Presentation layer for an ASP.NET web forms application is all the Forms (apsx pages and their code behinds) and the classes contained in the App_Code folder. The Presentation layer is responsible for taking the user input, showing the data to the user and mainly performing input data validation.

Note: Input data filtration and validation is typically done at the Presentation Layer(Both client side and server side). The business Rule validation will be done at the BLL.

So to visualize the above mentioned architecture:



Note: The Data Access Layer in this article was written using classic ADO.NET, due to which the amount of code in DAL is little too much. Nowadays using ORMs like Entity framework to generate the DAL is recommended. The DAL code will be generated by ORM itself.

Using the code


Let us develop a small Toy ASP.NET application that will use n-tier architecture. We will develop a small Employee Management application for the NorthWind Database. (For simplicity, I have removed all other tables from the DB and some columns from the Employee table). This application should be able to perform the basic CRUD operations on the DB.

The solution for this application will contain separate projects for DAL and BLL. The Data Layer will beSqlServer. The Presentation Layer is an ASP.NET website running on top of these projects.


The Data Layer


The data layer in this example contain only one table called Employee. The data layer also contains the stored procedures for all the basic operations on the Employee table. So let us look at the table and all the stored Procedures we have in our Data Layer.



Now we will create a set of stored procedures to perform the operations on the Employees Table.
--1. Procedure to add a new employee CREATE PROCEDURE dbo.AddNewEmployee
 (  
  @LastName nvarchar(20),
  @FirstName nvarchar(10),
  @Title  nvarchar(30), 
  @Address nvarchar(60),
  @City  nvarchar(15), 
  @Region  nvarchar(15), 
  @PostalCode nvarchar(10),
  @Country nvarchar(15),
  @Extension nvarchar(4)
 )
AS
 insert into Employees
 (LastName, FirstName, Title, Address, City, Region, PostalCode, Country, Extension)
 values
 (@LastName, @FirstName, @Title, @Address, @City, @Region, @PostalCode, @Country, @Extension)
 RETURN

--2. Procedure to delete an employee CREATE PROCEDURE dbo.DeleteEmployee
 (
 @empId int
 )
 
AS
 delete from Employees where EmployeeID = @empId
 RETURN

--3. Procedure to add get an employee details CREATE PROCEDURE dbo.GetEmployeeDetails
 (
 @empId int
 )
 
AS
 Select * from Employees where EmployeeID = @empId
 RETURN

--4. Procedure to get all the employees in the table CREATE PROCEDURE dbo.GetEmployeeList 
AS
 Select * from Employees
 
 RETURN

--5. Procedure to update an employee detailsCREATE PROCEDURE dbo.UpdateEmployee
 (
  @EmployeeID int,
  @LastName nvarchar(20),
  @FirstName nvarchar(10),
  @Title  nvarchar(30), 
  @Address nvarchar(60),
  @City  nvarchar(15), 
  @Region  nvarchar(15), 
  @PostalCode nvarchar(10),
  @Country nvarchar(15),
  @Extension nvarchar(4)
 )
AS
 update Employees
 set 
  LastName = @LastName, 
  FirstName = @FirstName, 
  Title = @Title, 
  Address = @Address, 
  City = @City, 
  Region = @Region, 
  PostalCode = @PostalCode, 
  Country = @Country, 
  Extension = @Extension
 where 
  EmployeeID = @EmployeeID
 RETURN

Now we have our Data Layer ready.

The Data Access Layer


Now we will go ahead and create a Data Access Layer for our application. The data access layer will contain 2 main type of classes. A set of classes that will represent the Table entities. And classes to perform the CRUDoperations on the database.



The Employee class in the above diagram is the Entity that will represent the Employee table. This class has been created so that the Layers above the DAL will use this class to perform operations in Employee table and they need not worry about the table schema related details.
public class Employee
{
 int employeeID;
 string lastName;    //  should be (20)  chars only string firstName;   // should be (10) chars only string title;       // should be (30) chars only string address;     // should be (60) chars only string city;        // should be (15) chars only string region;      // should be (15) chars only string postalCode;  // should be (10) chars only string country;     // should be (15) chars only string extension;   // should be (4) chars only
 public int EmployeeID
 {
  get
  {
   return employeeID;
  }
  set
  {
   employeeID = value;
  }
 }

 public string LastName
 {
  get
  {
   return lastName;
  }
  set
  {
   lastName  = value;
  }
 }

 public string FirstName
 {
  get
  {
   return firstName;
  }
  set
  {
   firstName = value;
  }
 }

 public string Title
 {
  get
  {
   return title;
  }
  set
  {
   title = value;
  }
 }

 public string Address
 {
  get
  {
   return address;
  }
  set
  {
   address = value;
  }
 }

 public string City
 {
  get
  {
   return city;
  }
  set
  {
   city = value;
  }
 }

 public string Region
 {
  get
  {
   return region;
  }
  set
  {
   region = value;
  }
 }

 public string PostalCode
 {
  get
  {
   return postalCode;
  }
  set
  {
   postalCode = value;
  }
 }

 public string Country
 {
  get
  {
   return country;
  }
  set
  {
   country = value;
  }
 }

 public string Extension
 {
  get
  {
   return extension;
  }
  set
  {
   extension = value;
  }
 }
}

The EmployeeDBAccess class expose the methods to perform the CRUD operations on the Employee table.
public class EmployeeDBAccess
{
 public bool AddNewEmployee(Employee employee)
 {
  SqlParameter[] parameters = new SqlParameter[]
  {                
   new SqlParameter("@LastName", employee.LastName),
   new SqlParameter("@FirstName", employee.FirstName),
   new SqlParameter("@Title", employee.Title),
   new SqlParameter("@Address", employee.Address),
   new SqlParameter("@City", employee.City),
   new SqlParameter("@Region", employee.Region),
   new SqlParameter("@PostalCode", employee.PostalCode),
   new SqlParameter("@Country", employee.Country),
   new SqlParameter("@Extension", employee.Extension)
  };

  return SqlDBHelper.ExecuteNonQuery("AddNewEmployee", CommandType.StoredProcedure, parameters);
 }

 public bool UpdateEmployee(Employee employee)
 {
  SqlParameter[] parameters = new SqlParameter[]
  {
   new SqlParameter("@EmployeeID", employee.EmployeeID),
   new SqlParameter("@LastName", employee.LastName),
   new SqlParameter("@FirstName", employee.FirstName),
   new SqlParameter("@Title", employee.Title),
   new SqlParameter("@Address", employee.Address),
   new SqlParameter("@City", employee.City),
   new SqlParameter("@Region", employee.Region),
   new SqlParameter("@PostalCode", employee.PostalCode),
   new SqlParameter("@Country", employee.Country),
   new SqlParameter("@Extension", employee.Extension)
  };

  return SqlDBHelper.ExecuteNonQuery("UpdateEmployee", CommandType.StoredProcedure, parameters);
 }

 public bool DeleteEmployee(int empID)
 {
  SqlParameter[] parameters = new SqlParameter[]
  {
   new SqlParameter("@empId", empID)
  };

  return SqlDBHelper.ExecuteNonQuery("DeleteEmployee", CommandType.StoredProcedure, parameters);
 }

 public Employee GetEmployeeDetails(int empID)
 {
  Employee employee = null;

  SqlParameter[] parameters = new SqlParameter[]
  {
   new SqlParameter("@empId", empID)
  };
  //Lets get the list of all employees in a datataable  using (DataTable table = SqlDBHelper.ExecuteParamerizedSelectCommand("GetEmployeeDetails", CommandType.StoredProcedure, parameters))
  {
   //check if any record exist or not   if (table.Rows.Count == 1)
   {
    DataRow row = table.Rows[0];

    //Lets go ahead and create the list of employees    employee = new Employee();

    //Now lets populate the employee details into the list of employees                                               employee.EmployeeID = Convert.ToInt32(row["EmployeeID"]);
    employee.LastName = row["LastName"].ToString();
    employee.FirstName = row["FirstName"].ToString();
    employee.Title = row["Title"].ToString();
    employee.Address = row["Address"].ToString();
    employee.City = row["City"].ToString();
    employee.Region = row["Region"].ToString();
    employee.PostalCode = row["PostalCode"].ToString();
    employee.Country = row["Country"].ToString();
    employee.Extension = row["Extension"].ToString();
   }
  }

  return employee;
 }

 public List<employee> GetEmployeeList()
 {
  List<employee> listEmployees = null;

  //Lets get the list of all employees in a datataable  using (DataTable table = SqlDBHelper.ExecuteSelectCommand("GetEmployeeList", CommandType.StoredProcedure))
  {
   //check if any record exist or not   if (table.Rows.Count > 0)
   {
    //Lets go ahead and create the list of employees    listEmployees = new List<employee>();

    //Now lets populate the employee details into the list of employees    foreach (DataRow row in table.Rows)
    {
     Employee employee = new Employee();
     employee.EmployeeID = Convert.ToInt32(row["EmployeeID"]);
     employee.LastName = row["LastName"].ToString();
     employee.FirstName = row["FirstName"].ToString();
     employee.Title = row["Title"].ToString();
     employee.Address = row["Address"].ToString();
     employee.City = row["City"].ToString();
     employee.Region = row["Region"].ToString();
     employee.PostalCode = row["PostalCode"].ToString();
     employee.Country = row["Country"].ToString();
     employee.Extension = row["Extension"].ToString();

     listEmployees.Add(employee);
    }
   }
  }

  return listEmployees;
 }        
}
</employee>

The class SqlDbHelper is a wrapper class for ADO.NET functions providing a more simpler interface to use by the rest of DAL.
class SqlDBHelper
{
 const string CONNECTION_STRING = @"Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\NORTHWND.MDF;Integrated Security=True;User Instance=True";

 // This function will be used to execute R(CRUD) operation of parameterless commands internal static DataTable ExecuteSelectCommand(string CommandName, CommandType cmdType)
 {
  DataTable table = null;
  using (SqlConnection con = new SqlConnection(CONNECTION_STRING))
  {
   using (SqlCommand cmd = con.CreateCommand())
   {
    cmd.CommandType = cmdType;
    cmd.CommandText = CommandName;

    try
    {
     if (con.State != ConnectionState.Open)
     {
      con.Open();
     }

     using (SqlDataAdapter da = new SqlDataAdapter(cmd))
     {
      table = new DataTable();
      da.Fill(table);
     }
    }
    catch
    {
     throw;
    }                   
   }
  }

  return table;
 }

 // This function will be used to execute R(CRUD) operation of parameterized commands internal static DataTable ExecuteParamerizedSelectCommand(string CommandName, CommandType cmdType, SqlParameter[] param)
 {
  DataTable table = new DataTable();

  using (SqlConnection con = new SqlConnection(CONNECTION_STRING))
  {
   using (SqlCommand cmd = con.CreateCommand())
   {
    cmd.CommandType = cmdType;
    cmd.CommandText = CommandName;
    cmd.Parameters.AddRange(param);

    try
    {
     if (con.State != ConnectionState.Open)
     {
      con.Open();
     }

     using (SqlDataAdapter da = new SqlDataAdapter(cmd))
     {
      da.Fill(table);
     }
    }
    catch
    {
     throw;
    }                    
   }
  }

  return table;
 }

 // This function will be used to execute CUD(CRUD) operation of parameterized commands internal static bool ExecuteNonQuery(string CommandName, CommandType cmdType, SqlParameter[] pars)
 {
  int result = 0;

  using (SqlConnection con = new SqlConnection(CONNECTION_STRING))
  {
   using (SqlCommand cmd = con.CreateCommand())
   {
    cmd.CommandType = cmdType;
    cmd.CommandText = CommandName;
    cmd.Parameters.AddRange(pars);                    

    try
    {
     if (con.State != ConnectionState.Open)
     {
      con.Open();
     }

     result = cmd.ExecuteNonQuery();
    }
    catch
    {
     throw;
    }                   
   }
  }

  return (result > 0);        
 }        
}

Note: If we use any ORM(Object Relation Mapper) then DAL need not be written. The ORM will generate all the DAL code. Entity framework is one of the best ORMs available. This DAL can simply be replaced with a class library containing the Entity Framework generated Entities and Contexts.

The Business Logic Layer


The business logic layer will have a reference to the DAL and will mainly perform Business rule validation and business logic specific calculations. In out example, I will write a simple BLL that will govern the IO between theDAL and Presentation layer. In real applications the BLL will contain more logic and code.


public class EmployeeHandler
{
 // Handle to the Employee DBAccess class EmployeeDBAccess employeeDb = null;

 public EmployeeHandler()
 {
  employeeDb = new EmployeeDBAccess();
 }

 // This fuction does not contain any business logic, it simply returns the  // list of employees, we can put some logic here if needed public List<employee> GetEmployeeList()
 {
  return employeeDb.GetEmployeeList();
 }

 // This fuction does not contain any business logic, it simply returns the  // list of employees, we can put some logic here if needed public bool UpdateEmployee(Employee employee)
 {
  return employeeDb.UpdateEmployee(employee);
 }

 // This fuction does not contain any business logic, it simply returns the  // list of employees, we can put some logic here if needed public Employee GetEmployeeDetails(int empID)
 {
  return employeeDb.GetEmployeeDetails(empID);
 }

 // This fuction does not contain any business logic, it simply returns the  // list of employees, we can put some logic here if needed public bool DeleteEmployee(int empID)
 {
  return employeeDb.DeleteEmployee(empID);
 }

 // This fuction does not contain any business logic, it simply returns the  // list of employees, we can put some logic here if needed public bool AddNewEmployee(Employee employee)
 {
  return employeeDb.AddNewEmployee(employee);
 }
}

The Presentation Layer


The presentation layer now contains only a set of pages and code behinds and it will use the BLL and the the Employee class to perform all the operations. The add Operation can be seen as an example how the BLL is being used to perform an operation.
Employee emp = new Employee();

emp.LastName = txtLName.Text;
emp.FirstName = txtFName.Text;
emp.Address = txtAddress.Text;
emp.City = txtCity.Text;
emp.Country = txtCountry.Text;
emp.Region = txtRegion.Text;
emp.PostalCode = txtCode.Text;
emp.Extension = txtExtension.Text;
emp.Title = txtTitle.Text;

EmployeeHandler empHandler = new EmployeeHandler();

if (empHandler.AddNewEmployee(emp) == true)
{
 //Successfully added a new employee in the database Response.Redirect("Default.aspx");
}



Note: All the CRUD operations have been implemented. Please refer tio the sample code for all the details. When we run the application we can see all the EDIT/UPDATE, DELETE and ADD operations in action.


Point of Interest


I created this small application to demonstrate application development using n-tier architecture. The demo application has been created to show the basic idea behind the 3-tier architecture. There are many things that are still missing from this sample from the completion perspective. Client side validation and server side validation in presentation layer, Business rule validation and calculations in BLL are some missing things.

Since the idea here was to talk about how to put n-tier architecture in actual code, I think this article might have provided some useful information on that. I hope this has been informative.

[UPDATE] Note: In this article I am reusing the Employee model in the presentation layer. This model is defined in Data Access Layer. Due to this the presentation layer has to refer to the data access layer. This is not ideal in the real world scenarios(as pointed out in many of the comments below). Ideal solution for this would be to have two different models for Employee. the current model which is defined in the data access layer can be called as the data model and the business logic layer can create a model for employee which will be called as domain model. The business logic layer will then have to contain the code for mapping the data model to the domain model and vice versa. This mapping can be done either manually or a tool like AutoMapper can also be used to perform such mapping. With this change the presentation layer need not refer to the data access layer but it can refer to the business logic layer and use the Employee domain model from that.

In this article the n-tier architecture is specifically a data centric n-tier and not a domain centric one. If we need to design the application in a domain centric n-tier architecture then we need to follow a different way of organizing our layers. But perhaps that is a topic which deserves a separate discussion altogether but I wanted to point out the possibility of a domain centric n-tier architecture in this article.

Tuesday, 16 February 2016

MOTO GP 3 PC GAME FULL FREE DOWNLOAD

Moto Gp 3 Pc Game Full Free Download



Name: Moto Gp 3
Genre: athletics
RAR Size: 600 MB
Description:
Experience the fervour, excitement and spectacle of MotoGP, the foremost thrilling motor sport within the world! MotoGP '07 brings the joy and energy of the fans and media into the sport world like ne'er before.
MotoGP '08 is that the sixth game within the critically acclaimed MotoGP series and also the definitive bike athletics game for the Xbox 360 and computer. Building on the success of MotoGP '07, the sport expands the atmosphere and depth of the series, capturing the essence of the game, in addition as making the foremost accomplished athletics expertise on Xbox 360 and computer
Minimum System Requirements:
1Ghz Processor
Win98 / Maine / Windows 2000 / XP/Win 7/Win 8
128Mb Ram
GeForce three or higher than DirectX compatible graphics card
DirectX Compatible Sound Card
950Mb Free Winchester drive area (installed)
DirectX 9.0c
4x CD-ROM drive
ScreenShots :







SNIPER ELITE III PC GAME DIRECT LINK



Sniper Elite III


The latest chapter in the award-winning series, SNIPER ELITE III takes players to the unforgiving yet exotic terrain of North Africa in a savage conflict against Germany’s infamous Africa Corps. Stalk your targets through the twisting canyons, lush oases and ancient cities of the Western Desert in the deadly rush to sabotage a Nazi super-weapons program that could end Allied resistance for good.

Features of Sniper Elite III


  • Award-winning gunplay – Experience celebrated rifle ballistics honed to perfection. Take account of distance, gravity, wind, even your heart rate for intensely satisfying third person combat.

  • Expansive new environments – Stalk huge multi-route levels with multiple primary and secondary objectives than can be tackled in any order. Never play the same way twice.

  • Real tactical choice – Adapt to any situation. Use stealth, distraction, traps and sound masking . If things go hot, use the new Relocate mechanic to slip into the shadows and start the hunt again on your own terms.

  • Revamped human X-Ray Kill cam – The acclaimed X-Ray kill-cam is back and bolder than ever, including a detailed muscle layers, 3D mesh particles and the complete human circulatory system.

  • New X-Ray vehicle takedowns – See vehicles disintegrate in intricate detail with X-Ray vehicle take downs. multi-stage destruction allows you to take out armoured cars, trucks and Tiger tanks piece-by-piece.

How to install it?


  • Burn or mount .iso file using DAEMON Tools or Extract the file using Winrar

  • Install The Game

  • Paste the Crack in Install Location

  • Enjoy the Game ! 

Note: As usual, block the game exe in your firewall

Screenshots


Minimum System Requirements



  • OS : Windows Vista/7/8

  • CPU : Dual-core CPU with SSE3 (Intel® Pentium® D 3GHz / AMD Athlon™ 64 X2 4200) or better

  • RAM : 2 GB

  • Graphics : DX 10.0 with 512 MB VRAM (NVIDIA GeForce 8800 or ATI Radeon HD 3870)  or better

  • Hard Drive : 18 GB available space

  • Sound Card : DirectX Compatible Sound Card


Download Login


username : gamewebster.com

password : gamewebster.com

Downloads (you will be asked to login to download, then enter above details)


Tekken 3 Pc Game Download

Tekken 3 Pc Game Download















Introduction to TFS

TFS stands for Team Foundation Server which is developed by Microsoft. Integration of TFS with Visual Studio enables a team to work together and organize their efforts to complete a project. Dot Net developers use TFS for source control, bug tracking, requirement gathering and to manage complete life cycle of software development. It has below listed features:-





  1. Communication Enhancement


    TFS enhance the communication among team members by ensuring that no information or work is lost when a team member hand over his task to team. Project of the team is stored on the TFS and every team member has its own credentials to connect to TFS for accessing the project. TFS provides a central location to team project and each team member coordinate his work at this location.


  2. Team Explorer


    All members of a team work together on the team project by using Team Explorer in Visual Studio. Team Explorer connects to the TFS and displays team projects from the server. By using Team Explorer, every team member can get updated work items, projects documents and task to do.


  3. Roles


    Roles can be defined on team project that is on TFS. Each role represents one or more disciplines that are required to successful completion of the team project.


  4. Alerts


    TFS also provides alerts that are sent to team members by e-mail when something has changed on the team project. We can customize alerts on TFS according to our need.


  5. Source Control


    TFS allow the team to manage all source files for a project. We can also add non-source files such as important project documents, project plans etc. to TFS.


  6. Builds


    TFS Build enables the team to create and manage product builds regularly. TFS Build also provides build reports on the status and quality of each build.


  7. Tracking Work Status


    Using TFS project head can track the assigned work status to developers to understand the health of the project.


  8. Work Item History


    All working items are logged on TFS with all changes. Anyone can review the complete history of activity on a work item at any time. The working item history can be exported into Microsoft Excel.


  9. Reports


    Reports related to track status and information (like as work item changes, check-ins and status of product builds etc.) about the project are stored in a database on the TFS.


TFS Installation Guide


For TFS installation guide refer the link Team Foundation Server 2010 Installation Guide

 
What do you think?

I hope you have got what is TFS and how to use it with in the application. I would like to have feedback from my blog readers. Your valuable feedback, question, or comments about this article are always welcome.

Saturday, 6 February 2016

OOPS Concept with Real-world example

Introduction




OOP is Nothing but Object Oriented Programming.According to Wikipedia,  Object-oriented programming (OOP) is a programming paradigm that uses "objects" and their interactions to design applications and computer programs.

OOPs have following features

1. Object   - Instance of class
2. Class    - Blue print of Object
3. encapsulation  - Protecting our data
4. polymorphism   - Different behaviors at diff. instances
5. abstraction    - Hidding our irrelavance data
6. inheritence    - one property of object is aquring to another property of object

1. Object
Basically an object is anything that is identifiable as an single material item. You can see around and find many objects like Camera, Monitor, Laptop etc. In OOP perspective, an object is nothing but an instance of a class that contains real values instead of variables

2. Class

A class is a template definition of the methods and variables for a particular kind of object. In other words, class is the blue print from which an individual objects are created.

every human has eye ,so eyecolor can be considered as the property of human being which can be encapsulted as a data in our class Human

class Human

{

    private:

    EyeColor IColor;

    NAME personname;

};


Consider object of class of
                Human myhuman;

we want set myhuman's name as "linto" and IColor as "black", For that we want methods to do that task.

So need methods for class to do a particular task on the data

class Human

{
    private:

    EyeColor IColor;

    NAME personname;

    public:

    void SetName(NAME anyName);

    void SetIColor(EyeColor eyecolor);

};


3. Abstraction

Abstraction is a process of identifying the relevant qualities and behvaiors an object should possess. Lets take an example to understand abstraction. A Laptop consists of many things such as processor, motherboard, RAM, keyboard, LCD screen, wireless antena, web camera, usb ports, battery, speakers etc. To use it, you don't need to know how internally LCD screens, keyboard, web camera, battery, wireless antena, speakers works.  You just need to know how to operate the laptop by switching it on. The intrinsic details are invisitble. Think about if you would have to call to the engineer  who knows all internal details of the laptop before operating it. This would have highly expensive as well as not easy to use everywhere by everyone. So here the Laptop is an object that is designed to hide its complexity.

Think If you need to write a piece of software to track the students details of a school, you may probably need to create Students objects. People comes in all different backgrounds, educational qualifications, locations, hobbies, ages and have multiple religion, language but in terms of application, an student is just a name, age, class and roll number, while the other qualities are not relevant to the application. Determining what other qualities (background, qualifications, location, hobbiels etc) are in terms of this application is abstraction.

In object-oriented software, complexity is managed by using abstraction. Abstraction is a process that involves identifying the critical behavior of an object and eliminating irrelevant and complex detilals. A well thought-out abstraction is usually simple, and easy to use in the perspective of the user, the person who is using your object.

4. Encapsulation

Encapsulation is a method for protecting data from unwanted access or alteration by packaging it in an object where it is only accessible through the object's interface. Encapsulation are often referred to as information hiding. But both are different. Infact information hiding is actually the result of Encapsulation. Encapsulation makes it possible to separate an object's implementation from its orgiinal behavior - to restrict access of its internal data. This restriction facilitate certains detiails of an object;s behavior to be hidden. This allows to protect an object's interal state from corruption by its user.

It is the mechanism by which Abstraction is implemented. In other words you can say that it is the result of the Encapsulation. For example,  the Laptop is an object that encapsulates many technologies/hardwares that might not be understood clearly by most people who use it.
Inheritance

5. Inheritance

Inheritance is the ability to define a new class or object that inherits the behaviour and its functionality of an existing class. The new class or object is called a child or subclass or derived class while the original class is called parent or base class. For example, in a software company Software Engineers, Sr. Software Engineers, Module Lead, Technical Lead, Project Lead, Project Manager, Program Manager, Directors all are the employees of the company but their work, perks, roles, responsibilities differs. So in OOP, the Employee base class would provide the common behaviours of all types/level of employee and also some behaviours properties that all employee must have for that company. The particular sub class or child class of the employee would implement behaviours specific to that level of the employee. So by above example you can notice that the main concept behind inheritance are extensibility and code reuse (in this case you are extending the Employee class and using its code into sub class or derived class).

6. Polymorphism

As name suggests, Polymorphism means an ability to assume different forms at different places. In OOP, it is a language's ability to handle objects differently based on their runtime type and use. Polymorphism is briefly described as "one interface, many implementations".Ppolymorphism is a characteristic of being able to assign a different meaning or usage to something in different contexts - specifically, to allow an entity such as a variable, a function, or an object to have more than one form.

There are two types of polymorphism.

  •     Compile time polymorphism - It is achieved by overloading functions and operators

  •     Run time polymorphism - It is achieved by overriding virtual functions

Lets say you have a class that have many Load methods having different parameters, this is called Compile time polymorphism. Lets take another example where you have a virtual method in the base class called Load with one parameter and you have redefined its functioanlity in your sub class by overriding base class Load method,  this is called Run time polymorphism.


Thursday, 4 February 2016

How to create Custom Filters in AngularJS

Have you ever used filters with the ng-repeat directive as shown in the listing below?













{{a.name}}{{a.price}}






If so, then you’ve used a filter in an AngularJS application. AngularJS provides us many in-built directives like search. If required, AngularJS also allows us to create custom filters, which we’ll explore in this post.

AngularJS gives us a simple API to create a custom filter. You’ll remember that we use app.controller() to create controllers and app.module() to create modules. In exactly the same way, AngularJS has given us the angular.filter API to create a custom filter in AngularJS.

A custom filter can be created using the following syntax:





To create a custom filter, you need to do the following steps:

  • Create a filter using the app.filter by passing a custom filter name and a function as input parameters to the app.filter()

  • App.filter() will return a function

  • The retuned function can take various optional input parameters

  • The returned function will have custom filter code and it will return the output.



Let us start with creating a very simple custom filter. We can apply this custom filter on a string and it will return the string with each character in capital case.

MyApp.filter('toUpperCase', function () {



return function (input)

{

var output = "";

output = input.toUpperCase();

return output;

}

})



We can use the toUpperCase custom filter in the view as shown the listing below:













{{a.name|toUpperCase}}{{a.price}}






We need to keep in mind that the name of the custom filter is case sensitive. The above created view is reading data from the controller as shown the listing below:

MyApp.controller("ProductController", function ($scope) {



$scope.products = [

{ 'name': 'pen', 'price': '200' },

{ 'name': 'pencil', 'price': '400' },

{ 'name': 'book', 'price': '2400' },

{ 'name': 'ball', 'price': '400' },

{ 'name': 'eraser', 'price': '1200' },

];



})



Now we’ll get the product name rendered in capital case on the view as shown in the image below:

The filter we created above does not take any input parameter, but let us say we want one there. This can be done very easily.  In the above filter we are returning each character of the string in upper case. In the next filter we will pass the position and only the character at that position will be converted to capital. So the filter which takes input parameter can be created as shown in the listing below:

MyApp.filter('toPositionUpperCase', function () {



return function (input,position)

{

var output = [];

var capLetter = input.charAt(position).toUpperCase();

for (var i = 0; i < input.length; i++) {



if (i == position) {

output.push(capLetter);

} else {

output.push(input[i]);

}



}

output = output.join('');

return output;

}

})



We can use toPositionUpperCase custom filter in the view as shown the listing below. As you will notice that we are passing the input parameter to the custom filter using the colon.













{{a.name|toPositionUpperCase:1}}{{a.price}}




We will get the second letter of product name rendered in the capital case on the view as shown in the image below:



Before we conclude this article, let us create a custom filter which will be applied on the collection of items. Let us say from the list of products, we want to filter all the products greater than a given price. We can write this custom filter as shown in the listing below:

MyApp.filter('priceGreaterThan', function () {



return function (input, price) {

var output = [];

if (isNaN(price)) {



output = input;

}

else {

angular.forEach(input, function (item) {



if (item.price > price) {

output.push(item)

}

});

}

return output;

}

})



We can use the custom filter on the view as shown in the listing below. We are passing the price parameter from the input type text box.

<h1>With Custom Filter</h1>



















{{b.name}}{{b.price}}






With this we will get a filtered array on the view as shown in the image below:

So there you have it – that’s how to create a custom filter! It’s easy – they’re nothing but functions that take one input and optional parameters to return a function. I hope you enjoyed reading!

Difference between Abstract class and Interface in Asp.Net

An Abstract class without any implementation just looks like an Interface; however there are lot of differences than similarities between an Abstract class and an Interface. Let's explain both concepts and compare their similarities and differences.

What is an Abstract Class?

An abstract class is a special kind of class that cannot be instantiated. So the question is why we need a class that cannot be instantiated? An abstract class is only to be sub-classed (inherited from). In other words, it only allows other classes to inherit from it but cannot be instantiated. The advantage is that it enforces certain hierarchies for all the subclasses. In simple words, it is a kind of contract that forces all the subclasses to carry on the same hierarchies or standards.



What is an Interface

An interface is not a class. It is an entity that is defined by the word Interface. An interface has no implementation; it only has the signature or in other words, just the definition of the methods without the body. As one of the similarities to Abstract class, it is a contract that is used to define hierarchies for all subclasses or it defines specific set of methods and their arguments. The main difference between them is that a class can implement more than one interface but can only inherit from one abstract class. Since C# doesn't support multiple inheritance, interfaces are used to implement multiple inheritance.

When we create an interface, we are basically creating a set of methods without any implementation that must be overridden by the implemented classes. The advantage is that it provides a way for a class to be a part of two classes: one from inheritance hierarchy and one from the interface.

When we create an abstract class, we are creating a base class that might have one or more completed methods but at least one or more methods are left uncompleted and declared abstract. If all the methods of an abstract class are uncompleted then it is same as an interface. The purpose of an abstract class is to provide a base class definition for how a set of derived classes will work and then allow the programmers to fill the implementation in the derived classes.



























































Feature


Interface


Abstract class


Multiple inheritance


A class may inherit several interfaces.


A class may inherit only one abstract class.


Default implementation


An interface cannot provide any code, just the signature.


An abstract class can provide complete, default code and/or just the details that have to be overridden.


Access Modfiers


An interface cannot have access modifiers for the subs, functions, properties etc everything is assumed as public


An abstract class can contain access modifiers for the subs, functions, properties


Core VS Peripheral


Interfaces are used to define the peripheral abilities of a class. In other words both Human and Vehicle can inherit from a IMovable interface.


An abstract class defines the core identity of a class and there it is used for objects of the same type.


Homogeneity


If various implementations only share method signatures then it is better to use Interfaces.


If various implementations are of the same kind and use common behaviour or status then abstract class is better to use.


Speed


Requires more time to find the actual method in the corresponding classes.


Fast


Adding functionality (Versioning)


If we add a new method to an Interface then we have to track down all the implementations of the interface and define implementation for the new method.


If we add a new method to an abstract class then we have the option of providing default implementation and therefore all the existing code might work properly.


Fields and Constants


No fields can be defined in interfaces


An abstract class can have fields and constrants defined



 I have explained the differences between an abstract class and an interface.

I think it helps you