Friday 28 March 2014

Sharepoint Material

Deploy custom Css,Js files in SharePoint 2010 using visual studio 2010
In this post you learn how to deploy files like Css, js or images in Sharepoint 2010′s “Style library” using a solution package created in Visual studio 2010.
For deploying files to “STYLES” folder in 14 hive or “_layouts/1033/Styles” please see the post
Add custom css file to styles folder in _layouts Sharepoint 2010
Steps to add Css file in “Style library” available in your SharePoint 2010 site -
1. Create an ‘Empty SharePoint project” in visual studio 2010 and name it “DeployFiles”. See the screen below.
Next, enter the url of your SharePoint site and select deploy as ‘Farm solution”.
2. Next, right click on the project and click Add -> New Item… then from the “Add new” item wizard select “Module” in SharePoint tab. Give it a name “CustomCssmodule”
3. Once you create the module you will get and “Elements.xml” and “Sample.txt” files create under it. For this example we will delete the Sample.txt file and will add our . I have used “Text File” from General tab to add my new Custom.css file. See the screen below. You can also add an existing CSS, XSL or Js file in the module.
4. After, adding the module and the css file your project should look like below.
5. Once your done adding your files you now need to modify your “Elements.xml” to specify the URL\ Path where the files will be deployed. To deploy the files into the “Styles Library” we will specify URL=”Style library” or if you want to deploy files into ‘MasterPage Gallery” use URl=”_catalogs/masterpage. You typically do that when your deploying custom master or layout page.
Modified elements.xml
Don’t forget to add Type=”GhostableInLibrary” in your File tag.
6. Next, you make sure your feature includes your module so just open the feature1.feature and check that all the files are included in the module in the right side of your feature. Here you can also set the feature “Scope” to “Site,Web,Farm or web application”. I have set to to “Site”.
7. Now, all we have to do is “Build solution f6″ and then “Deploy”( Right click project properties).
8. Now navigate to “Style Library” in Site Actions -> View All Site Content -> Style Library and verify that your file Custom.css is deployed.





 








SharePoint 2010 - Developing a feature using visual studio 2010

Overview
Creating a simple feature using Visual studio 2010 which deploys a custom site page.

Steps for creating a SP 2010 feature using VS 2010
Following are the steps for creating, deploying and activating a SharePoint 2010 feature using Visual Studio 2010.

1) Create a new empty project named SharePoint2010FeatureDemo.


2) Right click on the Features folder and add a new feature

3) A new feature named Feature1 will be added with supporting files as shown in the figure below.

4) In SharePoint 2010, there is a Feature manifest design view, where you can add the title, scope and items (element manifest, modules etc) in the feature.

5) Also, if you click on the manifest tab, you can see the feature manifest in xml format.

6) Now right click on the solution and add a new module named MyCustomModule.

7) By default, 2 helper files will be included when the module is added. First one is the Elements.xml (which includes the path and virtual url for Sample.txt) and second is the sample.txt which is just a simple text file.

8) Rename the Sample.txt to MyCustomSitePage.aspx and add the following mark-up inside it.

MyCustomSitePage.aspx Markup
<%@ Page MasterPageFile="~masterurl/default.master" meta:progid="SharePoint.WebPartPage.Document" %> 
<asp:Content ID="title" runat="server" ContentPlaceHolderID="PlaceHolderPageTitle"> 
   My Custom Site Page 
</asp:Content> 
<asp:Content ID="addhead" runat="server" ContentPlaceHolderID="PlaceHolderAdditionalPageHead"> 
</asp:Content> 
<asp:Content ID="Content1" runat="server" ContentPlaceHolderID="PlaceHolderMain"> 
   <h3>Welcome to My Custom Site Page</h3> 
</asp:Content>


9) Rename the Feature title to FeatureDemo, change the scope to Site and add the module to the feature via the design view.
The same activities mentioned in the above step can also be done through the Feature manifest tab. Edit the feature manifest in xml view and add the Element Manifest inside Feature tag as follows.

Feature.xml Markup
<Feature xmlns="http://schemas.microsoft.com/sharepoint/" Title="FeaturesDemo" Id="75de0c0a-9f9f-4033-a708-c168bf14ba96" Scope="Site">
  <ElementManifests>
    <ElementManifest Location="MyCustomModule\Elements.xml" />
    <ElementFile Location="MyCustomModule\MyCustomSitePage.aspx" />
  </ElementManifests>
</Feature>

10) Make the changes as follows in the Module.
i) Add Url attribute in the Module element which specifies the location (SitePages) of the custom site page.
ii) Add Url attribute in the File element which specifies the file name (MyCustomSitePage.aspx) of the custom site page.

From the following figure you can easily figure out the url that will be formed. 
(http://home:3000/SitePages/MyCustomSitePage.aspx)

Elements.xml Markup
<?xml version="1.0" encoding="utf-8"?>
<Elements xmlns="http://schemas.microsoft.com/sharepoint/">
  <Module Name="MyCustomModule" Url="SitePages">
    <File Path="MyCustomModule\MyCustomSitePage.aspx" Url="MyCustomSitePage.aspx" Type="Ghostable" />
  </Module>
</Elements>

11) Click on Build->Deploy to deploy the feature. By default activateOnDefault attribute will be true and the feature will automatically get activated. Click on the following url and you can see the custom master page that we deployed. (http://home:3000/SitePages/MyCustomSitePage.aspx).



What changes happened after deploying the feature

1) 14 Hive - A new folder in 14 Hive will be created as ProjectName_FeatureFileName. In our case following is the folder created. You can change the naming convention in the feature properties window.
C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\14\TEMPLATE\FEATURES\SharePoint2010FeaturesDemo_Feature1

2) Feature.xml - Inside the Feature folder there will be Feature.xml which is the feature manifest file and MyCustomModule folder.

3) Module - MyCustomModule folder will consist of 2 files.
    i) Elements.xml which is the element manifest file.

    ii) MyCustomSitePage.aspx which is the custom site page that we deployed.

4) GAC - Just like any other SharePoint server side component, the project dll is deployed to the GAC.

5) Site Collection - Go to Site Settings page and click on Site Collection Features link.

6) Feature Installed and Activated - You can see that the feature named FeatureDemo has been installed and activated in the Site Collection.



 

 

 

 

 

 

 

 

Deploying Master Pages & Themes via a Feature using Visual Studio 2010

Following this guide you’ll see the process that goes behind creating the feature which commonly be used to deploy branding items such as Master Pages, CSS, JavaScript, & Themes.

Configure the Project

  1. Open Visual Studio 2010
  2. File -> New -> Project

  1. Select SharePoint -> Empty SharePoint Project
  2. Add Name: TomDaly.SharePoint.Branding (this is my standard structure)
  3. Add Location: C:\Projects\TomDaly

  1. Click OK
  2. Enter your test site for debugging purposes.
  3. Select ‘Deploy as farm solution’

  1. Click Finish

Adding the CSS / Image / JavaScript Files

Add CSS file

  1. Right Click on the Project -> Add -> SharePoint ‘Layouts’ Mapped Folder

  1. This created a folder which is mapped to the layouts

** These files in here are accessible through the web via http://YOURSITE/_layouts/TomDaly.SharePoint.Branding/
  1. Right click on Layouts\TomDaly.SharePoint.Branding folder -> Add -> New Item

  1. Select Web on the left, and Style Sheet on the right, and Name the file at the bottom.
(I typically use base.css or style.css for the foundation of my styles, but this is all up to you)
  1. Click Add

Add Images & JavaScript Folder

This would be the location for any images associated with the site css.
  1. Right Click on the Layouts\TomDaly.SharePoint.Branding folder -> Add -> New Folder

  1. Name the folder ‘images’

OPTIONAL STEP
  1. Repeat Step 1 & 2 for the JavaScript folder. (I typically call this folder ‘js’)

I usually include a JavaScript folder because most of the time I end up using jQuery somewhere on the site, this is where I store those files which I would reference on page or in the Master Page. Depending on how it’s needed.
These files would be accessible: http://YOURSITE /_layouts/TomDaly.SharePoint.Branding/js/JSFILESHERE

Setting up the Feature

  1. In your project Right click on Features -> Add Feature

This will create a feature with some default name of ‘Feature 1′, which we don’t want
  1. Select Feature1, Right Click -> Rename

  1. Rename the Feature to TomDaly.SharePoint.Branding (I typically name it to the same as the project name)

  1. Double Click on your Primary feature, in the main left hand window the properties should appear

  1. Give your feature a normal title name Title and Description, and scope it accordingly. (I usually scope my master pages to (Site) as they are normally used through the site collection

  1. Click Save

Renaming the WSP

This is really annoying to me so I always change it. When a .WSP is generated it will usually come out as Feature_Feature.wsp. I prefer just Feature.wsp.
1. Double Click on the primary Feature, the Properties should appear right below it.
2. Change ‘Deployment Path’
From: $SharePoint.Project.FileNameWithoutExtension$_$SharePoint.Feature.FileNameWithoutExtension$
To: $SharePoint.Project.FileNameWithoutExtension$

Adding the Master Page

1. Right Click on the Project -> Add -> New Item

2. In the left Installed Template column, Select SharePoint 2010
3. On the right select Module
4. At the bottom name the Module, Master Pages

5. Click Add
** You module will be added to your project **
6. Under the Master Pages Module, right click on Sample.txt and Delete It

7. Now Drag & Drag and Drop your Custom Master Page from another folder into the project, In the Master Pages Module

8. Double Click on the Elements.xml in the Master Pages Module

9. In the Elements.xml file, make the following changes to the <Module> line
Change
<Module
Name=MasterPages>
To
<Module
Name=MasterPages
Url=_catalogs/masterpage>
10. In the Elements.xml file, make the following changes to the <File> line
    a. add IgnoreIfAlreadyExists=True
    b. add Type=GhostableInLibrary
    c. remove MasterPages/ from the
Url=MasterPages/TOMDALY.master
So essentially this line
<File
Path=MasterPages\TOMDALY.master
Url=MasterPages/TOMDALY.master />
Changes to
<File
Path=MasterPages\TOMDALY.master
Url=TOMDALY.master
IgnoreIfAlreadyExists=True
Type=GhostableInLibrary />
11. Click Save

Adding Theme

This step will incorporate a theme into your project. How to generate the .thmx is not covered here but a simple way would be to export from PowerPoint or use ThemeBuilder to generate this file.
1. Right Click on the Project -> Add -> New Item

2. On the left Click SharePoint -> 2010
3. On the Right Select “Module”
4. Add Name: Theme

5. Click Add
6. In the Theme node, Delete Sample.Txt

7. Copy in you custom .thmx file
8. Double Click on the Elements.xml in the Theme Module

9. In the Elements.xml file, make the following changes to the <Module> line
Change
<Module
Name=Theme>
To
<Module
Name=Theme
Url=_catalogs/theme>
10. In the Elements.xml file, make the following changes to the <File> line
    a. add IgnoreIfAlreadyExists=True
    b. add Type=GhostableInLibrary
    c. remove Theme/ from the
Url=Theme/TomDaly.thmx
So essentially this line
<File
Path=Theme\TomDaly.thmx
Url=Theme/TomDaly.thmx />
Changes to
<File
Path=Theme\TomDaly.thmx
Url=TomDaly.thmx
IgnoreIfAlreadyExists=True
Type=GhostableInLibrary />
11. Click Save

Adding the Feature Receiver

This whole step is optional. Its sole purpose is to automatically turn on the branding on the sites and subsites, apply a theme, or apply search master pages to your site collection. NOTE: If you changed the scope then there is no guarantee that this code will work.
Please take some time to look through the code as there are different sections you might want to comment out or fill in. Say if you want to configure the Site Logo or an Alternative CSS file. If you not interested and just want a working project jump down to the END and in the summary there is a link to download the project.
1. Right Click your primary Feature, Select Add Event Receiver

** This will get added Right under your feature**
2. Double Click on the new file TomDaly.SharePoint.EventReciever.cs

5. At the very top Add the following using statements
using Microsoft.SharePoint.Utilities;
using System.Collections.ObjectModel;

7. Under the class declaration add these three string constants which contain the names of the masterpages and the theme.

So my master page name is TomDaly.master, my search master page which I don’t have a custom one for yet is minimal.master, and my Custom Theme is called TomDaly
8. Replace the public override void FeatureActivated, with
ublic override void FeatureActivated(SPFeatureReceiverProperties properties)
{
SPSite site = properties.Feature.Parent as SPSite;
if (site != null)
{
using (SPWeb topLevelSite = site.RootWeb)
{
//Get the relative path
string relativePath = topLevelSite.ServerRelativeUrl;
if (!relativePath.EndsWith(“/”))
{
relativePath += “/”;
}

//Get Theme collection from site and the them we want
ReadOnlyCollection<ThmxTheme> themes = ThmxTheme.GetManagedThemes(site);
ThmxTheme customTheme = null;
foreach (ThmxTheme theme in themes)
{
if (theme.Name == themeName)
{
customTheme = theme;
break;
}
}

//Apply branding to each web in the site collection
foreach (SPWeb web in site.AllWebs)
{
//Apply masterpage and logo
if (web.WebTemplate == “SRCHCENTERLITE” || web.WebTemplate == “SRCHCEN” || web.WebTemplate == “SRCHCENTERFAST”)
{
web.CustomMasterUrl = relativePath + “_catalogs/masterpage/” + searchMasterPage;
}
else
{
web.MasterUrl = relativePath + “_catalogs/masterpage/” + masterPage;
web.CustomMasterUrl = relativePath + “_catalogs/masterpage/” + masterPage;
}

web.AlternateCssUrl = “”;
web.SiteLogoUrl = “”;
web.UIVersion = 4;
web.Update();

//Also apply the theme
if (customTheme != null)
{
customTheme.ApplyTo(web, true);
web.Update();
}
}
}
}
}
9. Replace the public override void FeatureDeactivated, with
public override void FeatureDeactivating(SPFeatureReceiverProperties properties)
{
SPSite site = properties.Feature.Parent as SPSite;

if (site != null)
{
using (SPWeb topLevelSite = site.RootWeb)
{
//Get the relative path
string relativePath = topLevelSite.ServerRelativeUrl;
if (!relativePath.EndsWith(“/”))
{
relativePath += “/”;
}

//Apply branding to each web the wen the site collection
foreach (SPWeb web in site.AllWebs)
{
//Apply default masterpage and logo
if (web.WebTemplate == “SRCHCENTERLITE” || web.WebTemplate == “SRCHCEN” || web.WebTemplate == “SRCHCENTERFAST”)
{
web.CustomMasterUrl = relativePath + “_catalogs/masterpage/minimal.master”;
}
else
{
web.MasterUrl = relativePath + “_catalogs/masterpage/v4.master”;
web.CustomMasterUrl = relativePath + “_catalogs/masterpage/v4.master”;
}

web.AlternateCssUrl = “”;
web.SiteLogoUrl = “”;
web.Update();
//reset the theme back to default
ThmxTheme.SetThemeUrlForWeb(web, null, true);
web.Update();
}
}
}
}
10. Click Save
11. Hit F6, or Build -> Build Solution … to ensure that everything is correct and ok. You should receive the “Build Succeed” in the bottom left corner



Changing the Site Url for Testing

Sometimes you want to create or re-use this package and you need to change the url of the site to deploy to.
1. Click on the project and in the Properties window you’ll notice the Site URL

2. Change that to your new site destination
3. Click Save

Deployment

If you’re testing on a development box, that visual studio is on then you can simply deploy through visual studio. Otherwise you’ll have to push out your solution with the .wsp file.

Deploy from Visual Studio

1. In the Build Menu, Select Deploy

OR

Getting the .WSP for manual deployment

1. In the Build menu, Select Build to ensure no errors
2. In the Build menu, Select Package to generate the .WSP file

3. The files will be in the project folder, and by default in the BIN\DEBUG
Either way once you deploy your solution should be available in the Site Collection Features Gallery as shown here

Summary

So that’s how you setup a project for deploying branding assets. This is the typical setup I use but can change from client to client depending on their needs.

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

Creating Lists in SharePoint Using Visual Studio 2012

​ The latest version of Visual Studio has some nice capabilities for creating lists and lookup fields that is compatible with SharePoint 2010, as well as, one assumes, SharePoint 2013. Let’s take a look.
Since it is NFL season, we are going to create an NFL standings list. We will create several site columns, a list definition, and then, finally, the list.
Creating a Solution
In Visual Studio 2012, create a SharePoint solution by selecting New Project and SharePoint 2010 Project. Similar to VS 2010, you will NEED to run VS with administrative privileges.

When developing applications for SharePoint, it is always best to start with a Sandboxed solution and if you have requirements that are not met by Sandbox solutions, convert the solution to a Farm solution. First, we are going to set our location, start with a Sandbox solution and click finish.

Creating Site Columns
Next, we are going to create site columns for example purposes. In the real world, it may not make a lot of sense to have a site column called NFL Conference, but this is the blogging world, not the real world.
Right click your project solution and choose Add New Item and then Site Column and call it NFLConference. This creates the XML for our SiteColumn definition. By default, Visual Studio 2010 creates the elements.xml as a Unique ID and some default settings for our site column.


Now we want to update things like the display name and the Group to be applicable for our scenario. Also, for the NFL conference, a text field would not make much sense. It would be a Choice field, where AFC and NFC are the only options. We update the XML schema to reflect these changes.

Next, we can add a second Site Column for the NFL Divisions. Again these will be choice fields. The end result is:

If we right click the solution and choose deploy, Visual Studio will automatically compile, deploy and activate the feature to our SharePoint website. We can see the Site Columns have been deployed by checking under Site Actions, Galleries and then Site Columns.



Creating the SharePoint List
Creating lists and list instances is where the new tooling in Visual Studio gets even slicker due to the addition of a Visual Designer in Visual Studio. We are going to create a new list, NFL standings. Right click the project, selection Add New Item, and select List. It will create both the list definition as well as a list instance.





Even cooler, is the new Visual Studio 2012 Editor for lists:

For our case, we are going to change the Title to Team Name, add our site columns, and then create some new fields. Our list definitions appear in the Add Column field. We’ll add number columns for Wins and Losses. However, for the Place field, we really only ever have five options, 1-5, so we can create a choice field.


The nice thing is, we can then go into the Visual Studios Property pane and set the values for these choices. Scroll down to the Type column and expand the node.



Within the node, expand items and update the text box with our five options.


Last, with the way the VS 2012 default deploy behavior works, whenever we deploy, we delete our existing list and list definitions. As a result, it is VERY beneficial to seed some values for testing purposes. You may even want to do this in a production environment.
Within the Instance of our list (usually the list definition name with Instance appended on), expand the node if necessary and edit the Elements.xml file. Do this by adding a Data element, and since data has rows, a Rows elements and then a Row for each data row you want, with values corresponding to the data you want to display. It is also good to update things like List Title and Description to reflect your environment.


Right click to deploy and take a look at your SharePoint site.

 

 

 

 

 

 

 

 

 

How to create Custom SharePoint 2010 List Column using Visual Studio 2010

In this article we are going to create custom column using visual studio 2010.

Steps Involved:

Creating Empty SharePoint Project:
  • Open Visual Studio 2010.
  • Go to File => New => Project.
  • Select 2010 from the installed templates SharePoint and choose Empty SharePoint Project.
  • Name it as CustomColumn.

  • Click Add.
  • Enter the SharePoint server farm URL.
  • Select 'Deploy it as a Farm Solution".
  • Click Finish.
Adding an Empty Element:
  • Right click the Solution Explorer and select Add a new item.
  • Select Empty Element from the installed templates SharePoint and name it as CustomColumn.

  • Double click the Elements.xml file.

  • Replace the code with the below one.

    <?xml version="1.0" encoding="utf-8"?>
    <Elements xmlns="http://schemas.microsoft.com/sharepoint/">
              <Field ID="{4678C6A2-F296-432C-A4CA-8C4D96DA6B46}"
                     Name="CustomColumn"
                     DisplayName="Custom Column"
                     Type="Text"
                     Group="Custom Columns">
              </Field>
    </Elements>
  • In the above code, we are adding a custom column with the Type "Text" and with the group name as "Custom Columns".
  • Build the solution.
  • Deploy the solution.
Testing:
  • Go to the SharePoint site.
  • Go to Site Actions => Site Settings =>Galleries =>Site Columns.

  • You will see the custom column that we have created in the group "Custom Columns".

 

 

 

 

 

 

 

 

 

SharePoint 2010: Creating a Custom Content Type using Visual Studio

In this article we will explore the ways of creating a custom content type.

What is a Content Type?

A Content Type is a reusable, shareable metadata. The base type of a content type could be an existing content type like:
  • Item
  • Document
  • Folder
  • Event
  • Task
  • Message
  • Comment
  • Post
Some more information on Content Type:
Base Type: The base type of the Content Type is System with Id 0x.
Example: If you need a common list format or document format across sites then Content Type is advisable.
Groups: The content types are organized in groups, for example, List Content Types, Document Content Types, and Folder Content Types.
Three important Content Types: Item, Document, and Folder.
Feature: A Content Type can be deployed as a feature.
Scope: The scope of a Content Type could be specified in the feature as Site, Web etc.

Creating Custom Content Types

We can use the following tools for creating Content Types:
  • SharePoint UI
  • Visual Studio 2010
  • SharePoint Designer 2010
The content type is in XML format so Notepad can also do the job but in a different way.

Creating a Content Type using Visual Studio 2010

Now we can try creating a content type using Visual Studio 2010. The SharePoint Developer Tools already contain the template for Content Type creation. Here we are trying to create an Item Content Type with the following fields:
  • Title
  • Contact Type
Open Visual Studio and create a new project from SharePoint > Content Type.

Enter the name of your content type and click the OK button.
In the next page, you will be prompted with the solution type:

Select the option as Sandboxed solution and click the Next button.
In the next page, select the base type. You can see a large list of base types possible.

Select the base type as Item and click the Finish button. Expand Content Type1 and enter the following code in Elements.xml:
Collapse | Copy Code
<?xml version="1.0" encoding="utf-8"?>
<Elements xmlns="http://schemas.microsoft.com/sharepoint/">
  <Field ID="{B7410A27-4E0C-42FB-BC6E-07928C43108D}" Name="ContactType" DisplayName="Contact Type" Type ="Choice" >
    <CHOICES>
      <CHOICE>Personal Contact</CHOICE>
      <CHOICE>Official Contact</CHOICE>
      <CHOICE>Other Contact</CHOICE>
    </CHOICES>
  </Field>
  <!-- Parent ContentType: Item (0x01) -->
  <ContentType ID="0x01009aa1f989a2604c99af0f57d80fe0b16d"
               Name="Contact Type"
               Group="Custom Content Types"
               Description="Contact Type"
               Inherits="TRUE"
               Version="0">
    <FieldRefs>
      <FieldRef ID="{B7410A27-4E0C-42FB-BC6E-07928C43108D}"/>
    </FieldRefs>
  </ContentType>
</Elements>
The above code performs the following:
  1. Create a new Choice field named ContactType
  2. Add three Choices for the field
  3. The new field is referred inside the Content Type

Deploying the Content Type

The content type is deployed as a feature. Right click on the project and use the menu command Deploy.

Possible Error

If you get the following error:
Error occurred in deployment step ‘Activate Features’: Cannot start service SPUserCodeV4 on computer
It means that the Sandboxed Solution Service is not running in your computer.
Solution: Go to Central Administration and open the following link:

Click the Start link of the following service:

Wait for a while until the service is started and now you can try deployment. After the deployment succeeds, go to the SharePoint site.

Testing the Content Type

Now we can try testing the new Content Type. Our Content Type will prompt with following properties:
  • Last Name
  • Contact Type
Create a new list from template Contacts and go to the List Settings > Advanced Settings.

Modify the Allow Management property to true and save the changes.
Back to the List Settings, now you can see the following option:

Click on the Add from existing site content types, and in the appearing dialog, choose the new deployed Contact Type, and click the OK button.

Now go back to the List Settings and choose the Change new button.. link

In the above page, choose our Contact Type as the default option and save the changes.
Now go back to the My Contacts list and try to enter a new contact.

You will get the new modified properties dialog. Here our Contact Type is being used. 
Note: The Last Name column is the default one with original name as Title.
So this concludes our Content Type creation using Visual Studio. In real world scenarios, packing the Content Type into one Solution would be advantageous for deployment purposes.

 

 

 

 

 

 

 

 

 

 

How to create custom SharePoint 2010 Application Page using Visual Studio 2010

In this article we are going to create a custom Application Page using visual studio 2010.

Steps Involved:

Creating Empty SharePoint Project:
  • Open Visual Studio 2010. 
  • Go to File => New => Project. 
  • Select 2010 from the installed templates SharePoint and choose Empty SharePoint Project. 
  • Name it as CustomApplicationPage.

  • Click Add. 
  • Enter the SharePoint server farm URL. 
  • Select 'Deploy it as a Farm Solution". 
  • Click Finish.
Adding Application Page:
  • Right click the Solution Explorer and select Add a new item. 
  • Select Application Page from the installed templates SharePoint and name it as CustomApplicationPage.

  • Once you add the application page it will automatically create the Layouts Folder.
  • In the solution explorer you could see Layouts -> CustomApplicationPage ->CustomApplicationPage.aspx.
  • Once you deploy the solution the pages will be automatically placed in the 14 hive layouts folder.
  • Open CustomApplicationPage.aspx from the solution explorer.
  • In the "PlaceHolderMain" add one asp label control.
  • And change the "PlaceHolderPageTitle" content to 'My Application Page" as shown in the following code.

    <%@ Assembly Name="$SharePoint.Project.AssemblyFullName$" %>
    <%@ Import Namespace="Microsoft.SharePoint.ApplicationPages" %>
    <%@ Register Tagprefix="SharePoint" Namespace="Microsoft.SharePoint.WebControls" Assembly="Microsoft.SharePoint, Version=14.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>
    <%@ Register Tagprefix="Utilities" Namespace="Microsoft.SharePoint.Utilities" Assembly="Microsoft.SharePoint, Version=14.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>
    <%@ Register Tagprefix="asp" Namespace="System.Web.UI" Assembly="System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" %>
    <%@ Import Namespace="Microsoft.SharePoint" %>
    <%@ Assembly Name="Microsoft.Web.CommandUI, Version=14.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>
    <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="CustomApplicationPage.aspx.cs" Inherits="CustomApplicationPage.Layouts.CustomApplicationPage.CustomApplicationPage" DynamicMasterPageFile="~masterurl/default.master" %>
    <asp:Content ID="PageHead" ContentPlaceHolderID="PlaceHolderAdditionalPageHead" runat="server">
    </
    asp:Content>
    <
    asp:Content ID="Main" ContentPlaceHolderID="PlaceHolderMain" runat="server">
    </
    asp:Content>
    <
    asp:Content ID="PageTitle" ContentPlaceHolderID="PlaceHolderPageTitle" runat="server">My Application Page
      <asp:Label runat="server" Text="My Custom Page"></asp:Label>
    </asp:Content>
    <
    asp:Content ID="PageTitleInTitleArea" ContentPlaceHolderID="PlaceHolderPageTitleInTitleArea" runat="server" >
    My Application Page
    </asp:Content>
  • Build the solution. 
  • Deploy the solution.
Testing:
  • Go to the http://servername:2010/_layouts/CustomApplicationPage/ CustomApplicationPage.aspx.
  • A new custom application page has been created in SharePoint 2010 as shown below.

Summary:

This article is mainly written to explain that a new template "Application Page" is available in the installed templates "SharePoint " -> "2010" and how to use that in visual studio 2010. 

 

 

Using Features and Solutions to Deploy your SharePoint Customizations

What are Features?
So what are these features I've mentioned?
Well, features are packages of functionality that you can activate or deactivate in a SharePoint farm. They have four possible scopes:
  • Farm
  • Web application
  • Site
  • Web
A farm level feature, as the name suggests, is something that affects the whole farm, for example provisioning a custom timer job or deploying a Business Connectivity Services model.
A web application feature can be activated so that it only affects a single web application, and a typical example is a feature that modifies the web.config file.
A site scoped feature can be activated so that it only affects a site collection, an example being the deployment of a master page to the master pages catalogue.
Finally, a web scoped feature can be activated for a single site, for instance setting the default master page for that site.
What are Solutions?
'And what are these solution files?' you may ask.
They are the files you use to deploy your changes to SharePoint. They have the WSP file extension, and are often referred to as just WSP files. In reality, they are cabinet files that contain your customizations, plus a manifest XML file that tells SharePoint how to deploy your changes. In fact, when you first see a WSP file, I encourage you to change the file extension to CAB and use Windows Explorer to browse the contents of the file. Open up the manifest XML file and look at its structure; it will tell you a great deal how SharePoint deploys your customizations.
In SharePoint 2010 there are two types of solutions: farm solutions and sandboxed solutions.
Farm solutions are the same as the solutions we had in SharePoint 2007 and are deployed to the farm. In layman's terms, your application or update is deployed as is; files on the file system are deployed exactly as that, files on the file system.
Sandboxed solutions are new to SharePoint 2010 and deploy your files to the SharePoint Content Database (see my previous article Visual Studio 2010 and SharePoint 2010: Support at Last.
You have a decision to make right here about how you are going to package your features: farm or sandboxed solution? Often the decision is made for you: sandboxed solutions permit only limited functionality (again, see Visual Studio 2010 and SharePoint 2010: Support at Last) but are available on a wider variety of SharePoint platforms including Office 365, previously known as BPOS. On the other hand, farm solutions allow the full functionality of SharePoint but are usually only deployed to dedicated farms. Whether a solution can be farm or sandbox is primarily determined by its contents, including the scope of the features it contains.
If your solution contains either a farm or a web application scoped feature, it can only be deployed as a farm solution.
Solutions that only contain site and web scoped features can usually be deployed using either a sandbox or farm solution. However, be aware that unless you take care, you could successfully deploy code using a sandboxed solution that is not permitted to run. The Community SharePoint Kit for Developers contains a great tool which limits Intellisense Visual Studio 2010 to show only supported methods and properties when building for sandbox solutions.
Sandboxed or Farm Solutions?
As I previously mentioned, whether you design for sandboxed or farm solutions is often driven by project requirements. Let's say I want to deploy a new master page for a site; this is perfectly achievable through a sandboxed solution. But then let's also say I need to deploy a new custom control that I've included in the master page, and that control needs to be deployed to the %SharePoint Root%\Template\CONTROLTEMPLATES folder as an ASCX file and its associated DLL needs to be placed into the GAC; now the story is different and I have to deploy using a farm solution.
As a guideline, the accepted best practice is to aim for a sandboxed solution initially, but move to a farm solution if your project functionality dictates this. However, it is important to remember that hosted SharePoint environments will often only permit sandboxed solutions, so in this case the platform is a major influencer in your decision.
Creating the visual changes
First off, we need to make the design changes to our custom master page. I'll use SharePoint Designer 2010 (SPD2010) to implement these changes (we will take a look at SPD2010 in a future article and examine some of its great new features).
So, open SPD2010, click Open Site, enter the URL of your site into the Site Name text box, and then click Open.
Next, in the left-hand Navigation Pane, select Master Pages and highlight the line that says v4.master. Don't click the hyperlink - this will take you into the properties window of the page, which we don't want at this time.
Now, right-click and select Copy, then right-click again and Paste. Then, right-click a third time and click Rename. Rename the master page to simple-talk.master.
Finally, do yet another right-click and select Set as Default Master Page. You can now edit simple-talk.master in SPD2010 if you wish, and immediately see the changes in your SharePoint site.
The extent of our styling of the master page will not be too much of a stretch. Add in mark-up as shown in Code Sample 1 just after the <div>; tag with an id attribute of s4-mainarea, and then save, clicking Yes when asked if you wish to continue customizing your page.
<div id="s4-mainarea" class="s4-pr s4-widecontentarea">
 <div style="height:15px;width:100%;background-color:#cc6633;" class="s4-notdlg><div>
  <div id="s4-leftpanel" class="s4-notdlg">
   <div id="s4-leftpanel-content">
Code Sample 1: Custom mark-up in master page
Your home page will now have a brownish bar across the page, under the top navigation menu bar.
Code Sample 1: Custom mark-up in master page
If this was the only site collection or farm we had, that would be it. But I'm assuming you now wish to deploy this change to other site collections or farms. In order to do this we now need to create a deployable feature.



Creating the feature
Open up Visual Studio 2010 and select File -> New -> Project. In the Add New Project dialog box (shown in Figure 2), under Installed Templates, select SharePoint -> 2010, highlight Empty SharePoint Project, and then name your project accordingly.
Figure 2: Add New Project dialog box
Next, on the SharePoint Customization Wizard dialog box, we want to select Deploy as a sandbox solution. Add in the URL to your site collection, which should be different from the one you edited your master page in, and click Finish. This will create a project called SimpleTalk.
Now select the SimpleTalk project node in the Solution Explorer, right-click and select Add -> New Item, then select Start Master Page (CKSDev), give it a name of simpletalk and click Add.
At this point we have all the files we need to deploy our master page and we just need to do a little cut-and-paste. But let's examine in a little more detail what we actually have in the solution, which should now look as in Figure 3.
Figure 3: SimpleTalk Solution Explorer
The feature folder contains two files used by Visual Studio 2010 (VS2010) for constructing the final feature that SharePoint will need in order to deploy your master page. These files are:
  • The feature control file with the extension .feature; this is used by VS2010 only and is never deployed.
  • The feature template XML file. This contains the outline XML that VS2010 will use to construct the final feature.xml file, which must be present in a SharePoint feature. This too is used only by VS2010 and is never itself deployed. 
It is the feature.xml file which actually gets deployed and which tells SharePoint 2010 what is in the feature, and thereby what SharePoint needs to do with the files associated with the feature. The feature.xml file will only be created when you instruct VS2010 to package your solution.
Next, we see the package control file and the package template. This works in a similar manner to the feature. Neither of these two files ever gets deployed, but they are used by VS2010 to construct a file called manifest.xml, which exists in the WSP solution file.
Finally, the folder simpletalk has been added with two files: Elements.xml and simpletalk.master. The second is plainly an ASP.NET Master Page; the former is another SharePoint specific file, and whilst it does not strictly need to be called Elements.xml, by convention it nearly always is. The Elements.xml file in this case looks as shown in Figure 4:
Figure 4: Elements.xml file
All this mark-up has been added by the CKS Item and will tell SharePoint that a file called simpletalk.master should be made available at a relative URL _catalogs/masterpage. Most of the other properties are metadata and should be replaced with meaningful data, and one I will mention specifically is Type='GhostableInLibrary', for two reasons:
  • Reason one is that this is the attribute that tells SharePoint that this document should be made available and versioned through a document library, which means that any change to the document through SPD2010 will result in the file being uploaded into the SharePoint content database and thereafter that is where the source code for the file will be held.
  • Reason two is that without this attribute, you will not see the document in the library listing and for some inexplicable reason it is omitted from the standard SharePoint Module Template in VS2010, which is why I used the CKS Template.
I want the feature to be scoped at the SiteCollection level, which means that it is available to all sites within the SiteCollection. I can do this quite easily in the Feature Designer shown in Figure 5. So, double-click on the Feature1 folder and in the Scope drop-down list change the scope to Site. We can see the simpletalk item is included in the feature as it is shown on the right-hand side of the designer.
Figure 5: Feature Designer
All we need to do now is copy the mark-up from our master page in SPD2010 and paste it into the simpletalk.master file in our VS2010 project, then save the master page. Once that is done we're good to go.
Deploying our feature
To deploy our feature, we need to do the following:
  1. Add it to a solution.
  2. Upload it to the Site Collection Solution Store.
  3. Activate the solution.
  4. Activate the feature.
Sounds a lot of work to you? It does to me too. And in Microsoft Office SharePoint Server (MOSS) 2007 it was, but now with VS2010, it's a breeze. Just right-click the SimpleTalk project and click Deploy. Wait a few seconds, and then open your SharePoint site and select Site Actions -> Site Settings -> Galleries ->Solutions, and you will see your solution appearing in the solutions gallery as in Figure 6. Note that the status is Activated, so the relevant features have all been deployed.
Figure 6: Solution Gallery
Select Site Actions -> Site Settings ->Site Collection Administration -> Site Collection Features, scroll down, and you should see the feature has been activated as shown in Figure 7:
Figure 7: Site Collection Feature
Finally, select Site Actions -> Site Settings -> Galleries -> Master Pages and page layouts. You will then see your deployed master page in the master page gallery.
Figure 8: Master page gallery
Where is our brown bar? We haven't set it as the default, so the master page is still the original v4.master. Let's enhance our feature so that it sets our new master page as the default master page.
Enhancing the feature with code
In our Visual Studio project, select the Feature1 folder, then right-click and select Add Event Receiver, which will create a class called Feature1.EventReceiver.cs.
We will add code to two protected overridden methods. Insert the following code into the FeatureActivated and FeatureDeactivating methods:
    publicclass Feature1EventReceiver : SPFeatureReceiver
    {
      public override void FeatureActivated(SPFeatureReceiverProperties properties)
      {
        SPSite site = properties.Feature.Parent as SPSite;
        if (site != null)
        {
          SPWeb web = site.RootWeb;
          web.AddProperty("OldMasterUrl", web.MasterUrl);
          web.MasterUrl = String.Format("{0}/{1}"
                  , (new Uri(web.Url)).AbsolutePath
                , properties.Feature.Properties["MasterUrl"].Value);
          web.Update();
        }
      }
      public override void FeatureDeactivating(SPFeatureReceiverProperties properties)
      {
        SPSite site = properties.Feature.Parent as SPSite;
        if (site != null)
        {
        SPWeb web = site.RootWeb;
        web.MasterUrl = web.AllProperties["OldMasterUrl"].ToString();
        web.DeleteProperty("OldMasterUrl");
        web.Update();
        }
      }
    }
Code sample 2: Feature code
In a production environment you will need code that is a bit more defensive than this, but it will suffice for our example. So what does this code do?
SPSite site = properties.Feature.Parent as SPSite;
This line retrieves a reference to the site collection in which we are deploying the master page.
SPWeb web = site.RootWeb;
This creates a reference to the root web site of the site collection.
web.AddProperty('OldMasterUrl',web.masterUrl);
This stores the existing master page URL into the 'bucket' collection for the root web site.
The next line is the line that actually sets the new master page.
    web.MasterUrl = String.Format("{0}/{1}"
        ,(new Uri(web.Url)).AbsolutePath
        , properties.Feature.Properties["MasterUrl"].Value);
The Uri object AbsolutePath property is used to ensure the correct path to the master page is used. The URL relative to the SiteCollection is read from the Feature Properties, a collection of user properties that you can add into the Feature.Template.xml shown in Figure 9:
Figure 9: Feature Properties
This configuration property is then available at runtime and makes your code more generic.  To ensure your changes are saved we must include the following line:
web.update();
In the FeatureDeactivating code, we simply restore the original master page. The ability to rollback is one of the key benefits of using features and solutions, and I recommend that you always properly test rollback code in the FeatureDeactivating method.
With this code in place, just hit Deploy again. This will build and package your solution, deactivate the existing feature, retract the existing solution, deploy your revised solution, activate the solution, and activate your feature. So wait a few seconds and you will see your site with the SimpleTalk brown band across the page beneath the top navigation menu, as shown in Figure 1 above.
Adding in a user control
Let us now enhance our interface by adding in a user control that simply outputs the current date. There is a multitude of ways of doing this, I know, but I'm illustrating a point here. In VS2010, highlight the SimpleTalk project, right-click and select Add -> SharePoint Mapped Folder. In the dialog box, select TEMPLATE/CONTROLTEMPLATES. You will now have a mapped folder and all files in this folder will be deployed into the CONTROLTEMPLATES folder under the SharePoint root folder known colloquially as the 14-Hive, which is normally located at:
C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\14.
Right-click the CONTROLTEMPLATES folder and select Add-> New Item, and then select UserControl. VS2010 will now add in a user control and all the necessary Assembly and Register Directives. In Figure 10 you can see this code as well as the additional line I've typed in:
<asp:Label runat="server" ID="MyDate" ForeColor="White"></asp:Label>
which is the ASP.NET Label control that will hold the current date.
Figure 10: UserControl mark-up
Notice the placeholder $SharePoint.Project.AssemblyFullName$. This will get replaced at packaging time with the full name of the assembly that the project gets built into.
The code-behind file is simple, and gets created in the project when you create the UserControl. Open up the code-behind file and you will see there is already a Page_Load event handler provided for you. Add the following line into the Page_Load event:
    MyDate.Text = DateTime.Today.ToLongDateString();
Your code file should now look as shown in Figure 11.
Figure 11: User control code-behind
This code simply sets the text of the label to today's date.
Finally, we need to amend our master page to include the new control, which we do by adding in an ASP.NET Control Register Directive at the top of the master page as follows:
<%@ Register TagPrefix="st" TagName="DateControl" src="~/_controltemplates/UserControl1.ascx" %>
And further down the page where we added in our brown bar mark-up, we alter the mark-up to add in the control itself as follows:
<div id="s4-mainarea" class="s4-pr s4-widecontentarea">
<div style="height:15px;width:100%;background-color:#cc6633;" class="s4-notdlg">
<st:DateControl runat="server" />

                              </div>
                              <div id="s4-leftpanel" class="s4-notdlg">
                              <div id="s4-leftpanel-content">
However, if we now go ahead and click the Deploy button, we will get an error and for once the error message is pretty self-explanatory and highlights one of the limitations of sandboxed solutions:
Figure 12: Sandbox solution error
Why is this?
As I mentioned in Visual Studio 2010 and SharePoint 2010: Support at Last ), if a solution needs to deploy items to the file system as a sandboxed solution we cannot deploy it as a sandboxed solution. In this case, we choose to revert to a farm based solution. We do this very simply; by selecting our project, and then, in the Project Properties window in VS2010, we change the Sandboxed Solution property to False.
Figure 13: Changing to a farm solution
As an aside, the move to a farm solution may not be possible, such as in some hosted SharePoint scenarios. In these cases, we have to use alternative methods to achieve the functionality we require. In this situation, a simple piece of JavaScript would suffice, but plainly this will not always be the case. We will examine this issue in another article.
Now if we click Deploy everything works fine. You will notice that the Application Pool has been recycled and so the page takes longer to come up the first time. This is a fact of life with farm solutions; the Application Pool always gets recycled. With sandboxed solutions this is not the case.
Once the site comes back up you should see the brown bar and the date as shown in Figure 14.
Figure 14: The final master page
Deploying into production
To complete the deployment to a production system, we take our WSP file, which you can find in bin/Debug, and upload this to the relevant solution gallery on our production server. We then activate the solution in that environment. We can do this using PowerShell, which we'll take a look at in another article soon.

 

 

 

 

 

 

How to Create a Custom Site Definition with Additional Content in SharePoint 2010 Using Visual Studio 2010

Site Definitions give you lots of flexibility in choosing custom layouts, features, elements, modules, etc., that are included when a new site is created in SharePoint. Furthermore, Site Definitions make it easier to maintain and upgrade your SharePoint solutions.
Challenge
How do I create a custom Site Definition, as well as content related to a Site Definition in SharePoint 2010, using the Visual Studio 2010 project template?
Solution
Creating a custom site definition using the Visual Studio project template.
To create a site template, follow these steps:
  • Open Visual Studio 2010, click New on the File menu, and then click Project.
  • In the Templates pane, select the Site Definition project template under SharePoint 2010 templates folder.
  • In the Name box, provide a name for your solution.
  • In the Name box, input DemoSiteDefs and then click OK (See Figure 1).
Figure 1
At this point, the SharePoint Customization Wizard will appear (See Figure 2).
Figure 2
  • You will see a SharePoint Customization Wizard asking for a local site for debugging and deployment. Enter the URL for the SharePoint server site where you want to debug the site definition, or use the default location (http://system name/).
  • Select Deploy as a farm solution for "What is the trust level for this SharePoint solution?"
  • Click Finish. The project appears in Solution Explorer.
  • A new solution will be created as shown in the image below. Note that two .xml files are created (WebTemp_DemoSiteDefs.xml, ONet.xml). As well, Features and Package folders are created. (See Figure 3)
Figure 3
WebTemp_DemoSiteDefs.xml
In WebTemp_DemoSiteDefs.xml, add our custom site definition into the catalog of site definitions so that we can pick the site definition to provision from the Create Site and Workspace application pages.  It is important that the Template Name exactly matches our site definition name. This file name begins with the "webtemp" prefix as required by SharePoint. The general format of WebTemp_DemoSiteDefs.xml is as shown in the following figure.
Figure 4
When this Site Definition is installed, a global WebTemp_DemoSiteDefs.xml is installed in %Program Files%\Common Files\Microsoft Shared\web server extensions\14\TEMPLATE\LCID\XML, where LCID is the numeric ID of language/culture. Ex: 1033 for English.
Onet.xml
Onet.xml is all about Navigation areas, List Definitions, Modules, List Templates, Configurations, BaseTypes, Components, etc. (See Figure 5).
Figure 5
When this Site Definition is installed, a global Onet.xml is installed in %Program Files%\Common Files\Microsoft Shared\web server extensions\14\TEMPLATE\GLOBAL\XML.
For each Site Definition, there is a corresponding Onet.xml installed in a sub-directory (template name) at  %Program Files%\Common Files\Microsoft Shared\web server extensions\14\TEMPLATE\SiteTemplates.
You can see more details about the format of Onet.xml file here: http://msdn.microsoft.com/en-us/library/ms474369.aspx.
Note: Once deployed, a Site definition cannot be modified. You should create a new kind of site. This can be done by creating a new WebTemp*.xml and Onet.xml.
  • Press F5 to run and deploy the project.
  • The solution will be deployed on SharePoint. You'll see a custom site Web page derived from your site definition (See Figure 6).
Figure 6
Open the newly created site, and you'll see a custom site Web page derived from your site definition.
Figure 7
Incorporating a custom master page into the Site Definition.
  • Create a master page. For more information, see ASP.NET Master Pages.
  • Export and then import the custom master page into Visual Studio, as outlined in Walkthrough: Import a Custom Master Page and Content Page with an Image.
  • For this demo, I'm using the master page in http://startermasterpages.codeplex.com/.
  • Add the master page to a module. To do this, right-click the project node in Solution Explorer, point to Add, and then click New Item.
  • Within the Add New Item dialog box, in the list of SharePoint templates, select Module. Give the module a name, input MasterPageModule.
  • In the module, delete the default Sample.txt file.
  • Add a folder to the module named _catalogs, and then another one under it called masterpage.
This matches the file location of other master pages in SharePoint.
  • Add the master page under the masterpage folder. To do this, select the module node and then, on the Project menu, click Add Existing Item. Locate the master page and select it. Master page files have a .master file name extension. I added meetingworkspace.master file. See the following figure:
Figure 8
  • Double-click Elements.xml in the module to open it in the XML Designer.
  • You must update the Elements.xml file to reference the master page.
  • Replace the existing module markup as shown in the following figure.
Figure 9
  • Update the master page reference in default.aspx file
We are going to use our own master page in our Site Definition, therefore we need to change default.master -> custom.master in our default.aspx page. SharePoint will replace the custom.master reference with our master page during runtime page rendering based on the site definition schema (onet.xml).
Figure: 10
When we create a master page module, Visual Studio 2010 generates a new feature called Feature1.feature. We need to change properties and apply the master page feature to our Site Definition. Visual Studio 2010 creates a separate feature for master page instead of depending on the Site Definition so that it can be operated independent of our Site Definition.
Click to Feature1.feature. In the Feature Design mode we can edit title, description, and scope of feature.
Figure: 11
In the Manifest mode, you also see title, ID, scope, and element files of this feature (See Figure 12).
Figure: 12
Next, we need to add this custom master page to the Site Definition.
Update onet.xml file:
Add our  master pages feature (which ID="23d9ad40-56e7-4473-af17-c8c7fbc39b99") under WebFeatures. If our master page feature had been a "Site" scoped feature we would specify it under the SiteFeatures section (See Figure 13).
Update the default configuration and specify that our configuration should use our custom master page by setting the CustomMasterUrl and MasterUrl points to our custom master page (living in the master page gallery). By setting these values, we are effectively telling SharePoint that whenever .aspx refers to custom.master page, replace that with meetingworkspace.master page which is our custom master page (See Figure 13).
Figure: 13
  • Press F5 to run and deploy the project.
  • Create a Site. In the new Site, you can see the custom master page as shown in the following figure.
Figure: 14
Creating custom fields and adding them to the site definition.
Define custom fields that will be used to create a custom list later. These fields provide additional data required by the code in the Site Definition.
To define custom fields:
  • Right-click the Site Definition node in Solution Explorer, point to Add, and then click on New Item.
  • Select Empty Element in the list of templates, and name the element SiteColumns.
  • In the Elements.xml file, I added two custom fields: Region, StandardRate. These fields are used to identify employees' region and their standard rate. You can add more fields if you want. Use the Create GUID tool on the Tools menu to generate a unique GUID for each additional field (See Figure 15).
Figure 15
Important
When adding a custom field, you must specify the ID, Type, Name, DisplayName, and Group attributes for the field in order for it to appear correctly in SharePoint. The statement completion erroneously indicates that you need only the first three of these attributes when, in fact, all five are required.
When we add an Empty Element, Visual Studio auto-generates Feature2 for this instance of Elements, so we need to change the default properties of Feature2. I changed title to Custom Contact Field Feature (scope is Site).
Next step, update onet.xml file:
Add the Custom Contact Field feature under SiteFeatures in onet.xml file (See Figure 16).
Figure 16
Press F5 to run and deploy the project.
At the top of the SharePoint Web page, click the Site Actions button and then click Site Settings. Under the Galleries section of the Site Settings page, click the Site columns link.
In the Site Column Gallery page, scroll the page down to the Custom Contact heading and note the new field item has been added, Region and Standard Rate (See Figure 17).
Figure 17
Creating a content type that includes the custom fields.
To add a content type
  • Right-click the site definition node in Solution Explorer, point to Add, and then click on New Item.
  • Select Content Type in the list of templates and name the new content type, input ContactContentType name.
  • On the Choose Content Type Settings page, select Contact in the list for the base contact type.
  • Click Finish. You should see the content type appear in Solution Explorer
  • In the Elements.xml file for the content type, add the two custom columns that were created above (See Figure 18)
Figure 18
Note: When I added the Contact content type, by default, Visual Studio added it to the Custom Contact Field feature (it will be deployed to Site scope). You can create a new feature for this content type if you wish.
Press F5 to run and deploy the project.
  • At the top of the SharePoint Web page, click the Site Actions button and then click Site Settings.
  • Under the Galleries section of the Site Settings page, click the Site Content Types link.
  • In the Site Content Types Gallery page, note the new content type we just created, DemoSiteDefs - ContactContentType. Click it to view its fields. In the list of fields for DemoSiteDefs - ContactContentType, note the field Region and Standard Rate has been added (See Figure 19).
Figure 19

Creating a list definition based on the content type and adding it to the site definition.
Creating a list definition and list instance that will use the new content type and field.
To create a list definition and list instance
  • Right-click the Site Definition node in Solution Explorer, point to Add, and then click on New Item.
  • Select List Definition in the list of templates and name the new list definition. I entered ContactListDefinition.
  • On the Choose List Definition Settings page, leave the default value, DemoSiteDefs - ContactListDefinition.
  • For What is the type of list definition? list, use Contact list.
  • Select the Add a list instance for this list definition box to add a list instance project item to the project. The list instance will be an instance of the new list definition.
  • Click Finish. You should see the list definition with list instance appear in Solution Explorer (See Figure 20).
Figure 20
To add a field to the list definition
  • Double-click Schema.xml under ContactListDefinition to view it.
  • Under the <ContentTypes> element, reference the ContactContentType that was created above (See Figure 21).
Figure 21
  • Under the <Fields> element, custom fields were added by the content type.
Figure 22
  • Add custom fields to view (See Figure 23).
Figure 23
  • Now, I want to deploy this list definition to scope Web, so I must create a feature for it.
  • To create a feature, right-click the Feature folder, click to Add Feature and then for the name of the feature, input ContactListDefinitionFeature.(See Figure 24)
  • In the Feture Design mode, I selected two items in the Items in the Solution box for this feature, ListInstance1 and ContactListDefinition (See Figure 24).
  • Change title of feature to Contact List Definition Feature (See Figure 24).
  • Change scope of feature to Web (See Figure 24).
Figure 24
  • Next step, update onet.xml file.  Add the Contact List Definition feature under WebFeatures in the onet.xml file (See Figure 25).
Figure 25
  • Press F5 to run and deploy the project.
  • Under the Lists section in the SharePoint QuickLaunch bar, click the DemoSiteDefs - ContactListDefinition link.
  • This is the list instance for the new list definition. Note that the new field Region and StandardRate must appear as a column in the list instance.
Figure 26
Adding default list data to a list instance
To provide an instance of the new list definition and some default employee information to the DemoSiteDefs - ContactListDefinition list after the site definition is deployed.
  • Double-click the Elements.xml file of ListInstance1 to open it.
  • I added two custom rows of data as shown in the following figure.
Figure 27
  • Press F5 to run and deploy the project.
  • Click on the DemoSiteDefs - ContactListDefinition link. You can see that the data has been added to the list instance as shown in the following figure.
Figure 28
Creating a visual Web Part and adding to the Site Definition.
We will create a visual Web Part to display on the Site Definition's main page.
To create a visual Web Part
  • Right-click the site definition node in Solution Explorer, point to Add, and then click on New Item.
  • Select Visual Web Part in the list of templates and provide a name. I entered the name as DemoVisualWebPart.
  • This opens the file DemoVisualWebPartUserControl.ascx. At the bottom of DemoVisualWebPartUserControl.ascx, add the following controls to the form: a label and a calendar (See Figure 29).
Figure 29
  • You can write the code behind this under file DemoVisualWebPartUserControl.ascx.cs.
Next step, add the visual Web Part to the Site Definition's default ASPX page.
  • Open the default.aspx page and add the following under the WebPartPages tag:
Figure 30
This line associates the name DemoVisualWebPart with the Web Part and its code. The Namespace parameter is the same as the namespace used in the DemoVisualWebPartUsercontrol.ascx code file.
  • We need to create a WebPartZone and add WebPart to WebPartZone.
Figure 31
  • Press F5 to run and deploy the project.
  • Create a Site. In the new Site, you can see the DemoVisualWebPart appear in the Site as shown in the following figure.
Figure 32
Our final solution structure should now look like the following figure.
Figure 33
All done! Our solution is now ready for packaging into a .wsp solution file and deployment into the SharePoint farm.

 

 

 

 

 

 

 

 

Creating SharePoint 2010 Workflows: Starting with Visual Studio 2010

The Scenario: Submitting an Expense Report

The workflow that we are going to create is an application that allows users to submit expense reports. As soon as an expense report is submitted, a workflow will be activated and will
  • generate a globally unique identifier (GUID) for the expense report
  • determine whether the report must be submitted for approval (for amounts less than $1,000, the expense report is automatically approved and the process is completed with a status of "autoapproved")
  • find the user's manager
  • create tasks for the manager to approve or reject the expense report
  • update the expense report status to "approved," "rejected," or "autoapproved"
Before starting this tutorial, you need to create a site (based on the template that you can download from the  hotlink at the beginning of this article) that has the following lists:
  • Expense Reports, with columns such as those in Figure 1
  • Managers, with columns such as those in Figure 2


Figure 1: Expense Reports list structure


Figure 2: Managers list structure 
Fill the Managers list with the accounts that Figure 3 shows (I've used accounts that Microsoft provides in its VM, but you can use your own accounts.) Make sure that the users in this list are at least contributors in the site (a setting that is not provided in the site template).


Figure 3: List of managers and their direct reports 

Creating the Workflow

Before creating the workflow, make sure that VS 2010 and SharePoint 2010 are running on the same computer. Start VS 2010 and create a new SharePoint 2010 project that is based on the Empty SharePoint Project template, as Figure 4 shows. Name the project Litware.ExpenseReport.


Figure 4: Creating a SharePoint project in VS 2010 
In the SharePoint Customization Wizard, when prompted to provide your web site URL for debugging, enter the URL and select the Deploy as a farm solution option, as Figure 5 shows. Workflows that are generated with VS cannot run in the sandbox.


Figure 5: Deploying the VS project 
Add a new SharePoint item, based on the Sequential Workflow template, to your project, as Figure 6 shows. Name the item ExpenseReportWorkflow.


Figure 6: Adding a sequential workflow project item 
Because workflows communicate with users by assigning tasks (I'll provide more details about this topic in another article), we usually need a task list (although it isn't mandatory). For this tutorial, the site template creates the task list. If you don't provide any task list, the SharePoint Customization Wizard generates an error message that begins "The SharePoint Site at xxxxx is missing a target, task, or history list..." (as Figure 7 shows). Don't worry too much about this for the moment, but keep it in mind.


Figure 7: Missing-list error message 
In the next window, you need to specify whether you want your workflow to be associated with a SharePoint list item. If so, select the List Workflow option; if not, select the Site Workflow option, which is new in SharePoint 2010.
Because our expense report will be stored in the Expense Reports SharePoint list, select List Workflow, as Figure 8 shows. Click Next.
In the next window, select the list that you want your workflow to be associated with: in our case, Expense Reports, as Figure 9 shows. (Note that the Workflow History list is a hidden list that contains key information about each workflow event, including date, status, participant, and description. The wizard creates this list for you. By default, the workflow history is visible for only 60 days after a workflow completes or is cancelled. I'll provide more information about the Workflow Auto Cleanup job in a future article.)
Click Next.


Figure 8: Choosing list or site workflows


Figure 9: Choosing lists for debugging 

The next window allows you to specify how you want the workflow to start.
When you associate a workflow to a list (which you can do manually, as I will illustrate later, or by using the SharePoint Customization Wizard), you can specify whether you want the workflow to start manually (i.e., the user will manually start the workflow) or automatically when a new list item is created or when an existing item is changed. (You can change these parameters later if you want.)
Let's keep the options that Figure 10 shows. Click Finish.


Figure 10: Selecting workflow starting options 
The workflow now shows up in the Workflow Designer, which Figure 11 shows. The first activity (or step) of a VS SharePoint workflow must be an onWorkflowActivated activity.


Figure 11: First workflow in the Workflow Designer 
Open the Solution Explorer, which Figure 12 shows. You will see that a new SharePoint project item (of type Workflow) has been generated. The associated .NET code can be found in the ExpenseReportWorkflow.cs file, which is also a .NET class; we usually call this class a workflow template.


Figure 12: Solution Explorer showing workflow generated code 

Building and Deploying

Go to the Build menu and select Deploy Solution. This generated code is called a workflow template; several instances of the same workflow template can be associated to the same list or to a different list in the site collection.
Go to your site, click the Expense Reports list, go to the list settings, and click the Workflow Settings button on the SharePoint Ribbon, as Figure 13 shows.


Figure 13: Workflow button  
The Workflow Settings window appears. This window shows a list of available workflow templates. Our workflow template is available because it is encapsulated in a SharePoint feature with a scope of Site (a site collection); more about this later.
In this window, you can associate your workflow template with the current list.
We already have one association (performed by VS 2010), named Litware, as Figure 14 shows.ExpenseReports-ExpenseReportWorkflow, but you can create other workflow associations by clicking the Add a workflow hyperlink. (You can display the list of available workflow templates by clicking the drop-down arrow.)
Click the Litware.ExpenseReports-ExpenseReportWorkflow association link to view the workflow association settings, which Figure 15 shows. Note that the option is selected to start the workflow when a new item is created. Click OK.


Figure 14: Workflow association


Figure 15: Workflow association settings 
Go to the Expense Report list and add a new item, as Figure 16 shows. Save this item. Because the workflow is configured to start when a new item is created, saving the item will cause a workflow instance to be created from our workflow template.


Figure 16: Adding a new list item 
Indeed, if you go back to the list view, which Figure 17 shows, you will notice a new column that has the workflow association as a name. If you click the Completed hyperlink, you will visualize the workflow status, history, and tasks in the Workflow Information window, which Figure 18 shows.


Figure 17: Workflow Association column


Figure 18: Workflow Information window

Using Workflow Activities

A workflow is a set of steps; each step is an activity. Activities are .NET classes. We can reuse existing activities or create custom activities, as I will illustrate later.
The Workflow Foundation (WF) infrastructure is a set of assemblies that can be visualized in the References folder of our VS 2010 project (see Figure 19).
As part of the .NET Framework 3.5, WF provides several interesting activities that can be used in SharePoint. (Not all WF activities can be used in SharePoint, however.)
These activities are provided in the System.Workflow.Activities assembly, as Figure 19 shows. For more information about WF see the sidebar "For Workflow Foundation Aficionados."


Figure 19: Workflow assemblies to reference 
The SharePoint team also provided more specific SharePoint activities, which you can find in the Microsoft.SharePoint.WorkflowActions assembly. This assembly can be found in the 14\ISAPI folder and is referenced by default in our VS 2010 project.
These activities can be dragged and dropped into the VS workflow design surface from the toolbox (select the SharePoint Workflow panel), which Figure 20 shows.


Figure 20: Workflow activities toolboxes 
Just to make sure that our basic workflow can at least say "Hello World," we will drag and drop LogToHistoryListActivity to the workflow surface. Figure 21 shows the addition of an activity.
Now, in Workflow Designer, select logToHistoryActivity, go to its property page, and type "Hello World" in the HistoryOutcome property, as Figure 22 shows. Deploy the solution as you did previously (selecting Deploy Solution from the Build menu).


Figure 21: Adding an activity


Figure 22: LogToHistoryList activity properties 
Go to the Expense Reports list. Select the expense report that you created earlier, and then click the Workflows button on the SharePoint Ribbon, as Figure 23 shows. The Start a New Workflow window, which Figure 24 shows, appears.
Click the Workflow button to start our workflow. Go to the workflow status, and you should see the Hello World message, as Figure 25 shows.


Figure 23: Choosing a workflow in the SharePoint Ribbon


Figure 24: Starting a workflow


Figure 25: Workflow outcome with Hello World 

Workflow Features

Workflows that are generated from VS 2010 are logically packaged as site collection features. If the feature is not activated, then the workflow template cannot be used.
Workflows that are generated by VS 2010 are compiled as .dll files that must be installed into the global assembly cache (GAC). Therefore, these kinds of workflows cannot run in the sandbox environment, even if we create custom sandbox activities (as I will illustrate in another article).
If you look at the elements.xml file that describes the workflow feature (Figure 26), you will find the <Workflow> element, which points to the workflow class Name, as well as the placeholder for the assembly name.
New in SharePoint 2010 is the <AssociationCategories> element, which can contain List (if the workflow must be associated with a SharePoint list), Site (if the workflow must be associated with a SharePoint site), or Content Type (if the workflow is associated with a content type, which is an excellent practice).
The <StatusPageUrl> element specifies the .aspx page that is used to display the workflow status. I usually keep the default _layouts/WrkStat.aspx, but you can replace it with a custom page if needed.


Figure 26: Workflow element.xml file 

Wizard Setting Configuration

If you want to modify the settings that the VS 2010 SharePoint Configuration Wizard provides, then you can select the workflow SharePoint project item, display its property page (which Figure 27 shows), and change the settings. For instance, you can change the Task List, or you can cancel the automatic association of the workflow with the list (via the Auto Associate property).
If you try to modify the task list, a new SharePoint Customization Wizard window will appear, as Figure 28 shows.


Figure 27: Workflow settings provided by the wizard


Figure 28: Triggering the wizard 

Reviewing the Code

If you open the file ExpenseReportWorkflow.cs, you will see a class that is derived from SequentialWorkflowActivity (see Figure 29), which is the root class for Sequential workflows. (There are two kinds of workflows: Sequential and State Machine, which I will illustrate in another article.)
If you open the Designer code, you will see that each activity is a member of this class, which Figure 30 shows.


Figure 29: Deriving a class from SequentialWorkflowActivity


Figure 30: Activities as class members  

 

 

 

 

Create a Workflow using Visual Studio 2010

Types of Workflows

There are basically two types of workflows inside Visual Studio:
  • Sequential Workflow
  • State Machine Workflow
Sequential Workflow once invoked continues execution until it is completed.
State Machine Workflow will have states persisted in between. The state could be continued execution between machine restarts.
In this example we are trying to create a Workflow which on activation updates the null Address column of the Manager list. (You need to have a Contact template named Manager.)
Step 1: Create Sequential Workflow Project
For the time being, we can start with a Sequential Workflow. Start Visual Studio and create a new project from the template SharePoint > Sequential Workflow.

In the next screen select the option Site Workflow as shown below:

In the next screen, leave the default option saying the user manually starts the Workflow. Click the Finish button to create the project.

You will get the following screen once the project is created.

Step 2: Create Activity
We need to create an Activity to perform our job.

What is an Activity?

A Workflow consists of a series of Activities. We can add Activities using the Toolbox. There are different types of Activities like Code Activity, SendEmail, etc. For our example we are using the more functional Code Activity.

Drag and drop a Code Activity from the toolbox. You can locate this from the v3.0 group inside Toolbox.

Step 3: Add code for the Activity
Now we need to add code for this Activity. Double click on the codeActivity1 item shown above. Place the following code in the appearing code view.
private void codeActivity1_ExecuteCode(object sender, EventArgs e)
{
    using (SPWeb web = SPContext.Current.Web)
    {
        SPList list = web.Lists["Manager"];
        foreach (SPListItem item in list.Items)
        {
            if (item["Address"] == null)
            {
                item["Address"] = "PLEASE SET THE ADDRESS!";
 
                item.Update();
            }
        }
    }
}
Step 4: Build and Deploy the Solution
Now we are ready to build and deploy the solution. Right click on the solution and use the Build and Deploy  command.  

Step 5: Execute the Workflow inside SharePoint
Now we are ready to test the Workflow inside SharePoint. As the Workflow was created as a Site Workflow it will be accessible for all the Lists and Libraries. You can click the Lists link inside the site.

Now click on the Site Workflows link. You will get the following screen.

Before executing the Workflow, you need to create a Manager item with Address not assigned.
Click on the highlighted button and your workflow gets executed. Wait for a while and you can see the invalid manager record is updated with the message.

 

 

 

 

 

 

 

 

 

 

Sequential Workflow in SharePoint 2010 Using Visual Studio 2010

Introduction

In this article we will see how to create a sequential workflow in SharePoint 2010 using VS 2010.

Objective

Let's make the scenario simple. We want to create a simple workflow and if the workflow status is not completed, we need to prevent the user from deleting the document.

Steps

First we need to create a "Status" column with a choice field type with various status options in our document library.
Once the "Status" column was created, the document library will be as shown below:
Open the VS2010 -> Select SharePoint 2010 -> Select the Sequential workflow project type and complete the wizard as shown below.
By default we have the following simple start page:
Just click the OnWorkFlowActivated step and create an event called OnWorkFlowActivated_Invoked:
Double-click the onWorkflowActivated step. It will redirect to the code behind file.
Drag a while loop step from the Tool Box, below the onWorkflowActivated step:
Select the while loop step and in the property window configure the "Condition" as "Code Condition" and create an event called "IsWorkFlowPending".
Place the following in the workflow:
Invoke the "IsWorkFlowPending" method in both the "onWorkflowActivated_Invoked" and the "onWorkflowItemChanged1_Invoked" methods.
Let's deploy the solution and we will check whether or not the workflow is deployed in our document library.
Upload a document and start the workflow:
We will see the workflow status as "InProgress" in the document library.
Edit the task and change the status to Approved. Our workflow status will change to "Completed".
We can prevent the user from "Deleting" the document, if the "Status" is not completed. Just add an Event Receiver in the same workflow project.
In the code behind file, we will prevent the user from deleting a document if the status is "Pending".
Let's check the code in the UI using a document which is in the InProgress Status and try to delete the document.
If we click ok the document is still in our repository.
Let's make some changes in the code to display a user friendly message:
Now when we try to delete the document we will see the following message.

 

How to create a simple approval workflow in SharePoint Designer

·         Synopsis

This guide will show you how to create a simple approval workflow in SharePoint Designer.

·         Applicable to

All PlexHosted SharePoint 2010 accounts.

·         Prerequisite

    • a PlexHosted SharePoint 2010 account
    • a PlexHosted SharePoint 2010 site
    • Microsoft SharePoint Designer program
Introduction: SharePoint Designer is a perfect tool to customize your sites and create the necessary workflows to make the working process more simple and efficient. It contains several workflow templates using which creating the approval one is easy and quick. But if you need to create your own, you may do this using the steps of this guide.

·         How to

  1. Open the Microsoft SharePoint Designer.
  2. Click on File tab and Open your SharePoint site.
  1. Go to your Task list (or to the list you need to run an approval workflow) and check the box Require content approval for submitted items.
  1. Return to the File tab and click New Item, choose List workflow. Specify the name and the list for your new approval workflow.
  1. Click on to the Workflow settings button and check the necessary boxes in Start Options section. You can set the workflow to be manually started or automatically.
  1. Return to editing your approval workflow. You will see Step 1, click on Action and choose Set Workflow variable.
  1. Click on workflow variable hyperlink and choose create new variable. Type the name of this variable; choose its type from the drop-down menu.
  1. Then click on value and define the workflow look up (for example Task type).
  1. Add the Condition to this action. (If any value equals value for our example)
  1. Define the value of the first hyperlink. For this choose the "Data Source" and "Field from source" from the drop-down menus and click OK (Current Item and Data for the example).
  1. Define the value of the second hyperlink and click OK (This in the example - the Data source, Field and Data).
  1. Add required action to this condition. (We`ve added Send an Email. If you `ve chosen it – you need to define the message and receivers for this approval email.)
  1. Then add Set Content Approval Status action to this current condition. Define the approval status clicking on the status hyperlink and add some comments. The last one is optional.
  1. Push the Check for Errors button and if there are no mistakes, you may Save and then Publish your approval workflow.

 

SharePoint 2010 - Use custom ItemStyle settings in Content Query Web Part.

Custom Item Style for a Content Query Web Part. But, still I will try and explain a small process in a simplified way.

Goal

The main goal is to use a Custom List name "Sample" and use a Content Query Web Part to show it with custom design style.

Process

  1. Create a custom list with name "Sample". The should just have 3 fields.
    1. Title - This is the main text to be shown for the picture.
    2. Picture - This is the hyperlink column for the picture of the item.
    3. Skills - This is a simple multiple line comment for the item.
  1. Go to any page. Add a web part. Drop a Content Query Web Part(CQWP) on the page from "Content Rollup".
  2. Click "Open tool pane".
  3. Content Query Tool Part > Query > Source > Show items from the following list: > Select "SAMPLE"
  4. Content Query Tool Part > Query > Presentation > Please see the picture as a default setting. I am going to leave it as it is.
  1. Click "Save" and the view of the web part will be a default text one which is going to look like picture below.
  1. On Clicking the picture it goes to the display record screen.

But now moving back to our goal. We need to show the data in a custom design layout. So follow the below given steps.
  1. Open a SharePoint 2010 designer.
  2. All Files > Style Library > XSL Style Sheets > ItemStyle.xsl(Edit it in advance mode)
  3. Find this element, copy it and paste it at the bottom of the XSL.
<xsl:template name="Default" match="*" mode="itemstyle">...</xsl:template>
  1. Change the name and match to Sample.
<xsl:template name="Sample" match="Row[@Style='Sample']" mode="itemstyle">...</xsl:template>
  1. Also if you edit the web part you can now see the item in the ItemStyle list. Make changes to map the correct fields too.

  1. Make the changes to the xsl(As you want the view of the list) or can copy the whole block and paste it at the bottom of the ItemStyle.xsl.
7.      <xsl:template name="Sample" match="Row[@Style='Sample']" mode="itemstyle">
8.              <xsl:variable name="SafeLinkUrl">
9.                  <xsl:call-template name="OuterTemplate.GetSafeLink">
10.                  <xsl:with-param name="UrlColumnName" select="'LinkUrl'"/>
11.              </xsl:call-template>
12.          </xsl:variable>
13.          <xsl:variable name="SafeImageUrl">
14.              <xsl:call-template name="OuterTemplate.GetSafeStaticUrl">
15.                  <xsl:with-param name="UrlColumnName" select="'ImageUrl'"/>
16.              </xsl:call-template>
17.          </xsl:variable>
18.          <xsl:variable name="DisplayTitle">
19.              <xsl:call-template name="OuterTemplate.GetTitle">
20.                  <xsl:with-param name="Title" select="@Title"/>
21.                  <xsl:with-param name="UrlColumnName" select="'LinkUrl'"/>
22.              </xsl:call-template>
23.          </xsl:variable>
24.          <table cellpadding="0" cellspacing="5" border="0" style="border:1px Solid #efefef;width:400px;">
25.              <tr>
26.                  <td style="width:100px" align="center">
27.                      <a href="{$SafeLinkUrl}" title="{@LinkToolTip}">
28.                          <img class="image" src="{$SafeImageUrl}" title="{@ImageUrlAltText}" />
29.                      </a>
30.                  </td>
31.                  <td valign="top" align="left"><a href="{$SafeLinkUrl}" title="{@LinkToolTip}">
32.                    <xsl:if test="$ItemsHaveStreams = 'True'">
33.                      <xsl:attribute name="onclick">
34.                        <xsl:value-of select="@OnClickForWebRendering"/>
35.                      </xsl:attribute>
36.                    </xsl:if>
37.                    <xsl:if test="$ItemsHaveStreams != 'True' and @OpenInNewWindow = 'True'">
38.                      <xsl:attribute name="onclick">
39.                        <xsl:value-of disable-output-escaping="yes" select="$OnClickTargetAttribute"/>
40.                      </xsl:attribute>
41.                    </xsl:if>
42.                    <xsl:value-of select="$DisplayTitle"/>
43.                  </a><br /><xsl:value-of select="@Description" disable-output-escaping="yes" /></td>
44.              </tr>
45.          </table> 
46.      </xsl:template>
  1. Once you are done with that you can see the below given view on the screen.
  1. Thats it.

 

 

 

 

 

 

 

 

 

 

 

SharePoint 2010 - Create List Definition and Instance

Introduction

In this article we can see how to create a List Definition using:
  • SharePoint user interface
  • Visual Studio 2010

Why we need List Definitions?

We need to have List Definitions for creating multiple list instances from it. This is the best way if we are dealing with data capture of same column types.
The built-in list definitions of SharePoint serve the same purpose. Example: Contact List, Task List, etc. Similarly depending on your project domain, it might be a good idea to turn common list formats into list definitions so that you can create multiple instances easily.
For example: a Computer Configuration list definition could be created for later creation of actual lists like Desktops and Laptops.

Scenario

In this example we are trying to capture a Computer Configuration list definition. Following is the field information it should contain:
Field
Description
Manufacturer
Text Field
Model
Text Field
CPU Make
Choice Field with values of Intel, AMD, Other
CPU Speed
Number Field with Speed in GHz
RAM Size
Number Field with Size in GB
Price
Number Field representing Price
Description
More information on the otherperipherals

Solution 1: Creating List Definition using SharePoint user interface

Step 1: Create a new List
Open a SharePoint site and create a new list named Desktops. You can start with a Custom list.
Following are the list columns after creation:

Following is the List in Default View:

Step 2: Template the List
Now we can proceed with creating a List Definition using the List Template feature of SharePoint. Go to List Settings and click on Save list as template link.

In the appearing dialog, enter the name for the template, for example: Computer Configuration Template.

You can leave the checkbox Include Content as unchecked. Click the OK button after entering the details. You will get the following message.

Step 3: Visit the Gallery
The newly created template is stored inside the gallery. Clicking the link from the above screen, you can view it.

You can also access the list template gallery from: Site Actions > Site Settings > Galleries.

Step 4: Create a new List from Template
Now we are ready to test the above template. Try creating a new List (Lists > Create) and in the selection dialog, you can see the new template as shown below:

Now you can create multiple list instances from this template. You can also upload this template to another SharePoint site for creating list instances using it.

Solution 2: Creating a List Definition using Visual Studio 2010

For proceeding with this part you need the SharePoint Developer Tools for Visual Studio 2010.  I hope you already have this installed; else you can download it from here.
Step 1: Create the Project
Open Visual Studio and create a new project from the List Definition template.

In the next page, select the farm solution option.

In the next page, enter the details as shown below and click the Finish button.

Please note that you need to derive it from Custom List as we are going to create custom columns for the List Definition.
Now inside the Solution Explorer, you can rename the List Definition name as ComputerConfiguration.

About the XML files

As you can see, there are two XML files for the List Definition:
  • Elements.xml
  • Schema.xml
The Elements.xml contains general information about the List Definition like the Name, Description, Quick Launch, etc. Schema.xml, as the name implies, contains the actual metadata information about the List Definition.
Following is the XML content of Elements.xml.
<?xml version="1.0" encoding="utf-8"?>
<Elements xmlns="http://schemas.microsoft.com/sharepoint/">
    <!-- Do not change the value of the Name attribute below. If it does not 
         match the folder name of the List Definition project item, 
         an error will occur when the project is run. -->
    <ListTemplate
        Name="ComputerConfiguration"
        Type="10000"
        BaseType="0"
        OnQuickLaunch="TRUE"
        SecurityBits="11"
        Sequence="410"
        DisplayName="Computer Configuration"
        Description="Computer Configuration"
        Image="/_layouts/images/itgen.png"/>
</Elements>
You can modify the above List Definition to change the Display Name and Description.
Step 2: Create the Fields for List Definition
The field information for the List is already mentioned in the beginning of the article. Please have a look at it before we proceed.

Field and FieldRef

For adding a List Definition we have to use the following tags:
  • Field
  • FieldRef
The Field tag is used to represent new field information like the Name, Display Name, ID, Type etc. The FieldRef tag is used to refer to an existing field using the Name.
Open Schema.xml and add the following fields.
Collapse | Copy Code
<Fields>
  <Field ID="{24B3F6C1-B75B-4821-A466-C1E979B87B81}" Name="Manufacturer" DisplayName="Manufacturer" Type="Text" Required="TRUE"/>
  <Field ID="{24B3F6C1-B75B-4821-A466-C1E979B87B82}" Name="Model" DisplayName="Model" Type="Text" Required="TRUE"/>
  <Field ID="{24B3F6C1-B75B-4821-A466-C1E979B87B83}" Name="CPUMake" DisplayName="CPU Make" Type="Choice" Required="TRUE">
    <CHOICES>
      <CHOICE>Intel</CHOICE>
      <CHOICE>AMD</CHOICE>
      <CHOICE>Other</CHOICE>
    </CHOICES>
  </Field>
  <Field ID="{24B3F6C1-B75B-4821-A466-C1E979B87B84}" Name="CPUSpeed" DisplayName="CPU Speed (GHz)" Type="Number"/>
  <Field ID="{24B3F6C1-B75B-4821-A466-C1E979B87B85}" Name="RAMSize" DisplayName="RAM Size (GB)" Type="Number"/>
  <Field ID="{24B3F6C1-B75B-4821-A466-C1E979B87B86}" Name="Price" DisplayName="Price" Type="Number"/>
  <Field ID="{24B3F6C1-B75B-4821-A466-C1E979B87B87}" Name="Description" DisplayName="Description" Type="Number"/>
</Fields>
Note: You can refer to the attached source code with this article.
The Choice field type is used to create a drop down list in the runtime. More field types can be found in the References link.
Step 3: Try a Test Deployment
Now you can build the project and if it succeeds, try deploying it. Once deployed, try opening the SharePoint site and create a new list. In the templates dialog you can see our Computer Configuration item.

You can try creating a test instance from it. You will notice the following:
  • In the items view there is only one column
  • In the new item dialog there is only one column

Where are the Fields we added?

So now I have to answer that till now we have created only Fields. We need to add the Field Reference in the appropriate sections to see the required columns.
Please note that there could be 50 fields in a list and we can just show only the required five fields in the view. We can make other calculated / auto assigned fields hidden in the new/edit dialogs as well.
Step 4: Add Fields to the View
Now we can add the required fields to the View of the list instance.
  • Manufacturer
  • Model
  • CPU Make
  • Price
To achieve this, we need to use the FieldRef tag as shown below.
Collapse | Copy Code
<View BaseViewID="1" Type="HTML" WebPartZoneID="Main" 
    DisplayName="$Resources:core,objectiv_schema_mwsidcamlidC24;" 
    DefaultView="TRUE" MobileView="TRUE" MobileDefaultView="TRUE" 
    SetupPath="pages\viewpage.aspx" 
    ImageUrl="/_layouts/images/generic.png" Url="AllItems.aspx">
<Toolbar Type="Standard" />
<XslLink Default="TRUE">main.xsl</XslLink>
<RowLimit Paged="TRUE">30</RowLimit>
<ViewFields>
  <FieldRef Name="Model"></FieldRef>
  <FieldRef Name="CPUMake"></FieldRef>
  <FieldRef Name="Price"></FieldRef>
</ViewFields>
Please add the bolded section inside the View with BaseViewID as 1.
Now build the project and deploy it. Go to the SharePoint site and refresh the list which we have created. You can see that the above three fields are displayed.

 

Creating List Programatically in SharePoint 2010 using Visual Studio 2010

Today we will discuss about creating List programmatically in SharePoint 2010 using Visual studio 2010.
If we are using only one instance of list we will follow this approach for creating list.
open the visual studio 2010.
File-->New-->Project
Select C#-->SharePoint-->2010
Select Empty SharePoint Project




Deploy as a Form solution.
Click on Finish



Project Solution structure is below for Empty SharePoint Project.



Select the project and click on F4 for the properties.
Check for the Sandbox Solution property it is set to false now as we select the Trust level for SharePoint solution as From Solution.
From here if you change that to Sandbox solution by setting property
Sandbox Solution=”True”
You can edit the site URL which you want to deploy using site URL property.





Right Click on Feature node and click on AddFeature.



It will add Feature1 to the Features node in the project.
Change the Title according to your requirement .Here it is Devendra Employee List feature.
I want this List available at site collection level to achieve this we need to change the
Scope From Web to Site.



Now I am using Scope as web level only.



We will create a list using object model because we are going to use only one instance of this list so there is no point of creating list definition.
To do that I will add a feature receiver.
Add Event Receiver to the Feature1 node in the project.



Go ahead and add . Then uncomment the FeatureActivated event .
We will write a code here which will add the Employee List whenever we activated this feature.


using System;
using System.Runtime.InteropServices;
using System.Security.Permissions;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Security;
 
namespace Devendra_Feature_Event_Receivers.Features.AddList
{
 /// 
 /// This class handles events raised during feature activation, deactivation, installation, uninstallation, and upgrade.
 /// 
 /// 
 /// The GUID attached to this class may be used during packaging and should not be modified.
 /// 
 
 [Guid("5bf5f6c5-c371-419a-984b-f0ecf9ddeda0")]
 public class Feature1EventReceiver : SPFeatureReceiver
 {
     // Uncomment the method below to handle the event raised after a feature has been activated.
     public override void FeatureActivated(SPFeatureReceiverProperties properties)
     {
         try
         {
             //get the current web object.
             SPWeb web = properties.Feature.Parent as SPWeb;
 
          
             SPList list = web.EnsureList("Employee", "This list contains Employee details.", SPListTemplateType.GenericList);
 
         
             if (list != null)
             {
              
                 SPField field = list.EnsureField("Title", "", SPFieldType.Text, true);
                 field.Title = "FirstName";
                 field.Update();
 
              
                 SPField fld = null;
             
                 fld = list.EnsureField("LastName", "Employee LastName", SPFieldType.Text, true);
 
              
                 if (fld != null)
                 {
                     SPView view = list.Views[0];
                     view.ViewFields.Add(fld);
                     view.Update();
                     fld = null;
                 }
              
                 SPListItemCollection listItems = list.Items;
                 AddItems(listItems, "Devendra", "Velegandla");
             }
             else
             {
 
             }
         }
         catch (Exception ex)
         {
             throw ex;
         }
     }
     public static void AddItems(SPListItemCollection listItems, string FirstName, string LastName)
     {
         SPListItem item = null;
         item = listItems.Add();
         item["FirstName"] = FirstName;
         item["LastName"] = LastName;
         item.Update();
     }
 
     public override void FeatureDeactivating(SPFeatureReceiverProperties properties)
     {
     
         SPWeb web = properties.Feature.Parent as SPWeb;
   
         web.DeleteList("Employee");
     }
 
 
 
 }
 
}


add one more class called utilities.cs of type static.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.SharePoint;
namespace Devendra_Feature_Event_Receivers.Features.AddList
{
 public static class Utilities
 {
 
     public static SPList EnsureList(this SPWeb web, string listTitle, string desc, SPListTemplateType lstTemplateType)
     {
     
         SPListCollection lstCollection = web.Lists;
 
    
         SPList lstObj = (from SPList lst in lstCollection
                          where string.Equals(lst.Title, listTitle, StringComparison.InvariantCultureIgnoreCase) == true
                          select lst).FirstOrDefault();
 
     
         if (lstObj != null)
         {
             return lstObj;
         }
     
         Guid lstGuid = web.Lists.Add(listTitle, desc, lstTemplateType);
         try
         {
             SPList newList = web.Lists.GetList(lstGuid, true);
             newList.OnQuickLaunch = true;
             newList.Update();
             return newList;
         }
         catch
         {
             return null;
         }
     }
 
     public static SPField EnsureField(this SPList list, string fldDisplayName, string fldDesc, SPFieldType fldType, bool isMadatory)
     {
     
         SPFieldCollection fieldCollection = list.Fields;
 
     
         SPField spField = (from SPField field in fieldCollection
                            where string.Equals(field.Title, fldDisplayName, StringComparison.InvariantCultureIgnoreCase) == true
                            select field).FirstOrDefault();
 
     
         if (spField != null)
         {
             return spField;
         }
      
         try
         {
             list.Fields.Add(fldDisplayName, fldType, isMadatory);
             SPField spfield = list.Fields.GetField(fldDisplayName);
             spfield.Description = fldDesc;
             spfield.Update();
             return spfield;
         }
         catch
         {
             return null;
         }
     }
 
     public static bool DeleteList(this SPWeb web, string listTitle)
     {
      
         SPListCollection lstCollection = web.Lists;
 
      
         SPList lstObj = (from SPList lst in lstCollection
                          where
                              string.Equals(lst.Title, listTitle, StringComparison.InvariantCultureIgnoreCase) == true
                          select lst).FirstOrDefault();
 
      
         if (lstObj != null)
         {
             try
             {
                 lstObj.Delete();
                 return true;
             }
             catch (Exception ex)
             {
             }
         }
         return false;
     }
 }
}




Add Item to the list data to the Employee List.
Once we deactivate this feature the list will get deleted.
Add one more class call utilities.



Once you click on the package .go to Bin folder of the project get the WSP file.



Add the solution using stsadm command.
Click on run: type CMD
Execute below command
Stsadm –o addsolution –filename c:\Devendra_Feature_Event_Receiver.wsp.

Open Central Admin to deploy the solution.
Got o system settings -> Manage Form solutions



Deploy the solution.
You can see the below screen solution deployed globally.



Open the site URL which we deployed the solution.
Click on SiteActions-->Site settings
Under Site Actions click on Manage Site Features.




Activate the feature Devendra Employee List Feature.



After activation we can see the Employee list and data inserted into the list.



Once you deactivate the feature list will get deleted.

 

 

 

 

 

 

 

 

SharePoint 2010 : Create List Definition Using Visual Studio

Introduction

In this article we explore List Definition creation using Visual Studio. Please note that the same can be achieved through the SharePoint Designer as well.
Create List Definition Project

To begin, use the List Definition project in the New Project dialog.
Enter the name as Coders. Select the site from the wizard as shown below.
Choose Custom List in the next step.
Enter the details as shown above and click the Finish button to close the wizard. Now the Solution Explorer looks like below:
Open the ListDefinition1>ListInstance1>Elements.xml (Please note that there are 2 Elements.xml inside the Solution Explorer)
Change the Title and Url attributes as following:
<?xml version="1.0" encoding="utf-8"?>
<
Elements xmlns="http://schemas.microsoft.com/sharepoint/">
  <
ListInstance Title="Coders"
                        
OnQuickLaunch="TRUE" TemplateType="10000"
        
               ="" Url="Lists/Coders"
        
               ="" Description="My List Instance">
  </
ListInstance>
</
Elements>
Now click the Build button and upon success, right-click the project and click Deploy. If no error messages are there, the deployment has succeeded and you will see the new List inside SharePoint.
On clicking the Coders list you will see the new list opened in SharePoint.
Now we need to add a custom column to the List Definition. Our column is of a single line and named CoderName. The following are the activities included in the Column Creation:
  • Create a new Field
  • Specify the properties like ID (GUID), Name etc.
  • Add the Field Reference inside the Default View
Inside the Fields section of Schema.xml add the following field definition:
<Field Type="Note" Name="CoderName" DisplayName="CoderName" Required="FALSE" ID="{1D54AAC6-DBB8-4454-91B7-E2FAE7697D6A}"></Field>
Inside the ViewFields section of the second View, add the following FieldRef node:
<FieldRef Name="CoderName"></FieldRef>
You can go back to SharePoint and Refresh the Coders List. The changes are visible there:
The new CoderName property is visible now. This concludes our List creation using Visual Studio. For adding more columns, use the Schema.xml file.

Business Connectivity services using Visual Studio 2010

Using SharePoint Designer you can connect and communicate to external Database or Data. But you don’t have much control using SharePoint 2010 designer.

Other option is you can use Visual studio to write custom code to achieve External Content type. Using Custom code you have full control over the business logic to external Data Sources.
How it Works


BDC Runtime API which manipulate the External data, External content type behave similar like a SharePoint content types, you can manage security on external Lists, Default farms for add, edit, and delete are created , List are available for BI solution, Data in Lists are available for Search.
How to Create BCS Solution in Visual Studio 2010
1.       First we need to identify the Data Store/Database which we want to use as external Content type, in this example I am using very simple table with the name of Customers which contain only 3 columns. Database Table script is
Create TABLE [dbo].[Customers](
   [CustomerID] [int] IDENTITY(1,1) NOT NULL,
   [CustomerName] [nvarchar](50) NULL,
   [CusAddress] [nvarchar](50) NULL,
 CONSTRAINT [PK_Customers1] PRIMARY KEY CLUSTERED
(
   [CustomerID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]

2.       Create new project using Visual studio 2010
3.       Select SharePoint project templates
4.       Select Business connectivity as Project type, Project name to solution and project and Press Ok




5.       Business connectivity Solution can only deployed as Farm solution, select the Site URL and Press finish button.




6.       After Finish button Visual Studio 2010 will Create Some structure for you


7.       Rename the File Entity1.cs to Customers.cs
This is entity Class; here we need to define entity like in my case entity is Customer

8.       Open the Code View of Customer.cs


9.       Remove the existing properties And write new properties based on your entity.

 private int _ID;
        public int ID
        {
            get { return _ID; }
            set { _ID = value; }
        }
        private string _CustomerName;

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

        public string CusAddress
        {
            get { return _CusAddress; }
            set { _CusAddress = value; }
        }

10.    Now open the designer mode of BDC Model ,
11.    Rename the Model name. right click on Model -> select properties -> Change name to CustomersModel (can choose any name)
12.    Select the identifier -> open properties and rename to ID and change Type Name to System.Int32. As an Example ID is identifier


13.    Visual studio will Create 2 methods by default ReadList and Readitem, Select ReadItem method and in below properties select Type Descriptor (its Dropdown) select and Press Edit.



14.    Rename the type descriptor to ID. As in below screen shot. Change Name to ID instead of identifier1 and Change Type Name to System.Int32.


15.    Now look at readitem Method again and select the second parameter (Return Parameter), Select the type Descriptor and Press Edit from the Dropdown. As we done for previous parameter name id.
16.    Rename Entity1 to Customer, change (Rename) Identifer1 to ID and rename its Type Name to System.Int32.


17.    Now we have to add Additional type descriptors. Rename Message to Our Second Field (CustomerName) in Entity and type name to system.string.


18.    Right Click on Customer and add New Descriptor as we have one more field

19. As third property or field is CusAddress and type is String.




That’s we done with ReadItem method.

20.    Now next for ReadList Method. Expand ReadList Method  -> Return parameter -> Entity, Right Click and delete this Entity.


21.    Expand the ReadItem Method and Expand the Copy the Customer Entity for Return parameter (as we define it earlier so no need to do this effort again ). 


22.    Copy to ReadList Method Return Parameter and Rename EntityList1 to Customers and Paste entity to Customers.



Till we have done to get specific Item Method (readItem) and get All items (ReadList), Now we are looking to create Creator method.
23.    Select the model Open the Propertied and select the Creator Method from Dropdown. And click on it. It will setup everything (in previous method we need to define entity it will setup automatically).



No do same step for Deleter and Updater Methods. Just select Model Diagram and open the BDC Model Detail Pain and select Deleter and Updater, it will configure everything in default based on our previous settings. And your Detail View look like Below screenshot.

This is all that we need to do using designer, now open the Code view (CustomerModelService.cs Class). And see it there are 5 methods now we have to write the code for Create, update, delete, readList and ReadItem methods.


Here you can write code with any logic, I am using very simple ADO.Net Method to perform these actions.


Here is My Code … Again – (here you can use your own way to write the Code. And you own logic)

Create Method

public static Customer Create(Customer newCustomerModel)
        {
            SqlConnection cnn;
            cnn = new SqlConnection(connetionString);
            try
            {
                cnn.Open();
                SqlCommand myCommand = new SqlCommand("INSERT INTO [Customers]([CustomerName],[CusAddress])VALUES('" + newCustomerModel.CustomerName + "','" + newCustomerModel.CusAddress + "')", cnn);
                myCommand.ExecuteNonQuery();
                cnn.Close();
                return newCustomerModel;
            }
            catch (Exception ex)
            {
                return newCustomerModel;
            }
        }

 Delete Method      

public static void Delete(int iD)
{
    SqlConnection cnn;
    cnn = new SqlConnection(connetionString);
    try
    {
        cnn.Open();
 SqlCommand myCommand = new SqlCommand("Delete [Customers] Where CustomerID='"
 iD + "'", cnn);
        myCommand.ExecuteNonQuery();
        cnn.Close();
    }
    catch (Exception ex)
    {
        // return newCustomerEntity;
    }
}
 Update Method

public static void Update(Customer customerModel)
        {
            SqlConnection cnn;
            cnn = new SqlConnection(connetionString);
            try
            {
                cnn.Open();
                SqlCommand myCommand = new SqlCommand("Update [Customers] Set [CustomerName]='" + customerModel.CustomerName + "',[CusAddress]='" + customerModel.CusAddress + "' Where CustomerID=" + customerModel.ID + "", cnn);
                myCommand.ExecuteNonQuery();
                cnn.Close();
            }
            catch (Exception ex)
            {
                // return newCustomerEntity;
            }
        }



ReadList Method
public static IEnumerable<Customer> ReadList()
        {
            int count = ItemCounter();
            Customer[] CustomersList = new Customer[count];
            Customer ObjCustomer = new Customer();
            //CustomersList[0] = ObjCustomer;
            SqlConnection cnn;
            cnn = new SqlConnection(connetionString);
            try
            {
                cnn.Open();
                SqlDataReader myReader = null;
                SqlCommand myCommand = new SqlCommand("SELECT [CustomerID],[CustomerName],[CusAddress] FROM [Customers] ", cnn);
                myReader = myCommand.ExecuteReader();
                int i = 0;
                while (myReader.Read())
                {
                    ObjCustomer.ID = Convert.ToInt32(myReader["CustomerID"]);
                    ObjCustomer.CustomerName = Convert.ToString(myReader["CustomerName"].ToString());
                    ObjCustomer.CusAddress = Convert.ToString(myReader["CusAddress"].ToString());
                    CustomersList[i] = ObjCustomer;
                    i++;
                    ObjCustomer = new Customer();
                }

                cnn.Close();
                return CustomersList;
            }
            catch (Exception ex)
            {
                CustomersList = new Customer[1];
                ObjCustomer.ID = 0;//Convert.ToInt32(myReader["CustomerID"]);
                ObjCustomer.CustomerName = "Not Found";//Convert.ToString(myReader["CustomerName"].ToString());
                ObjCustomer.CusAddress = "Not Found";
                CustomersList[0] = ObjCustomer;
                return CustomersList;
            }
        }


Read Item Method

public static Customer ReadItem(int id)
        {
            //TODO: This is just a sample. Replace this simple sample with valid code.
            Customer ObjCustomer = new Customer();
            SqlConnection cnn;
            cnn = new SqlConnection(connetionString);
            try
            {
                cnn.Open();
                SqlDataReader myReader = null;
                SqlCommand myCommand = new SqlCommand("SELECT [CustomerID],[CustomerName],[CusAddress] FROM [Customers] Where [CustomerID]=" + id + "", cnn);
                myReader = myCommand.ExecuteReader();
                while (myReader.Read())
                {
                    ObjCustomer.ID = Convert.ToInt32(myReader["CustomerID"]);
                    ObjCustomer.CustomerName = Convert.ToString(myReader["CustomerName"].ToString());
                    ObjCustomer.CusAddress = Convert.ToString(myReader["CusAddress"].ToString());
                }

                cnn.Close();
                return ObjCustomer;
            }
            catch (Exception ex)
            {
                return ObjCustomer;
            }
         
        }


After This Deploy your solution either using Visual studio or Powershell.

Open the particular site - > site action -> Select More Option  -> Select External List from the Templates and Click Create.

Provide name and select External Content type.

Now see that your items from Database are in SharePoint List, we Implement Create, Update delete, readitem and readList Methods so it will work for all solutions..