Monday 26 September 2011

What is CAML?Using CAML In SharePoint Object Model To Query List

The Collaborative Application Markup Language (known as CAML) is an XML-based query language that helps querying, building and customizing Web sites based on Windows SharePoint Services. The XML elements define various aspects of a WSS(Windows SharePoint Services) site.

The CAML language has been associated with SharePoint since the first version. It is based on a defined Extensible Markup Language (XML) document that will help to perform a data manipulation task in SharePoint. It is easy to relate a list to CAML if you compare it to a database table and query.

A CAML query must be a well-formed XML document.

Its root element is Query. Within the Query element two other elements are possible but not required: the “OrderBy” element and the “Where” element.

The “OrderBy” clause is not required and it consists of fields which you required to sort. There is a property “Ascending”. If it is set to “True” then result is sort in ascending order and if it is “False” then the result is sort in descending order if you not declare the “Ascending” property then the result is in ascending by default.

The Where clause is used to specify one or more filter criteria. This clause can be very simple but can end up being rather complex. In its most simple form you specify an operator, a field name for which you want to specify a criterion, and a value.

Example:

SQL where Clasue: ” Where Name=’Shoaib’ and RollNo=’28’ order by Name Desc ”

Now convert this into CAML:
<query>
 <where>
  <and>
   <eq>
    <fieldref name='Name'>
   <value type='Text'>Shoaib</value>
    </fieldref>
   </eq>
   <eq>
    <fieldref name='RollNo'>
    <value type='Text'>28</value>
    </fieldref>
  </eq>
 </and>
</where>
 <orderby>
  <fieldref ascending='False' name='Name'>
  </fieldref>
</orderby>
</query>

Now In Above example “Where” and “OrderBy” is the main clause after that “And” tag which is used to “And” both the result. Most important thing is “Eq” tag Eq(Equal to) is same as “=” operator. Similarly following are the different operators which we can use in CAML.

Eq:   Equals

Neq:   Not equal

Gt:   Greater than

Geq:   Greater than or equal

Lt:   Lower than

Leq:   Lower than or equal

IsNull:   Is null

BeginsWith:   Begins with

Contains:    Contains
Fields

“Value” element in above example is simple contains the data type of the attribute and value to compare with.

Now here is the simple example of console programming retrieving List Items with CAML using the SharePoint Object Model.


Example:
1) Open a visual studio2010 in higher privileges mode (Run as Administrator).It is required because to access sharepoint 2010 object models we need higher privilege mode.

2) Create new console C# project.

Note: please select .net 3.5 for targeting framework otherwise it is difficult to find the “Microsoft.Sharepoint” library which is referenced later.

3) Now add rederence to the “Microsoft.Sharepoint” found in .Net Tab.

4)It is important to build and run your application in 64 bit mode to access sharepoint 2010 object models. For this purpose right click your project in solution explorer and click properties.

In properties window click on build tab and select platform target as “x64” instead of “x86”.Save and close the property window.

5) Now type the following code:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.SharePoint;

namespace ConsoleApplication3
{
    class Program
    {
        static void Main(string[] args)
        {
          //Create object of your site
            using (SPSite siteCollection = new SPSite("http://shoaibmuhammadk/"))
            {           

              //get tasks list from your website
                SPList Tasks = siteCollection.AllWebs[0].Lists["Tasks"];
                //create query object on View of your task list
                SPQuery query = new SPQuery(Tasks.DefaultView);
                //Here we define the fields which display in output of caml query
               query.ViewFields = "<FieldRef Name='Title'/><FieldRef Name='DueDate'/><FieldRef Name='Status'/>";
                query.Query = "<Where><Eq><FieldRef Name='Title'/>"
                    + "<Value Type='Text'>"
                    + "MyTask"
                    + "</Value></Eq></Where>";
               //Get all tsks item satisfy the CAML query
               SPListItemCollection mydata=Tasks.GetItems(query);
               //Now loop the obtained list items and display it
               foreach (SPListItem ListItem in mydata)
               {
                   Console.WriteLine("Title:"+ListItem["Title"].ToString()+" Due-date:"+ListItem["Due Date"].ToString()+" Progress:"+ListItem["Status"].ToString());

               }               
            }

            Console.Write("Press ENTER to continue");
            Console.ReadLine();
        }
    }
}

6) Build your application to ensure there is no error!

7) Before running the project. Open your sharepoint site and add some data to list which is queried by our code.




As you see in above image I add four rows to Tasks,Three rows with Title ”MyTask” and one row is with different Title.
We query to the list through CAML with where clause Title=’MyTask’

So three rows should display in output of our code.

6) Run the project.


Three rows in output so our CAML query tested successfully.

Hope It Helps!

Happy Coding :)

For further details about CAML visit: http://msdn.microsoft.com/en-us/library/ms467521.aspx

Wednesday 21 September 2011

What is Abstract Class? Why We Use Abstract Class?Difference Between Abstract Class and Interface?

Abstract Class is a class which cannot be instantiated. It may be partially implemented or unimplemented. The method which is not implemented in abstract class must be declare abstract also.
Have a look simple example:


abstract class MyClass
{
  public void Method_Implemented()
  { 
  //Your Code Here
  }

  public abstract void Method_NotImplemented();
}

Implementation of all methods must be given in class which is derived from abstract class same as interface. When we implement abstract method in derived class it must be marked as override.

Have a Look:

abstract class MyClass
{
  public void Method_Implemented()
  { 
  //Your Code Here
  }
  public abstract void Method_NotImplemented();
}

class ImplementClass : MyClass
{
  public void Method_ClassOwnMethod()//Class own method
  {
  //Your Code Here
  }
  public override void Method_NotImplemented()//Abstract class method implementation
  { 
  //Your Code Here
  } 
}

If we want to unimplement method of abstract class so the derived class also must declare as abstract class.

Have a look:

abstract class MyClass
{
  public void Method_Implemented()
  { 
  //Your Code Here
  }
  public abstract void Method_NotImplemented();
}

abstract class ImplementClass : MyClass
{
  public void Method_ClassOwnMethod()//Class own method
  {
  //Your Code Here
  }
  //Not implement abstract class method
}

In above example derived class also mark as abstract because it not implement method of its parent abstract class.

Now what is the difference between abstract class and Interface?

1) Interface is only contain declaration of members (not code)whereas abstract class may contain code or not.

2) A class derived from multiple interfaces whereas class derived from at most one abstract class (As multiple inheritance not allowed in classes discussed in previous post).

3)Class restrict to implement all members of an interface whereas there is no restriction to implement all members in abstract class in that case the derived class must declare as abstract(Mentioned Above).

What is the purpose of abstract class?

OR

How we choose interface or abstract class for our scenarios?

When we want to build scenario in which all the classes have same structure but totally different implementation than we use interface.

When we want to build scenario in which all the classes have same structure and its implementation is different and have some same functionality.
For example the horse and cow both are herbivorous and both can speak but speak differently.

Example:

abstract class Animal
{
  public void eat()//Same for horse and cow
  {
  Console.WriteLine("herbivorous");
  }
  public abstract void speak();//Only declaration because both speak differently
}

abstract class Horse : Animal
{
  public override void speak()//Implementation according to Horse
  { 
  //Your Code here
  }
}

abstract class COW : Animal
{
  public override void speak()//Implementation according to cow
  {  
  //Your Code Here
  }
}

Take a look diagrammatically:


Please feel free to ask.
Any corrections must be appreciable.
Thank You
hope it helps!

Happy Coding :)

Tuesday 13 September 2011

What Is Interface And Why We Use It?

Interface is simply like a class in OOP(Object Oriented Programming)In which we only declare the functions, properties, events and indexers but not defined that.Interface cannot contain fields. Implementation of all members (functions, properties, events and indexers) of interface must be given in a class which is derived from it.
Very common question is that why we use interface? Answered after some examples so it is more understandable.

Sample Example of Interface:

public interface IA
{
void Add();
int Count { get; }
event MYEvent Changed;
string this[int index] { get; set; }
}

Point to be noted that that there is no access modifies in any of the function or other members of interface in above example. Because declaring member in interface must be without access modifier and when we implement these members in derived class they all must declare as a public otherwise compile error occurs.

Complete Sample Example:

interface IA
{
void Method1();                     //Declare function without definition
void Method2(int i);                //Declare function without definition
}

class Implement_IA : IA       //Derived class of IA so it must implemts all members of interface IA
{
public void Method1()            //Implement method1 of IA must be public
{//....Do Some Work} 

public void Method2(int i)       //Implement method2 of IA must be public
{ //....Do Some Work }

public void ClassOwnMethod(string str)   //This is class own method
{ //....Do Some Work} 

}
public static void Main()
{

//Use of Methods is normal as we use

Implement_IA obj = new Implement_IA ();
obj.ClassOwnMethod("String");
obj.Method1();
obj.Method2(10);
}

In above example we made interface “IA” declare two methods,One class “Implement_IA ” inherit from “IA” and implements methods of interface and contain one its own method.

Why we use interface and purpose of interface?

Now come to question what is the purpose of interface and why we use it.
It is understand by the following phenomenon: 

Human beings have same structure of skeleton. But Outer Covering is different of each human. So consider skeleton as an interface and Outer Covering as class .All Outer Covering of human beings (Classes) inherits from same skeleton (Interface) and implement different functionalities according to that each human is differen from other.
Similarly all types of horses has same skeleton (Interface) but each horse is different from another on the basis of colour,cast etc same as defined above.

So this is the purpose of interface that it provides the structure of a scenario. For example we have to make method of numeric series so we made interface and declare method of series. Now if  we want series of numbers odd, even, multiple of 3, Etc. we implement the same method with different implementation according to type of series. 

Here is one Example:

interface IAnimal
{
void speak();
}
class Cow : IAnimal
{
public void speak()
{      //Implementation of Speak according to Cow           }
}
class Horse : IAnimal
public void speak() 
{       //Implementation of Speak according to Horse       }
}
public static void Main()
{
Cow objCow = new Cow();
Horse objHorse = new Horse();

//Calling same function with different implementations

objCow.speak();
objHorse.speak();
}

So in above example “Speak” function is implementing two times one for “Horse” and one for “Cow”. It can be say that Interfaces have no work without Class or Structure. 
Take a look diagrammatically

Now hope you understand why we use interfaces and what the purpose of it.

FAQ:

1) Can we create object of interface?

No! Object of interface cannot be created because it is only structure it has no implementation of anything only declaration, Second it has no constructor as well so it cannot be instantiate.
However we made object of interface by instantiating it to the derived class
Example 

Interface IA{ }

Class B:IA{ }

Main()
{
IA obj=new B();
//or
B objB=new B();
IA obj=objB;
}

2) Can Interface derived from other interface?

Yes! Inheritance between interfaces is allowed

Example:

Interface IA{ }
Interface IB:IA{ } 
However when class derived from interface “IB” so it must give implementation of “IA” and “IB” both.

3) How implement Multiple Inheritance in interfaces?

Multiple inheritances is allowed in Interfaces in C#

For example:

Interface IA{ }
Interface IB { } 

Class MyClass:IA,IB //here we inherit class from two interfaces
{
//Class must implement both interfaces IA and IB
}

Please feel free to ask.
Any corrections must be appreciable.
Thank You
hope it helps!

Happy Coding :)



Friday 9 September 2011

Why Multiple Inheritance Not Allowed in C# or Java In Classes?

I took this topic because this question is asked to me in my recent interview and I have no answer
Now first we understand what is multiple inheritance

What is Multiple Inheritance?

Multiple inheritance is one of the feature of object oriented concepts or programming.In Multiple inheritance we inherit class with more than one classes that is not allowed but allow in interfaces,what is Interfaces this is another topic may be discussed later.

Example:

Class A
{}

Class B
{}

Class C : A,B  // This is not allowed in C# or Java called multiple inheritance
{}

In above code we declare two classes A,B and declare another class C which is inherited by A and B Both So it is not allowed.

Why?

We consider one example

Class A
{
Public Void MethodA(){……}
}

Class B:A
{ 
}

Class C:A
{ 
}

Class BC: B, C
{ 
}

What is the problem in this example?

The problem is that when we make object of “BC” class there is duplication of Sub object of “A“ class.

BC obj=new BC();

And when we call the method.

obj.MethodA();

This will result in compiler error, because the compiler does not know whether the call to MethodA refers to the copy of “B” class or refers to the copy of “C” class. So, the call to MethodA in the code above is ambiguous and will not get past the compiler. This scenario is also called “Diamond Inheritance Problem”.

Take a look diagrammatically:



That’s why multiple inheritance is not allowed,If compiler designer try to solve this issue the complexities increase too much.

However this problem is resolved in C++ through pointers and virtual methods, So multiple inheritance allowed in C++.

Hope it helps!

Happy Coding 
J

Thursday 8 September 2011

Problem Already Installed JDK Not Found During Android SDK Installation

This error occured while you are installing andriod sdk and jdk(java development kit) already installed.
So,I found a very strange solution.


Solution:
When you came across the following error press "Back" button and then press "Next" button again.Your problem will be resolved.

Very Simple

Happy Coding :)