Pages

Friday, 10 April 2015

CAML Query

CAML Query tutorial for SharePoint 

  •    CAML - Collaborative Application Markup Language
  •   XML- Extensible Markup Language based query language
       CAML:   Used to perform a query operation against SharePoint Lists

How SharePoint List Items are retrieved?

SharePoint List data can be retrieved in any one of the following ways:
1. Using the SharePoint object model – used when code runs on the server         (Example: Developing a web part or an application page)
2. Using the SharePoint Lists web service – used when your code doesn’t run on the server where the SharePoint is installed (Example: Developing a windows application)
3. Using Power shell –used mostly by the ADMIN of the SharePoint when they quickly want to retrieve some information from the SharePoint site

How does CAML query looks like?

As I already mentioned, it is XML based query language and it contains tags in it. The root element of the CAML query root element is Query. But it is not necessary to use Query element in the query you form.
Within the Query element you have two elements possible:
1. Where   – to filter the data
2. OrderBy – to categorize the data
A simple structure of the CAML query is as follows:
<Query>
          <Where> 
                   <Eq>
                             <FieldRef Name=”FieldName” />
                             <Value Type=”DataType”>Value</Value>
                   </Eq>
          </Where>
          <OrderBy>
                             <FieldRef Name=”FieldName” />
                             <FieldRef Name=”FieldName” />
          </OrderBy>
</Query>

Refer: Query Schema Elements

 

Operators in CAML Query

From the above structure, we came to know that it uses Where and OrderBy elements to retrieve the data from the list.
Let us know about the operators present in the CAML query and its usage:

Inside the Where element

1. Logical Operators - AND, OR
2. Comparison Operators - Listed Below in the table
AND – Which takes two conditions are satisfied
OR – Which takes when either of the conditions is satisfied

Comparison Operators
Inside the OrderBy/GroupBy element

OrderBy – Which orders or sort the data depends upon the field (FieldRef element) given.
GroupBy – Which groups the data depends upon the group by field (FieldRef element) given.

Examples
Logical & Comparison Operators

Use of AND, Gt, Leq
<Query>
<Where>
<And>
<Gt>
<FieldRef Name="Quantity" />
<Value Type="Number">0</Value>
</Gt>
<Leq>
<FieldRef Name="Price" />
<Value Type="Number">2000</Value>
</Leq>
</And>
</Where>
</Query>
Use of OR, Gt, Leq
<Query>
<Where>
<Or>
     <Gt>
<FieldRef Name="Quantity" />
<Value Type="Number">0</Value>
     </Gt>
                     <Leq>
  <FieldRef Name="Price" />
<Value Type="Number">2000</Value>
     </Leq>
               </Or>
       </Where>
</Query>
Use of BeginsWith, Leq
<Query> 
<Where>
<And>
      <BeginsWith>
  <FieldRef Name="Title" />
  <Value Type="Text">M</Value>
      </BeginsWith>
      <Leq>
     <FieldRef Name="Quantity" />
<Value Type="Number">1000</Value>
      </Leq>
</And>
</Where>
<OrderBy>
<FieldRef Name="Price" Ascending="False" />
</OrderBy>
</Query>

OrderBy Operator
 
<Query>
<Where>
<Or>
    <Gt>
<FieldRef Name="Quantity" />
<Value Type="Number">0</Value>
   </Gt>
      <Leq>
<FieldRef Name="Price" />
<Value Type="Number">2000</Value>
   </Leq>
</Or>
</Where>
<OrderBy>
<FieldRef Name="Price" Ascending="True" />
</OrderBy>
</Query>

 

CAML Query

 

  • A caml query is build in two parts.
    • 1) Sort
    • 2) Filter
  • Sort part is the sorting based on some columns
  • Filter part is the where clause of the CAML query
  • In order to build up the XML for the CAML we create the where clause as follows:
    • Write the where clause just as you write in sql
    • Find out the operators such as =, <=, <,> etc.
    • Find out the keywords for these operators in CAML language. For example = is eq, < is lt and so on.
    • Break the sql string such that the operator comes first and then comes the operands. Continue this till the whole string is completed in this fashion.
    • Replace the operators with the keywords in CAML language.
    • Example: where column1=”a” and column2=”b” and column3 like ‘%c%’
    • => where (column1=”a” and column2=”b”) and column3 like ‘%c%’
    • => where and (column1=”a” and column2=”b”) (column3 like ‘%c%’)
    • => where and (and (column1=”a” column2=”b”) column3 like ‘%c%’)
    • => where and and (= column1 a column2 b) contains column3 c
    • => where and and eq column1 a eq column2 b contains column3 c
    • => <where>
<and>
          <and>
                   <eq>
                             <FieldRef name=”Column1” />
                             <Value Type=string>a</Value>
                   </eq>
                   <eq>
                             <FieldRef name=”Column2” />
                             <Value Type=string>b</Value>                                 
 </eq>
          </and>
          <contains>
                   <FieldRef name=”Column3” />
                   <Value Type=string>c</Value>
          </contains>
</and>
                           </where>

     

Retrieving List Items with CAML Query - Examples

 

If you need to retrieve items from a list when developing web parts, application pages or custom field types you can best use the SPQueryobject from the SharePoint object model. This object is located in the Microsoft.SharePoint namespace of theMicrosoft.SharePoint.dll located in the Global Assembly Cache.

Instantiate the object as follows:
SPQuery query = new SPQuery();
 
The most important property is the Query property, which needs to be set to your CAML query:

string camlquery = "<OrderBy><FieldRef Name='Country' /></OrderBy><Where>"
    + "<Eq><FieldRef Name='LastName' /><Value Type='Text'>Smith</Value></Eq>"
    + </Where>";
query.Query = camlquery;
 
At this point you can execute the query on your list:
SPListItemCollection listItemsCollection = list.GetItems(qry); 

Get data in datatable

A small remark with the GetItems method of the SPList instance: this method returns a collection of typeSPListItemCollection. It is possible that it is easier working with a DataTable. In that case you can execute the query as follows:


DataTable listItemsTable = list.GetItems(qry).GetDataTable(); 

View fields property

The query will not only return all list items that have their last name set to Smith, but also all columns of each list item. In cases you work with large lists it can be important to retrieve a subset of list items containing only the columns you need. In that case you will have to set the ViewFields property of the SPQuery object. 

You can do this by specifying all columns you want to see returned:


qry.ViewFields = "<FieldRef Name='FirstName' /><FieldRef Name='LastName' />";
query.ViewFieldsOnly = true;
 
This will return the first name and the last name of the retrieved employees, but also the system fields like the ID and theCreated date.

The major disadvantage of the SPQuery object is that you can query only one list. If you want to query more than one list you will have to use the SPSiteDataQuery. More on this object in a later article because it earns special attention.
It is common knowledge by now but let me remind you that it’s always a good idea to use SPQuery to retrieve a subset of list items. You can loop through the list item collection to find the list items that match your needs but this will have a serious negative impact on the performance of your work.

IncludeMandatoryColumns

When this Boolean property is set to True, the result set will not only return the columns as defined in the ViewFieldsproperty, but also the columns that you defined in the list as required.
When working with the SPQuery object:
qry.IncludeMandatoryColumns = true;
When working with the GetListItems method of the Lists.asmx web service:

XmlNode queryOptionsNode = camlDocument.CreateElement("QueryOptions");
queryOptionsNode.InnerXml =
    "<IncludeMandatoryColumns>True</IncludeMandatoryColumns>";

RowLimit

Setting this property limits the number of rows returned in the result set.
When working with the SPQuery object:
qry.RowLimit = 10;
 

Example: 



 using (SPSite site = new SPSite("http://localhost"))
         {
            using (SPWeb web = site.OpenWeb())
            {
SPList List = oWebsiteRoot.Lists["Tasks"];
               // Build a query. 
 SPQuery query = new SPQuery();
 
Query.Query = "<Where><Eq><FieldRef Name='Status'/>" +
    "<Value Type='Text'>Completed</Value></Eq></Where>";

 query.ViewFields = string.Concat(
                                   "<FieldRef Name='AssignedTo' />",
                                   "<FieldRef Name='LinkTitle' />",
                                   "<FieldRef Name='DueDate' />",
                                   "<FieldRef Name='Priority' />"); 
 
query.ViewFieldsOnly = true;
query.RowLimit = 10; 
 
SPListItemCollection collListItems = List.GetItems(query);
DataTable listItemsTable = List.GetItems(query).GetDataTable(); 
}
} 

Another Example - Using Sharepoint Client Object Model: 

Four properties of ListItem are not available by default when you return list items: 
DisplayName, EffectiveBasePermissions, HasUniqueRoleAssignments, and RoleAssignments
Use Include method to get them. 
Only the specified properties are available after query execution.
Therefore, you receive a PropertyOrFieldNotInitializedException
if you attempt to access other properties beyond those that have been specified. 
In addition, you receive this error if you attempt to use properties such as 
ContentType or ParentList to access the properties of containing objects.

using System;
using Microsoft.SharePoint.Client;
using SP = Microsoft.SharePoint.Client;

namespace Microsoft.SDK.SharePointServices.Samples
{
    class RetrieveListItems
    {
        static void Main()
        {
            string siteUrl = "http://MyServer/sites/MySiteCollection";

            ClientContext clientContext = new ClientContext(siteUrl);
            SP.List oList = clientContext.Web.Lists.GetByTitle("Announcements");

            CamlQuery camlQuery = new CamlQuery();
            camlQuery.ViewXml = "<View><Query><Where><Geq><FieldRef Name='ID'/>" +
                "<Value Type='Number'>10</Value></Geq></Where></Query><RowLimit>100</RowLimit></View>";
            ListItemCollection collListItem = oList.GetItems(camlQuery);

clientContext.Load(collListItem);
OR
clientContext.Load(collListItem,
                 items => items.Include(
                    item => item.Id,
                    item => item.DisplayName,
                    item => item.HasUniqueRoleAssignments));
 
 
 clientContext.ExecuteQuery();

            foreach (ListItem oListItem in collListItem)
            {
                Console.WriteLine("ID: {0} \nTitle: {1} \nBody: {2}", oListItem.Id, oListItem["Title"], oListItem["Body"]);
            }
        }
    }
}
 

Retrieving specific fields from a specified number of items

 

The following example shows how to retrieve specific fields from only the first five items in a list. Because only the Title and Body columns are specified, these are the only properties that are available.


using System;
using System.Linq;
using Microsoft.SharePoint.Client;
using SP = Microsoft.SharePoint.Client;

namespace Microsoft.SDK.SharePointServices.Samples
{
    class RetrieveSpecificItemsFields
    {
        static void Main()
        {
            string siteUrl = "http://MyServer/sites/MySiteCollection";

            ClientContext clientContext = new ClientContext(siteUrl);
            SP.List oList = clientContext.Web.Lists.GetByTitle("Announcements");

            CamlQuery camlQuery = new CamlQuery();
            ListItemCollection collListItem = oList.GetItems(camlQuery);

            clientContext.Load(
                collListItem,
                items => items.Take(5).Include(
                item => item["Title"],
                item => item["Body"]));

            clientContext.ExecuteQuery();

            foreach (ListItem oListItem in collListItem)
            {
                Console.WriteLine("Title: {0} \nBody: {1}\n", oListItem["Title"], oListItem["Body"]);
            }
        }
    }
}

Retrieving items from all the lists in a Web site 

 

using System;
using System.Linq;
using Microsoft.SharePoint.Client;
using SP = Microsoft.SharePoint.Client;

namespace Microsoft.SDK.SharePointServices.Samples
{
    class RetrieveFirstTenItemsAllLists
    {
        static void Main()
        {
            string siteUrl = "http://MyServer/sites/MySiteCollection";

            ClientContext clientContext = new ClientContext(siteUrl);
            ListCollection collList = clientContext.Web.Lists;

            clientContext.Load(
                collList,
                lists => lists.Where(
                    list => list.Hidden == false).Include(
                    list => list.Title,
                    list => list.Items.Take(10)));

            clientContext.ExecuteQuery();

            foreach (SP.List oList in clientContext.Web.Lists)
            {
                string listTitle = oList.Title;
                int itemCount = oList.Items.Count;

                Console.WriteLine("List {0} returned with {1} items", listTitle, itemCount);
            }
        }
    }
}

Thursday, 9 April 2015

List and Library interview questions

  1.  Difference between list and library?
  2.  New features introduced in sp2010 on Lists and Libraries compared to SP2007?
  3. List throttling?
  4. External List throttling?
  5. Column level validations?
  6. How to show the documents that were created by the current user only?
  7. Update a SharePoint list item without changes its version?
  8. Difference between Update and systemupdate in SharePoint list?
  9. What is the default size of upload document in SharePoint?
  10. How to upload large size of documents to document library in SharePoint?
  11. Document Library name and sub site name cannot be the same. Why?
  12. Check in and checked out documents in SharePoint?
  13. How to make document changes Offline?
  14. How to check in all the checked out documents at once?
visit the SharePoint Interview Questions and Answers: List vs Library2:

1. Difference between list and library?
List means: A list contains items that are collections of fields/properties/columns. Optionally each item can have one or more attachments.
Library means: A library is a list, but has one and exactly one file associated with each item. A library item also has fields/properties/columns.
Simple way to say this is that a list item has a focus on "text" stored in fields/properties/columns, while a library has a focus on a single document.
Checking option: SharePoint list doesn’t support check in and check out options but SharePoint Library supports.
Search: When the user searches for a keyword in a document, if the document is in a list then search returns the list item as the result. When the user searches for a keyword in a document, if the document is in a library then they find the document listed in the search results.
List examples: Contact lists, Task lists etc.
Library examples: Picture library, Form library etc.

2. New features introduced in sp2010 on Lists and Libraries compared to SP2007?
  • Column validation.
  • Enforce unique values
  • Customize the form using InfoPath
  • New/ updated column Types:
    • Lookup fields.
    • Managed metadata.
  • View:
    • Inline editing.
    • Views by location.
3. List throttling:
4. External list throttling:
5. Column validation supports:
  • Single Line of Text
  • Choice (single only)
  • Number
  • Currency
  • Date & Time
6. Column validation rules:
A validation formula at the column level cannot include any other columns besides itself. For example, [Column1]> [Column2] is an invalid formula and SharePoint will not allow it to be used at the column level. In this case, you want to use list-level validation.
Column validation will not support to validate even Today function also. For example: [Column1]> [Today]. 
7. How to validate at list level and field level in SharePoint?
8. How to do validation if the field values don’t allow more than 8?
Formula = LEN ([REGION]) <8.
How to do validate if Due date is not greater than equal to current date [means disallow the Due date that is in past]?
Enter the [Due Date] > Today () formulae in column validation while creating the “Due Date” field.
9. What if you have both column level validation and list level validation? 
The column level formulas will be evaluated first, then the list formulas.
10. What if the column and list level validations are in conflict?
Best ref: http://digsharepoint.blogspot.in/2011/06/sharepoint-2010-column-validation.html

11. How to show the documents that were created by the current user only?

You can do this using the user interface by specifying that the Created By field needed to be equal to [Me].

Comparison of CAML and LINQ in SharePoint 2010


Comparison of CAML and LINQ in SharePoint 2010

Disadvantages of CAML:
  • CAML query is text based so, if we are joining two lists across a lookup field there may be various problems associated with that.
  • CAML offers no compile time validation for the queries as queries are just
    strings that are used with objects like SPQuery, which means that during
    compile your query will never be checked for syntax errors. Furthermore, if
    your syntax is not correct you won’t get an error during runtime, the query
    just won’t return any items. That makes it extremely hard to analyze issues
    caused by faulty CAML-based queries.
  • There is no mechanism to know until run time if the query is written correctly or not. If the query is not correct, then it will simply fail at run time. Means it won’t support at design time
  • When writing the query, you have no idea what CAML elements are legal in the syntax without having a reference open.
  • The query is somewhat difficult to understand. We cannot determine easily what the query is doing and what lists are being joined.
  • The data returned from the query is placed in a SPListItem collection, which does not provide strongly typed business entities.
 Advantages of LINQ over CAML:
  • First advantage is, it is an object-oriented query language.
  • Linq stands for Linera Integrated Query. LINQ adds syntax of type SQL and vocabulary, which is used to query the data from data source. LINQ to sharepoint is defined inMicrosoft.SharePoint.Linq namespace. It translates the LINQ query into CAML (Collaborative Markup Language).
  • It can provide strongly typed objects at design time; we can create queries in code and can check that they are correct because we can the compiles the code.
  • The results are returned from queries are strongly typed objects, so the items and fields can provide compile-time checking.

Disadvantages of Using LINQ
  • ·          LINQ translates the LINQ queries into Collaborative Application Markup Language (CAML) queries thus adding an extra step for retrieving the items.
  • ow some of you may think that how CAML or LINQ queries are able to fetch the data from a list. So, below steps will clear your confusion about CAML and LINQ queries:
    • LINQ queries are converted to CAML queries.
    • CAML queries are also translated into SQL queries.

Wednesday, 8 April 2015

Client Object Model Sharepoint 2010

Client Object Model:SharePoint 2010

The Client Object Model is a new object model introduced in SharePoint 2010 which is aimed at making things easier for the developer when developing client-side applications for SharePoint 2010. Client Object Model can run on the client machines (Where SharePoint is not installed) and communicate with the SharePoint server remotely.

Why Client Object Model comes into the picture? Are there any specialties of them?

The main started points to think by SharePoint team are as follows.

  1. Is it really necessary to have SharePoint installed on server for SharePoint development? - Yes, in SharePoint 2007 you have to install SharePoint on the server to write code and test it. 
  2. What is the advantage of writing more web services to serve what the clients are looking for? - This is completely not a feasible solution to give or expose web services for each and every single requirement to get and manipulate data. It has plenty of limitations and if Microsoft exposes 500 web services and you didn't find what you really need and they are just waste. Instead write whatever you want and use them.
  3. The great thinking and beautiful solution to the people who don't allow server side coding in the SharePoint sites is ECMAScript client OM. You can create a simple JavaScript file and deploy into the server to get what you needed. As we know, most of the clients don't allow server side coding but they want something to be developed. In SharePoint 2007 it's very difficult to get this job done. But now in SP 2010 very easy.
So, these things take into high priority and make them to come up with a great solution in the form of Client Object Model. The great advantage of it is completely looks [Syntax] like the SharePoint Object Model. So, nothing new for the developers and no confusion. In fact very simple to manage and write code.

How SharePoint Client Object Model Works:


SharePoint Client Managed Object Model is a SharePoint API that runs on the client side. It converts the API calls made by the application, into XML request and sends it to the SharePoint server. On the server, the XML request is handled by a service called Client.svc where it translates the XML request in to appropriate Object Model calls (SharePoint Server Object Model) and gets the results. After getting the results, Client.svc translates them into JavaScript Object Notation (JSON) and sends back to the Client Managed Object Model. On the client side the JSON response is translated into ECMAScript objects for ECMAScript.

When a request is made to access a page, only the files required to render the page are downloaded to the client. For example, if your programs use only the SP.CORE.js script, you can specify that only this script is downloaded to the client. This is a huge performance boost from earlier version of SharePoint which downloaded the complete set of core JavaScript files when a page was accessed. If the script has references to any other files, they are also automatically downloaded to the client. 
  
It is important to be aware that you control when the SharePoint Foundation 2010 managed client object model starts to send the XML to the server and receives the JSON back from the server.

The SharePoint Foundation 2010 managed client object model bundles method calls and sends a request to the server. As part of this process, before you start the interaction with the server, you must explicitly specify what content that you want to retrieve from the server. This is the biggest difference between the SharePoint Foundation 2010 managed client object model and the SharePoint Foundation 2010 object model.

ExecuteQuery method
The call to the ExecuteQuery method causes the SharePoint Foundation 2010 managed client object model to send the request to the server. There is no network traffic until the application calls theExecuteQuery method.
An important point to make about this example is that the call to the Load method does not actually load anything. Instead, it informs the client object model that when the application calls the ExecuteQuerymethod, you want to load the property values of the siteCollection object.

Client.svc is an internal WCF service; it is reserved for SharePoint usage and is not intended to be used directly in client code. If you attempt to add a service reference to this service, no proxy will be generated. Internally, the Client.svc leverages the server-side object model to handle all client requests and return a JSON response.

Three new client APIs:

With the Client Object Model, Microsoft has introduced a set of new APIs to work with to ease the daily tasks of developers.
  • .NET Managed Applications (using the .NET CLR)
  • Silverlight Applications
  • ECMAScript (JavaScript, JScript)
The client APIs provide you as a developer with a subset of the Microsoft.SharePoint namespace which is based on the server-side object model.

Naming conventions:
As a small side-note I would like to mention that the objects you are comfortable with calling “SPWeb”, “SPSite”, “SPList” and so on are now named “Web”, “Site”, “List”.
So to conclude the naming convention, the “SP” in the objects has been dropped. Easy enough to remember, right?

The main assembly’s references for the client object models are:
·         .NET Managed Applications
o   Microsoft.SharePoint.Client.Runtime.dll (Located in:
" C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\14\ISAPI").
  • Silverlight Applications
    • Microsoft.SharePoint.Client.Silverlight.dll and Microsoft.SharePoint.Client.Silverlight.Runtime.dll (Located in: "14\TEMPLATE\LAYOUTS\ClientBin").
  •  ECMAScript Applications
    • SP.js (Located in: “14\TEMPLATE\LAYOUTS”).

Remembering points:
1.      There are a few differences between the object models provided, with the most significant one being that both the .NET and Silverlight OMs allow communication with any SharePoint site, while the ECMAScript OM only allows communication with the originating SharePoint site. The reason for this is that JavaScript can have cross-site scripting controls, and allowing communication with other SharePoint sites is a large security risk. 

2.      There are couple of important points to remember about “ClientContext”
    1. SharePoint client object model uses client context object that is operational bridge head between your code and data in SharePoint.
    2. Context gathers all queries and modifications and completes requested operations whenExecuteQuery() method is called.
3.      The ExecuteQuery () method is used by the .NET client OM, and is a synchronous call. ExecuteQueryAsync () is used by both the Silverlight and ECMAScript OMs, and is an asynchronous call. Notice that this method takes two callback parameters, which specify methods to execute if the commands being sent (and processed) succeed or fail.
4.      While using ECMAScript Client OM, if your code modifies SharePoint content, you need to add a FormDigest control inside your page.
5.      The ExecuteQuery () method is invoked asynchronously passing two functions: onSuccess andOnFailed which will be called on success and fail correspondingly.

Microsoft released an installer, to install the SharePoint client dll's on a non-SharePoint pc. Refer to get to know more on it here. 



Q. How does Client object model works?
Ans. When we use SharePoint client API’s to perform a specific task, the SharePoint Foundation 2010 managed client object model bundles up these uses of the API into XML and sends it to the server that runs SharePoint Foundation. The server receives this request, and makes appropriate calls into the object model on the server, collects the responses, forms them into JavaScript Object Notation (JSON), and sends that JSON back to the SharePoint Foundation 2010 managed client object model. The client object model parses the JSON and presents the results to the application as .NET Framework objects (or ECMAScript objects for ECMAScript).

Q. How many types of Client Object model extension are available in 2010 and when would you use one or the other.
Ans. To develop rich client side solutions, three set of client-side APIs has been introduced in the Microsoft.SharePoint.Client namespace. The three APIs are targeted for three different types of clients.
1. .net Managed applications – These are used when we have to create console applications or window applications, web applications which are not running inside SharePoint Contex.
2. For Silverlight applications
3. ECMAScript – It is a client object model extension for using with JavaScript or JScript. This is used for creating applications which are hosted inside SharePoint. For example, web part deployed in SharePoint site can use this JavaScript API for accessing SharePoint from browser using JavaScript.

Q. What is the purpose of calling clientContext.ExecuteQuery() ?
Ans. ExecuteQuery gives you the option to minimize the number of roundtrips to the server from your client code. All the components loaded into the clientcontext are executed in one go.

Q. What Do you know about SharePoint Object Model?
Ans. In Sharepoint Object model there are two Important namespaces, Microsoft.Office.Server and Microsoft.SharePoint . The Microsoft.Office.Server namespace is the root namespace of all Office Server objects and Microsoft.SharePoint is the root namespace for all WSS objects.

Q. How Do you use\refer External Javascript and Css file in your WebPart?
Ans. You can use javascript,Css or Image files placed in _Layouts or any other location by registering them on the webpart page.

Q. How Do you bind a Drop-Down Listbox with a Column in SharePoint List ?
Ans.
Method 1 : You can get a datatable for all items in the list and add that table to a data set. Finally, specify the dataset table as datasource for dropdown listbox.

Method 2 : You can also use SPDatasource in your aspx or design page.

Q. What are the various tools used for creating the solutions?

Ans. Some of the common tools are

1. WsPBuilder

2. VSeWSS (Visual Studio extensions for WSS )

3. Stsdev

Q. Client Object Model vs Server Object Model in SharePoint 2010 ?
Ans. using Client Object Model we can access the data from the system where sharepoint server is not installed on the machine via Web Services , API , JavaScript etc

Where as In Server Object Model is like a Production Server Environment to access the data where SharePoint server installed on the machine .

Library


Problem

Let's understand how we can organize content using the different types of libraries and to understand what a library is all about?

Solution

A library is a container for creating, organizing and managing different types of documents. It allows us to store files and meta information about the files, so that it can be used among different team members. You can create, store and manage almost every type of file in different kinds of libraries (i.e. Word documents, spreadsheets, presentations, forms etc).

By default a Shared Library is created when you create a site and additionally you can create as many types of libraries as you want. There are specialized types of libraries available in SharePoint Server 2010 to store specific types of content such as:

Type of LibraryDescription
Asset LibraryAsset Library allows you to create a rich media library and lets you create, browse, share, organize and mange images, audio and video files.
Data Connection LibraryHere you can create, browse, share, organize and manage files that contain information about connecting to external data connections.
Document LibraryHere you can create, browse, share, organize and manage documents or other files. It also allows creating folders, versioning of documents and check-in/check-out of files.
Form LibraryHere you store and manage Microsoft Office InfoPath forms (or XML files for use with Microsoft Office InfoPath) for instance business forms like a status report, purchase orders, etc...
Picture LibraryHere you can upload and share pictures with others and it includes a built-in image viewer.
Report LibraryHere you can create web pages and reports to track business metrics, goals, KPIs (Key Performance Indicators) and business intelligence information.
Slide LibraryIt allows you to create a library for storing and sharing Microsoft PowerPoint slides.
Wiki Page LibraryIt allows you to create and store customizable pages of content that are linked together and can be edited by several people.

Creating a Document Library...

In your SharePoint Web application, select the site under which you want to create the Document Library and expand the Site Actions menu on the top left side as shown below. You will notice there is a specialized option to create a Document Library from here or you can click on More Options to select the type of Library you want to create as shown below.
On the left pane select "Library" to limit your choices to just Library objects. Select the appropriate type of library you want to create from the middle pane and on the right side specify the name of the library and finally click on the "Create" button. If you want to specify different properties or behaviors of your library, you can click on the "More Options" button which will open a screen as shown below.
Here along with the name of your library you can also specify a brief description. In the Navigation section you can select whether you want your library to be listed on the Quick Launch on left side of the site. Next you can enable versioning for all the documents in the document library, or in other words, each time a file in the library will be edited a major version will be created for it. Document Template allows you to select what default type of file will be created in the document library; for example as you can see below I have selected Microsoft Word document and on the next screen I will show how it appears in the New Document menu.
Click on the "Create" button and wait for your library to be created. Below shows the Library that was created. Notice the Library Tools menu option becomes available in the ribbon style menu which has the Document and Library menus.
Click on the "Add" document link to add documents to your library. You can either upload one document at a time or have multiple documents uploaded in a batch.
As I said before, the Library Tools menu appears in the ribbon menu when you select a library. It has Documents and Library options. The Documents menu allows you to create a new document, upload documents, create folders in the library, check-out, check-in files, etc. The Library menu option has several options to manage your library, for example you can edit your library in SharePoint Designer and change different library settings.


Tuesday, 7 April 2015

Lists

What are Sharepoint Lists?

SharePoint lists are tables of data, much like Excel spreadsheets. But lists can do a lot more than just store columns and rows of data—in fact, lists are like mini-applications in SharePoint.   
Create a list using one of the built-in templates. 
Add columns to collect additional data and calculate values as required. 
Create supporting lists for lookups and master lists. 
Add views to display required reports. 
Enable email, versioning, and item approval as required. 
Optionally customize the data entry forms. 
Save the final list as a template and deploy it to other site collections.

As a developer you sometimes forget to look at the functionality that is available just out of the box. One of those things is the standard functionality that is available in the SharePoint lists. Most people knowledgable of SharePoint will think: what is your point? Didn't you know this? Why do you bother me with this: read the f*cking manual. For those other people who forgot to read the manual, I would like to enumerate some things about lists that are "out of the ordinary".

Did you know that:

Lists based on the "Links" list have a "Change Order" option in the menu bar of it's views that allow you to reorder the list items 
Lists based on "Tasks" and "Issues" have an "Assign to:" field that is a lookup to users in the UserInfo list for the web the list is on. This list contains all users that ever visited the list. What does this mean:

Users who did not visit the web yet are not in the list 
Users who ever visited the web site, but whom's account is now removed is still in the list (Should be like this: task/issue can be assigned to user that is now gone, if you edit the task/issue to change something, the user shouls still be in the list, otherwise it must always be reassigned on edit.) 
System accounts that crawl the list are in the list (we filter those out using the MacawSharePointSkinner)
Lists based on "Issues" have an option to sent the "Assigned To" person a notification e-mail (General Settintgs ->Email Notification) on changed item or when ownership is assigned. 
Lists based on "Issues" have a "View reports" action with reports to track issue trends 
Lists based on "Contacts" have "Export Contact" functionality in the menu of an entry that created a vcard file 
Lists based on "Contacts" can "link to Outlook", this creates a read-only contacts list in outlook, with in each item a link to update the contact. This list in outlook stays up to date automatically 
Lists based on "Contacts" can import contacts from the address book 
Lists based on "Events" can "link to Outlook", this creates a read-only calendar in outlook, with in each item a link to update the event. This list in outlook stays up to date automatically 
Lists based on "Discussion" support threading on items, and that this list sucks for discussions (in my opinion). We rewrote the new/edit/view pages to se things like the thread you are replying on, the complete thread of a single discussion item, see the newest discussion thread first. This makes it usable. 
List items can have multiple files attached 
There are no events available on lists, only on libraries. When I asked Mike Fitzmaurice about this on the PDC 2003 he answered that it was due to lack of time. There was a big launching customer who needed events on libraries, so this was implemented.
All this functionality is somewhere available in the list definitions, so if you define your own template you can combine all this functionality!!

Server Object Model



Sharepoint Interview Questions on Sharepoint Object Model

What is a SPSite and SPWeb object, and what is the difference between each of the objects?  

The SPSite object represents a collection of sites (site collection [a top level sites and all its subsites]). The SPWeb object represents an instance SharePoint Web, and SPWeb object contains things like the actual content. A SPSite object contains the various subsites and the information regarding them. 
 
How would you go about getting a reference to a site? 

Select For Unformatted Code
C#: 
oSPSite = new SPSite("http:/server");
oSPWeb = oSPSite.OpenWeb(); 
Internet Explorer 6, Netscape Navigator 6.2 or later.

What does a SPWebApplication object represent?  

The SPWebApplication objects represents a SharePoint Web Application, which essentially is an IIS virtual server. Using the class you can instigate high level operations, such as getting all the features of an entire Web Application instance, or doing high level creation operations like creating new Web Applications through code. 
 
Would you use SPWebApplication to get information like the SMTP address of the SharePoint site? 
Yes, since this is a Web Application level setting. You would iterate through each SPWebApplication in the SPWebApplication collection, and then use the appropriate property calls (OutboundMailServiceInstance) in order to return settings regarding the mail service such as the SMTP address. 

How do you connect (reference) to a SharePoint list, and how do you insert a new List Item?  

Select For Unformatted Code
C#: 
1. using(SPSite mySite = new SPSite("yourserver"))
2. {
3. using(SPWeb myWeb = mySite.OpenWeb())
4. {
5. SPList interviewList = myWeb.Lists["listtoinsert"];
6. SPListItem newItem = interviewList.Items.Add();
7. 8. newItem["interview"] = "interview";
9. newItem.Update();
10. }
11. } 

How would you loop using SPList through all SharePont List items, assuming you know the name (in a string value) of the list you want to iterate through, and already have all the site code written? 

Select For Unformatted Code
C#: 
1. SPList interviewList = myWeb.Lists["listtoiterate"];
2. foreach (SPListItem interview in interviewList)
3. {
4.  Here you put any condition to filter the values
            If(Interview[“name”].ToString()==”test”)
{
Add to ArrayList
}

“name” is column name in particular list
}

Another method use can CAML Query to get values from list. This method is faster compared to above

SPList interviewList = web.Lists["listtoiterate"];
SPQuery spQuery = new SPQuery();
spQuery.Query = @”<Where>
  <Eq>
    <FieldRef Name="name" />
      <Value Type="Text">test</Value>
  </Eq>
</Where>”;

SPListItemCollection queryitems = interviewList.GetItems(spQuery);

What does AllowUnsafeUpdates do ?

If your code modifies Windows SharePoint Services data in some way, you may need to allow unsafe updates on the Web site, without requiring a security validation. You can do by setting the AllowUnsafeUpdates property.

C#:
using(SPSite mySite = new SPSite("yourserver"))
{
using(SPWeb myWeb = mySite.OpenWeb())
{
myWeb.AllowUnsafeUpdates = true;
SPList interviewList = myWeb.Lists["listtoinsert"];
SPListItem newItem = interviewList.Items.Add();

newItem["interview"] = "interview";
newItem.Update();
}
}

What does RunWithElevatedPrivileges do?

Assume that you have a Web Part in which you want to display information obtained through the Windows SharePoint Services object model, such as the name of the current site collection owner, usage statistics, or auditing information. These are examples of calls into the object model that require site-administration privileges. Your Web Part experiences an access-denied error if it attempts to obtain this information when the current user is not a site administrator. The request is initiated by a nonprivileged user. you can still successfully make these calls into the object model by calling the RunWithElevatedPrivileges method provided by the SPSecurity class.
C#:
SPSite siteColl = SPContext.Current.Site;
SPWeb site = SPContext.Current.Web;
SPSecurity.RunWithElevatedPrivileges(delegate() {

using (SPSite ElevatedsiteColl = new SPSite(siteColl.ID)) {
using (SPWeb ElevatedSite = ElevatedsiteColl.OpenWeb(site.ID)) {
string SiteCollectionOwner = ElevatedsiteColl.Owner.Name;
string Visits = ElevatedsiteColl.Usage.Visits.ToString();
string RootAuditEntries =
ElevatedSite.RootFolder.Audit.GetEntries().Count.ToString();
}
}

});

In some place you will get error “Access Denied”  like when you try to execute caml query or something in that case if ypu place you caml query code inside this RunWithElevatedPrivileges delegate then automatically it will take system account rights and run the code.

What is ServerUpdate() and SystemUpdate() ?

Any changes in the list, i.e. new addition or modification of an item.. the operation is complete by calling the Update method.


But if a List is set to maintain versions .. and you are editing an item, but don't want to save it as a new version, then use the SystemUpdate method instead and pass in 'false' as the parameter.