Wednesday, October 19, 2011

Dot Net Framework - Interview Questions

1. What is mean by .Net Framework?
The .NET framework is a collection of all the tools and utilities required to execute the .NET managed applications on a particular platform.
2. What is mean by CLR?
Common Language Runtime is the core component of .Net framework. It is similar to the Java Virtual Machine or JVM in Java, which handles the execution of code and provides useful services for the implementation of the program. It provides a number of services, including the following
management (loading and execution)
Application memory isolation
Verification of type safety
Conversion of IL to native code
Access to metadata (enhanced type information)
Managing memory for managed objects
Enforcement of code access security
Exception handling, including cross-language exceptions
Interoperation between managed code, COM objects, and pre-existing DLLs (unmanaged code and data)
Automation of object layout
Support for developer services (profiling, debugging, and so on)

3. What is difference between managed and unmanaged code?
The managed code is always executed by a managed runtime execution environment like CLR for .Net. Metadata information of the code will be exchanged with runtime, so runtime environment can guarantee what the code is going to do and provide the necessary security checks before executing any piece of code
Code that is directly executed by the Operating System is known as un-managed code. Example applications written in VB 6.0, C++, C, etc are unmanaged code that typically targets the processor architecture and is always dependent on the computer architecture. In unmanaged code the memory allocation, type safety, security, etc needs to be taken care of by the developer.

4. What is mean by MSIL?
MSIL or IL stands for Microsoft Intermediate Language; if you compile managed code, the compiler translates your source code into Microsoft intermediate language. MSIL is platform independent language which can be converted to native code while installing software or at runtime by using Just-in compiler.

5. What is mean by CTS?
Common type system defines how types are declared, used, and managed in the runtime, and is also an important part of the runtime's support for cross-language integration. CTS is responsible for defining types that can be used across the .Net Languages. CTS Provides the data types, values, object types. This helps developers to develop applications in different languages.
For example, an integer variable in C# is written as int, whereas in VB.Net it is written as integer. Therefore in .Net Framework you have single class called System.Int32 to interpret these variables.

6. What is mean by CLS?
Common Language Specification is the subset of CTS; it is specification that defines the set rules and guidelines that all supporting language should follow. It integrate in such a way that programs written in any language can interoperate with one another.

7. What is mean by JIT?
Just In Time(JIT) compilers which compile the IL code to native executable code (.exe or .dll) for the specific machine and OS. JIT are slightly different from traditional compilers as they compile the IL to native code only when desired e.g., when a function is called, IL of function's body is converted to native code; just in time of need. If same function is called next time, the CLR uses the same copy of native code without re-compiling. As JIT are aware of processor and OS exactly at runtime, they can optimize the code extremely efficiently resulting in very robust applications.

8. What are different types of JIT?
Pre-JIT - Pre-JIT compiles complete source code into native code in a single compilation cycle. This is done at the time of deployment of the application.
Econo-JIT - Econo-JIT compiles only those functions that are called at runtime. However, these compiled functions are removed when they are not required.
Normal-JIT - Normal-JIT compiles only those functions that are called at runtime and they are stored in cache. If same function is called next time, the CLR uses the same copy of compiled code without re-compiling.

9. What is mean by Assembly?
Assemblies are self-describing installation units, consisting of one or more files.
Assemblies are the deployment units of .Net applications. .Net application consists of one or more assemblies.
An assembly may also contain references to other assemblies and it include metadata that describes all the types that are defined in the assembly with information about it members-methods, properties, events and fields.
One assembly could be a single Dll or exe that includes metadata, or it can be made of different files e.g resource files, modules and an exe.
Assembly manifests is a part of the metadata, it describes the assembly with all the information that's needed to reference it and lists all its dependencies.

10. What are the features of Assembly?
Assemblies are self-describing, it includes metadata that describes the assembly. It does not required to register key as like COM component.
Version dependencies are recorded inside an assembly manifest. The version of the referenced assembly that will be used can be configured by the developer and the system administrator.
Two different version of same assembly can be used inside single process.

11. What are different type's assemblies?
Private assembly- Private assembly is used within your application and it is installed at the same time as the application itself. It will be located in the same directory as the application or subdirectories thereof.
Shared assembly- Shared assemblies are used by several application. Shared assembly must have version number and unique name and it is usually installed in GAC (Global assembly catch). It reduces the need for disk space and memory space.

12. What are parts of assembly manifests?
Identity - Name, version, culture and public key
A list of files - Files belonging to the assembly, it can have one or more files.
Lists of referenced assemblies - all assemblies referenced by the assembly are documented inside the manifest.
Set of permission requests- these are the permission needed to run the assembly.
Exported types - It describes the structures, class with properties, method and events. It is used to create instance of the class.
13. What is mean by Namespace?
Namespace Logically group classes, it avoids name clashes between classes.
Example : most of the general purpose .net base classes are in a namespace called System. The base class Array is in this namespace is accessed with full name System.Array.

14. What is difference between Assembly and Namespace?
Assembly is physical grouping of classes. Namespace logically groups classes.
Single assembly can have different namespaces
Sample namespace can be used in different assembly. E.g the assembly mscorlib and system contain the namespace System.Threading

15. What is the difference between an executable assembly and a class library?
An executable assembly exists as the .exe file while a class library exists as the .dll file. Executable assembly represent executable applications having some entry (e.g., Main() method in C#). A class library, on the other hand, contains components and libraries to be used inside various applications. A Class library cannot be executed and thus it does not have any entry point.

16. What is ILDASM?
ILDASM(Intermediate Language DisAssembler ), this is inbuild tool to view content and manifest of the assembly. We can run the ILDASM by running following exe "C:\Program Files\Microsoft SDKs\Windows\v7.0A\bin\NETFX 4.0 Tools\ildasm.exe"
Note : Currently I am using V4, file path will vary for different version of SDK installation.

17. What is mean by Manifest?
Manifest is used to describe the information about the assembly, it contains following information.
Assembly name - Aids in versioning and visibility scope.
Version information - The version number is integrated into the assembly's identity.
Types - Boundaries and scopes of methods, classes, properties, events and attributes.
Locale - Information describing language/culture.
Reference - provides information for type references in an assembly and other referenced assemblies.
Cryptographic Hash - Public key encoded hash acting as version/security check.
Security Permissions - The permissions within the assembly determine the permissions that can be granted for all aspects of the assembly contents.

18. How will you created shared assembly?
Shared assembly can be created by signing the assembly. Sets to created shared assembly
Create new class library project using visual studio
Navigate to the property page of the class library
Select "Signing" tab
Select "Sign the assembly" check-box
Now select < New >... from "Choose a strong name key file" dropdown
Enter new Signing key file name and click Ok
Next the build the project. Now the shared assembly is ready to use in different project.

19. What is the use of Shared Assembly?
If you want to use the same assembly in different projects, we can create a shared assembly and placed inside the GAC(Global assembly Catch). So that assembly is access by all the application. Private assembly also be used in different projects, but we need to copy the private assembly files to different application folder. But if we are using Shared assembly, the assembly file remains in single location.
Shared assembly is highly secured, only administrator can uninstall the shared assembly.

20. What is GAC?
GAC(Global assembly catch) is used to store .Net assembly. It is located in "C:\Windows\assembly"
Assembly located in GAC is shared by multiple applications
Adding an Assembly to GAC
"gacutil -i (assembly_name)", where (assembly_name) is the DLL name of the project.

21. What is mean by Delay signing?
During development process, usually private key will not be exposed to the developer due to security reason. In this kind of scenario, we will go with delay signing.Delay signing allows you to place a shared assembly in the GAC by signing the assembly with just the public key. This allows the assembly to be signed with the private key at a later stage, when the development process is complete and the component or assembly is ready to be deployed. This process enables developers to work with shared assemblies as if they were strongly named, and it secures the private key of the signature from being accessed at different stages of development.
E.g
VB.Net(Assemblyinfo.vb) < Assembly: AssemblyKeyFileAttribute("myKey.snk") >
< Assembly: AssemblyDelaySignAttribute(True) >
C#(Assemblyinfo.cs)
[assembly: AssemblyKeyFileAttribute("myKey.snk")]
[assembly: AssemblyDelaySignAttribute(true)]

22. What is mean by Satellite assembly?
When we write a multilingual or multi-cultural application in .NET, and want to distribute the core application separately from the localized modules, the localized assemblies that modify the core application are called satellite assemblies.

23. What is portable executable (PE)?
The file format defining the structure that all executable files (EXE) and Dynamic Link Libraries (DLL) must use to allow them to be loaded and executed by Windows. PE is derived from the Microsoft Common Object File Format (COFF). The EXE and DLL files created using the .NET Framework obey the PE/COFF formats and also add additional header and data sections to the files that are only used by the CLR.

24. What is mean by Garbage collection?
Garbage collection is a CLR features used to automatically manages memory. CLR automatically release the objects which are not longer used or referenced. Developer who forget to release the dispose the objects will be cleared by GC. But it is not known when GC will be called by CLR to clean the memory. So better we can dispose the objects once it is used.

25. What are the different levels of GC is available?
Generation 0 , Generation 1, Generation 2

26. How Garbage collector will get memory from OS?
When execution engine starts, GC will initialize segment of memory for its operation. GC reserves memory in segment, each segment is 16MB. When we run out of segments we reserve a new segment. If a segment of memory is not in use, it will be deleted.

27. What is mean by LOH?
LOH-(Large Object Heap). If size of the object are very high(>64KB) then it will be stored in different segment of memory called as LOH. GC will treat the large objects differently from small objects.

28. What are situations GC will be called?
If user forcefully calls System.GC.Collect
System is in low memory situation
Memory allocation exceeds the Generation0 threshold

29. What is mean by value type and Reference type?
Value type- Value type stores their value directly to memory address. Value type's values are allocated on the stack memory.
Reference type - Reference type stores the reference to the value's memory address. Reference type values are allocated on head memory.

30. What is mean by Boxing and Unboxing?
Boxing - Converting value type variable to reference type is called as boxing
UnBoxing - Converting reference type variable to value type is called as unboxing int vType = 35;
object rType;
//Boxing process
rType = vType;
//Unboxing process
vType =(int) rType;

31. How will you decide when to use value type and reference type?
All depends upon need.

32. What is difference between System exception and Application exception?
All exceptions are derived from the Exception base class. Where Exception class is derived from the Object class. Both System and Application exception are derived from exception class but it has difference between them. System exceptions are thrown by the CLR where as Application exceptions are thrown by Application.
System Exception
Application Exception
System exceptions are thrown by CLR
Application exceptions are thrown by Application
E.g OutOfMemoryException, NullReferenceException,etc
E.g User defined exception are created to throw application's exception and user defined exceptions are derived from ApplicationException

33. What is Reflection?
.Net compilers store metadata information(types defined) about the assemblies inside the assembly itself. Using this metadata we can load an assembly dynamically (at runtime), get information about its containing types, instantiate these types and call methods.
"Reflection" is a mechanism using which we can load an assembly dynamically and call its method. The System.Reflection is the root namespace that contains classes to implement the reflection. The Assembly class is the one which is used to represent the assembly in .Net environment.
Example:static void Main(string[] args)
{
// Load an assembly from file
Assembly myAssembly = Assembly.LoadFrom("MyService.dll");
// Get the types contained in the assembly and print their names
Type[] types = myAssembly.GetTypes();
foreach (Type type in types)
{
Console.WriteLine(type.FullName);
//Get the members(methods) present inside each type
foreach (MemberInfo member in type.GetMembers())
{
Console.WriteLine(" "+member.Name);
}
}
Console.ReadLine();
}


34. How will you decompile your assembly?
Any assembly can be disassembled using ILDASM(Intermediate Language Disassembler), it is ships with the .Net framework SDK. Using third party tools like Reflector or Anakrino can also be easily decompile the assemblies.

35. What is mean by Obfuscation?
Obfuscation is a technique used to mangle symbols and rearrange code blocks to foil decompiling. Dotfuscator, is a popular obfuscation package ships with Visual Studio.

36. If we have two different version of same assembly in GAC how do we make a choice?
Let us consider the scenario where one of the applications uses the dll which is available in GAC. Now we are creating the second version of the same dll and placed inside the GAC. So GAC contains both version of the assembly, since application referring the dll from GAC, definitely it will take latest version of the dll. But we need old version of the assembly to be executed. How to achieve this requirement?
Answer: using < bindingRedirect > tag in App.config file
Example:
Step 1: Create sample library class with MyVersion() method. This method will return current version of the assembly.namespace AssemblyVersionExample
{
public class Class1
{
public string MyVersion()
{
return "The old version: 1.0.0.10";
}
}
}
Step 2:Modify the "AssemblyVersion" attribute with the old version say ‘"1.0.0.10"// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.10")]
[assembly: AssemblyFileVersion("1.0.0.10")]
Step 3:Compile the dll and register to assembly using "gacutil"
Step 4:Create a public token key using following command [ sn -T "filepath"]. Now the public key for the assembly is created.
Step 5:Repeat the step 2,3 with different version for same assembly
public string MyVersion()
{
return "The new version: 1.0.0.20";
}
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.20")]
Step6: Now let's start creating the application, which refer the AssemblyVersionExample.dll Create a instance of the class and invoke the method. Output of the assembly will be new version. static void Main(string[] args)
{
AssemblyVersionExample.Class1 objClass = new AssemblyVersionExample.Class1();
Console.WriteLine(objClass.MyVersion());
Console.ReadLine();
}

Step 7: Since we need to use the old version of the assembly from GAC, we should make use of "bindingRedirect" tag in the application. In the below sample, you can find that new attribute is set with old version value (newVersion="1.0.0.10") and attribute is set with new version value (oldVersion="1.0.0.20"). When we execute the application, resultant output will be from old version of the dll.




publicKeyToken="7c779e284ebe2e8c"
culture="neutral" />
newVersion="1.0.0.10"/>




Output:

37. What is mean by Dll Hell?
DLL hell means deploying the same DLL in your application multiple times. In windows application dlls are shared across multiple application. Suppose when App1 is using MyAssembly.dll and it is working fine. Suppose I am installing new application App2 which also having assembly MyAssembly.dll, while installing App2 it will override the old assembly with new MyAssembly.dll. Now only App2 will function properly where as App1 which depends on MyAssembly.dll will fail. This is called as Dll hell. It can be solved by assembly versioning.

38. How's the DLL Hell problem solved in .NET?
Assembly versioning allows the application to specify not only the library it needs to run (which was available under Win32), but also the version of the assembly.

39. What's the difference between the System.Array.CopyTo() and System.Array.Clone()?
System.Array.CopyTo() - Performs a deep copy of the array
System.Array.Clone()- Performs a shallow copy of the array

40. What is difference between application running in Debug and Release mode?
In a debug build mode the complete symbolic debug information is added to complile assembly to help while debugging applications and also the code optimization is not taken into account. While in release build the symbolic debug infrmation is not added to the compiled assembly and the code execution is optimized. Since debuging information is not added in a release build, the size of the final executable is lesser than a debug executable.

41. What is the difference between traditional development and .NET development?
In traditional programming languages, the source code of a program is compiled to a specific platform's assembly language and then machine language code. Later the library code required by the program is linked to it. Finally the operating system executes the program when desired by the user
In the presence of dot net framework, a program is not compiled to the native machine executable code; rather it gets compiled to an intermediate language code called Microsoft Intermediate Language (MSIL) or Common Intermediate Language (CIL). The Dot Net Common Language Runtime (CLR) then converts this intermediate code at runtime to the machine executable code. The optimization is carried out at runtime

41. How true it is that .NET and Java programs are quite in-efficient when compared to C++?
In .Net and Java programming, initial execution of the program will be little bit slower than the C++ programming. Because .Net and Java involves the hosting of CLR into managed applcaiotn process in .Net and starting the JVM in a new process in case of Java. Since, the CLR and JVM optimizes the code more efficiently than the static C++ compilers, the execution speed of the program may actually be faster after sometime of the program startup when most of the code is translated. Hence, in the longer run, the .Net and Java based programs should not be in-efficient when compared to C++.

42. How Finaliz() method will work in .net?
.Net framework provides ahte Object.Finalize() method to clean up objects unmanaged resources. In general garbage collector keeps track of objects that have Finalize methods, using an internal structure called the finalization queue. Each time your application creates an object that has a Finalize method, the garbage collector places an entry in the finalization queue that points to that object. The finalization queue contains entries for all the objects in the managed heap that need to have their finalization code called before the garbage collector can free their memory.
Finalize methods requires at least two garbage collections to free the resources. When the garbage collector performs a collection, it reclaims the memory for inaccessible objects without finalizers. At this time, it cannot collect the inaccessible objects that do have finalizers. Instead, it removes the entries for these objects from the finalization queue and places them in a list of objects marked as ready for finalization. Entries in this list point to the objects in the managed heap that are ready to have their finalization code called. The garbage collector calls the Finalize methods for the objects in this list and then removes the entries from the list. A future garbage collection will determine that the finalized objects are truly garbage because they are no longer pointed to by entries in the list of objects marked as ready for finalization. In this future garbage collection, the objects' memory is actually reclaimed.


Object Oriented Programming - Interview Questions.

1. What is mean by Class?
Class is a structure that describes the state (property) and behavior (methods) of the object. It is a template or blueprint to create objects of the class. Class represents the noun and it can be used as type in programming language. E.g Car, Person etc

2. What is mean by Objects?
Object is an executable copy of a class. State and behavior of the objects are defined by class definition. We can create multiple objects for single class. It is also called as instance of the class. When an object is created from the class, memory will be allocated in RAM. e.g Car- Maruthi, Alto, Zen etc. Person- Ram, Sam, John etc

3. What is mean by Struture?
Structure is a light-weight class used to create user-defined types containing only public fields. Structure can't have implementation inheritance, but it can have interface inheritance. We cannot modify the default constructors as like a class. Structure is a value type holds their value in memory when they are declared.

4. What is difference between Class and Object?
Classes are the template or blueprint its state of how objects should be and behave, where as Object is an actual real term object. E.g CAR define state like it should have four wheel and body structure with moving, accelerating and break functionality. Maruthi, Alto or Zen is the real object which has different kind of state from one another.

5. What is difference between Class and Structure?
Class is Reference type(Reference types hold a reference to an object in memory) - Structure is a Value type(Value types hold their value in memory when they are declared)
User can modify default constructor and destructor of class- structure can't modify default constructor
Class supports inheritance - Structure will not support inheritance
Classes must be instantiated using the new operator - Structure can be instantiated without using the new operator
6. Which case we have to use Class and Structure?
Structure can be used for things that we no need for identity. Class can be used when we need the identity for an object.

7. What is the advantage of Structure over Class?
Since Stucture is a value type and if we use at the proper location, it will improve the performance.

8. What are different access modifiers in .Net?
Private - The type or member can only be accessed by code in the same class or struct. Protected - The type or member can only be accessed by code in the same class or struct, or in a derived class. Internal - The type or member can be accessed by any code in the same assembly, but not from another assembly. Procted Internal - The type or member can be accessed by any code in the same assembly, or by any derived class in another assembly. Public -The type or member can be accessed by any other code in the same assembly or another assembly that references it. Note: In VB.Net 'Internal' is called as 'Friend'

9. What are advantages of using private constructor, method, property?
Due to security reason, methods and properties are not exposed outside the class using Private access modifier. For implementing Singleton pattern we go for Private Constructor, so we will not able to create instance. Separate method is used to create and return the instance.

10. What is mean by Partial class?
It is new features in .Net 2.0; partial classes mean that class definition can be split into multiple physical files. Logically, partial classes do not make any difference to the compiler. The compiler intelligently combines the definitions together into a single class at compile-time.

Example for Partial Class

partial class Employee
{
string m_Name;
public String Name
{
get { return m_Name; }
set { m_Name = value; }
}
}

partial class Employee
{
int m_Age;
public int Age
{
get { return m_Age; }
set { m_Age = value; }
}
}

public class ExampleofPartical
{
public void Method1()
{
Employee objClass1 = new Employee();
objClass1.Name="Name";
objClass1.Age = 12;
}
}

11. What is mean by Partial method?
Partial methods are methods defined in a partial class that are (optionally) divided across two files. With partial methods one file contains the method signature - the method name, its return type, and its input parameters - while the body is (optionally) defined in a separate file. If the partial method's body is not defined then the compiler automatically removes the partial method signature and all calls to the method at compile-time.

Example for Partial method


{
string m_Name;
public String Name
{
get { return m_Name; }
set { m_Name = value; }
}
public partial string GetEmpDetails(string ID);

}

partial class Employee
{
int m_Age;
public int Age
{
get { return m_Age; }
set { m_Age = value; }
}
public partial string GetEmpDetails(string ID)
{
return "Employee1";
}
}

12. Why do we go for Partial method?
Partial methods are mainly useful in auto-generated code situations. A code generating tool might know that there are certain extension points that some users are going to be interested in customizing. For example, the objects created in LINQ to SQL have partial methods like OnLoaded, OnCreated, OnPropertyNameChanging, and OnPropertyNameChanged. The auto-generated code calls the OnCreated partial method from its constructor. If you want to run custom code when one of these objects is created you can create a partial class and define the body for the OnCreated partial method.

13. Why do we go for Partial class?
Improve the readability of extremely large classes by partitioning related methods into separate files.
Partial classes enable the code generator to generate code in one file while the developer who may need to extend the auto-generated logic can do so in a separate file, which eliminates the worry that the code generator might overwrite a developer's customizations.
14. Where we use Partial method and class?
Partial classes and partial methods are most commonly used in auto-generated code. It provides a simple and safe way to add new functionality or extend existing functionality of auto-generated code.

15. What are restrictions for Partial method?
Partial definitions must preceded with the key word "Partial"
Method signature should be same in both partial class file
We cannot have partial implementation in one file and another implementation in other file. We can have declaration in one file and implementation in another file.
16. What is mean by Static class?
Static class is used to create attributes and methods that can be accessed without creating the instance of the class. Static classes are loaded automatically by the .NET Framework when application or assembly is loaded. 'Static' key word is used to mention the static class. e.g MyStaticClass.PI

Example for Static Class

public static class MyStaticClass
{
public static decimal PI = 3.14M;
public static int Add(int num1, int num2)
{
return num1 + num2;
}
public static string Append(string str1, string str2)
{
return str1 + str2;
}
}
MyStaticClass.PI


17. What is mean by Static method?
Static method can be accessed without creating the instance of the class. 'Static' key word is used to mention the static method. Static methods can be created inside the normal class or static class. If we create the static method inside the normal class, static method will not be able to access by creating instance of the class. e.g Math.Add()

18. Can we override static method?
No, compiler will not allow overriding the static method.

19. What are uses of static class and method?
Compiler will not allow creating the instance of the class
Static class also makes the implementation simpler and faster
Cannot inherit a static class since it is sealed
20. What is static constructor?
A static constructor is used to initialize any static data, or to perform a particular action that needs performed once only. It is called automatically before the first instance is created or any static members are referenced.

Example:

public class MyStaticClass
{
static int count;

static MyStaticClass()
{
count = 0;
Console.WriteLine("Static class is initialized");
}

public static void MyMethod(string name)
{
Console.WriteLine("Static class is initialized " + name);
}
}

MyStaticClass.MyMethod("John");

Output:

Static class is initialized
Hello John

21. What are shared (VB.NET)/Static(C#) variables?
Static members are not associated with a particular instance of any class, which can be invoked directly from the class level, rather than from its instance

Example

public static double PI = 3.1457;

22. What is Nested Classes?
Classes with in classes are called as Nested class.

Example

public class MyClassLevel_1
{
public void Display()
{
Console.WriteLine("Level_1");
}
public class MyClassLevel_2
{
public void Display()
{
Console.WriteLine("Level_2");
}

public class MyClassLevel_3
{
public void Display()
{
Console.WriteLine("Level_3");
}
}
}
}

Creating instance of the nested class

MyClassLevel_1 L1 = new MyClassLevel_1();
MyClassLevel_1.MyClassLevel_2 L2 = new MyClassLevel_1.MyClassLevel_2();
MyClassLevel_1.MyClassLevel_2.MyClassLevel_3 L3 = new
MyClassLevel_1.MyClassLevel_2.MyClassLevel_3();
L1.Display();
L2.Display();
L3.Display();

Output
Level_1
Level_2
Level_3


23. What are difference between Singleton and Static class?
Singleton can extend classes and implement interfaces, while a static class cannot implement the interface.
Singleton can be initialized lazily or asynchronously while a static class is generally initialized when it is first loaded.
Singleton class can be extended and it's methods can be overridden.
24. Why Main () method is static?
To ensure there is only one entry point to the application.

25. What is mean by inheritance?
Inheritance is one of the concepts of object-oriented programming, where a new class is created from an existing class. Inheritance class is often referred to as subclasses, comes from the fact that the subclass (the newly created class) contains the attributes and methods of the parent class. This can be used to create a highly specialized hierarchical class structure.

Example of Inheritance


class Circle
{
private double m_radius;

public double Radius
{
get { return m_radius; }
set { m_radius = value; }
}
public double Diameter
{
get { return Radius * 2; }
}
public double Circumference
{
get { return Diameter * 3.14; }
}
public double Area
{
get { return Radius * Radius * 3.14; }
}
}

class Sphere : Circle
{
new public double Area
{
get { return 4 * Radius * Radius * 3.14; }
}

public double Volume
{
get { return 4 * 3.14 * Radius * Radius * Radius / 3; }
}
}


26. Can we inherit multiple classes?
No, multiple inheritances are not supported in .Net. Because consider the provided example. Here there are two Parent class Paretn1 and Parent2. This is inherited by Child class, In GetData method, child call the parent class method PrintData(). In this case which method will be executed? It is very difficult for CLR to identify which method to call. It shows that we multiple inheritance create ambiguity to oops concept. In order to avoid this ambiguity we are going for multiple interface implementations.

public class Parent1
{
public string PrintData()
{
return "This is parent1";
}
}
public class Parent2
{
public string PrintData()
{
return "This is parent2";
}
}

public class Child1 : Parent1, Parent2
{
public string GetData()
{
return this.PrintData();
}
}

27. What is mean by Shadowing?
When the method is defined in base class are not override able and we need to provide different implementation for the same in derived class. In this kind of scenario we can use hide the base class implementation and provide new implementation using Shadows (VB.Net)/new(C#) keyword.

Example:

Public Class ParentClass
Public Sub Display()
Console.WriteLine("Parent class")
End Sub

End Class

Public Class ChildClass
Inherits ParentClass

Public Shadows Sub Display()
Console.WriteLine("Child class")
End Sub
End Class


Dim p As New ParentClass
Dim c As New ChildClass
Dim pc As ParentClass = New ChildClass
p.Display()
c.Display()
pc.Display()

Output:
Parent class
Child class
Parent class


28. How a base class method is hidden?
Using new keyword in the derived class, base class method can be hidden or suppressed. New implementation can be added to the derived class.

29. What does the keyword virtual mean in the method definition?
The method can be over-ridden.

30. How method overriding different from overloading?
If we are overriding the method, derived class method behavior is changed from the base class. In Overloading, method with same name by different signature is used.

Example:

{
public virtual void Display()
{
Console.WriteLine("ParentClass");
}
}

public class ChildClass : ParentClass
{
//Example for method override
public override void Display()
{
Console.WriteLine("ChildClass");
}

//Example for method overload
public void Display(string name)
{
Console.WriteLine(name);
}
//Example for method overload
public void Display(string name, string country)
{
Console.WriteLine("Name:"+name +"Country: "+ country );
}
}


ParentClass p = new ParentClass();
ChildClass c = new ChildClass();
ParentClass pc = new ChildClass();
p.Display();
c.Display();
pc.Display();
 
OutPut:
ParentClass
ChildClass
ChildClass


31. Can you declare the override method static while the original method is non-static?
No

32. What is mean by Sealed Class?
Class which cannot be inherited is called as sealed class. If we need to prevent a class from being inherited, use “Sealed” keyword. But sealed class can inherited from other classes.

Example:

public class MyBaseClass
{
public void Display()
{
Console.WriteLine("Base class");
}
}

//Compile Success: This class cannot be inherited
public sealed class MySealedClass:MyBaseClass
{
public void Display()
{
base.Display();
Console.WriteLine("Sealed class");
}
}

//Compilation Error: cannot derive from sealed type MySealedClass
public class MyChildClass : MySealedClass
{

}


33. Can you allow class to be inherited, but prevent the method from being over-ridden?
Yes, just leave the class public and make the method sealed.

34. Will sealed class allows inheritance, if not why?
Sealed means it is not inheritable

35. What are the advantages of Private constructor?
Private constructor will prevent the user from creating the instance of the class which contains only static members.
Private constructor are used for implementing the singleton pattern
36. While using inheritance, derived class construct will call base class constructor?
Yes, base class constructor will be called before child class constructor

37. Overloaded constructor will call default constructor internally?
No, overload constructor will not call default constructor

38. What is difference between Overrides and Overridable?
Overridable (VB.Net)/ virtual (C#) is used in parent class to indicate that a method can be overridden. Overrides(VB.Net)/ override(C#) is used in the child class to indicate that you are overriding a method.

39. What is Method overloading?
Method overloading occurs when a class contains two methods with the same name, but different signatures.

40. What is operator overloading?
Operator overloading is used to provide a custom functionality to existing operators. For Example +,-,* and / operators are used for mathematical functionality. But we can overload these operators to perform custom operation on classes or structure.

Example:

To concatenate the two strings we have to use Concat method

Dim str1, str2, str3 As String
str1 = "Hello"
str2 = "world"
str3 = String.Concat(str1, str2)

But .Net provides in build operator overloading for string we can use ‘+’ operator for concatenating the string value

str3=str1+str2

Similarly we can also implement operator overloading for classes or structure

Employee3= Employee1 + Employee2

41. What is mean by abstraction?
Abstraction is the process of showing necessary information and hiding unwanted information. Let us consider the "CalculateSalary" in your Employee class, which takes EmployeeId as parameter and returns the salary of the employee for the current month as an integer value. Now if someone wants to use that method. He does not need to care about how Employee object calculates the salary? An only thing he needs to be concern is name of the method, its input parameters and format of resulting member

42. What is mean by abstraction class?
Abstract classes contain one or more abstract methods that do not have implementation. An abstract class is a parent class that allows inheritance but can never be instantiated. Abstract classes allow specialization of inherited classes.

43. What id mean by Interface?
Interface defines the set of properties, signature of the methods and events. It does not include any implementation. Class which implements the interface can provide the behavior to the implemented method. For example two class MyEnglishClass and MyFreanchClass implementing same interface and provide two different set of behavior in their implementation.

public interface IMyInterface
{
string Hello(string name);
}

public class MyEnglishClass:IMyInterface
{
public string Hello(string name)
{
return "Hello " + name;
}
}

public class MyFrenchClass : IMyInterface
{
public String Hello(string name)
{
return "allo " + name;
}
}


44. What is difference between Abstract class and Interface?
In Interface all the method must be abstract; in abstract class we can have both abstract and concrete methods.
Access modifiers cannot be specified in interface because it should always be public; in Abstract class, we can specify the access modifier.
45. In which Scenario you will go for Abstract or Interface Class?
Abstract classes are useful when creating components because they allow you specify an invariant level of functionality in some methods, but leave the implementation of other methods until a specific implementation of that class is needed. They also version well, because if additional functionality is needed in derived classes, it can be added to the base class without breaking code.

Interfaces are often used to describe the peripheral abilities of a class, not its central identity, e.g. an Automobile class might implement the Recyclable interface, which could apply to many otherwise totally unrelated objects.

46. What is mean by polymorphism?
Polymorphism means the ability to take more than one form. An operation may exhibit different behaviors in different instances. The behavior depends on the data types used in the operation. Polymorphism is extensively used in implementing Inheritance.

47. What are different types of polymorphism?
There are two types of polymorphism

Static polymorphism - defining the method with same name and different signature is called as static polymorphism. In the below example there are three different Add() functionality this Add() will be executed based on the parameter passed.
Example :
public int Add(int a, int b)
{
return a + b;
}

public double Add(double a, double b)
{
return a + b;
}

public long Add(long a, long b)
{
return a + b;
}
Dynamic polymorphism – Dynamic polymorphism can be implemented using Virtual and Override keyword. By using polymorphism, each derived class can have its own behavior, Even though classes are derived or inherited from the same parent class.
Example:

In the below example ClassB is inherited from ClassA. ClassB can have its own behavior by overriding the parent class method. Parent class method should be represented with virtual keyword to override the same method in derived class.

public class ClassA
{
public virtual void Display()
{
Console.WriteLine ( "ClassA");
}
}

public class ClassB:ClassA
{
public override void Display()
{
Console.WriteLine ( "ClassB");
}
}

static void Main(string[] args)
{
ClassA a = new ClassA();
ClassB b = new ClassB();
ClassA c = new ClassB();
a.Display();
b.Display();
c.Display();
Console.ReadLine();

}

OutPut:
ClassA
ClassB
ClassB
48. What you mean by Encapsulation?
Encapsulation is the procedure of covering up of data and functions into a single unit and protects the data from the outside world. Example “Class” only public functions and properties are exposed; functions implementation and private variables are hidden from outside world.

49. What is difference between data encapsulation and abstraction?
Abstraction refers to the act of representing essential features without including the background details or explanations. Storing data and functions in a single unit is called as encapsulation.

50. What is mean by Delegate?
Delegate is a type that holds a reference to a method or a function. . Once a delegate is assigned a method, it behaves exactly like that method. We can call the method using delegate instead of directly calling the method. Using delegate, we can also pass the parameter and get return value. Any method with matched the signature of the delegate can be assigned. Simply we can say .NET implements the concept of function pointers using delegate.

Example:

There are three step to following for using Delegate

Declaration
Instantiation
Invocation
In the below example we have declared the new delegate “MyDelegate”, which accept string as parameter and return value as string. Two methods SayHello and SayBye function will be called using delegate.

//Declaring the delegate
delegate string MyDelegate(string name);

//function called by delegate dynamically
private static string SayHello(string name)
{
return "Hello " + name;
}

private static string SayBye(string name)
{
return "Bye " + name;
}


After declaration of delegate, we have initialized with SayHello function. Now this delegate will hold reference to specified function. Function will be called using Invoke () method of delegate. In this example we have called two methods (SayHello and SayBye) with same signature(parameter type and return type).

static void Main(string[] args)
{

//Initialllizing delegate with function name
MyDelegate delg = new MyDelegate(SayHello);
//Invoking function using delegate
Console.WriteLine(delg.Invoke("Sam"));

delg = new MyDelegate(SayBye);
//Invoking diffent function using same delegate
Console.WriteLine(delg.Invoke("Sam"));

Console.ReadLine();
}

OutPut:
Hello Sam
Bye Sam


51. What’s a multicast delegate?
It’s a delegate that stores the address of multiple methods and eventually fires off several methods. Multicast delegate must have a return type of void.

52. What is an Asynchronous delegate?
When you invoke a delegate asynchronously, no new thread is created. Instead, the CLR automatically assigns a free thread from a small thread pool that it maintains. Typically, this thread pool starts with one thread and increases to a maximum of about 25 free threads on a single-CPU computer. As a result, if you start 50 asynchronous operations, one after the other, the first 25 will complete first. As soon as one ends, the freed thread is used to execute the next asynchronous operation.

53. What is mean by Events?
Events are nothing but a publisher and subscriber model. Any subscriber who is interested in receiving notification from the publisher can subscribe the events. If source event is fired or publisher raises the event, a notification will be send to all subscribers. One publisher can have multiple subscribers. Internally events will try to make use of delegate for this publisher, subscription model.

Example:

In the below example, we have created new event called "SampleEvent" and this event will be fired once MyMethod() is called. Anyone who wants to subscribe to this event can create a instance of the MyClassWithEvent and add handler to the event. So when ever event is raised, add handler method will be called.

Public Class MyClassWithEvent

'Created New Event, which will return a message to all subscriber
Event SampleEvent(ByVal message As String)

'Event will be fired once this method is called
Public Sub MyMethod()
Console.WriteLine("MyMethod is called")
'Raising the event with message
RaiseEvent SampleEvent("Event is Raised from MyClassWithEvent")
End Sub
End Class

Module Module1

Sub Main()

Dim c As New MyClassWithEvent
'First subscriber of the event
AddHandler c.SampleEvent, AddressOf EventSubscriber1
'Second subscriber of the event
AddHandler c.SampleEvent, AddressOf EventSubscriber2
c.MyMethod()
Console.ReadLine()
End Sub

Private Sub EventSubscriber1(ByVal message As String)
Console.WriteLine("Subscriber 1")
Console.WriteLine("Message: " + message)
End Sub

Private Sub EventSubscriber2(ByVal message As String)
Console.WriteLine("Subscriber 2")
Console.WriteLine("Message: " + message)
End Sub
End Module

OutPut:
MyMethod is called
Subscriber 1
Message: Event is Raised from MyClassWithEvent
Subscriber 2
Message: Event is Raised from MyClassWithEvent


54. Can event’s have access modifiers?
Yes, Event’s can have access modifier, if we mention it as Protected events can be subscribed only within inherited class, If you mention it as Internal(C#)/Friends(VB.Net) it can be subscribed by all class inside the assembly. If you mention it as Private it can subscribed with in class where it is declared.

55. Can we have static/shared events?
Yes, we can have static(C#)/shared(VB.Net) event, but only shared method can raise shared events.

56. Can we have different access modifier for Get/Set of the properties?
Yes, in C# 3.0 and above, we can use different access modifier for Get/Set of the properties, but this is not possible in C#2.0 and lower

57. What is an indexer?
An indexer is an accessor that enables an object to be treated in the same way as an array. An indexer is considered when a class is better represented as a virtual container of data that can be retrieved or set using indices. Since an indexer is nameless, its signature is specified by the keyword “this” followed by its indexing parameters within square brackets.

Example:

In the below example we have created new index for class of type string. During get and set operation string manipulations are done.


public class MyClassForIndexer
{
private string m_Name = "This is example for indexer";
public string this[int index]
{
get
{
return m_Name.Substring( index);
}
set
{
m_Name = m_Name.Insert(index, value);
}
}
}
MyClassForIndexer ind = new MyClassForIndexer();
Console.WriteLine (ind[0]);
ind[7] = "Appended String";
Console.WriteLine(ind[0]);
Output:
This is example for indexer
This isAppended String example for indexer


58. What is ENUM?
ENUM means Enumeration; it is used to group related sets of constants. To create a enumeration you use the Enum statement

Example:

Enum Months
January = 1
Feburary = 2
March = 3
April = 4
May = 5
June = 6
July = 7
August = 8
September = 9
October = 10
November = 11
December = 12
End Enum

Tuesday, October 18, 2011

The SharePoint 2010 Developer Platform

SharePoint 2010 as an Application Platform
What is an application platform? It’s a broad idea that can include a range of interconnected technologies. ASP.NET is a platform for creating Web applications, for example, while at the same time belonging to the larger application platform provided by the .NET Framework.
SharePoint 2010 also provides an application platform. This platform relies on ASP.NET and other .NET Framework technologies, but it adds plenty of SharePoint-specific functionality. A developer creating an application on SharePoint will use ASP.NET, but he’ll also use other services that the platform provides.
Because the SharePoint 2010 application platform is based on ASP.NET, learning how to use it isn’t a huge leap for ASP.NET developers. But when does it make sense to build an application on SharePoint rather than on raw ASP.NET?
The goal of this paper is to answer that question. Doing this requires describing what the SharePoint 2010 platform provides as well as looking at the types of applications SharePoint is designed to support. If your application can benefit from the SharePoint framework, building it on SharePoint will let you focus more on creating value and less on building infrastructure.
What is SharePoint?
If you’re like most developers, you probably think of SharePoint as a technology that lets users create their own Web sites, then use those sites to do things like share documents. This is exactly right. Rather than needing to work with an ASP.NET developer, deal with a database administrator (DBA), and talk to their Web admin, a user can create a new site by just filling in and submitting an online SharePoint form. And since users want many different kinds of Web sites, SharePoint includes many different templates, each defining a specific style of site.
In this sense, SharePoint acts like an application. Yet the Web sites that SharePoint creates for its users are implemented with ASP.NET. Because developers can create their own ASP.NET-based applications on the foundation that SharePoint provides, it’s also correct to view this technology as providing a developer platform.
Understanding that platform requires first teasing apart the main SharePoint components. The 2010 release of SharePoint can be viewed in three parts:
Microsoft SharePoint Foundation 2010: The basis of everything else in SharePoint, SharePoint Foundation 2010 is the successor to Windows SharePoint Services 3.0. It contains the basic services that developers use to build applications on this platform, and it’s available as a free download for Windows Server 2008.
Microsoft SharePoint Server 2010: The successor to Microsoft Office SharePoint Server (MOSS) 2007, this product contains a group of technologies that address more specialized problems. Among the functions SharePoint Server 2010
3
provides are enterprise content management, enterprise search, and support for using InfoPath Forms. While SharePoint Server 2010 is built largely on SharePoint Foundation 2010, it’s a separate product—using it requires purchasing a license.
SharePoint Online: A Microsoft-hosted version of SharePoint technology, this offering lets both users and developers use SharePoint’s functionality without installing any on-premises SharePoint software.
A note on terminology: This paper uses "SharePoint" as an umbrella term for all of these things. Whenever it’s important to distinguish among them—and it often is—a specific name is used.
It’s worth pointing out just how popular SharePoint has become. WSS 3.0, the predecessor to SharePoint Foundation 2010, is part of Windows Server, and it’s in use at many, many organizations today. Microsoft Office SharePoint Server 2007, the predecessor to Microsoft SharePoint Server 2010, is a billion dollar business for Microsoft. Microsoft’s commitment to SharePoint is evident—it’s a profitable area for the company. For developers, this popularity and commitment help make SharePoint a safe platform to build on.
There’s an obvious question here: If SharePoint provides such a useful platform for creating ASP.NET-based applications, why don’t more ASP.NET developers use it today? A big part of the answer is that, prior to SharePoint 2010, the SharePoint platform wasn’t as developer-friendly as it might have been. With SharePoint 2010, Microsoft has worked to correct this, making the platform more natural and easier to use for mainstream ASP.NET developers. Today, your ASP.NET skills are likely to fit quite well with the SharePoint world.
Building SharePoint Applications
SharePoint lets ordinary users—non-developers—do useful things all by themselves. Along with creating Web sites, users can customize many aspects of how a site looks and acts, such as its user interface, without relying on a developer. If a SharePoint-knowledgeable developer is available, though, more customization of a SharePoint site is possible. For example, adding a new menu item to a site’s user interface, then writing code to carry out an action for that new option requires a developer. A significant majority of the code written for SharePoint today provides some kind of customized behavior for a SharePoint Web site created by a user.
Yet writing this kind of customization code for SharePoint isn’t the focus here. Instead, imagine that you’re assigned the task of creating a new ASP.NET application. You can build the application in the usual way, using the .NET Framework, Internet Information Services (IIS), and a relational database such as SQL Server. Or, if you choose to, you can build it as a SharePoint application. It’s important to understand that the SharePoint development platform itself relies on the .NET Framework, IIS, and SQL Server. Because of this, creating a Web application on this platform means using Windows technologies you already know.
To get a big-picture view of where the SharePoint platform adds value for developers, look at the abstract model of a Web application shown in Figure 1.



Figure 1: Web applications commonly have the same basic components.
As the figure shows, a Web application typically includes a user interface, business logic, and data. The application runs on some kind of execution environment, and it’s created using one or more development tools. Interacting with all of this technology are people in three different categories: users, developers, and administrators.
With this picture in mind, it’s possible to summarize the main things that the SharePoint 2010 development platform provides: A widely deployed execution environment for SharePoint applications, complete with trained administrators who understand this environment. A built-in way to work with data as lists, together with the ability to access other data, including data stored in relational databases. Support for building business logic using ASP.NET pages, workflows created with Windows Workflow Foundation (WF), and in other ways. A way for developers to create a user interface in the common SharePoint style that many users already know, then let users customize this interface themselves. A set of development tools, both Visual Studio-based and SharePoint-specific, to help create and maintain applications for the SharePoint environment.
An application written for the SharePoint platform can use all of these options or just some of them—there’s no requirement to adopt everything.
In fact, one way to think of the SharePoint platform is as a Microsoft-provided application framework for Web-based software. Creating an ASP.NET application from scratch usually requires specifying a user interface, doing some database design, and maybe even setting up a server farm to run the application. To make this simpler, many organizations have created their own in-house application frameworks for ASP.NET, providing standard solutions for these areas. Yet for at least some applications, using the Microsoft-provided SharePoint platform is a better idea. Much of what you need can be provided by SharePoint Foundation 2010, so there’s nothing
5
extra to buy. And as always, using a framework can let you focus more on creating the business logic that provides the application’s value and less on building infrastructure.
Buying into the SharePoint world does require some changes, however. For example, ASP.NET developers are accustomed to having control of their environment, such as the ability to directly edit their application’s web.config file. For SharePoint applications, this file is under the control of your SharePoint administrators, not you. While changes are possible, they must be made programmatically. Also, access to SharePoint services typically requires using the SharePoint object model, a set of classes specifically designed for this environment. Learning these classes isn’t especially difficult, but it is different from the standard ASP.NET environment.
As with any application framework, understanding the platform you’re building on is essential to writing good code. The first step in grasping the SharePoint development platform is understanding what SharePoint Foundation 2010 provides. The next section takes a look at this fundamental technology. Microsoft SharePoint Foundation 2010
For application developers, SharePoint Foundation 2010 is the most important part of SharePoint. In fact, while SharePoint Server 2010 provides plenty of useful services for application developers, it’s possible to build applications entirely on SharePoint Foundation.
The services that SharePoint Foundation 2010 provides for developers can be grouped into four categories: data, business logic, user interface, and access control. This section describes all four. First, however, we need to walk through the basics of the SharePoint execution environment.
The Execution Environment
SharePoint is built on ASP.NET. Accordingly, the SharePoint execution environment looks much like any other group of machines set up to run ASP.NET applications. This group, called a SharePoint farm, is illustrated in Figure 2


Figure 2: A SharePoint farm contains one or more machines dedicated to running SharePoint and SharePoint applications.
As the figure shows, a SharePoint farm always contains IIS and SQL Server. This example shows the most general possibility—separate machines for IIS, applications, and SQL Server—although a farm can be simpler than this. In a development environment, for instance, it’s typical to run everything on a single machine. The right structure depends on variables such as how the farm is used and how many users it must support.
Whatever the physical structure of a SharePoint farm, its logical structure is defined by one or more SharePoint sites grouped into site collections. Figure 3 illustrates the relationship between sites, site collections, and a SharePoint farm.



Figure 3: A SharePoint farm can support multiple SharePoint sites grouped into site collections.
A SharePoint site is just what it sounds like: It’s a Web site that one or more users can access. SharePoint Foundation 2010 includes a variety of different templates for creating SharePoint sites, and Microsoft SharePoint Server 2010 provides still more. For example, SharePoint Foundation 2010 provides pre-defined sites that let users share documents, create blogs, and many others.
As Figure 3 shows, each SharePoint site belongs to some site collection. A site collection always has a root site, and this root can optionally have other sites beneath it. Although it’s not shown in the figure, those sites can also have children, and so on, allowing a site collection to be a multi-level hierarchy.
To understand why SharePoint sites are organized this way, think about a primary purpose of this technology: giving organizations a quick and easy way to create and use Web sites. Making an organization’s users rely on their IT department to create every site isn’t an attractive option, especially in big companies. With SharePoint, a user—not an IT person—is typically given administrative permissions to a site collection. Rather than relying on IT, this site collection admin can create new sites in the collection, add and remove users, and more. She can also create site administrators, people with power over a single SharePoint site in this collection. Yet being a site collection admin or a site admin confers no administrative rights to the underlying machines in the SharePoint farm. This lower-level work, things such as adding new machines to the farm and creating site collections, is done by the
8
administrators of the farm itself. This multi-level administrative structure neatly separates responsibilities, giving both IT and users the rights that they need.
Working with Data
Both the people who use SharePoint and the developers who create SharePoint-based applications must work with data. And while SharePoint is built on SQL Server, it doesn’t expose ordinary relational tables. Instead, SharePoint data is represented using a higher-level abstraction called a list. For end users, lists are simple to understand and easy to use.
Lists can also be useful for application developers. But SharePoint applications need other ways to work with information too, such as access to data stored outside the SharePoint environment. Fortunately, SharePoint Foundation 2010 makes this possible.
In fact, there are three ways for a SharePoint application to work with data: Lists, a SharePoint-specific way to represent data. External lists, which allow reading and writing various kinds of data stored outside a SharePoint farm as if that data was an ordinary SharePoint list. Direct ADO.NET access to relational data stored in databases outside a SharePoint farm.
Figure 4 illustrates all three options, and the rest of this section takes a brief look at each one.





Figure 4: A SharePoint application can work with data in SharePoint lists, in external lists, and in relational databases.
A SharePoint list is just what it sounds like: a list of items, each of which has some number of fields. For example, the items in a list containing information about the students enrolled in a course might have fields such as Name and Grade, while list items describing a firm’s products might have fields like Product Number, Size, and Color. SharePoint also provides a predefined list type called a document library, which can contain documents such as Microsoft Word files. Document libraries are a specialization of SharePoint’s general list structure, adding things like a built-in facility for checking documents in and out of the library. To access lists, applications can use either the SharePoint object model, which provides SharePoint-specific ways to query and modify list data, or LINQ to SharePoint, a version of LINQ designed to be used with SharePoint lists.
Lists can be quite useful. Their attractions include: Lists are simpler to use than ordinary relational data. The administrator of a site or of a site collection or even an ordinary user can create new lists and add new fields. There’s no need for relational table design, defining connection strings, or negotiating with a DBA. Users can work with list data directly. As described later, SharePoint Foundation 2010 provides built-in user interface elements that allow list access via a browser. It’s possible to create relationships between lists. This allows creating helpful behaviors such as cascading deletes, where deleting a list item also deletes all of the list items related to it. SharePoint provides built-in access control mechanisms for lists, a topic discussed in more detail later.
10
Useful as they are, lists aren’t relational databases, and LINQ to SharePoint can’t always be used. Instead, things such as access to external lists require using a SharePoint-defined language called the Collaborative Application Markup Language (CAML). CAML isn’t especially difficult, but it is another language for developers to learn. Also, because data in lists isn’t exposed as standard relational tables, making that data available to technologies such as SQL Reporting Services can take work.
Still, lists are the primary abstraction for storage in the SharePoint world. But what about SharePoint applications that need to access data outside this world? Another alternative is to use ADO.NET to access an external relational database. Just like an ordinary ASP.NET application, a SharePoint application is free to do this, as Figure 4 shows. This approach allows broad data access, at the cost of giving up the benefits and simplicity of SharePoint lists.
The third data access option, external lists, is new with SharePoint Foundation 2010. The goal of external lists is to allow access to data stored outside a SharePoint farm while still retaining many of the advantages of lists. To a SharePoint application (and a SharePoint user), an external list looks much like any other list. The big difference is that the data it exposes actually comes from a source outside this SharePoint farm.
An external list relies on a SharePoint Foundation 2010 technology called Business Connectivity Services (BCS). BCS can use Web services, ADO.NET, or custom code to access external data sources, presenting it as an external list. SharePoint users and applications are free to read and write this data just as with ordinary lists.
While external lists are new with SharePoint Foundation 2010, Business Connectivity Services is the evolution of an earlier SharePoint technology called the Business Data Catalog (BDC). This technology was part of Microsoft Office SharePoint Server 2007, however, not WSS 3.0. More important, this previous version was read-only, while the version in SharePoint Foundation 2010 is read-write. These changes make accessing data stored outside an application’s SharePoint farm both simpler and more general.
So far, this discussion has focused on how an application running in a SharePoint farm can access data. But what about the opposite problem? How can an application running outside of the SharePoint world access data held in a SharePoint farm? In SharePoint Foundation 2010, SharePoint lists can be accessed from the outside world using SOAP or the RESTful approach of ADO.NET Data Services. To make this easier, Microsoft also provides client libraries for JavaScript, Silverlight, and the .NET Framework. Using the client object model these libraries provide, a non-SharePoint application can work with lists stored in a SharePoint farm. For example, an AJAX application might use the JavaScript client library to access a SharePoint list, while a Silverlight or .NET Framework application might use a SharePoint document library to provide check-in/check-out capabilities for its users. The key point is that data stored in a SharePoint farm can still be accessed by other software; it’s not available solely to SharePoint applications running in that farm.
Writing Business Logic
By definition, applications implement logic. If she chooses to, an ASP.NET developer building a SharePoint application can create that logic using familiar .NET Framework technologies. She can also create logic using SharePoint-specific mechanisms. Figure 5 shows the options.


Figure 5: Business logic for a SharePoint application can be created using ASPX pages, ASMX Web services, WF workflows, and more.
To create a SharePoint application’s logic, a developer can use ASPX pages, as Figure 5 shows. There are some restrictions—pages typically can’t contain script, for example, so code-behind is required, and your application will commonly need to integrate with a SharePoint-provided master page—but still, a SharePoint application is an ASP.NET application. To expose Web services, a developer can use ASMX or Windows Communication Foundation (WCF).
It’s common to implement a SharePoint application’s logic in a Web Part. Most ASP.NET developers today are familiar with Web Parts—they’re a standard component of that technology. (In fact, Web Parts originated in SharePoint, then were added to ASP.NET.) A Web Part is just a special kind of ASP.NET control that’s deployed inside a Web Part zone. Each Web Part can contain code-behind logic in ASPX pages, and so it provides a self-contained way to implement logic and the user interface for that logic.
A developer can also implement a SharePoint application’s business logic as a workflow using Windows Workflow Foundation (WF) 3.5. Workflows are a common choice for supporting long-running business processes, such as employee onboarding and claims processing. By itself, WF provides only the basics needed to create workflows. SharePoint Foundation 2010 fills in the gaps, offering a host (a SharePoint worker process), tools for creating workflows (including SharePoint Designer, described later), a way for people to interact with a running workflow (through a kind of SharePoint list called a task list), and more. Building a workflow application on SharePoint Foundation 2010 is significantly easier than building one using just raw WF.
Along with these familiar .NET Framework technologies, SharePoint Foundation 2010 provides two more ways to create business logic. The first, called an event receiver, acts much like a trigger in a relational database. For example, a developer can create an event receiver that runs when a specific event occurs for a particular list, such as a user’s attempt to update data. The event receiver might, say, validate that data before it’s stored in the list, making sure that the user isn’t inserting invalid information. Event
12
receivers can also handle other list-related events, such as a user’s attempt to delete a list. Note the difference between a workflow and an event receiver: While a workflow has state and typically runs for a reasonably long time, an event receiver runs only long enough to handle the event that triggered it, and it doesn’t maintain any state between events.
One more option for implementing business logic in a SharePoint application is to create a timer job. As the name suggests, a timer job is code that runs at a specific time. For example, suppose an application needs to copy data from a SharePoint list to an external system once a day. The creator of that application might write a timer job to carry out this function, setting it to run each day at 4 am.
Business logic is an important part of most applications. Yet to make this logic useful commonly requires exposing it to people through some user interface. How SharePoint allows this is described next.
Creating User Interfaces
Just like ordinary ASP.NET applications, SharePoint applications commonly present a browser-based user interface. To make life simpler for users, SharePoint defines basic user interface elements, together with conventions for how those elements should be applied. Figure 6 shows the basics of the default SharePoint user interface.



Figure 6: The default user interface for a SharePoint application has a banner, a navigation section, and one or more Web Parts.
13
As the figure shows, a typical SharePoint user interface provides a banner at the top of the page. This area can be used to show a company logo, display an enterprise search box, or for other things. The default interface also contains navigation areas along the left side and across the top. These typically provide a direct way to access interesting things in the site, such as document libraries and other important lists.
The third element in the standard SharePoint user interface is Web Parts. As described earlier, a Web Part encapsulates logic behind a user interface element. Each Web Part can expose actions, such as the ability to change the content this Web Part is displaying or move the Web Part to a new location on the screen. This lets a user customize the page he sees, rearranging and configuring Web Parts as desired. This flexibility makes it easier for developers to create an application that users can customize.
Developers are free to create their own Web Parts. SharePoint Foundation 2010 provides a number of built-in Web parts, however, and Microsoft SharePoint Server 2010 adds even more. For example, some of the more commonly used Web Parts included with SharePoint Foundation 2010 are: List View Web Part: Displays the contents of a SharePoint list Data View Web Part: Provides a customizable and quite general way to display a range of data types, including SharePoint lists, XML documents, data from a relational database, and others. Image Web Part: Allows displaying an image or graphic.
While it’s fair to say that SharePoint applications usually use Web Parts and often use the interface style shown in Figure 6, it’s possible for a SharePoint developer to create his own entirely custom user interface. He’s not required to follow SharePoint’s default conventions. For example, the creator of a public Web site built on SharePoint probably wouldn’t use these defaults, choosing instead to implement a more customized look.
Many ASP.NET developers are accustomed to having complete freedom in designing an application’s user interface. Why would they ever want to limit themselves by adhering to the default SharePoint interface style? Perhaps the most important reason is that, because SharePoint is so widely used today, more and more people are familiar with this kind of interface. If people feel immediately comfortable with a new application’s interface, they’re more likely to adopt and use that application. Adopting the default interface style also saves development time, since there’s no longer any need to design (and probably argue about) the basic layout of your user interface. Furthermore, because the SharePoint interface relies on Web Parts, your application can easily present a customizable face to its users, and the built-in Web Parts that SharePoint provides can help you create your application more quickly.
SharePoint Foundation 2010 includes some user interface improvements over its predecessor. For one thing, there’s now support for a broad range of Web browsers. Just as important, it’s now possible to deploy a Silverlight application in a SharePoint Web Part. This lets a SharePoint application download and run Silverlight code in the user’s browser. This code can then talk back to the SharePoint application through the client object model or in some other way, accessing SharePoint lists and more. The
14
result is the ability to create SharePoint applications with more capable user interfaces.
Providing Access Control
ASP.NET applications commonly require their users to authenticate themselves, proving who they are with a password or something else. Once an application knows who its user is, the next problem is to figure out what that user is authorized to do. Building an ASP.NET application typically requires solving both of these problems. Building that application on SharePoint Foundation 2010 can make doing this easier.
Rather than recreating the wheel, SharePoint Foundation 2010 relies on IIS for authentication. Part of setting up SharePoint is configuring an IIS Web site to support multiple SharePoint sites. All of the SharePoint sites contained within that IIS Web site will then use the same mechanism to authenticate their users.
Once a user has been authenticated, the application must make an authorization decision. If it’s built using raw ASP.NET, the application will likely contain custom code to do this. If the application is built on SharePoint Foundation 2010, however, it can rely on SharePoint’s built-in authorization mechanisms.
To let a SharePoint application use these mechanisms, a site collection administrator first uses standard SharePoint tools to define groups, then adds users as members of these groups. Because they’re defined at the site collection level, these groups can be referenced across all sites in this collection. For example, the administrator can use them to define who’s allowed access to a specific site in the collection.
More fine-grained access control is also possible. An administrator can specify which users and/or groups have access to specific lists within a site, for example, then rely on SharePoint Foundation 2010 to enforce these restrictions. Rather than requiring the application developer to write her own authorization code for site and list access, SharePoint Foundation 2010 provides this for her.
SharePoint Foundation 2010 also provides standard Web Parts for working with authorization. For example, the Site Users Web Part, which can be added to any Web Part page, displays a list of the users and groups who have permission to use a site. Especially for applications that use lists, SharePoint can make authorization significantly simpler. Once again, the goal is to let developers focus their efforts on meeting business requirements rather than on writing infrastructure code. The SharePoint 2010 Execution Environment: A Closer Look
To an ASP.NET developer, one of the attractive things about SharePoint is that organizations that use it already have a managed environment with trained administrators. SharePoint farm admins know how to add servers, perform backups, install applications, and more. Because a new SharePoint application can take advantage of this existing human infrastructure, a developer’s life can be simpler.
But while SharePoint farm administrators can help, they can also set limits on what SharePoint applications can do. To see why requires understanding how SharePoint applications are deployed, described next.
15
Farm and Sandboxed Solutions
When a user customizes his view of a SharePoint site, such as by rearranging the Web Parts he sees, those customizations are stored in a content database. All of the sites in a site collection typically share a single content database, which is stored in the SharePoint farm’s SQL Server database.
When a new SharePoint farm solution is deployed, its code is not placed in the content database. Instead, the files for a farm solution must be installed directly in the file system of the farm’s Web servers (or, if they’re present, on its application servers). The good thing about this is that a farm solution is potentially available to all of that farm’s users. Yet think what else this implies: First, farm solutions must be installed by farm administrators. Site and site collection administrators can’t do it. Second, a solution installed directly on the farm’s Web servers (or application servers) can affect anything in the entire farm. If a farm solution installed for use at just one site within some site collection behaves badly, it can hurt performance or otherwise destabilize the entire SharePoint farm.
If you were a SharePoint farm administrator responsible for keeping a farm running, wouldn’t you be very conservative about the farm solutions you installed? In fact, might you even refuse to install new farm solutions at all? Why risk damaging the entire farm and all of its users for solutions that benefit only some of them?
This was a concern with the previous version of SharePoint, since it only supported farm solutions. SharePoint Foundation 2010, however, brings a new answer to this problem: sandboxing. A sandboxed solution no longer need be installed by a farm administrator and be made available to any site in the farm. Instead, it can be installed by a site collection administrator and be made accessible only to the sites in that collection. For this to work, a sandboxed solution can’t be installed on the farm’s Web or application servers. Instead, the solution’s code is installed in the content database, alongside user customizations and other information. Figure 7 illustrates this.



Figure 7: Farm solutions and sandboxed solutions are installed in different places in a SharePoint farm.
Unsurprisingly, sandboxed solutions are subject to some constraints. For example, there are limits to the CPU time and SQL query execution time each sandboxed solution can consume. Without this, a sandboxed solution installed for one site collection could hurt performance for the entire farm. Also, a sandboxed solution isn’t allowed to access everything exposed by the SharePoint object model, nor can it access SharePoint data outside of the site collection it’s installed in. There are other restrictions too, such as limitations on how workflows can be used. Still, for applications that can live within these restrictions, sandboxing makes SharePoint Foundation 2010 significantly more practical than its predecessor as a development platform.
Whether your app runs as a sandboxed or farm solution, it’s packaged into what SharePoint calls a WSP file. This file is just a CAB file with a .WSP extension, and it contains all of the parts of your solution: assemblies, configuration information, and more. The nice thing about this is that it provides a single deployment unit for an entire SharePoint solution, wherever it will be deployed.
Using SharePoint Online
One more deployment option that hasn’t yet been mentioned is hosted SharePoint. A number of companies provide this service, letting organizations use SharePoint without any on-premises infrastructure. Microsoft also provides its own hosted offering, called SharePoint Online, as part of the Business Productivity Online Suite (BPOS).
In its initial incarnation, SharePoint Online was relatively limited as an application platform. While customers could get their own site collections, running complete custom applications wasn’t possible. This changes with the 2010 version of SharePoint Online. With this new release, customers can upload and run sandboxed
17
solutions. Organizations that want to build SharePoint applications but don’t have their own SharePoint farm can now use SharePoint Online instead. SharePoint 2010 Developer Tools
As with any other application, building SharePoint applications depends on tools. Microsoft provides two choices, each targeting a specific audience: Visual Studio 2010, which contains templates and tools targeting .NET Framework developers building SharePoint applications SharePoint Designer (SPD) 2010, targeting SharePoint users and, in some situations, developers customizing SharePoint sites and creating more limited application logic.
Figure 8 illustrates these options.



Figure 8: Both SharePoint Designer and Visual Studio can be used in creating SharePoint applications.
Visual Studio is a familiar tool to ASP.NET developers. To create a SharePoint application with Visual Studio 2010, a developer creates a SharePoint project. Once
18
this is done, Visual Studio 2010 provides a variety of SharePoint-specific features. For example, the Server Explorer for SharePoint lets a developer view SharePoint lists and other information from inside Visual Studio, while various wizards support things such as creating SharePoint event receivers. Visual Studio 2010 also provides tools to create a WSP file, structuring its contents as needed. There’s even a checkbox that lets a SharePoint developer indicate that a project will run in a sandbox. Checking this causes Visual Studio 2010 to allow only behaviors that are legal for sandboxed solutions.
All of these are examples of an important philosophical shift in SharePoint development. Prior to SharePoint 2010, creating SharePoint applications with Visual Studio could be challenging—the tools just weren’t as good as they might have been. Microsoft set out to fix this with the 2010 release, making SharePoint a first-class development environment with first-class tools. This new perspective is what underlies the significant changes in Visual Studio 2010. It motivated other changes as well, such as the ability for developers to install a SharePoint environment on 64-bit versions of Windows 7 and Windows Vista. This new release also lets the creators of SharePoint applications use Visual Studio Team System and Team Foundation Server, helping improve the development process. Making it easier and more natural for .NET developers to create SharePoint applications was a high priority for this new version of the technology.
Along with Visual Studio, SharePoint developers are also likely to use SPD. SPD can be useful in two ways: as a customization tool for SharePoint sites and as a companion to Visual Studio. In fact, some things that developers want to do are easier in SPD than in Visual Studio. For example, creating a user interface can be simpler with SPD, while customizing the Data View Web Part mentioned earlier effectively requires using this tool. Creating a workflow can also be easier, since SPD provides a workflow designer intended for less technical people.
It’s also possible to use SPD and Visual Studio together. For instance, suppose a business-oriented developer uses SPD’s designer to create a workflow. A .NET developer can import this workflow into Visual Studio, then add more technical detail. This approach helps professional .NET developers work more effectively with less technically oriented people, each using a tool that’s appropriate for their role.
The bottom line is that effective development depends on effective tools. With SharePoint 2010, what was a sub-optimal story gets significantly better. Lack of good tools is no longer the roadblock it once was to creating SharePoint applications. Using Microsoft SharePoint Server 2010
SharePoint Foundation 2010 is the underpinning for every SharePoint application. Yet for some of those applications, life is simpler for developers if they also use Microsoft SharePoint Server 2010. Unlike SharePoint Foundation, SharePoint Server isn’t freely downloadable—it’s a separately licensed product. Still, if the built-in functionality it provides saves enough effort, both in development and maintenance, writing this check can make sense.
To a great degree, SharePoint Server is focused on providing immediate value to end users. It’s not just a platform for custom development. Yet the product also contains a
19
large number of Web Parts, .NET assemblies, and other useful components that developers creating SharePoint applications can use.
Microsoft groups the functions of SharePoint Server 2010 into six areas: Content: One of the most popular uses of SharePoint Server is for enterprise content management (ECM). In general, ECM means managing the flow of documents and other content, including things like creating the content, approving it, making it available to people, and updating it. SharePoint applications focused in this area might benefit from building on these services. SharePoint Server also supports records management, including a toolkit to help organizations build their own custom solutions. Communities: SharePoint Foundation 2010 allows creating sites with blogs and wikis. SharePoint Server adds extra functionality here, aimed at making these social computing technologies more effective for enterprises. It also includes broadly useful things such as an address book, letting the developers of a SharePoint application focus on writing business-specific code. Composites: Many applications combine assorted parts into a more useful whole, and SharePoint Server includes several services to help do this. For example, while SharePoint Foundation provides support for workflows, SharePoint Server builds on this with pre-defined workflows for document approval and other purposes. The product also includes Forms Services, a helpful addition for applications that use InfoPath forms. Without Forms Services, a SharePoint application that presents InfoPath forms to its users requires every desktop to have an installed copy of InfoPath. SharePoint Server also adds extra functionality to Business Connectivity Services, such as the ability to connect to Office clients. Search: Just as Internet search has become part of all our lives, enterprise search matters more every day. SharePoint Server provides a search engine that can be configured to search data in SharePoint as well as data in an organization’s line of business applications. This can include full-text searches as well as searches over relational data. A SharePoint application can build on this facility to present search capabilities to its users. Insights: Providing business insights to users is a fundamentally important goal of enterprise software, and so several aspects of SharePoint Server fit in this category. For example, the product includes Web Parts for displaying key performance indicators. Combined with Business Connectivity Services, this allows creating a SharePoint application that acts as a business dashboard, displaying up to date information about an organization’s status gleaned from its most important applications. SharePoint Server also includes Excel Services, which allows storing and processing Excel spreadsheets on a server rather than on each user’s desktop. This technology stores those spreadsheets in a SharePoint document library, letting users share a single instance of a spreadsheet as well as providing auditing services for spreadsheet access. Sites: Letting users create Web sites easily and quickly is a fundamental goal of SharePoint. SharePoint Foundation allows this on its own, but SharePoint Server adds more functionality in this area. For example, it provides support for
20
publishing Web content, something that’s especially useful for working with larger sites.
For developers, Microsoft SharePoint Server presents a buy-vs.-build decision. To make the right choice, anybody creating SharePoint applications should understand what the product offers, if only to avoid recreating what they could more easily buy. The SharePoint Community Ecosystem
Creating SharePoint applications means becoming a SharePoint developer. As should be clear by now, this isn’t a great leap for anybody who’s conversant with ASP.NET. Still, even a highly skilled ASP.NET developer should take this transition seriously.
As with any other platform, books and training courses can help you use this new technology more effectively. Bookstore shelves groan with volumes on SharePoint today—it’s a popular technology—and many companies offer training for SharePoint developers. There’s also a SharePoint developer community, much like that for ASP.NET. Microsoft designates SharePoint MVPs, provides an official curriculum and certification exams for SharePoint developers, and runs MSDN forums devoted to SharePoint. The Patterns and Practices group in Redmond provides guidance for SharePoint development, just as they do for other Microsoft platforms.
While the SharePoint platform owes a great deal to ASP.NET and the rest of the .NET Framework, it’s not the same thing. Learning how to use this platform well is essential to creating effective SharePoint applications. Target Application Types
Every application platform has its sweet spot, the application types for which it’s best suited. For SharePoint, the target application types include these: Business Collaboration Applications: “Collaboration” is a broad word, but it’s fair to think of SharePoint whenever you need to build an application that helps people work together. Whether this application relies on a WF workflow with InfoPath forms or just logic built using Web Parts, creating a SharePoint application rather than a raw ASP.NET application can be a good option. Portals for LOB Application Data: By using Business Connectivity Services, a SharePoint application can have direct access to data in SAP, Oracle Applications, and other line of business software. An application that’s meant to expose this kind of diverse data to business users is a natural fit for SharePoint. One Web Part Solutions: Small, specialized applications implemented as a single Web Part can be an attractive way to use SharePoint. Think of a custom scheduler for your organization’s conference rooms, for instance, or a simple app that displays current sales volume. Because the SharePoint user interface allows snapping in diverse Web Parts, users can insert this kind of application in whatever context they find useful.
21
Applications that use Microsoft SharePoint Server 2010: If an application can benefit from building on the functions provided with SharePoint Server, it’s an obvious candidate for the SharePoint platform. If the app needs enterprise search capabilities, for example, or records management functions or something else that this product provides, using its pre-built services can make sense. Corporate Web Sites: An organization might use SharePoint to implement its public Web site. An application like this probably wouldn’t use the standard SharePoint user interface style, and it would likely contain other custom code for specific functions. It might also use SharePoint Server for content management or other things.
Understanding the kinds of applications that SharePoint targets is important. It’s also important to understand the kinds of applications that aren’t a great fit for this platform. Building a high-volume transactional system as a SharePoint application isn’t likely to lead to great results, for example, especially if the data is stored in SharePoint lists—they’re not designed for this kind of load. Similarly, you wouldn’t use SharePoint to support data-intensive applications that don’t have end users, such as batch processes or parallel processing software. SharePoint also isn’t usually the right platform for application integration. A Microsoft-oriented integration project should instead use BizTalk Server.
What about independent software vendors (ISVs)? When does it make sense for an ISV to build a commercial application on SharePoint? All of the observations above still hold, of course—some kinds of apps are better suited for SharePoint than others. And ISVs face an additional consideration: Building an application on SharePoint limits the market for that application to customers that use SharePoint. If the application uses only SharePoint Foundation, this is less of an issue. SharePoint Foundation 2010 is a free download for Windows Server, so it’s easily available. Building on Microsoft SharePoint Server is somewhat more constraining, since now customers for the application must also license this product from Microsoft.
Still, the advantages of building on SharePoint, such as faster development time and a standard execution environment, might outweigh these constraints. In fact, a number of ISVs focus solely on selling to SharePoint customers—it’s not a small market. Microsoft’s partner program for SharePoint ISVs can help, too, both with building and selling applications. As the SharePoint environment continues to spread, we’re likely to see the number of ISVs building on it increase as well.
22
Conclusions
For anybody who knows ASP.NET, SharePoint presents a familiar world. By letting developers reuse existing skills in a new context, it provides a development platform that can sometimes be a big step up from the raw .NET Framework. And learning how to build new SharePoint applications also makes developers capable of customizing existing SharePoint sites, a skill that’s in wide demand today.
In the past, many ASP.NET developers were turned off by the SharePoint platform. It was too hard to work with and too different from the standard .NET world. With SharePoint 2010, Microsoft has made a serious effort to fix these problems. Better Visual Studio integration, support for standard .NET technologies such as LINQ, and other improvements make SharePoint a less unnatural world. The addition of sandboxing also helps, letting developers deploy SharePoint applications without risking the entire farm.
If all you needed to do was build a single ASP.NET application, climbing the SharePoint learning curve might not make much sense. If your organization plans to build a number of Web applications, however, understanding what the SharePoint platform has to offer is worthwhile. By providing a common environment with reusable elements for user interfaces, access control, and other typical functions, SharePoint just might make these applications faster to build, easier to maintain, and more attractive to their users. At the end of the day, aren’t these the things that every developer is looking for? About the Author
David Chappell is Principal of Chappell & Associates (www.davidchappell.com) in San Francisco, California. Through his speaking, writing, and consulting, he helps people around the world understand, use, and make better decisions about new technology.