Search This Blog

Tuesday, July 1, 2014

Develop SharePoint webparts


Develop SharePoint webparts 

Most of the times you need to  develop SharePoint webparts based on various requirements of the project by customizing your SharePoint site.
Even though there are lots of requirements and functionality can be achieved using SharePoint OOB (out of the box) features, still you might require more often than not need to write code to develop SharePoint webparts to achieve the requirements of the client. 

Webpart development: Most of the above details are important while developing a basic SharePoint development. Especially while developing the SharePoint webparts.
We will use Visual studio 2012 to develop SharePoint webparts and deployed them to SharePoint 2013 environment.
To start developing webparts, open visual studio 2012
Click on [file] [New Project] ,  it will open the below figure from the SharePoint solutions  select SharePoint 2013-empty project .
SharePoint 2013 Empty project
Once you click ok, It will open the create project wizard where you can select or enter  the site URL from where you can deploy the SharePoint webparts as a sandboxed solution or farm solution. In this POC select deploy as a sandbox solution.
project-wizard
Click on finish button. It will create an empty project. Now its time to add web part to the project that has been created.
Right click on the project and [add] [New item..] , select web part item  and enter "Projects" in Name section and click  "Add" button. The web part item will get added to the project.
SharePoint Webpart
Once you add the SharePoint webpart it will create feature1 under features folder. Edit the feature by right clicking on the feature or select it and press F2 keyword then modify the feature name.
To change the Title and description properties double click on it. In the below figure we are mentioning Title as Projects and Description as "Add and display the Projects"  and also the scope of the web part always is at site level i.e. Referring a particular Site collection.
There are four levels of scopes in SharePoint.
1. Farm : This scope will be used to deploy the components at Farm level.
2. Web application : This scope will be used to deploy the components at web application level.
3. Site : This scope will be used to deploy the components at site collection level.
4. Web : This scope will be used to deploy the components at site level.

webpart feature

Elements.xml :

Once you add a webpart to the project it will create two files one is Elemnts.xml and other one is .webpart file. Below code snippet shows the details of elements.xml file.
Module in elements.xml file specifys where to deploy the component or arifact in SharePoint site and the list id =113, which specifies web part gallery  and URL Specifies the virtual path where the files will get deployed when you deploy the feature.
12345678
<?xml version="1.0" encoding="utf-8"?>
<Elements xmlns="http://schemas.microsoft.com/sharepoint/" >
<Module Name="Projects" List="113" Url="_catalogs/wp">
<File Path="Projects\Projects.webpart" Url="SharePoint-webpart_Projects.webpart" Type="GhostableInLibrary">
<Property Name="Group" Value="Custom" />
</File>
</Module>
</Elements>
view rawwebpart-element.xml hosted with ❤ by GitHub

Please check more details about module  here.

.webpart File :

Below code snippet shows the details of .webpart file.
In the below code metadata  will have information about the webpart. Type contains the full path of the source file and importErrorMessage  used to display the message to the users where there is an error while importing the webpart and you can see the usage of resource files for multilingual support..
123456789101112131415
<?xml version="1.0" encoding="utf-8"?>
<webParts>
<webPart xmlns="http://schemas.microsoft.com/WebPart/v3">
<metaData>
<type name="SharePoint_webpart.Projects.Projects, $SharePoint.Project.AssemblyFullName$" />
<importErrorMessage>$Resources:core,ImportErrorMessage;</importErrorMessage>
</metaData>
<data>
<properties>
<property name="Title" type="string">SharePoint-webpart - Projects</property>
<property name="Description" type="string">My Web Part</property>
</properties>
</data>
</webPart>
</webParts>
view rawprojects.webpart.xml hosted with ❤ by GitHub
To see how the properties will work, deploy this SharePoint webpart by right clicking on the project and click on deploy, it will get deployed to the SharePoint site which you specified in the properties. 
Open the SharePoint site ..
Go to [site settings] [webparts under web designer galleries] where all SharePoint webparts will be available.
To check the webpart you have deployed just now by sorting modified date field. Recently deployed web part  will show  *New symbol.
Click on Edit button against your webpart, it will show the below figure how the values of Title and Description properties you have in .webpart file showing it here.
If you want to change the values of  these properties, you simply use the Export button in the ribbon control and download it your local folder and upload it back again to change the Title and description values.
web-part-gallery
Please check here for full reference of .webpart file

Webpart class file:

The webpart class file inherits from System.Web.UI.WebControls.WebParts.webpart and which is an ASP.net class. Once you add a webpart, CreateChildControls method will get created by default. This method is very important in a webpart life cycle where different events will fire.
CreateChildControls method used to render various controls like textbox, button, gridview etc.

12345678910111213141516171819
using System;
using System.ComponentModel;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;
 
namespace SharePoint_webpart.Projects
{
[ToolboxItemAttribute(false)]
public class Projects : WebPart
{
protected override void CreateChildControls()
{
}
}
}
view rawprojects.cs hosted with ❤ by GitHub

Add List Item:

The below code snippet is used to add project details to a SharePoint list.
In the below code I have used Textbox and button controls.
If you observe the below snippet the controls are created and added in createchildcontrols method.
In the button click event we have written a simple object model to deploy the values to SharePoint list.
12345678910111213141516171819202122232425262728293031323334353637383940414243444546
using System;
using System.ComponentModel;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;
 
namespace SharePoint_webpart.Projects
{
[ToolboxItemAttribute(false)]
public class Projects : WebPart
{
//declare all variables
 
TextBox txtproject;
Button btnadd;
 
//load all controls
protected override void CreateChildControls()
{
txtproject = new TextBox();
txtproject.ID = "txtproject";
btnadd = new Button();
btnadd.ID = "btnadd";
btnadd.Text = "Add Project";
btnadd.Click += btnadd_Click;
Controls.Add(txtproject);
Controls.Add(btnadd);
}
 
//Add the project to a list
void btnadd_Click(object sender, EventArgs e)
{
SPWeb web = SPContext.Current.Web;
//SPList projectsList = web.Lists["Projects"];
//use the below line code for best prectices
SPList projectsList = web.GetList("http://sharepoint-journey/sites/Apps/Lists/Projects/AllItems.aspx");
SPListItem newItem = projectsList.Items.Add();
newItem["Title"] = txtproject.Text.ToString();
newItem.Update();
txtproject.Text = string.Empty;
}
}
}
view rawcomplete-projects.cs hosted with ❤ by GitHub
Check the best coding practices article.
After adding the above code, build the solution and right click on the project and deploy it.
To add webpart click on Page and click on the Edit button from the ribbon control.
From the below figure click on Insert and select webpart from custom category select your webpart and click on add.
Add-webpart-to-page
Once you have added the webpart, save and publish the page.
Project Details-Add Item

Test webpart:

Create SharePoint List:

Create Projects List to store the values by clicking on site contents from recent section on the home page or the settings button on the top right of the site.
Click on add an App button and select the Custom List and enter the Name as Projects and click on create button.
Once you created the Projects list, go the webpart page enter Project name as "Project A" and click Add, you can see that item has been added to the list. See the below figure for reference.
Project Details-Added to List
So far we have developed SharePoint webpart which will used to save items in custom SharePoint list.
The next part is how to display the details which we have stored in a SharePoint list.

Display List details:

To display SharePoint list we have many ways such as using CAML query, Jquery with the help of SPservices etc.
In this post we will be using CAML query to get the list details which have been stored before.
Lets quickly see the below code snippet where we are using getdata method to get the Id and Title of projects list. We are using SPquery object to execute the CAML query.
If you are learning CAML check this article to learn the basics of CAML.
You can check the CAML designer  under the downloads section of site for SharePoint 2013 here earlier we call it as CAML builder.
In the below CAML query where condition doesn't have any impact, but you can learn how the Where condition will be used in CAML query.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112
using System;
using System.ComponentModel;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;
using System.Data;
 
namespace SharePoint_webpart.Projects
{
[ToolboxItemAttribute(false)]
public class Projects : WebPart
{
//declare all variables
 
TextBox txtproject;
Button btnadd;
GridView grdprojects;
 
// A table for layout
Table tbl;
TableRow row;
TableCell cell;
 
//load all controls
protected override void CreateChildControls()
{
tbl = new Table();
row = new TableRow();
cell = new TableCell();
 
txtproject = new TextBox();
txtproject.ID = "txtproject";
 
cell.Controls.Add(txtproject);
cell.Width = 10;
row.Controls.Add(cell);
 
 
btnadd = new Button();
btnadd.ID = "btnadd";
btnadd.Text = "Add Project";
btnadd.Click += btnadd_Click;
 
cell = new TableCell();
cell.Controls.Add(btnadd);
row.Controls.Add(cell);
tbl.Controls.Add(row);
 
row = new TableRow();
cell = new TableCell();
cell.ColumnSpan = 2;
 
grdprojects = new GridView();
grdprojects.AutoGenerateColumns = true;
 
 
grdprojects.DataSource = getdata();
 
grdprojects.DataBind();
cell.Controls.Add(grdprojects);
row.Controls.Add(cell);
tbl.Controls.Add(row);
Controls.Add(tbl);
 
}
 
private DataTable getdata()
{
SPWeb web = SPContext.Current.Web;
 
SPList projectsList = web.GetList("http://sharepoint-journey/sites/Apps/Lists/Projects/AllItems.aspx");
 
//In the below CAMl query i am using Where condition even though it is not applicable, so that you can always remebre the standard sysntax.
var query = "<Query>" +
"<Where>" +
"<Neq>" +
"<FieldRef Name='ID'/><Value Type='Number'>0</Value>" +
"</Neq>" +
"</Where>" +
"<OrderBy>" +
"<FieldRef Name='Title'/>" +
"</OrderBy>" +
"</Query>";
 
SPQuery spQuery = new SPQuery();
spQuery.ViewFields = "<FieldRef Name='Id' /><FieldRef Name='Title' />";
 
spQuery.Query = query;
SPListItemCollection items = projectsList.GetItems(spQuery);
DataTable dtprojects = items.GetDataTable();
 
return dtprojects;
}
 
//Add the project to a list
void btnadd_Click(object sender, EventArgs e)
{
 
SPWeb web = SPContext.Current.Web;
SPList projectsList = web.GetList("http://sharepoint-journey/sites/Apps/Lists/Projects/AllItems.aspx");
 
SPListItem newItem = projectsList.Items.Add();
newItem["Title"] = txtproject.Text.ToString();
newItem.Update();
txtproject.Text = string.Empty;
 
}
}
}
- See more at: http://www.sharepoint-journey.com/sharepoint-webparts.html#sthash.ZEL8bAbT.dpuf

No comments:

Post a Comment