The
most commonly developed components for SharePoint are web parts.
SharePoint 2010 now contains project templates that contain all the
functionality that supports the immediate deployment of a variety of
objects including but not limited to workflows, event receivers, web
parts, business data connectivity objects, and even list definitions.
SharePoint 2007 developers will be pleased to note that the packaging of
these components as a SharePoint solution (.wsp) is automatic.
Follow the next steps to
create a Visual Web Part that renders a SharePoint announcements list in
a custom format. To show some of the more recent advancements of both
.NET and SharePoint 2010, this example uses LINQ and a ListView control.
LINQ is an advanced query tool that enables developers to reference
database objects directly as native types. The ListView control is a
powerful new UI component that allows for complete control of the HTML
output based upon developer-defined templates.
To create a Visual Web Part,
follow these steps on a system with SharePoint Server 2010 Standard or
Enterprise installed and Visual Studio 2010 Professional or Ultimate:
1. | Choose
a site in a development SharePoint site collection. In this example,
the site used is a site collection created beneath a top-level portal
site collection (http://abcsp1004/sites/VSTest). It needs an
announcements list and a picture library. If these do not exist, they
need to be created. The announcements list needs to be named
Announcements for the code included in this exercise to work. The image
library can be named anything because it is not directly addressed in
the code. For this exercise, the picture library is named Images.
| 2. | The announcements list needs to have several columns added, but otherwise settings should be left at their default. Table 1 shows the columns that need to be added and relevant settings.
Table 1. Add These Columns to the Announcements ListColumn | Data Type |
---|
Author | Person or Group | Start Date | Date and Time | Picture | Hyperlink or Picture (Choose the Picture Option under Format URL As) |
| 3. | The
picture library should have an image uploaded to it. When the image is
uploaded, capture the URL for the image; then create an announcement and
paste the URL for the image in the Picture field. Figure 1 shows the Announcements list with an entry in it that references a picture.
|
Before continuing with the
web part development, verify that the account used to run Visual Studio
2010 has the following rights:
Local administrator rights to the development machine Farm administrator rights (not necessary if a sandboxed solution is created, but always helpful to have if possible) Site collection administrator rights to the site collection where the solution will be deployed during debugging
To create a project in Visual Studio 2010, which will be used in the following exercise, follow these steps:
1. | Open Visual Studio 2010 by clicking the Start button, then All Programs, SharePoint, and click Microsoft Visual Studio 2010.
| 2. | The
first time it is opened, the default environment settings need to be
set. Different developers have their preferences, the first setting, General Development Settings, is
sufficient.
| 3. | When Visual Studio is open, access the File menu, then click New then Project.
| 4. | In
the New Project window, choose Visual C#, and choose the SharePoint
node from the list of choices in the left pane. Expand the SharePoint
node and select the entry 2010, as shown in Figure 2.
| 5. | Then select the Visual Web Part template from the center pane. Name the Visual Web Part project EventWebPart,
and it will be auto-populated in the Solution name field. Verify the
location where Visual Studio 2010 creates the project folder structure
is suitable. Click OK.
Caution
If SharePoint 2010 is not
installed on the machine, an error message displays. In addition, if
the account used does not have sufficient permissions, an error message
appears. It may be necessary to restart Visual Studio 2010 by
right-clicking it from the Start menu and choosing Run as Administrator.
Note
Templates include Empty
SharePoint Project, Visual Web Part, Sequential Workflow, State Machine
Workflow, Business Data Connectivity Model, Event Receiver, List
Definition, Content Type, Module, Site Definition, Import Reusable
Workflow, and Import SharePoint Solution Package for both the Visual C#
and Visual Basic languages.
| 6. | The
SharePoint Customization Wizard dialog then opens. Enter the URL for
the target SharePoint site with the Announcements list configured in the
previous section running on the server where Visual Studio 2010 deploys
the code. In this example,
the URL is http://abcsp1004/sites/vstest. Press the Validate button,
and Visual Studio 2010 verifies that the URL responds properly and runs
the appropriate version of SharePoint 2010 and should display a
Connection Successful message. Click OK to close the message. Verify
that Deploy as Farm Solution is checked, as shown in Figure 3, and click Finish. The resulting view should be similar to Figure 4.
Note
Sandboxed solutions are “safer,”
because they can be deployed to a site collection, instead of deployed
to the whole farm. Also they are run in a more secure fashion by using a
combination of features, solution galleries, solution monitoring, and a
validation framework. In addition, the sandboxed solution’s assembly is
not loaded into the IIS process (w3wp.exe); it is loaded into a
separate process (SPUCWorkerProcess.exe) that is more closely monitored
and managed by SharePoint 2010. Sandboxed solutions have some
limitations, such as a not offering site definitions and workflows, and
only types in the Microsoft SharePoint Foundation 2010 assembly
Microsoft.SharePoint can be used in sandboxed solutions.
There is a Boolean
project property called Sandboxed Solution that can be changed in the
project. However, changing the Sandboxed Solution property of a project
after it is created may cause validation errors. Farm solutions require
higher-level privileges to run or deploy the solution.
| 7. | By default, Visual Studio creates the web part with the name VisualWebPart1, as shown in the Solution Explorer to the right of Figure 4.
(Click the View menu and choose Solution Explorer if it is not already
visible.) To give the web part a more meaningful name, open the
VisualWebPart1.webpart file by double-clicking it, and a new tab will
open.
| 8. | In the new tab in the code editor, under <properties>, replace the Title text VisualWebPart1 with the text Event Web Part; then in the next line, replace the text My Visual Web Part with the text Web Part to Display Events with an Image and click the Save icon. The results are shown in Figure 5 where the two modified lines of code are highlighted. Now click the Save icon to save the project.
| 9. | Before
adding any code or UI components to the Visual Web Part, debug the web
part by clicking the Debug menu, and then click Start Debugging.
Debugging the web part before adding code or UI components allows the
developer to verify that the project and development environment work as
expected, and in this case, packages and deploys the solution, and then
removes the solution when it is complete.
Note
An error message may
appear after Start Debugging is clicked. This message states The Project
Cannot Be Debugged Because Debugging Is Not Enabled in the Web.config
file. If this message appears, select Modify the Web.Config File to
Enable Debugging or Run Without Debugging. A note in this window also
suggests that debugging should be disabled in production SharePoint 2010
environments, so this is a judgment call. Debugging is generally
considered to be essential in most development efforts, so in general
the option to Modify the Web.Config File to Enable Debugging needs to be
enabled.
Note
Installing a solution into
SharePoint 2010 using Visual Studio 2010 by deploying or debugging the
solution can complete an IISReset that automatically forces all http
requests to be temporarily unavailable.
| 10. | A
browser window opens to the SharePoint site as part of the debugging
process, because manual intervention is required to add the web part to
the SharePoint site. From this window, click Site Actions, Edit Page.
| 11. | Click the Add a Web Part link in a zone on the page.
| 12. | Click
the Custom folder in the Categories list under the Ribbon, and then
select Event Web Part. Click the Add button and the web part should be
added to the zone selected. Figure 29.17 shows the result (other contents of the page may vary) where the web part title Event Web Part is visible on the page.
| 13. | If
needed, depending upon the type of site being edited, click Save and if
necessary publish the page. Then close the browser and return to Visual
Studio.
| 14. | In
Visual Studio, the debug process completes, and the Output window shows
the activities taking place, ending with the solution being retracted.
| 15. | Next,
to take advantage of the LINQ feature in this project, a reference to
Microsoft.SharePoint.Linq needs to be added. In the Solution Explorer,
right-click References, and click Add Reference.
| 16. | Click
the .NET tab, scroll roughly halfway down, and find and click
Microsft.SharePoint.Linq. Click OK to save this reference, and it
appears under the References node.
| 17. | Next,
the SPMetal program will be run from the command prompt to generate a
LINQ class file. Open a command prompt by clicking the Start button and
entering cmd in the Search field and pressing Enter.
| 18. | Navigate to the c:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\14\BIN folder.
| 19. | Run
the following command to generate a LINQ class file, EventLinq.cs, that
the web part can use to read the announcements list created previously.
Be sure to update the following command by replacing the text in bold
to reference the project directory where SPMetal will place the
EventLinq.cs file. Figure 29.18
shows a sample of code with the servername and site collection name
included (http://abcsp1004/sites/vstest), and the username to set the
correct EventWebPart directory location (administrator.abc). Type the
following code and press Enter, and SPMetal will run:
spmetal.exe /web:http://servernameandsitename/code: "c:\Users\username\Documents\Visual Studio 2010\Projects\EventWebPart\EventWebPart\EventLinq.cs" /namespace:EventWebPart
Note
LINQ enables developers to
access data using strongly typed .NET objects. A program shipped with
SharePoint 2010 called SPMetal.exe generates the LINQ class file that
enables these strongly typed .NET components to be used.
Tip
The SPMETAL utility may fail
with The Web Application at http://servername Could Not be Found error
because the username and password were not provided or, in some cases,
if the SharePoint server name is not properly added to the alternate
access mapping collection.
| 20. | No message appears, but a new line appears when the process finishes. Close the command prompt and return to Visual Studio.
| 21. | After
successfully generating the EventLinq.cs code file, the code can now be
consumed by the EventWebPart project. In Visual Studio 2010, in the
Solution Explorer, right-click the project’s title EventWebPart. A
context menu appears; click Add, and then choose Add Existing Item.
Tip
If the file does not appear
in the project directory, check to see if it were produced in the
solution’s directory that often has the same name as the project
directory. If this is the case, run SPMETAL again, and make sure that
the output path contains the full project path.
| 22. | In the dialog box that opens, locate and select the EventLinq.cs file created previously and click Add, as shown in Figure 8. The EventLinq.cs should now appear in the Solution Explorer.
| 23. | Click Save in Visual Studio to save the progress.
| 24. | In the Solution Explorer, locate the VisualWebPart1UserControl.ascx file, and open it by double-clicking it.
| 25. | Click the Split button under the active tab for VisualWebPart1UserControl.ascx.
| 26. | Access
the View menu, and click Toolbox to display the Toolbox. Locate the
ListView component in the Data node, and drag it to the Design pane
(which opened when the Split button was pressed), as shown in Figure 9, where the ListView can be seen in the Design pane.
| 27. | Return
to the Source view by clicking the Source button on the
WebPart1UserControl.ascx editing window. Position the cursor after the
code:
<asp:ListView ID="ListView1" runat="server">
| 28. | Then paste in the following code, and the results will look like Figure 10. Be sure to modify the href so that the sharepointservernameandsitename portion of the code refers to the test site collection and site in the code below before pasting:
<LayoutTemplate> <asp:PlaceHolder runat="server" ID="itemPlaceholder"></asp:PlaceHolder> </LayoutTemplate> <ItemTemplate> <div style="width:100%;float:left"> <a href="http://sharepointservernameandsitename/lists/announcements/DispForm.aspx?id=<%#Eval( "ID")%>"><%#Eval("Title")%></a> <br /> <img src="<%#((String)Eval("Picture")).Substring(0,((String)Eval("Picture")). IndexOf(" ")-1)%>"style="width:160px; height:120px; padding:3px" align="left" alt=""> <%#Eval("Body")%> </div> </ItemTemplate> <ItemSeparatorTemplate> <hr /> </ItemSeparatorTemplate>
Note
Adding the ListView component using the Design view enables Visual Studio 2010 to update the import and tag prefixes as needed.
Note
Using the Eval()
statement with LINQ objects provides a relatively easy way to insert
code directly into the web part; however, in some cases, the result of
the Eval() statement needs to be modified. The code inside the <img tag demonstrates the use of standard .NET string operations against the results of an Eval() statement.
| 29. | In
the Solution Explorer, click the plus button next to the
VisualWebPart1UserControl.ascx; a child file appears named
VisualWebPart1UserControl.ascx.cs. Double-click this file and paste the
following code within the Page_Load method (between the brackets under
the line that starts with “protected void”). Make sure to update sharepointservernameandsitename with the appropriate site name, as done previously. Figure 11 shows the results, with the new lines of code highlighted:
EventLinqDataContext dsEvent = new EventLinqDataContext("http://sharepointservernameandsitename"); ListView1.DataSource = dsEvent.Announcements.GetEnumerator(); ListView1.DataBind();
| 30. | Click the Save button to save the work done so far.
| 31. | To debug the solution, click the Debug menu, and choose Start Debugging or simply click F5.
| 32. | Again,
a browser opens to the site home page. If the web part doesn’t display,
edit the page as done before, and add the Event Web Part to a zone on
the page. Figure 12 shows a sample result.
| 33. | Close the browser and return to Visual Studio where the debugging process completes.
|
Although the results may
not appear to be earth shattering, this web part is quite different from
a normal list view web part, an example of which is shown in Figure 13.
In this regular list view, note that the image has not been resized,
which was accomplished in the WebPart1UserControl.ascx code. Of course, a
contributor to the images library could simply go in and resize the
image, but that gets time-consuming. Also note that in Figure 12,
the column headers are not included, making the web part more
esthetically pleasing. This is a common request and an example of making
a page look “less SharePointy.”
Packaging a Visual Web Part
This section assumes that the previous section was completed successfully and the web part displays, as shown in Figure 29.23
(with the exception that most likely a different image displayed). To
deploy the solution to a staging or production machine, follow these
steps:
1. | With
the SharePoint 2010 solution open in Visual Studio 2010, access the
Solution Configuration drop-down menu on the Standard toolbar, as shown
in Figure 14,
visible just beneath the top menu bar, and change the configuration to
Release. The next time the project is built, Visual Studio 2010
generates each project’s binaries (DLLs) without the debug symbols,
making them optimized for deployment to production environments.
| 2. | Next, rebuild the solution by clicking the Build menu and choosing Rebuild Solution.
| 3. | Open the Solution Explorer and right mouse key on the project name, and choose Package, as shown in Figure 15.
Packaging the solution creates a SharePoint solution file with the
familiar .wsp extension. The solution file is a compressed cab file that
contains the web part’s DLL, its visual components, and a manifest.
| 4. | After
packaging the project, a solution file with the .wsp extension appears
in the project’s bin/release directory. To locate this directory, open
Windows Explorer from the Start menu, and navigate to \Documents\Visual
Studio 2010\Projects\ EventWebPart\EventWebPart\bin\Release. Within the
release directory, the .wsp file should appear, as shown in Figure 1.
| 5. | On the Start menu, click All Programs, Microsoft SharePoint 2010 Products, and SharePoint 2010 Management Shell.
| 6. | At the Windows PowerShell command prompt, type the following command, where <SolutionPath> is replaced by the full path to the .wsp file, including the .wsp filename, as shown in the top part of Figure 17, and press Enter:
Add-SPSolution -LiteralPath <SolutionPath>
| 7. | The
PowerShell screen should then show the name of the solution, the
SolutionID, and the Deployed state, which is false at this point.
| 8. | Next,
navigate to the Central Administrator site; click System Settings. In
the Farm Management section, click Manage Farm Solutions.
| 9. | On the Solution Management page, click the solution eventwebpart.asp.
| 10. | On the Solution Properties page, click Deploy Solution, as shown in Figure 18.
| 11. | On the Deploy Solution page, in the Deploy When section, leave the Now option selected.
| 12. | In the Deploy To section, select a specific web application. In this example, http://abcsp1004 is selected. Click OK.
|
The web part should now be
available to add to the test site (http://abcsp1004/sites/test), as it
was during the debugging process.
|