Archive for Sharepoint 2010

Most viewed documents in SharePoint 2010

The Task

You want to see the top 10 most viewed documents in a library

The Answer

1. Enable the two reporting features in your site collection features.

Enable the reporting features

2. Go to the list and click on “Library Settings” in the ribbon

Library Settings

3. Click on “Information management policy settings” under “Permission and Management”

Information management policy settings

4. Click on document

5. Activate the checkbox “Enable Auditing” and select “Opening or downloading documents, viewing items in lists, or viewing item properties”

Enable Auditing

Now the auditing is enabled and each time when an item in the doclib is viewed a log entrie is generated. You can limit the size of the lib in the site collection settings under “Site collection audit settings” in the group “Site Collection Administration”. Here you can specify that the log should be holded for a period of time.

6. Create a custom webpart or control. Here is the sample code to get the entries you want

 using (SPSite site = new SPSite(mUrl))  
 {  
   using (SPWeb web = site.OpenWeb())  
   {  
     SPList list = web.Lists[mListName];  
     SPAuditQuery spQuery = new SPAuditQuery(site);  
     spQuery.RestrictToList(list);  
     SPAuditEntryCollection auditCol = site.Audit.GetEntries(spQuery);      
     // Getting Audits  
     foreach (SPAuditEntry entry in auditCol)  
     {  
       if (entry.ItemType == SPAuditItemType.Document && entry.Event == SPAuditEventType.View)  
       {                
         // Some Code to cumulate results or linq perhaps  
         // by entry.ItemIds in to an other list or array  
       }  
     }  
     // Show top ten  
     SPListItem item = null;  
     foreach (Guid guid in topTenList) {  
       item = list.GetItemByUniqueId(guid);  
       Console.WriteLine("Item: {0}", item.Name);  
     }  
   }  
 }  

You have to cumulate the results and display the top ten. This is at the same time the disadvantage of this solution. If you have large lists, the accumulation can be time consuming. A solution for that can be a timer job which writes the nr into hidden field in the library or an object cache.

Additional info

SharePoint offers a webanalytics webpart out of the box. It is within the “Content Rollup” webparts group. To use the webanalytics webparts, the webanalytics service must be started. The webanalytics webparts uses a webanalytics service proxy to get the data. Unfortunately the proxy class is internal. I couldn’t found any API to access the webanalytics data, perhaps Microsoft will provide it later. The reporting db offers some stored procedures, but they were too complicated for me.

Sharepoint: Apply background color to custom list column based on other column value

Today we are going to learn how to apply the background color to a custom list column based on other column value, firstly, I tried this scenario using calculated formula column type but some javascript code is needed to render the background color based on calculated formula value,  so I did some research and come up with the best easy way…..

STEPS:

I have created a simple custom list and name it as ‘My List

Modified the ‘Title‘ column name as ‘Student Name

Created one more column ‘Subject‘ which is of type single line text

Also, created one column ‘Marks‘ which is of type Number min is 1 and max is 100

Open the AllItems.aspx page using Sharepoint Designer 2007

Select the list, right click and Convert into XSLT mode

Write the XSL condition in between the ‘Subject TD tag as show in the below image

Here goes the XSL code……



background-color:Green;


background-color:Yellow;


background-color:Red;

XSL condition in Sharepoint Designer 2007

XSL condition in Sharepoint Designer 2007

Output:

Background color to Sharepoint Custom List column based on Marks

Background color to Sharepoint Custom List column based on Marks

Conditional Formatting of List Views for SharePoint 2010 – Changing the Font Colour

There are often times when it’s useful to draw attention to particular items in a SharePoint list or library. For example, you might want to highlight overdue tasks, colour-code items according to priority, or draw attention to undesirable information. In other words, you want to apply conditional formatting based on field values. Now, as you probably know, SharePoint 2010 uses XSLT-based list views by default. By editing the XSLT for a list view you can apply all manner of rules and conditional formatting. Even better, SharePoint Designer 2010 includes some built-in tools that will figure out the XSLT for you. In the List View Tools tab group, on the Options tab, there’s a handy dropdown menu:

In most cases, you’re probably going to want to apply conditional formatting by row. First you set your conditions:
 

Then you choose the styles you want to apply when the conditions are met.

 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 


When you’ve set your style, SharePoint Designer modifies the XSLT so that your formatting is rendered as an inline style on the row (
) element when your conditions are met. I’ve stripped out some of the less relevant attributes to improve readability.


 
   

 
So far so good. Everything looks correct in SharePoint Designer. However, if you’ve tried this, you might have found that when you load the list view in the browser you get mixed results – in particular:
  • Changing background colours and text decorations (such as bolding or italics) works fine.
  • Changing fonts or font colours works in SharePoint Designer but doesn’t work in the browser.

As a result, you’ll end up with something like this when you view the list through the browser:

A quick web search revealed that I’m not the first person to encounter this, and I’ve yet to see a definitive answer, so here goes.

Short version – the problem is down to the way the default styles are structured in corev4.css. Row styles do not cascade down to individual cells (regardless of whether you append an !important flag). If you want to change the background colour, apply conditional formatting at the row level. If you want to change the font colour, and you don’t fancy messing around with CSS, apply conditional formatting at the column level.

Long version – read on for a more detailed explanation…

Using IE Developer Tools, you can take a look at how styles are applied to individual HTML elements on the page. The XSLT rule created by SharePoint Designer applies an inline style to a row (tr) element. If we use IE Developer Tools to look at how the row is styled, we can see that everything looks correct – the inline style takes precedence:

 

However, if we look at how the text within one of the individual cells is styled, you can see that our inline style at the tr level is getting overridden by a more specific style, defined by thems-vb2 class, at the td level.

Unfortunately there’s not much we can do about this. If you want to modify any of the styles defined by the ms-vb2 class, such as font, font size and font colour, you need to create a column-level rule rather than a row-level rule. The two types of rules work in exactly the same way in SharePoint Designer—when you create a column-level rule, you can still set conditions based on any field value, not just the column to which you are applying the conditional formatting. If you want to conditionally change the font colour of an entire row, you simply create a column-level rule on every column. This time, SharePoint Designer modifies the XSLT so that your formatting is rendered as an inline style on the column ( ) element when your conditions are met:

 
     

  …

This time the browser will render the view as expected. The following image shows the results of a column-level rule on the Target Pub Date column, in addition to the row-level rule described earlier.

If we take a look at the CSS, we can see that our inline column style is overriding the styles provided by ms-vb2.

In summary, there’s no real difference between row-level conditional formatting and column-level conditional formatting, other than the scope at which your inline styles are applied. In practice you may often need to use a combination of the two in order to realise a particular style or effect.

Change the Color of a Column in a List in SharePoint

In this article, we will know how to change the color of a column based upon the values in the column. It is something like “Color Indicator” in SharePoint.
 
Scenario:
We have a custom list used for Project Tracking. In the list, we have column named STATUSfor tracking the project.
Whenever an item in the list is updated with the status in the column, then the background color of the status column should automatically change depending upon the status. Hence it gives a proper UI for tracking the status.
 
Solution:
1. Create a custom list named “Project Tracking System” with the columns such as “Title”, “Description” and Status with the data type as shown below:
 

Columns with the data types to be created:

 
2. Now, we will insert 4-5 items in the list created.
In the above list, we can see that the status column is updated, but it would be good when we have background color of the each status separately. It is gives easy tracking to the users.
3. We can achieve this through JAVA SCRIPT.
4. Add a Content Editor Web part below the list as shown below:

5. Now in the content editor web part, add the below java script code (Open the tool pane -> Source Editor -> Place the Java Script -> Click Ok) and save the page.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
6. Now, you can see the status column background is changed depending upon the status inserted for each item as shown below:
It is gives good interface to the users and also we can categorize the status easily.

SharePoint: Color Coding SharePoint Lists

Color Coding SharePoint Lists – without custom web parts or server code deployments 

SharePoint does not have an out of the box way to set colors based on the data in a list or library. There are both third party web parts and open source projects, such as codeplex.com, that can color code lists, but these usually require installing code on the SharePoint web servers. In this article we will look at color coding lists just using the built-in Content Editor web part and some JavaScript. 

Each list will need a slightly different fragment of JavaScript to set the colors. 

Color coded calendars? 

For other lists and libraries you will find examples below to: 

  • Set color backgrounds for rows in task lists to show the status of the task 
    Color coded SharePoint task list
  • Set colors in libraries to show approval status 
    Color coded SharePoint task list (approval status)
  • Color coded SharePoint list(task status)
  • Set the color of a single column based on its value

 

To add the Content Editor web part and JavaScript: 

  • Display the view to color code (each view will need its own web part and JavaScript) 
  • Add a Content Editor web part 
    • Site Actions, Site Settings, Edit Page 
    • Add a Content Editor web part and move it below the calendar web part 
    • Move this web part so it is below the list you are color coding 
    • Click in the web part, click Edit, Modify Shared Web Part, and in the Appearance section change “Chrome” to “None”. 
  • Add the JavaScript 
    • Click Source Editor 
    • Type or paste the JavaScript (examples below) 

Example 1: Set the background color of a row based on data in the row 

To color code a row all we need is: 

  • A column to check (such as the Task Lists’ status column) 
  • JavaScript to find this item in a table TD tag 
  • JavaScript to assign a style to the TD’s parent row (TR) 
  • And of course, the web part described above to hold the JavaScript 

Here is the example for a task list: 

 

 

 

Code Notes:

  • x[i] is one of the table cells (TD) 
  • x[i].innerHTML is the contents of a cell (TD) (which may include additional HTML) 
  • x[i].parentNode is the row containing the cell (a TR) 
  • x[i].parentNode.style.stylename is used to set any valid style on the TR 

 

Example 2: Set the color of a field based on data in the field 

To color code a cell all we need is: 

  • A column to check (such as the Task Lists’ status column or a library’s approval status column) 
  • JavaScript to find this item in a table TD tag 
  • JavaScript to assign a style to the TD 

Here is the revised JavaScript fragment for a color coding a single cell:

if (x[i].className==”ms-vb2″) //find the TDs styled for lists 
{ 
  if (x[i].innerHTML==”Completed”) //find the data to use to determine the color 
  { 
    x[i].style.backgroundColor=’darkblue’; // set the background color 
    x[i].style.color=’white’; //set the font color 
  } 
} 

SharePoint Color Coded list based on a Field in the Row

SharePoint doesn’t provide an out of the box way of color coding lists. But, thank goodness, we can use a little scripting to edit the styling of our lists!
Mike Smith provided a great script that allows you to color the background of the row if the cell’s value matches the value it’s looking for. But, what if another field in the same row has one of the other values and throws off your color coding?


Case in point: color coding is thrown off because the Description field
can have the same value that is being used to color code on

  
Well, this script below will search only the cell index of the row that you would like to base your color coding on. In our case, we would like to search only on the Status field/column. To get started:
1. Add a content editor web part directly underneath the list
2. Open the source editor and place the script below into it
3. Modify the columnIndexToSearch and the columnSpan variables to match the cell/field index to search for and the number of cells in each row respectively.
Note: In this case, the attachment field counts as a cell. Since we are searching only on the Status, our columnIndexToSearch is 2 (0 = Attachment field and 1 = Title field). The total number of columns we are displaying on our list is 5. If you add or remove columns in the view, the color coding will get thrown off. So, make sure to update these variables if you do make updates to the list view.


Final Result: Color coded based on the Status column only

   



SharePoint 2010 Interview Questions

Q. What is 14 hive in SharePoint?

Ans. See SharePoint 2010 Object Model

Q. How would you re-deploy the old custom solutions in SharePoint 2010.What Changes are needed to the old Solution files.

Ans. SharePoint 2010 object model contains many changes and enhancements, but our custom code will still compile and, will run as expected. You should however, rewrite and recompile any code that refers to files and resources in “12 hive”.
For Details See :
See SharePoint 2010 Object Model – Backward Compatibility

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 are the security improvements in SharePoint 2010 ?

Ans. In SharePoint 2010 a variety of security methods have been introduced.

Claims-Based Authentication – Claims based authentication is based on identity. and trust.

Code Access Security – in which you can specify your own code access
security (CAS) policy for your web parts.

Sandbox Solutions – Sandbox Solutions which when deployed to the server, SharePoint runs in a special process that has limited permissions.

Cross-Site Scripting – Introduced to prevent Cross – Site Scripting (XSS) attacks.

Q. Whats New with SharePoint WebParts?

A developer can create two types of webparts using Visual Studio 2010.

1. Visual Webparts –
 Allows you to Drag and Drop the controls from the Toolbox to WebPart Design surface. You can of course write your custom code in the code file. You can also package and deploy your webparts directly to Sharepoint from VS by pressing Clt+F5. Visual studio 2010 also provides you with three different views for developing webparts. The views are split view, design view and Source view(as we have in designer 2007).

Note : The Visual Webpart project Item basically loads a User Control as a WebPart.


2. ASP.Net WebParts –
 Where a developer can build up User Interface and logic in a class file. You do not have designer for drag and drop of controls. This webpart inherits from standard ASP.Net webpart. For Deployment we can again use ctrl+f5 to deploy this webpart.

Q. What are the Visual Studio 2010 Tools for SharePoint.

Ans.
 Visual Studio 2010 includes SharePoint-specific project types and project item types, and includes powerful packaging, deployment, and debugging features that help increase your efficiency as a SharePoint 2010 developer.

Some of the Templates avaiable are :
1.Visual Web Part project template.
2. List defination template.
3. Content Type template.
4. Empty Project template.
5. Event Receiver template.
6. some workflow template.
7. the Site Definition template
and many more….

Q. What are SharePoint Sandboxed soultions ?

Ans. SharePoint 2010 provides a new sandboxed environment that enables you to run user solutions without affecting the rest of the SharePoint farm. This environment means that users can upload their own custom solutions without requiring intervention from administrators, and without putting the rest of the farm at risk. This means that the existing sites\pages or components will not be effected by the newly added soultion.

Users can deploy the below four things as sandboxed soultions :
1. WebParts.
2. Event Receivers.
3. List Definations.
4. Workflows.

Q. What are Requirenments for SharePoint 2010.

Ans. SharePoint Server 2010 will support only 64 – bit. It will require 64 bit Windows Server 2008 or 64 bit Windows Server 2008 R2. In addition to this, it will require 64 bit version of SQL Server 2008 or 64-bit version of SQL Server 2005.


Q. What is LINQ. How is it used in Sharepoint ?

Ans. LINQ is a feature of the programming languages C# 3.0 and Visual Basic .NET. LINQ allows you to query in an object-oriented way, supports compile-time check, gives you intellisense support in Visual Studio and defines a unified, SQL like syntax to query any data source. But unlike other languages and query syntaxes which vary from one type of data source to another, LINQ can be used to query, in principle, any data source whatsoever. It is commonly used to query objects collections, XML and SQL server data sources.

The LINQ to SharePoint Provider is defined in the Microsoft.SharePoint.Linq namespace. It translates LINQ queries into Collaborative Application Markup Language (CAML) queries.

Q. What Changes are made in SharePoint 2010 to enforce Referential Integrity?

Ans. In SharePoint 2010, Referential Integrity is enforced using two options, available with Look-up columns.

While creating a Look-up column, you can either choose a) Restrict Delete or b) Cascade Delete to define a relationship between the Look-up list and the list containing the look-up Column. Read Details at SharePoint 2010 Referential integrity – Using LookUp Column


Q . Whats New in SPALerts ?

Ans. In SharePoint 2007, alerts were send only through e-mails, but in SP2010 users can also send an alert to mobile devices as SMS Message. A New property DeliveryChannels is introduced to indicate, whether the alert is delivered as E-mail or as an SMS Message.

Q. What Has Changed with SSP in SharePoint 2010.

Ans. In SharePoint 2010 Shared Service Providers (SSP’s) are replaced by Service Applications. Services are no longer combined into a SSP. They are running independent as a service application. The service application architecture is now also built into MicrosoftSharePoint Foundation 2010, in contrast to the Shared Services Provider (SSP) architecture that was only part of Office SharePoint Server 2007.

A key benefit here is that all services are installed by default and there is no SSP setup

 

Q. What has Changed in SharePoint 2010 Object model?

Ans. Microsoft has replaced the “12 hive” structure that we had in SharePoint 2007 with “14 Hive” structure in 2010.

It has apparently added three new folders to its hive.

The Folders are :

* UserCode – files used to support sandboxed solutions
* WebClients – used for the client Object Model
* WebServices – New .svc files


Q. How would you deploy WebPart Using Windows PowerShell?

Ans. At the Windows PowerShell command prompt (PS C:\>), type the below command :
Install -SPWebPartPack -LiteralPath “FullPathofCabFile” -Name “Nameof WebPart”

Q. How would you re-deploy the old custom solutions in SharePoint 2010.What Changes are needed to the old Solution files.

Ans. SharePoint 2010 object model contains many changes and enhancements, but our custom code will still compile and, will run as expected. You should however, rewrite and recompile any code that refers to files and resources in “12 hive”.
For Details See :
SharePoint Object Model – Backward Compatibility

Q. How would you add a link in the Ribbon?

Ans. You can add any link or Custom Action under any of the existing tabs of the ribbon or can create a new a new tab and place your links under it.

Q. What does CMDUI.XML contain?

Ans. The definitions for the out-of-the-box ribbon elements are split across several files in the SharePoint root, with TEMPLATE\GLOBAL\XML\CMDUI.XML being the main one.

Q. What are the Disadvantages of Using LINQ in your Code?

Ans. LINQ translates the LINQ queries into Collaborative Application Markup Language (CAML) queries thus adding an extra step for retrieving the items.

Q. What is different with SharePoint 2010 workflows ?

Ans. Some of the additions in workflow model are :

1. SharePoint 2010 workflows are build upon the the workflow engine provide .Net Framework 3.5.

2. In addition to the SharePoint lists we can now create workflows for SharePoint sites as well.

3. SharePoint Designer 2010 also has a new graphical workflow designer for designing workflows and deploying them directly to SharePoint.

4. Another Improvement in SharePoint Designer 2010 is that it now allows you to edit the out-of-the-box workflows that come with SharePoint.

Creating Custom Properties in Webpart SharePoint.

A web part by default has some properties like Title, Height, and Width etc. The values for these properties can be either set through code or by using Edit Web Part option. The properties are normally displayed in a Property Pane on the right hand side, when Edit Web Part is clicked. Also these properties are grouped into sections like Appearance, Layout and Advanced.

In MSDN Article describing good for regarding custom properties in SharePoint Web part.

There are some properties below for use in webparts.


Property Type: String
Displayed in property pane as : TextBox

    private string _stringurl = "";
[Category("Custom Properties")]
[DefaultValue("")]
[Description("Enter the String Url :")]
[WebBrowsable(true)]
[Personalizable(true)]
public string Stringurl
{
get
{
return _stringurl;
}
set
{
_stringurl = value;
}
}

Property Type: Integer
Displayed in property pane as : TextBox

        private int _displayitem = 10;
[Category("Custom Properties")]
[DefaultValue(10)]
[FriendlyNameAttribute("Please Select this.")]
[Description("Please Select this.")]
[WebBrowsable(true)]
[Personalizable(true)]
public int Displayitem
{
get
{
return _displayitem;
}
set
{
_displayitem = value;
}
}

Property Type: bool
Displayed in property pane as : Check box

        private bool _checkbox = false;
[Category("Custom Properties")]
[DefaultValue(10)]
[FriendlyNameAttribute("Custom Boolean")]
[Description("Boolean")]
[WebBrowsable(true)]
[Personalizable(true)]
public bool Checkbox
{
get
{
return _checkbox;
}
set
{
_checkbox = value;
}
}

Property Type: enum
Displayed in property pane as : Dropdown list

       public enum ControlModes
{
[Description("Filter mode")]
FilterMode,
[Description("Last 10 item mode")]
LastItemmode

}
[Category("Custom Properties")]
[DefaultValue(ControlModes.FilterMode)]
[Description("Select Display Type:")]
[WebBrowsable(true)]
[Personalizable(true)]
public ControlModes ControlMode
{
get;
set;
}

so finally i am put whole code of my webpart.

    [ToolboxItemAttribute(false)]
public class WebPart1 : System.Web.UI.WebControls.WebParts.WebPart
{

private string _stringurl = "";
[Category("Custom Properties")]
[DefaultValue("")]
[Description("Enter the String Url :")]
[WebBrowsable(true)]
[Personalizable(true)]
public string Stringurl
{
get
{
return _stringurl;
}
set
{
_stringurl = value;
}
}

public enum ControlModes
{
[Description("Filter mode")]
FilterMode,
[Description("Last 10 item mode")]
LastItemmode

}
[Category("Custom Properties")]
[DefaultValue(ControlModes.FilterMode)]
[Description("Select Display Type:")]
[WebBrowsable(true)]
[Personalizable(true)]
public ControlModes ControlMode
{
get;
set;
}

private int _displayitem = 10;
[Category("Custom Properties")]
[DefaultValue(10)]
[FriendlyNameAttribute("Please Select this.")]
[Description("Please Select this.")]
[WebBrowsable(true)]
[Personalizable(true)]
public int Displayitem
{
get
{
return _displayitem;
}
set
{
_displayitem = value;
}
}

private bool _checkbox = false;
[Category("Custom Properties")]
[DefaultValue(10)]
[FriendlyNameAttribute("Custom Boolean")]
[Description("Boolean")]
[WebBrowsable(true)]
[Personalizable(true)]
public bool Checkbox
{
get
{
return _checkbox;
}
set
{
_checkbox = value;
}
}

LiteralControl ltcntrl;
StringBuilder sb;
protected override void CreateChildControls()
{
base.CreateChildControls();
ltcntrl = new LiteralControl();

sb = new StringBuilder();
sb.Append("String Property Value :" + this.Stringurl + "
");
sb.Append("Int Property Value :" + Convert.ToString(this.Displayitem) + "
");
sb.Append("Dropdownlist Property Value :" + Convert.ToString(this.ControlMode) + "
");
sb.Append("Boolean Property Value :" + Convert.ToString(this.Checkbox) + "
");
ltcntrl.Text = sb.ToString();
this.Controls.Add(ltcntrl);

}
protected override void Render(HtmlTextWriter writer)
{
base.Render(writer);
ltcntrl.RenderControl(writer);
}

public override void RenderControl(HtmlTextWriter writer)
{
RenderChildren(writer);
}
}

now deployed your solution and make sure Activated Feature in Site Collection which your webparts exist on that feature.

afterward add your web part from web part gallery to your page and click on toolbar of verb-collection on that webpart than
goto Edit Webpart Property.

You will  able to see your custom webpart properties category which describe on your properties and  set values.

than set your property value as you like than do applied.now See the outputs

Url Properties of SPSite and SPWeb

 

There are some properties for SPSite and SPWeb class using which we can get the URL values for the sites and webs. The two most used of these properties are – ‘ServerRelativeUrl‘ and ‘Url

As a developer we use the values of the properties for writing some logic for satifying the business needs. Whenever I used to write a OM code to use these properties, the first question which flashes in my mind – “What values are returned by these properties?“. I immediately create a cosole application, and check the values returned by these properties and contiue with the actual work. I have seen many other developers doing this. So, for a quick reference I prepared the below table which has the url values returned by these properties.

Some poeple may find this easy, but some (like me ;)) get confused when the sites have managed paths. These properties return the managed path if the site has one. Here goes the list

SCENARIO 1: A Site Collection (SPSite) without any managed path.

URL : ‘http://rams’
Property Value
SPSite.ServerRelativeUrl /
SPSite.Url http://rams
SPWeb.ServerRelativeUrl /
SPWeb.Url http://rams
Url – http://rams/about (‘about’ is a sub site)
SPSite.ServerRelativeUrl /
SPSite.Url http://rams
SPWeb.ServerRelativeUrl /about
SPWeb.Url http://rams/about

This looks pretty simple. We get confused when sites are created using managed paths. Below are the samples values for site created with managed paths

SCENARIO 2: A Site Collection with a managed path (of type Explict inclusion). For the below URL ‘/my’ is the managed path

URL : ‘http://rams/my’
Property Value
SPSite.ServerRelativeUrl /my
SPSite.Url http://rams/my
SPWeb.ServerRelativeUrl /my
SPWeb.Url http://rams/my
Url – http://rams/my/about (‘about’ is a sub site)
SPSite.ServerRelativeUrl /my
SPSite.Url http://rams/my
SPWeb.ServerRelativeUrl /my/about
SPWeb.Url http://rams/my/about

 

SCENARIO 3: A Site Collection with a managed path (of type Wilcard inclusion). For the below URL ‘/sites’ is the managed path, and a site collection is created at ‘/blog’

URL : ‘http://rams/sites/blog’
Property Value
SPSite.ServerRelativeUrl /sites/blog
SPSite.Url http://rams/sites/blog
SPWeb.ServerRelativeUrl /sites/blog
SPWeb.Url http://rams/sites/blog
Url – http://rams/sites/blog/about (‘about’ is a sub site)
SPSite.ServerRelativeUrl /sites/blog
SPSite.Url http://rams/sites/blog
SPWeb.ServerRelativeUrl /sites/blog/about
SPWeb.Url http://rams/sites/blog/about

Create a List Definition in SharePoint 2010 using Visual Studio 2010

In this demonstration, I am going to create a list definition using Visual Studio 2010. For the demonstration purpose, I am going to create a list definition for storing expenses, once deployed, the list definition can be used to create lists to store expenses. The list definition will define a list template that inherit from custom list and add columns expensedate and amount.

Open Visual Studio, Go to File -> New project, In the Template selection dialog, choose List Definition as the template type.

Give a proper name to your List Definition project. Make sure the .Net framework selected is 3.5 as SharePoint 2010 is built on .Net framework 3.5.clip_image002

Click OK button, once you entered all the details.

In the next dialog you need to choose the SharePoint portal you need to use for debug. Also you need to specify whether it is a farm solution or sand boxed solution. Enter your SharePoint portal address and Click Next

clip_image003

Click Next once you are done

Now Visual Studio will bring you the List definition settings dialog. Here you can define the title for your list definition and choose a base list to inherit from. I choose my base list as “Custom List”. In addition to this you can decide whether to include a list instance when deploying this feature. Since I want to check my list definition, I selected “Add a list instance to this list definition” option. Click finish button, once you are done

clip_image004

Click Finish button once you are done with this step.

Visual Studio will add a default feature to your project and add a list definition. In the solution explorer the project will look similar to the following. I published an article for developing a SharePoint 2010 feature using Visual Studio, to read that article click here.

clip_image005

Let me explain the files exists under the List Definition

Elements.xml – this file defines the list template and fields such as name, display name, type etc. The properties specified in this file will be displayed in the Create Page, when you create a list template from this file.

Let us examine the Elements.Xml file. See the snapshot of the elements.xml file

clip_image006

The complete reference for Elements file for List template can be found in the below URL

http://msdn.microsoft.com/en-us/library/ms462947.aspx

The type identifier must be unique within the feature, but need not be unique across all feature definitions or site definitions. So make sure when you have multiple list templates in the same feature, you made them with different type attributes. It is also recommended to create Type value greater than 10000. For my List Instance I assigned the Type attribute with a value of 10001.

After Modifications, the List template file looks as follows.

clip_image007

Notice that, I just updated the Type attribute, but depending on your needs you may add other attributes.

Now I am going to add fields for my List template. As I mentioned initially, I will have only 2 fields date and amount. Refer this link to under stand more about Field element http://msdn.microsoft.com/en-us/library/ms437580.aspx

When you define a field, you need to specifiy a guid as ID enclosed in braces{}. To create a Guid, do the following steps.

From visual Studio menu, select tools, then select create guid

clip_image009

The Create Guid dialog will appear as follows

clip_image010

I have added the following fields to List Template.

 

 

Make sure for each field you create you use unique guid. Now I want to create a content type that includes these fields. When you define a content type, you need to define an ID for the content type. This is a bit tricky. Refer the below article to under stand more about content type ID.

http://msdn.microsoft.com/en-us/library/aa543822.aspx

My content type should be a sub of item content type, so I am going to use the following rule to create my list content type id.

 

System

Item

prefix

Hexadecimal GUID

0x

01

00

4FDDEDBF38D14332A625BCBC60F1667A

 

(for hexadecimal guid, I create a guid from visual studio and then removed braces and hyphens)

So my content type id is 0x01004FDDEDBF38D14332A625BCBC60F1667A

Add the following content type tag just above the ListTemplate start tag.

 
   
     
     
 
 

The definition is very straight forward. See the tags where you add the reference to previously created fields.

Find the snapshot of Elements.xml file after the above items added.

clip_image012

Now you have defined fields, content type and list template. Now you need to link your list definition to content type. You need to perform this in the schema.xml file. Open schema.xml file, by default it will look similar to the below snapshot.

clip_image013

Now you need to replace the element with the below

 

 
   

Now copy all the tags from Elements.xml and paste in between and . This is a duplication of work but you need to do this. After replaced, the Fields tag will look as follows.

 

 
   
  StaticName=”ExpenseDate” Name=”ExpenseDate” Group=”Expense Columns” /> 
   
  StaticName=”Amount” Name=”Amount” Group=”Expense Columns” /> 

Now you need to add the field references to view fields. There will be multiple tags, you can add field references in all or atleast in the View with BaseViewID=1, as this is the default view. See the snapshot of default view in the schema.xml file

clip_image014

In between ViewFields add the below markup.

See the snapshot of schema.xml after made the changes.

clip_image016

clip_image018

Now you are done with the list definition. Now you need to modify the List Instance to use the template you just created. Open the elements.xml file under the List Instance 1, the snap shot of default Elements.xml is as follows.

clip_image019

You need to change the TemplateType to the Type attribute you mentioned in the List Template, i.e. 10001. Also you can modify the list title, url etc. Also you can add initial data to the list instance so that the data will be inserted to the default list instance on feature activation.

Place the below xml inside tag for inserting initial data

 
   
     
      travel expense 
      01-01-2011 
      20.00 
   
 
     
       your expense title 
      01-01-2011 
      10.00 
   
 
 
 

See the snap shot of List Instance 1 after all changes were made.

clip_image020

Now we are ready to deploy the List defenition. Right click the project and click on deploy.

clip_image021

If you made everything correct, visual Studio will successfully deploy the list definition. Now you can find one list instance created in your SharePoint site. Open the list instance, you will find the data already inserted to it.

clip_image023

When you create new item in SharePoint, you will find the expense template.

clip_image025

It is easy to create List Definitions for SharePoint 2010 using Visual Studio 2010. Once you successfully tested your list definition project, you can package it to WSP file and deploy to multiple farms.

« Older Entries