Friday, June 19, 2009

OOPS Part II -- Pillars of OOPS -- Inheritance, Polymorphism, Encapsulation

Part I --> OOPS Part I -- OOPS Part I -- Understanding the Object Oriented Programming

All object-based languages must contend with three core principals of object-oriented programming, often called the "pillars of object-oriented programming (OOP)":

Encapsulation: How does this language hide an object’s internal implementation details and preserve data integrity?
Inheritance: How does this language promote code reuse?
Polymorphism: How does this language let you treat related objects in a similar way?

The Role of Encapsulation



The first pillar of OOP is called encapsulation. This trait boils down to the language’s ability to hide unnecessary implementation details from the object user.

For example, assume you are using a class named DatabaseReader, which has two primary methods: Open() and Close():

// This type encapsulates the details of opening and closing a database.
DatabaseReader dbReader = new DatabaseReader();
dbReader.Open(@"C:\MyCars.mdf");
// Do something with data file and close the file.
dbReader.Close();

The fictitious DatabaseReader class encapsulates the inner details of locating, loading, manipulating, and closing the data file. Object users love encapsulation, as this pillar of OOP keeps programming tasks simpler. There is no need to worry about the numerous lines of code that are working behind the scenes to carry out the work of the DatabaseReader class. All you do is create an instance and send the appropriate messages

Closely related to the notion of encapsulating programming logic is the idea of data hiding. Ideally, an object’s state data should be specified using the private (or possibly protected) keyword. In this way, the outside world must ask politely in order to change or obtain the underlying value. This is a good thing, as publicly declared data points can easily become corrupted (hopefully by accident rather than intent!). You will formally examine this aspect of encapsulation in just a bit.

The Role of Inheritance



The next pillar of OOP, inheritance, boils down to the language’s ability to allow you to build new class definitions based on existing class definitions.

In essence, inheritance allows you to extend the behavior of a base (or parent) class by inheriting core functionality into the derived subclass (also called a child class).

Figure below shows a simple example. You can read the diagram in Figure as "A Hexagon is-a Shape that is-an Object."




When you have classes related by this form of inheritance, you establish "is-a" relationships between types. The "is-a" relationship is termed classical inheritance.

Here, you can assume that Shape defines some number of members that are common to all
descendents. Given that the Hexagon class extends Shape, it inherits the core functionality defined by Shape and Object, as well as defines additional hexagon-related details of its own (whatever those may be).

There is another form of code reuse in the world of OOP: the containment/delegation model
(also known as the “has-a” relationship or aggregation). This form of reuse is not used to establish parent/child relationships. Rather, the “has-a” relationship allows one class to define a member variable of another class and expose its functionality (if required) to the object user indirectly.

For example, assume you are again modeling an automobile. You might want to express the
idea that a car “has-a” radio. It would be illogical to attempt to derive the Car class from a Radio, or vice versa (a Car “is-a” Radio? I think not!). Rather, you have two independent classes working together, where the Car class creates and exposes the Radio’s functionality:

class Radio
{
public void Power(bool turnOn)
{
Console.WriteLine("Radio on: {0}", turnOn);
}
}
class Car
{
// Car 'has-a' Radio
private Radio myRadio = new Radio();
public void TurnOnRadio(bool onOff)
{
// Delegate call to inner object.
myRadio.Power(onOff);
}
}
Notice that the object user has no clue that the Car class is making use of an inner Radio object.
static void Main(string[] args)
{
// Call is forwarded to Radio internally.
Car viper = new Car();
viper.TurnOnRadio(false);
}

Difference Between Inherating a class and instantiating a class



When you inherit a class, you get the superclass attributes and methods that you can use without instantiating a superclass object. You can only use those which are public or protected.
If you instantiate them, you make an object and upon that object you call methods defined in the object's class.

When you inherit a class, base class from which a class is derived does not have state, behaviour or identity where as if you create an instance of a class, the base class sets it's identity, state, behaviour.

When you create an instance of an object, you can access the method of the class by using dot operator (.) but if you inherit a class, you can not access base class method by using dot operator.

Use Inheritance when you are sure that you need to extend few methods of the base class or need to add some more methods to it otherwise just create the instance of the class.

The Role of Polymorphism



The final pillar of OOP is polymorphism. This trait captures a language’s ability to treat related objects in a similar manner. Specifically, this tenant of an object-oriented language allows a base class to define a set of members (formally termed the polymorphic interface) that are available to all descendents. A class’s polymorphic interface is constructed using any number of virtual or abstract members.

In a nutshell, a virtual member is a member in a base class that defines a default implementation that may be changed (or more formally speaking, overridden) by a derived class. In contrast, an abstract method is a member in a base class that does not provide a default implementation, but does provide a signature. When a class derives from a base class defining an abstract method, it must be overridden by a derived type. In either case, when derived types override the members defined by a base class, they are essentially redefining how they respond to the same request.

To preview polymorphism, let’s provide some details behind the shapes hierarchy shown in
Figure. Assume that the Shape class has defined a virtual method named Draw() that takes no parameters. Given the fact that every shape needs to render itself in a unique manner, subclasses (such as Hexagon and Circle) are free to override this method to their own liking.




Once a polymorphic interface has been designed, you can begin to make various assumptions
in your code. For example, given that Hexagon and Circle derive from a common parent (Shape), an array of Shape types could contain anything deriving from this base class. Furthermore, given that Shape defines a polymorphic interface to all derived types (the Draw() method in this example), we can assume each member in the array has this functionality. Consider the following Main() method, which instructs an array of Shape-derived types to render themselves using the Draw() method:

class Program
{
static void Main(string[] args)
{
Shape[] myShapes = new Shape[3];
myShapes[0] = new Hexagon();
myShapes[1] = new Circle();
myShapes[2] = new Hexagon();
foreach (Shape s in myShapes)
{
s.Draw();
}Console.ReadLine();
}
}

This wraps up our brisk overview of the pillars of OOP. Now that you have the theory in your mind, the remainder of this chapter explores further details of how encapsulation is handled under C#. The next chapter will tackle the details of inheritance and polymorphism.

Thursday, June 18, 2009

OOPS Part I -- Understanding the Object Oriented Programming

This chapter is a basic introduction to object-oriented programming. It introduces you to some of the basic concepts and terms you need to know as you get a handle on the specific details of how object-oriented programming works.


What Is Object-Oriented Programming?

The term object-oriented programming means many different things. But at its heart, object-oriented programming is a type of computer programming based on the premise that all programs are essentially computer-based simulations of real-world objects or abstract concepts.

For example: Flight-simulator programs attempt to mimic the behavior of real airplanes. Some do an amazingly good job; military and commercial pilots train on them.


Understanding Objects

Objects-both in the real world and in the world of programming-are entities that have certain basic characteristics. The following sections describe some of the more important of these characteristics: identity, type, state, and behavior.


Objects have identity

Every object in an object-oriented program has an identity. In other words, every occurrence of a particular type of object-called an instance-can be distinguished from every other occurrence of the same type of object, as well as from objects of other types.


Objects have type

Object-oriented programming lets you assign names to the different kind of objects in a program. Types are defined by classes. So when you create an object from a type, you're saying that the object is of the type specified by the class. For example, the following statement creates an object of type Invoice:

Invoice i = new Invoice();

In this case, the identity of this object (that is, its address in memory) is assigned to the variable i, which the compiler knows can hold references to objects of type Invoice.


Objects have state

The type of an object determines what attributes the object has. Thus, all objects of a particular type have the same attributes. However, they don't necessarily have the same values for those attributes.
The combination of the values for all the attributes of an object is called the object's state. Unlike its identity, an object's state can and usually does change over its lifetime.

Here are a few more interesting details about object state:

  • Some of the attributes of an object are publicly known, but others can be private. The private attributes may be vital to the internal operation of the object, but no one outside of the object knows they exist. They're like your private thoughts: They affect what you say and do, but nobody knows them but you.
  • The state of an object is represented by class variables, which are called fields. A public field is a field that's declared with the public keyword so the variable can be visible to the outside world.


Objects have behaviour


Another characteristic of objects is that they have behavior, which means they can do things. Like state, the specific behavior of an object depends on its type. But unlike state, the behavior isn't different for each instance of a type.

Another way to say that objects have behavior is to say they provide services that can be used by other objects. The behavior of an object is provided by its methods.




OOPS Part II -- Pillars of OOPS -- Inheritance, Polymorphism, Encapsulation

Interview Experience with PWC

Recently I gave an interview with PWC.. Though not selected, I would like to share my experience with you all. Here are the list of questions asked in Round I:


01. Tell me about your education background, work profile.
02. Is dot net object oriented?
Here I said 'YES'..so next question

Lets start with OOPS
------OOPS------------
03. What is an abstract class?
04. What is an interface?
05. What is the difference between abstract class and an interface?
06. When to use what (abstract/interface)?
07. Give practical scenario regarding usage.
08. What is the relation between virtual and override keyword?
09. What is Polymorphism?
10. What is method overloading and method overriding?
11. What is singleton class?
12. When to use singleton class?
13. Any class in dot net framework that is an example of singleton class?
14. What is inheritance?
-------------------------

------SHAREPOINT-------------
You have worked on SharePoint also....YES
SharePoint coding or just Out-Of-Box? ... Coding

15. What is a web part?
16. Advantage of web part?
17. How to deploy a web part..step by step
18. What is the command line utility used in SharePoint?
19. How you can implement List Item listener?
20. Scenario: You need to check before inserting an item to list that whether the EmpID( field) is unique or not? How will you implement?
21. How will you deploy a feature?
-------------------------

-------Database-----------
22. What is an index?
23. How many types of index are there?
24. How many index I can have on a table? Any max limit?
25. What is difference between a primary key and unique key?
26. What are constraints?
27. Name any constraint?
28. Scenario: Table: EMPID, EMPDEPT, SALARY. You need to restrict that one can insert a row where salary is less than 5000. How will you implement that?
29. What is trigger and of how many types?
30. Have you worked on cursors?..I said no..that's why no further questions
---------------------------

--------DOT NET-----------
31. What are attributes in dot net?
32. Can we define user defined attributes?..IF yes then How?
33. How web service communicates between two non-compatible platforms?
34. Can web service preserve state? How?
35. What is singleton web service?
36. When we add a class file, what remains the default assess modifier?
37. Difference between protected internal, protected ?
38. What is MVC?
39. How will you relate MVC with 3-tier architecture?
--------------------------

-------Process Oriented----------
40. Can you name and explain any design pattern with example
41. Have you ever used any defect analysis?
42. What type of proceed flow you use?
43. Have you ever designed design document?
44. What are the main parts of a design document?
45. What tool you used in order to draw class diagrams?
46. Any idea regarding UML?

Sunday, June 14, 2009

Structure of Sharepoint Site and Navigation

SharePoint sites are always part of a site collection, which has a single parent or top - level site .

The top - level site can have any number of child sites, grandchildren, and so on, and each site will have one or more pages in a page library .

The site structure is therefore based on pages(the leaf nodes, which are viewable by end users) and sites (the containers, each of which has at least one default page to display).

Thursday, June 11, 2009

How to get Data from Active Directory using C#

Today, I am going to discuss how to fetch data from active directory and how to store it into a clas..

We can access LDAP or AD by using two class: DirectoryEntry and DirectorySearcher

Step 1:

Add reference to System.DirectoryServices amd import it in the code by entering using System.DirectoryServices;

Step 2:

We need the AD Location, AD Userid and AD Password in order to read data from it.

We store these values in web.config:
<appSettings>
<add key="GaadLocation" value="LDAP://XXXXX:XXX"/>
<add key="GaadUserName" value="XXXXXX"/>
<add key="GaadPassword" value="XXXXXX"/>
</appSettings>


Step 3:

In order to store the data fetched from AD, we created a class and defined some properties.

public class ADContact
{
public string UniqueId {get; set; }
public string LastName { get; set; }
public string DepartmentNumber { get; set; }
public string EmployeeType { get; set; }
public string TelephoneNumber { get; set; }
public string FirstName { get; set; }
public string UserStatus { get; set; }
public string Mail { get; set; }
public string Mobile { get; set; }
public string Title {get; set; }
}


Step 4: Create a method that will return a datatable so that we can iterate through the result.

public List GetADContacts(string SirName, string GivenName, string UniqueId)
{}

Step 5:

Within the method, create a SearchResultCollection object , a datatable, and list of AD properties to access:

SearchResultCollection results = null;
List GaadData = new List();

string ADLocation, ADUserId, ADUserPassword = string.Empty;
#region List of AD Properties
string[] properties = new string[]
{
"modifyTimestamp",
"uid",
"sn",
"departmentNumber",
"facsimileTelephoneNumber",
"givenName",
"mail"
};
#endregion


Step 6:
Declare a try-catch block and within try- write the following code:

try {

string strfilter = string.Empty;


//Get AD Settings from web.config
ADLocation = ConfigurationManager.AppSettings["ADLocation"];
ADUserId = ConfigurationManager.AppSettings["ADUserName"];
ADUserPassword = ConfigurationManager.AppSettings["ADPassword"];


//Create an instance of DirectoryEntry by passing the setting valies)
DirectoryEntry root = new DirectoryEntry(ADLocation, ADUserId, ADUserPassword, AuthenticationTypes.FastBind);

//Create the filter string : we need to search the Ad for people matching the search criteria. Here we are passing three parameters: SirName, GivenName, Uid. If any field is blank, we are putting * there. that is to get all values

strfilter = String.Format(
"(&(&(sn={0})(givenname={1})(uid={2})))",
String.IsNullOrEmpty(SirName) ? "*" : SirName + "*",
String.IsNullOrEmpty(GivenName) ? "*" : GivenName + "*",
String.IsNullOrEmpty(UniqueId) ? "*" : UniqueId + "*");

if (strfilter != "")
{
DirectorySearcher searcher = new DirectorySearcher(root, strfilter, properties);
searcher.Asynchronous = true;
searcher.SearchScope = SearchScope.Subtree;
results = searcher.FindAll();
}
foreach (SearchResult result in results)
{
ADContact contact = new ADContact();

if (result.Properties["uid"].Count > 0)
contact.UniqueId= Convert.ToString(result.Properties["uid"][0]);

if (result.Properties["title"].Count > 0)
contact.Title = Convert.ToString(result.Properties["title"][0]);

if (result.Properties["sn"].Count > 0)
contact.LastName = Convert.ToString(result.Properties["sn"][0]);

if (result.Properties["givenName"].Count > 0)
contact.FirstName = Convert.ToString(result.Properties["givenName"][0]);

if (result.Properties["facsimileTelephoneNumber"].Count > 0)
contact.TelephoneNumber = Convert.ToString(result.Properties["facsimileTelephoneNumber"][0]);

if (result.Properties["mobile"].Count > 0)
contact.Mobile = Convert.ToString(result.Properties["mobile"][0]);

if (result.Properties["mail"].Count > 0)
contact.Mail = Convert.ToString(result.Properties["mail"][0]);

ADData.Add(contact);
}
return ADData;
}
catch (Exception ex)
{
throw ex;
}

Tuesday, June 9, 2009

New Features of dot Net 3.5 Framework

Dot net framework 3.5 is built on dot net 2.0 runtime library with addition of few dlls like: System.Core.dll, System.XML.LINQ.dll, System.AjaxExtension.dll etc..

Mainly enhancements are done with related to LINQ and Entitiy Model. Here are few enhancements listed:


1. Automatic Properties :

If you remember, prior to framework 3.5, we used to declare property within a class like this:

class Class1 {

privtae string _CustomerName;
public string CustomerName
{
get { return _CustomerName; }
set { _CustomerName = value; }
}
}


Now, we will see how to implement the same code in dot net 3.5:

class Class1 {
public string CustomerName {get; set;}
}





2. Object Initializers :

Another new feature coming with .NET 3.5, C# 3 and VB 9 is object initialization. Object Initializers allow you to pass in named values for each of the public properties that will then be used to initialize the object.

Suppose we have a class called School and few fields, we used to initialization the class like this:

School school1=new School();
school1.Name="ABC";
school1.Address="DEF";


Now the problem is that if we need to initialize different fields based on logic, we need to create different constructors based on our logic. Here comes the use of Object Initializers.

Object Initializers allow you to pass in any named public property to the constructor of the class. This is a great feature as it removes the need to create multiple overloaded constructors using different parameter lists to achieve the same goal.

So, from framework 3.5 onwards, we will use:

School school1=new School {
Name="ABC";
Address="DEF";
};





3. Collection Initializers :

Like Object Initializers, the new Collection Initializers allow you to create a collection and initialize it with a series of objects in a single statement. The following statement demonstrates how the syntax is very similar to that of the Object Initializers. Initializing a List is accomplished by passing the instances of the Customer objects wrapped inside of curly braces.

Getting this feature as part of framwork, we don not need to declare the collection first and then add items to it.


List SchoolList = new List
{
new School {ID = 101, SchoolName = "School1"},
new School {ID = 102, SchoolName = "School2"},
new School {ID = 103, SchoolName = "School3"}
};




4. Extension Method

Extension methods are a new feature that allows you to enhance an existing class by adding a new method to it without modifying the actual code for the class. This is especially useful when using LINQ because several extension methods are available in writing LINQ query expressions.

For more details on extension method, check "What is Enxtension Method "

Extension Methods are very useful when you cannot add a method to the class itself, as in the case of creating a Cube method on the int class. Just because you can use a tool, does not mean you should use a tool.




5. Anonymous Types

When you create an Anonymous Type you need to declare a variable to refer to the object. Since you do not know what type you will be getting (since it is a new and anonymous type), you can declare the variable with the var keyword. This technique is called using an Implicitly Typed Variable.

Chek more details on "All about Anonymous Types

Steps in Compliation in ASP.NET

We all know the term compilation in Asp.Net. But do you know what is the order of compilation in an asp.net project. Do you know which folder in the application structure gets compiled first and which when get compiled last?

Here is the compilation life cycle of an Asp.Net project in the order they get compiled.

App_GlobalResources: First of all the global resources are compiled and the resource assembly is built. All the assembly's in the bin folder are linked to this assembly.

App_WebResources: Next the web resource folder will be compiled. This will create all the proxy types for the web services. The web reference created is then linked to the resource assembly (if it exists.).

Profile properties (defined in the Web.config file): If we have defined the profile properties in the web.config file than an assembly will be generated for the profile objects.

App_Code: Next all the files in the App_Code folder will be compiled. All code assemblies and the profile assembly are linked to the resources and Web references assemblies if any.

Global.asax: Next the Application object is compiled and then it is linked with all other previously generated assembly's.

Once the top-level items are compiled, the compilation of folder, pages and other items start as and when needed. Here is a list of how this process continues?

App_LocalResources: If the folder containing the requested item contains an App_LocalResources folder, the contents of the local resources folder are compiled and linked to the global resources assembly.

Individual Web pages (.aspx files),
User Controls (.ascx files),
HTTP handlers (.ashx files),

HTTP modules (.asmx files): Next these files are compiled.

Themes, master pages, other source files are compiled when referenced page is compiled.

Monday, June 8, 2009

What's the difference between encapsulation and abstraction?

Encapsulation protects abstractions. Encapsulation is the bodyguard; abstraction is the VIP.

Encapsulation provides the explicit boundary between an object's abstract interface (its abstraction) and its internal implementation details. Encapsulation puts the implementation details "in a capsule." Encapsulation tells users which features are stable, permanent services of the object and which features are implementation details that are subject to change without notice.

Encapsulation helps the developers of an abstraction: it provides the freedom to implement the abstraction in any way consistent with the interface. (Encapsulation tells developers exactly what users can and cannot access.) Encapsulation also helps the users of an abstraction: it provides protection by preventing dependence on volatile implementation details.

Abstraction provides business value; encapsulation "protects" these abstractions. If a developer provides a good abstraction, users won't be tempted to peek at the object's internal mechanisms. Encapsulation is simply a safety feature that reminds users not to stray over the line inadvertently.

What is an abstraction ?

An abstraction is a simplified view of an object in the user's own vocabulary.

In OO ,an abstraction is the simplest interface to an object that provides all the features and services the intended users expect.

An abstraction tells users everything they need to know about an object but nothing else. It is the well-defined, unambiguously specified interface. For example, on a vending machine, the abstraction is formed by the buttons and their meanings; users don't have to know about levers, internal counters, or other parts that are needed for the machine to operate. Furthermore the vending machine's price list implies a legally binding promise to users: if users put in the right amount of money, the machine promises to dispense the desired item.

The key to a good abstraction is deep knowledge of the problem domain. A good abstraction allows users to use an object in a relatively safe and predictable manner. It reduces the learning curve by providing a simple interface described in terms of the user's own vocabulary.

A good abstraction separates specification from implementation. It doesn't expose too much nor does it hide features that users need to know about. If an abstraction is good, users aren't tempted to peek at the object's implementation. The net result is simpler, more stable user code.

Sunday, June 7, 2009

How to use RunWithElevatedPrivileges in Sharepoint

The SPSecurity class provides a static method named RunWithElevatedPrivileges that enables code to execute as system code running under the identity of SHAREPOINT\system. This allows code to run in an escalated security context to perform actions as the system.

This method should be used with care and should not expose direct access to system resources, but rather should be used when you need to perform actions on behalf of the system. The method is simple. You can either create a delegate to a public void method or simply write code within an inline delegate.

The signature looks like the following:

SPSecurity.RunWithElevatedPrivileges(delegate()
{
// Code runs as the "SharePoint\system" user
});


Note that :
Code running with the escalated privilege should use a new SPSite object for code running as the system and use the SPContext.Current property to access the actual calling user’s identity.

To modify WSS content under the System credentials, you need to create a new SPSite site collection that generates a new security context for objects referenced from the site, as in the following example. You cannot switch the security context of the SPSite once it has been created, but must instead create a new SPSite reference to switch user contexts. The following code uses the system credentials to add a list item using the profile data of the current Web user:

SPSecurity.RunWithElevatedPrivileges(
delegate() {
using (SPSite site = new SPSite(web.Site.ID)) {
using (SPWeb web2 = site.OpenWeb()) {
SPList theList = web2.Lists["visitors"];
SPListItem record = theList.Items.Add();
record["User"] = SPContext.Current.Web.CurrentUser;
record.Update();
}
}
);

How to add a SPGroup to a Site Collection- Sharepoint

Groups cannot directly be added to a site-they must be added to the site collection.
If you try to add a group to the site’s Groups collection, you get an exception stating, “You cannot add a group directly to the Groups collection. You can add a group to the SiteGroups collection.”

This situation occurs because the SPGroup is always created at the Site Collection level and assigned to the site. The following code is valid and adds the LitwareSecurityGroup to the site collection groups.

// Adds a new group to the site collection groups:
site.SiteGroups.Add("LitwareSecurityGroup", site.CurrentUser,site.CurrentUser, "A group to manage Litware Security");

However, this still does not associate the group with our site, nor would it be useful within the site without any permissions. To add the group to the site, create a new SPRoleAssignment by associating an SPRoleDefinition with the SPGroup, and then add that role assignment to the site, as in the following code sample:


SPGroup secGroup = site.SiteGroups["LitwareSecurityGroup"];
SPRoleAssignment roleAssignment = new SPRoleAssignment(secGroup);
SPRoleDefinition roleDefinition = site.RoleDefinitions["Full Control"];
roleAssignment.RoleDefinitionBindings.Add(roleDefinition);
site.RoleAssignments.Add(roleAssignment);

How to get list of SPGroups in Sharepoint Site Collection

Sharepoint Gropus (or SPGroups) are never created in the context of the site-they are always created in the context of the site collection and assigned to a site.

We can get list of groups of a site by suing site.Groups


SPSite siteCollection = new SPSite("http://localhost/litware/sales/");
SPWeb site = siteCollection.OpenWeb();

foreach(SPGroup group in site.Groups){
Console.WriteLine(group.Name);
}