WEBSITE

Sharepoint 2013 : Understanding Your Development Options (part 2) - Creating Web Parts - Visual Web Parts

9/22/2013 9:43:20 PM

2. Common Developer Tasks

Although everything is technically an “app” in SharePoint 2013, you will find yourself building different types of apps, and when doing so, you will run into several of the same tasks many times over. It is helpful to identify these familiar tasks so that you can hone the skills associated with them, as you’ll be using them often. Some of the more common tasks you’ll likely find yourself doing are as follows:

  • Creating Web Parts
  • Creating SharePoint-hosted apps
  • Accessing and managing data
  • Creating cloud-hosted apps
  • Creating event receivers
  • Creating ASPX pages
  • Creating master pages

Let’s walk through each of these tasks and explore what they are and the skills required for your success in completing them.

2.1 Creating Web Parts

One of the most common developer tasks you’ll likely engage in is the creation and deployment of a Web Part. This historically has been the key artifact that a developer develops and deploys to SharePoint.

In SharePoint 2013, you work primarily with three different types of Web Parts: Standard, Visual, and Silverlight. Many other SharePoint artifacts might feel like a Web Part, but in many cases these are ASP.NET objects, containers, or IFRAMEs that provide dynamic client-side code rendering and pass-through capabilities to other Web Parts or applications, or views to list data. Because of the rich designer capabilities, the Visual and Silverlight Web Parts will likely be your first choice; however, this section covers all three.

Standard Web Parts

A Standard Web Part provides the plumbing for you to create a Web Part and deploy it to SharePoint. When you create a Standard Web Part, you are creating most objects from scratch and assembling the Web Part without the aid of a designer. This can be good and bad. If you’re a skilled developer and are familiar with the ASP.NET/SharePoint APIs and object model, then this won’t be too much trouble. However, you do gain some advantage when using more designer-driven Web Parts, if nothing more than to improve your productivity around creating a user interface for your Web Part.

To follow is a short code snippet that includes a text box, label, and button control that are being instantiated, properties set, and a Click event that corresponds to the button control. In this code snippet, you can see that the four controls are declared at the class level, and then in the CreateChildControls method the properties for those objects are set, the Add method is called to add the controls to the Controls collection (to display them in the Web Part), and the myButton_Click event is called to render the user’s entry as text in one of the labels. If you have not coded Web Parts before, this is pretty standard; that is, creating the controls, setting the properties for those controls, adding the controls to the Controls collection, and also adding any event handlers for those controls. This code illustrates the explicit code you need to write to generate the UI through ASP.NET objects:

namespace MyFirstDevTask.TaskOneWebPart
{
[ToolboxItemAttribute(false)]
public class TaskOneWebPart : WebPart
{
Label myLabel = new Label();
TextBox myTextbox = new TextBox();
Label myResponse = new Label();
Button myButton = new Button();

protected override void CreateChildControls()
{
myLabel.Text = "Enter Text:";
myResponse.Text = "";
myTextbox.Enabled = true;
myTextbox.Text = "";
myButton.Text = "Click Me";
this.Controls.Add(myLabel);
this.Controls.Add(myTextbox);
this.Controls.Add(new LiteralControl("<br/>"));
this.Controls.Add(myResponse);
this.Controls.Add(new LiteralControl("<br/>"));
this.Controls.Add(myButton);

myButton.Click += new EventHandler(myButton_Click);
}

void myButton_Click(object sender, EventArgs e)
{
string userResponse = myTextbox.Text;
myResponse.Text = userResponse;
}
}
}

Figure 1 shows the end result if you were to deploy this Web Part to SharePoint.

FIGURE 1

image

Visual Web Parts

The Visual Web Part is different from the Standard Web Part in that you have a designer experience for creating the user interface (UI) for the Web Part. This makes it very easy to add controls and code-behind for this type of Web Part. Because SharePoint is built on ASP.NET, you have many of the same underlying constructs and objects that you might have learned through ASP.NET for the creation of a Standard Web Part. You can create and apply many of the same objects and events when building out a Visual Web Part that you might have used when building out an older ASP.NET Web Part.

Using the designer experience in Visual Studio to create the Web Part UI, you can drag and drop a wide array of library controls from the toolbox onto the designer surface. Where you would manually write the code in the Standard Web Part to create controls or events, in the Visual Web Part you use a method with which you’re likely familiar: drag and drop the control and then double-click the control in the designer to add the code-behind. For example, if you were to take the same functionality shown earlier in the Standard Web Part and implement it in the Visual Web Part, then you would have an ASP.NET user control (ASCX file) that represents the UI with a code-behind file. The ASCX user control code would look like the following:

<asp:Label ID="myLabel" runat="server" Text="Enter Text:"></asp:Label>
<asp:TextBox ID="myTextbox" runat="server"></asp:TextBox>
<p>
<asp:Label ID="myResponse" runat="server" Text="Label"></asp:Label>
</p>
<asp:Button ID="myButton" runat="server" onclick="myButton_Click"
Text="Click Me" />

The code-behind for the ASCX user control would look like the following:

using System;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;

namespace MyFirstDevTask.TaskTwoWebPart
{
public partial class TaskTwoWebPartUserControl : UserControl
{
...

protected void myButton_Click(object sender, EventArgs e)
{
string userResponse = myTextbox.Text;
myResponse.Text = userResponse;
}

}
}

Note that the control declarations do not appear in this specific ASCX code-behind (ASCX is the file extension for the ASP.NET user control file); however, a reference exists to the ASCX control in the core Web Part class that loads the user control you build with the designer experience at runtime. The following shows the code that represents this reference inside of the core Web Part class. Note that the _ascxPath object simply represents a filesystem path to the location of the ASCX file you created using the designer.

public class TaskTwoWebPart : WebPart
{
private const string _ascxPath =
@"~/_CONTROLTEMPLATES/MyFirstDevTask/TaskTwoWebPart/TaskTwoWebPartUserControl.ascx";

protected override void CreateChildControls()
{
Control control = Page.LoadControl(_ascxPath);
Controls.Add(control);
}
}

Figure 2 shows what this Visual Web Part looks like.

FIGURE 2

image

Now that you’ve seen a bit of code behind both a Standard and Visual Web Part, let’s walk through an exercise to create a new Visual Web Part. This exercise assumes that you’ve created a SharePoint site (a developer site).


TRY IT OUT: Creating a Visual Web Part

Visual Web Parts provide a designer experience for your Web Part customization. To create a Visual Web Part, perform the following steps:

1. Open Visual Studio 2012.
2. Click File ⇒ New Project, navigate to Office/SharePoint ⇒ SharePoint Solutions, and then select SharePoint 2013 – Empty SharePoint Solution.
3. Provide a name for the project (MyFirstSPProject), as shown in Figure 3.

FIGURE 3

image

4. After the new project has been created, right-click the SharePoint project and select Add ⇒ New Item.
5. In the Add New Item dialog, select the Visual Web Part item template.
6. A prompt appears, asking you to designate the application as a sandboxed solution or a farm-level application. Select Deploy as a farm solution, and click Finish, as shown in Figure 4.

FIGURE 4

image

7. Provide a name for the Visual Web Part (MyNewVisualWebPart), and click Add. See Figure 5.

FIGURE 5

image

8. After the Visual Web Part is added to the project, right-click the SharePoint project and select Add ⇒ Class, and provide a name for the new class (Sales).
9. Click Add.
10. Add the bolded code as per the following code snippet:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace MyFirstSPProj
{
class Sales
{
public int ID { get; set; }
public string Quarter { get; set; }
public string TotalSales { get; set; }

}
}
11. Right-click the Default.aspx page and select View Designer. Click the Source tab and add the bolded code as per the following code snippet:
<%@ Assembly Name="$SharePoint.Project.AssemblyFullName$" %>
<%@ Assembly Name="Microsoft.Web.CommandUI, Version=15.0.0.0, Culture=neutral,
PublicKeyToken=71e9bce111e9429c" %>
...

<p style="font-family: calibri">
My First Visual Web Part</p>
<asp:GridView ID="salesGridView" runat="server" CellPadding="4"
Font-Names="Calibri" Font-Size="Small" ForeColor="#333333" GridLines="None">
<AlternatingRowStyle BackColor="White" ForeColor="#284775" />
<EditRowStyle BackColor="#999999" />
<FooterStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
<HeaderStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
<PagerStyle BackColor="#284775" ForeColor="White" HorizontalAlign="Center" />
<RowStyle BackColor="#F7F6F3" ForeColor="#333333" />
<SelectedRowStyle BackColor="#E2DED6" Font-Bold="True" ForeColor="#333333" />
<sortedascendingcellstyle backcolor="#E9E7E2" />
<sortedascendingheaderstyle backcolor="#506C8C" />
<sorteddescendingcellstyle backcolor="#FFFDF8" />
<sorteddescendingheaderstyle backcolor="#6F8DAE" />
</asp:GridView>
<br />
<asp:LinkButton ID="lnkGetSalesData" runat="server" Font-Names="Calibri"
Font-Size="Small">Get Sales</asp:LinkButton>
12. Double-click the Default.aspx.cs file and add the bolded code as per the following code snippet:
using System;
using System.ComponentModel;
using System.Web.UI.WebControls.WebParts;
using System.Collections.Generic;

namespace MyFirstSPProj.MyNewVisualWebPart
{
[ToolboxItemAttribute(false)]
public partial class MyNewVisualWebPart : WebPart
{

List<Sales> mySalesData = new List<Sales>();
Sales FY11 = new Sales();
Sales FY12 = new Sales();
Sales FY13 = new Sales();


public MyNewVisualWebPart()
{
}

protected override void OnInit(EventArgs e)
{
base.OnInit(e);
InitializeControl();
}

protected void Page_Load(object sender, EventArgs e)
{
}

protected void lnkGetSalesData_Click(object sender, EventArgs e)
{
FY11.ID = 1;
FY11.Quarter = "FY11";
FY11.TotalSales = "$2,002,102.00";
mySalesData.Add(FY11);

FY12.ID = 2;
FY12.Quarter = "FY12";
FY12.TotalSales = "$2,500,201.00";
mySalesData.Add(FY12);

FY13.ID = 3;
FY13.Quarter = "FY13";
FY13.TotalSales = "$2,902,211.00";
mySalesData.Add(FY13);

salesGridView.DataSource = mySalesData;
salesGridView.DataBind();
}

}
}
13. Right-click the SharePoint project and select Deploy. This builds and deploys the Visual Web Part to your SharePoint site.
14. After the Visual Web Part successfully deploys to the SharePoint site, navigate to the top-level SharePoint site.
15. Click Page and then Edit.
16. Click the Insert tab, and then select Web Part ⇒ Custom, and then add the newly deployed Visual Web Part. The result will look similar to Figure 6.

FIGURE 6

image

How It Works

In this exercise, you created a simple Visual Web Part. The Web Part uses a Sales object with three properties: a record ID, fiscal quarter, and sales figure, as shown in the following:
Class Sales
{
public int ID {get; set;}
public string Quarter {get; set;}
public string TotalSales {get; set;}
}
The code then added three objects to a List collection that was then bound to the GridView object. This event was triggered by a linkbutton, which created the ListGridView. collection and bound it to the
Other  
 
Top 10
Review : Sigma 24mm f/1.4 DG HSM Art
Review : Canon EF11-24mm f/4L USM
Review : Creative Sound Blaster Roar 2
Review : Philips Fidelio M2L
Review : Alienware 17 - Dell's Alienware laptops
Review Smartwatch : Wellograph
Review : Xiaomi Redmi 2
Extending LINQ to Objects : Writing a Single Element Operator (part 2) - Building the RandomElement Operator
Extending LINQ to Objects : Writing a Single Element Operator (part 1) - Building Our Own Last Operator
3 Tips for Maintaining Your Cell Phone Battery (part 2) - Discharge Smart, Use Smart
REVIEW
- First look: Apple Watch

- 3 Tips for Maintaining Your Cell Phone Battery (part 1)

- 3 Tips for Maintaining Your Cell Phone Battery (part 2)
VIDEO TUTORIAL
- How to create your first Swimlane Diagram or Cross-Functional Flowchart Diagram by using Microsoft Visio 2010 (Part 1)

- How to create your first Swimlane Diagram or Cross-Functional Flowchart Diagram by using Microsoft Visio 2010 (Part 2)

- How to create your first Swimlane Diagram or Cross-Functional Flowchart Diagram by using Microsoft Visio 2010 (Part 3)
Popular Tags
Microsoft Access Microsoft Excel Microsoft OneNote Microsoft PowerPoint Microsoft Project Microsoft Visio Microsoft Word Active Directory Biztalk Exchange Server Microsoft LynC Server Microsoft Dynamic Sharepoint Sql Server Windows Server 2008 Windows Server 2012 Windows 7 Windows 8 Adobe Indesign Adobe Flash Professional Dreamweaver Adobe Illustrator Adobe After Effects Adobe Photoshop Adobe Fireworks Adobe Flash Catalyst Corel Painter X CorelDRAW X5 CorelDraw 10 QuarkXPress 8 windows Phone 7 windows Phone 8
Visit movie_stars's profile on Pinterest.