Archive

Archive for the ‘Visual Studio 2010’ Category

Walkthrough 5: Creating and Using External Lists in SharePoint 2010

Exercise Duration: 15 minutes

Exercise Overview 

This example illustrates how to create a Business Connectivity Services (BCS) with an external content type using Visual Studio and utilize this content type in a SharePoint external list.

Feature Overview

An external list is a list based on data from an external system outside of SharePoint such as a CRM system or relational database. 

Task 1: Create a new Business Data Catalog Model project.

1. Open Visual Studio 2010 from the Start | Programs | Visual Studio 2010 menu.

2. Create a new project by using File | New Project.

3. Pick the SharePoint | 2010 templates.

4. From the SharePoint | 2010 templates select the Business Data Connectivity Model template.

5. Use BCSExample as the name.

6. Set the location to be C:\SPHOLs.

7. Press OK to create the project.  

image

 

8. On the SharePoint Customization Wizard dialog, type the address of the site you want to deploy to, and select to deploy this as a farm solution.

9. Click Finish to proceed.

 

image

 

Task 2: Extend the custom entity to allow updating. 

1. Click on the Entity1 | Methods area in the designer.

2. This brings up the BDC Method Details window for Entity1.

3. At the bottom of this window (you may need to scroll) find the Add a Method area.

4. Open the combo box on the Add a Method area and select Create Updater Method.

 

image

 

5. Select the newly created method called Update to retrieve the properties pane. Change Is Static = True.

 

image

Task 3: Add the code to store list data in an in memory collection.

1. Right click on Update and select View Code.

 

image

2. Add the following variable to the Entity1Service class;

 

static Dictionary<string, string> EntityCollection = new Dictionary<string, string>();

 

This variable will be used to hold the lists state information. A real world application would use a durable system such as a relational database instead.

3. Replace the existing method implementations with the following code: 

 

public Entity1Service()

{

    if (EntityCollection.Count == 0)

    {

        // Create some test list items.

        Entity1 e1 = new Entity1();

        e1.Identifier1 = "e1";

        e1.Message = "e1 Item Data";

        EntityCollection.Add(e1.Identifier1, e1.Message);

 

        Entity1 e2 = new Entity1();

        e2.Identifier1 = "e2";

        e2.Message = "e2 Item Data";

        EntityCollection.Add(e2.Identifier1, e2.Message);

    }

}

public static Entity1 GetEntityById(string id)

{

    // Looks up the Entity information based on the id passed

    Entity1 entity1 = new Entity1();

    entity1.Identifier1 = id;

    entity1.Message = EntityCollection[id];

    return entity1;

}

public static IEnumerable<Entity1> FindAllEntities()

{

    // Iterates through our backing  

    List<Entity1> entities = new List<Entity1>();

    foreach (String key in EntityCollection.Keys)

    {

        Entity1 entity1 = new Entity1();

        entity1.Identifier1 = key;

        entity1.Message = EntityCollection[key];

        entities.Add(entity1);

    }

    return entities;

}

 

public static void Update(Entity1 inParameter1)

{

    // Updates the corresponding item in the collection

    EntityCollection[inParameter1.Identifier1] = inParameter1.Message;

}

 

Task 4: Deploy and create an entity backed list based on this example.

1. Right click on the BusinessDataCatalog1 project and select deploy.

2. In the web browser click Site Actions -> View All Site Content -> Create.

3. Beneath Custom Lists click External List.

 

image

4. Specify CustomList as the name of the new list. Beneath Entity Type click the browse icon. Select the newly created Business Data Type in the list and click OK.

 

image

The list will render the sample list items we added in the entity’s constructor.

image

Selecting an item and pressing edit allows changing of the field which in turn calls the Update method we defined in the custom entity.

 

image

Exercise Summary

In this walkthrough you built an External Content Type in Visual Studio and deployed it to SharePoint 2010 for use in an External List. 

February 10th, 2010 Neal McFee No comments

Walkthrough 4: Accessing List Data using the JavaScript Client OM

 

Exercise Duration: 30 minutes

Exercise Overview 

This example illustrates how to use the ECMAScript client side object model to update and read list data dynamically. Also shown is how to use the new Dialog API’s from client side script.

Feature Overview

The JavaScript client side object model allows JavaScript developers access to SharePoint objects such as Site, Web and List (and more) from client side JavaScript. 

Task 1: Create a new Empty Project and add a web part. 

1. Open Visual Studio 2010 from the Start | Programs | Visual Studio 2010 menu.

2. Create a new project by using File | New Project.

3. Pick the SharePoint | 2010 templates.

4. From the SharePoint | 2010 templates select the Visual Web Part template.

5. Use ScriptOMExample as the name.

6. Set the location to be C:\SPHOLs.

7. Press OK to create the project.  

 

image

8. On the SharePoint Customization Wizard dialog, type the address of the site you want to deploy to, and select to deploy this as a farm solution.

9. Click Finish to proceed.

image

  

10. In the Solution Explorer expand the VisualWebPart1 item, and open VisualWebPart1.webpart by double-clicking on it.

a. Set the value of title element to: ScriptOMPart Title

b. Set the value of description element to: ScriptOMPart Description

 

image

Task 2: Add scripting code to access and render SharePoint list data.

1. In the Solution Explorer, open the VisualWebPart1Control.ascx by double-clicking on it.  Add the following the following markup code at the bottom of the file.

 

<SharePoint:ScriptLink ID="ScriptLink1" runat="server" Name="sp.js" Localizable="false" LoadAfterUI="true" />  

 

<script language="ecmascript" type="text/ecmascript">

 

</script>

 

2. Add the following JavaScript code within the Script block (before the closing </script> tag).

 

 

This code declares important variables our code will use later on and adds our Initialize() function to be called after all of the SharePoint client side objects have loaded.

/* SharePoint list names */

var ContactsListName = "Contacts List";

var CompanyListName = "Company List";

 

/* SharePoint list field names */

var CompanyNameField = "Title";

var CompanyPhoneField = "Company_x0020_Phone_x0020_Number";

var CompanyDescriptionField = "Company_x0020_Description";

var ContactFirstNameField = "First_x0020_Name";

var ContactTitleField = "Title";

var ContactLastNameField = "Last_x0020_Name";

var ContactEmailField = "E_x002d_Mail";

var ContactCompanyListField = "Company_x0020_List";

 

/* List objects */

var contactsList;

var companyList;

 

/* variable to hold list items from the contactsList */

var contacts;

 

/* client context object – used to access SharePoint data */

var context;

 

/* web (SPWeb) that our page is running on */

var web;

 

/* variable to hold modalDialog to close later */

var modalDialog;

 

/* used when creating a new contactListItem 

need to reference the Id field for setting the fieldLookupValue. */

var companyListItem;

 

var copyOfAddCompanyForm;

 

/* our startup method when the page loads */

_spBodyOnLoadFunctionNames.push("Initialize()");

 

3. Add the following JavaScript code within the Script block below the previous code.

 

 

Our Initialize() function retrieves the SharePoint ClientContext object and loads up the contacts list, company list and initializes contacts (Contacts list items).

/* Initialize useful variables and retrieve ClientContext */

function Initialize() {

 

    /* Retrieves the current ClientContext object */

    context = SP.ClientContext.get_current();

    web = context.get_web();

 

    // Get references to the lists we will use

    contactsList = web.get_lists().getByTitle(ContactsListName);

    companyList = web.get_lists().getByTitle(CompanyListName);

 

    // Get the list items for the contacts list 

    contacts = contactsList.getItems();

 

    // context.load tells the object model to load the objects scalar 

    // properties. Otherwise they will not be accessible 

 

    context.load(contacts);

    context.load(contactsList);

    context.executeQueryAsync(onListsLoaded);

}

 

4. Add the following JavaScript code within the Script block below the previous code.

 

 

The onListsLoaded() event is called asynchronously from the Initialize() function.

/* Event handler called loading the contacts and companies lists

This method dynamically renders an HTML table to display the list data */

function onListsLoaded() {

    var contactCount = contactsList.get_itemCount();

    var companyTable = document.getElementById("tblCompanyList");

    // clear out the table so when we add a new company there are not duplicates

    while (companyTable.rows.length > 0)

        companyTable.deleteRow(companyTable.rows.length – 1);

    var row = new Array();

    var content;

    var cell;

    var tbo = document.createElement(‘tbody’);

    // Loop for each contact

    for (contactIndex = 0; contactIndex < contactCount; contactIndex++) {

        // For each contact create a row in the table

        row[contactIndex] = document.createElement(‘tr’);

        // itemAt() retrieves the listitem

        var contactLI = contacts.itemAt(contactIndex);

        // get_item() retrieves the listitem value 

        // if the listitem value is from a lookup field we call get_lookupValue() 

        var companyName = 

        contactLI.get_item(ContactCompanyListField).get_lookupValue();

        var companyPhone = contactLI.get_item(CompanyPhoneField).get_lookupValue();

        var companyDesc = 

        contactLI.get_item(CompanyDescriptionField).get_lookupValue();

        var companyContact = contactLI.get_item(ContactFirstNameField) + " " + 

        contactLI.get_item(ContactLastNameField);

        var companyContactEmail = contactLI.get_item(ContactEmailField);

        // add the cells for the row

        cell = document.createElement(‘td’);

        content = document.createTextNode(companyName);

        cell.appendChild(content);

        row[contactIndex].appendChild(cell);

        cell = document.createElement(‘td’);

        content = document.createTextNode(companyPhone);

        cell.appendChild(content);

        row[contactIndex].appendChild(cell);

        cell = document.createElement(‘td’);

        content = document.createTextNode(companyDesc);

        cell.appendChild(content);

        row[contactIndex].appendChild(cell);

        cell = document.createElement(‘td’);

        content = document.createTextNode(companyContact);

        cell.appendChild(content);

        row[contactIndex].appendChild(cell);

        cell = document.createElement(‘td’);

        content = document.createTextNode(companyContactEmail);

        cell.appendChild(content);

        row[contactIndex].appendChild(cell);

        // Add the row to the table body

        tbo.appendChild(row[contactIndex]);

    }

    // add the table body to the table

    companyTable.appendChild(tbo);

}

 

5. Add the following JavaScript code within the Script block below the previous code.

 

 

The ShowAddCompany() function finds the divAddCompanyElement (which we’ll add later) and displays it using the ModalDialog.showModalDialog() method.

/* Hide the modal dialog and display the updated UI */

function onContactAdded() {

    HideAddCompany();

}

 

/* Show a modalDialog with the contents of divAddCompany */

function ShowAddCompany() {

    var divAddCompany = document.getElementById("divAddCompany");

 

    // showModalDialog removes the element passed in from the DOM

    // so we save a copy and add it back later

    copyOfAddCompanyForm = divAddCompany.cloneNode(true);

 

    divAddCompany.style.display = "block";

    var options = { html: divAddCompany, width: 200, height: 350, dialogReturnValueCallback: ReAddClonedForm };

    modalDialog = SP.UI.ModalDialog.showModalDialog(options);

}

 

/* Close the modalDialog */

function HideAddCompany() {

    modalDialog.close();

    Initialize();

}

 

function ReAddClonedForm() {

    document.body.appendChild(copyOfAddCompanyForm);

}

 

6. Add the following JavaScript code within the Script block below the previous code.

 

 

The AddCompany() function creates a new list item in the  Company List.

/* Called from the Add Company modal dialog 

Creates a list item in the Company List list and when that query is executed

onCompanyAdded creates the contact list item. */

function AddCompany() {

    var lici1 = new SP.ListItemCreationInformation();

    companyListItem = companyList.addItem(lici1);

    companyListItem.set_item(CompanyNameField, getTBValue("txtCompanyName"));

    companyListItem.set_item(CompanyPhoneField, getTBValue("txtPhoneNumber"));

    companyListItem.set_item(CompanyDescriptionField, getTBValue("txtDescription"));

    companyListItem.update();

    context.load(companyListItem);

    // Execute the query to create the company list

    // onCompanyAdded is our call back method called when the call to the server has completed

    context.executeQuery(onCompanyAdded, OnError);

}

 

7. Add the following JavaScript code within the Script block below the previous code.

 

When the company list item is created we then create the lookup fields for the associated contacts. In the onContactAdded event handler the modal dialog is hidden.

/* Called when AddCompany has finished executing 

Note we have to wait until completion because we need access to companyListItem

to set the correct lookupId */

function onCompanyAdded(args) {

    var lici = new SP.ListItemCreationInformation();

    var companyLookupField = new SP.FieldLookupValue();

    companyLookupField.set_lookupId(companyListItem.get_id());

    var contactListItem = contactsList.addItem(lici);

    contactListItem.set_item(ContactTitleField, getTBValue("txtContactTitle"));

    contactListItem.set_item(ContactFirstNameField, getTBValue("txtFirstName"));

    contactListItem.set_item(ContactLastNameField, getTBValue("txtLastName"));

    contactListItem.set_item(ContactEmailField, getTBValue("txtEMail"));

    contactListItem.set_item(ContactCompanyListField, companyLookupField);

    contactListItem.update();

    context.executeQuery(onContactAdded);

}

/* Hide the modal dialog and display the updated UI */

function onContactAdded() {

    HideAddCompany();

}

 

8. Add the following JavaScript code within the Script block below the previous code.

 

Helper functions / Error handler

/* Error handler */

function OnError(sender, args) {

  var spnError = document.getElementById("spnError");

  spnError.innerHTML = args.get_message();

}

/* Helper function – shortcut to the value property of a textbox */

function getTBValue(elID) {

    var el = document.getElementById(elID);

    return el.value;

}

 

9. Add the following HTML code below the ending script block tag (</script>)

 

tblCompanyList is an empty table that our script dynamically adds rows/columns to for each contact/company. 

There is also a link to invoke ShowAddCompany() which will launch a modal dialog box.

<div style="font-weight: bold">Company List</div>

<br />

<table id="tblCompanyList" style="border: solid 1px silver">

    

</table>

<br />

<a href="javascript:ShowAddCompany()">Add a company</a>

<br /> 

 

 

<div id="divAddCompany" style="display: none; padding: 5px">

   <b>Company Information</b><br /><br />

 

    Name <br />

    <input type="text" id="txtCompanyName" /><br />

    Phone Number<br />

    <input type="text" id="txtPhoneNumber" /><br />

    Description<br />

    <input type="text" id="txtDescription" /><br />

    <b>Contact Information</b><br /><br />

    Title<br />

    <input type="text" id="txtContactTitle" /><br />

    First Name<br />

    <input type="text" id="txtFirstName" /><br />

    Last Name<br />

    <input type="text" id="txtLastName" /><br />

    E-Mail<br />

    <input type="text" id="txtEMail" /><br />

    <span id="spnError" style="color: Red" /><br />

    <input type="button" value="Add New Company" onclick="AddCompany()" />

</div>

The markup within divAddCompany will be displayed in a modal dialog that allows the user to input data to create a new company/contact. 

Task 3: Deploy and test the web part.

1. Right click on the ScriptOMExample project in the Solution Explorer and select Deploy. 

2. Add the web part to a web part page:

Click the Edit button to put the page in edit mode. 

Click Insert

Click Web Part

Click Custom

Click ScriptOMPart Title

Click Add 

 

image

 

The rendered web part looks like this:

 

image

3. To test the functionality of the web part click the Add a company link and fill out the modal form.

image

 

4. Click the Add New Company button and the new company will be added to the list dynamically with no post backs.

 

image

 

Exercise Summary

In this walkthrough you built a Visual Web Part that contains ECMAScript that uses the SharePoint Client Object Model and the SharePoint Dialog Platform to show a model dialog which gathers input for a new list item instance.

  

February 10th, 2010 Neal McFee No comments

Walkthrough 3: SharePoint Designer Workflows imported to Visual Studio 2010

 

Exercise Duration : 20 minutes

Exercise Overview

This exercise shows how to create a custom workflow activity used by a SharePoint Designer reusable workflow and deploy them together as a single *.WSP. It also shows how to import that whole workflow model into Visual Studio 2010.

Feature Overview 

SharePoint Designer allows creating a workflow that is reusable across multiple lists and multiple sites. The workflow can be exported as a SharePoint Solution File (*.WSP). 

Task 1: Create and Prepare Project 

1. Open Visual Studio 2010 from the Start | Programs | Visual Studio 2010 menu.

2. Create a new project by using File | New Project.

3. Pick the SharePoint | 2010 templates.

4. From the SharePoint | 2010 templates select the Empty Project template.

5. Use SPDWorkflowDemo as the name.

6. Set the location to be C:\SPHOLs.

7. Press OK to create the project.

image

 

 

8. When the SharePoint Customization Wizard dialog appears, select Deploy as a farm solution, and press Finish.

 

image

Task 2: Create a new Workflow Activity for use by the Reusable Workflow

1. Right-click on the SPDWorkflowDemo solution in the Solution Explorer and select Add | New Project.

2. Under the Visual C# | Workflow project templates, select  the Workflow Activity Library template.   

3. Name the project SPDActivityDemo and press OK to add the project to the SPDWorkflowDemo solution. 

 

image

4. Right-click on the SPActivityDemo project in the Solution Explorer and select Add Reference.

5. Under the .Browse tab, browse to C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\14\ISAPI  and select both Microsoft.SharePoint.dll and Microsoft.SharePoint.WorkflowActions.dll.

6. Press OK to add these two references to the SPDActivityDemo project.

7. Right-click on the Activity1.cs (under the SPActivityDemo project in the Solution Explorer) and select rename.

8. Rename the file CreateDocumentLibrary.cs.

9. Select Yes when the Microsoft Visual Studio dialog appears to allow Visual Studio to re-factor the code.

 

 

Task 3: Add code to create a document library based on parameters passed to our activity.

 

1. Right-click on the CreateDocumentLibrary.cs activity and select View Code.

2. Change the CreateDocumentLibrary base class from SeqeuenceActivity to : Activity

 

public partial class CreateDocumentLibrary: Activity

 

3. Add the following using statements to the activity:

 

using Microsoft.SharePoint;

using Microsoft.SharePoint.Workflow;

using Microsoft.SharePoint.WorkflowActions;

 

4. Add a new DependencyProperty to the CreateDocumentLibrary class named UrlProperty of type string. (Hint – type wdp inside of the class definition and then tab twice – this will create the DependencyProperty using the built-in Workflow Dependency Property snippet)

This will be the location where the document library will be created.

 

public static DependencyProperty UrlProperty = DependencyProperty.Register("Url", typeof(string), typeof(CreateDocumentLibrary));

[DescriptionAttribute("Url of base site")]

[CategoryAttribute("Input Property")]

[BrowsableAttribute(true)]

[DesignerSerializationVisibilityAttribute(DesignerSerializationVisibility.Visible)]

[ValidationOption(ValidationOption.Required)]

public string Url

{

    get

    {

        return ((string)(base.GetValue(CreateDocumentLibrary.UrlProperty)));

    }

    set

    {

        base.SetValue(CreateDocumentLibrary.UrlProperty, value);

    }

}

 

5. Add a new DependencyProperty  of type string to the activity named DocLibNameProperty.

This will be the name of the document library created by the activity.

 

 

public static DependencyProperty DocLibNameProperty = DependencyProperty.Register("DocLibName", typeof(string), typeof(CreateDocumentLibrary));

[DescriptionAttribute("Used as doc lib name")]

[CategoryAttribute("Input Property")]

[BrowsableAttribute(true)]

[DesignerSerializationVisibilityAttribute(DesignerSerializationVisibility.Visible)]

[ValidationOption(ValidationOption.Required)]

public string DocLibName

{

    get

    {

        return ((string)(base.GetValue(CreateDocumentLibrary.DocLibNameProperty)));

    }

    set

    {

        base.SetValue(CreateDocumentLibrary.DocLibNameProperty, value);

    }

}

 

6. Add the following code inside of the CreateDocumentLibrary class:

 

protected override ActivityExecutionStatus Execute(ActivityExecutionContext executionContext)

{

    CreateDocLib();

    return ActivityExecutionStatus.Closed;

}

 

private void CreateDocLib()

{

    using (SPSite sps = new SPSite(Url))

    {

        using (SPWeb spw = sps.RootWeb)

        {

            Guid ID = spw.Lists.Add(DocLibName, DocLibName + " Document Library", SPListTemplateType.DocumentLibrary);

            SPList spdl = spw.Lists[ID];

            spdl.OnQuickLaunch = true;

            spdl.Update();

        }

    }

}

 

Task 4: Configure activity for deployment.

 

1. To deploy the assembly to the GAC with your SharePoint project you need to configure the project to have a strong-name.

2. Right-click on the SPActivityDemo project and select Properties.

3. Click on the Signing tab in the properties page.

4. Select New under the Choose a strong name key file text from the combo box.

5. Type key as the Key file name value, uncheck Protect my key file with a password and press OK.

 

image

6. Build your project (CTRL-SHIFT-B or use Build | Build Solution) and fix any errors.

7. Right click on the SPDWorkflowDemo project and click Add | SharePoint Mapped Folder.

image

8. Browse to Template\1033\Workflow and select OK to add the mapped folder to the SPWorkflowDemo

9. Right-click on the  SPDWorkflowDemo folder in the Solution Explorer (under the Workflow folder).  

10. Right-click on the Workflow folder and select Add | New Item.

11. Select XML File from the list of Installed Templates, name the file SPDActivityDemo.ACTIONS¸ and select OK to add the file.

image

 

12. Replace the contents of SPDActivityDemo.ACTIONS with the following XML

 

<WorkflowInfo>

  <Actions Sequential="then" Parallel="and">

    <Action Name="Create Document Library"

  ClassName="SPDActivityDemo.CreateDocumentLibrary"

  Assembly="SPDActivityDemo, Version=1.0.0.0, Culture=neutral, PublicKeyToken=1a4a7a2c3215a71b"

  AppliesTo="all"

  Category="Labs">

      <RuleDesigner Sentence="Document Library Name %1 to site %2.">

        <FieldBind Field="DocLibName" Text="Document Library Name"  

           DesignerType="TextArea" Id="1"/>

        <FieldBind Field="Url" Text="Url of base site" Id="2" 

           DesignerType="TextArea"/>

      </RuleDesigner>

      <Parameters>

        <Parameter Name="DocLibName" Type="System.String, mscorlib" 

      Direction="In" />

        <Parameter Name="Url" Type="System.String, mscorlib" 

      Direction="In" />

      </Parameters>

    </Action>

  </Actions>

</WorkflowInfo>

10. IMPORTANT – Update the PublicKeyToken within the .ACTIONS file with the public key token from SPDActivityDemo.dll. Do not use the PublicKeyToken in this example. Ensure you generate your own. 

11. To find the PublicKeyToken start a Visual Studio 2010 Command Prompt from the Start | All Programs | Visual Studio 2010 | Visual Studio Tools |Visual Studio Command Prompt (2010) menu

12. Type the following command:

 

sn -tc:\SPHOLS\SPDWorkflowDemo\SPDActivityDemo\bin\Debug\SPDActivityDemo.dll | clip

13. In the of SPDActivityDemo.ACTIONS file highlight the value of the PublicKeyToken ("1a4a7a2c3215a71b") and paste (CTRL-V).

14. Remove all the pasted text except the value of your public key.  Make sure there are no extra spaces or line feed characters after the public key token (the quote needs to be next to the value of the public key token).

15. Highlight the whole value of the Assembly attribute and copy that value to the clipboard (CTRL-C).

 

 

Task 5: Add the SPDActivityDemo activity to be deployed with SPDWorkflowDemo.

1. In the Solution Explorer, under the SPDWorkflowDemo project, double-click on Package folder

2. In the Package designer click on Advanced (at the bottom of the designer in the middle pane).

3. Click on the Add button.

4. Click on the ellipses button in the Add Custom Assembly dialog.  Browse to the SPDActivityDemo.dll file (C:\SPHOLS\SPDWorkflowDemo\SPDActivityDemo\bin\debug).

5. Within Safe Controls add the following:

 

Assembly Name: SPDActivityDemo, Version=1.0.0.0, Culture=neutral, PublicKeyToken=YOURPUBLICKEY – ensure you use a Public Key Token you generated using the sn.exe utility. (Hint – you can paste the value you copied to the clipboard in the last step here).

Name Space: SPDActivityDemo

Safe: Checked

Type Name : *

6. Select OK to add the assembly as part of the SharePoint project deployment package.

 

image

 

Task 6: Configure a Feature using Feature Designer

1. Right-click on SPDWorkflowDemo project Features folder and select Add Feature.

2. Right-click on the Feature1 node and select Rename. Rename it to SPDWorkflowDemoFeature. 

3. In the Feature designer change the value of the Scope combo box to WebApplication.

4. Change the feature title to SPDWorkflowDemoFeature. 

 

image

Task 7: Add and code a Event Receiver for the Feature

1. Right-click on the SPDWorkflowDemoFeature in the Solution Explorer and select Add Event Receiver 

 

image

2. Add a using statement to the top of the code file that appears in the editor:

 

using Microsoft.SharePoint.Administration;

 

3. Add the following code to your FeatureReceiver class declaration: 

 

 

public override void FeatureActivated(SPFeatureReceiverProperties properties)

{

    SPWebApplication wappCurrent = (SPWebApplication)properties.Feature.Parent;

    SPWebConfigModification modAuthorizedType = new SPWebConfigModification();

    modAuthorizedType.Name = "AuthType";

    modAuthorizedType.Owner = "SPDActivityDemo";

    modAuthorizedType.Path = 

    "configuration/System.Workflow.ComponentModel.WorkflowCompiler/authorizedTypes";

    modAuthorizedType.Type =

    SPWebConfigModification.SPWebConfigModificationType.EnsureChildNode;

    modAuthorizedType.Value = @"<authorizedType Assembly=""SPDActivityDemo, 

    Version=1.0.0.0, Culture=neutral, PublicKeyToken=YOURPUBLICKEYTOKEN"" 

    Namespace=""SPDActivityDemo"" TypeName=""*"" Authorized=""True"" />";

    wappCurrent.WebConfigModifications.Add(modAuthorizedType);

    wappCurrent.WebService.ApplyWebConfigModifications();

}

 

4. Note: You will need to update the YOURPUBLICKEYTOKEN section in the above code with the correct key from the SPDActivityDemo.ACTIONS file.

5. Build and Deploy the SPDWorkflowDemo project by right-clicking on the SPDWorkflowDemo project in the Solution Explorer and select Deploy.

 

Task 8: Create a re-usable workflow using SharePoint Designer

1. Start SharePoint Designer 2010  from the start menu under All Programs | Microsoft Office | Microsoft SharePoint Designer 2010.

2. Click the Open Site button, and put in the address of the site you used to deploy the SPDWorkflowDemo project to as the Site Name.  Press Open twice. Once to open the site, the second to cause SharePoint Designer to open the site at the root level.  

 

image

 

3. Click on the Workflows node in the navigation pane on the left.

4. Click the Workflows tab in the ribbon.

5. Click the Reusable Workflow button in the Workflows ribbon.

image

 

6. Enter SPDWorkflow as the name of the workflow, and press OK to create the workflow.

 

image

 

7. Click the Workflow ribbon, then click Actions and scroll down to Labs and click Create a Document Library. Note: This is the activity you created in Visual Studio 2010 previously

image

 

8. Click the Fx button and select Current Item:Title as the document library name and type in http://servername as the Url of the base site. Click Save

image

 

9. Save the workflow (click the Save button or press CTRL-S).

10. Click the Workflows in the Navigation pane on the left again.

11. Highlight the SPDWorkflow in the right pane.

12. Click the Workflow Ribbon again.

13. Click Save as Template to save the .WSP file in the Site Assets Library SharePoint list.

image

 

14. Go back to Visual Studio 2010.

15. In the Server Explorer (if not visible, go to View | Server Explorer), expand SharePoint Connections 

16. Find your site. If your site isn’t visible, right-click on SharePoint Connections and select Add Connection.  Type in the URL of your site and press OK.

17. In your site, expand Lists and Libraries | Document Libraries

18. Right-click on Site Assets and select View in Browser.

 

image

 

19. Once the Site Assets library appears in the browser, click on the menu to the right of SPWorkflow.

20. Click Send To | Download a Copy

 

image

21. Save the SPDWorkflow.wsp file to the C:\SPHOLS directory.

 

Task 9: Import the reusable workflow into Visual Studio

1. Return to Visual Studio 2010.

2. Right-click on the SPDWorkflowDemo solution, and select Add | New Project.

3. From the SharePoint | 2010 project templates, pick the Import Reusable Workflow project template.

4. Name the project SPDWorkflowImport. 

5. Press OK.

6. On the SharePoint Customization Wizard dialog, make sure the site is the same as the site you deployed the SPDWorkflowDemo project to earlier.

7. Select Deploy as farm solution.

8. Press Next.

9. In the next dialog, browse to C:\SPHOLS and select SPDWorkflow.wsp as the template.

image

 

 

10. Click Next.

11. On the next dialog, press Finish.

12. Right-click on the SPDWorkflowImport project in the Solution Explorer and select Add Reference.

13. Select the Projects tab and select to reference the SPDActivityDemo project.  This is necessary because the newly imported workflow uses the custom activity from that project.

14. Double click on Package folder in the SPDWorkflowDemo project.

15. In the Package designer select the Converted workflows feature in the Items in the Solution pane

16. Click the add button ( > ) to move that feature to Items in the Package pane.  This will cause this feature to be deployed with the solution.

 

image

17. Right-click on the SPDWorkflowDemo project in the Solution Explorer and select Deploy.

 

Task 10: Associate the workflow with a list in SharePoint

1. Open the site you’ve deployed this project to (HINT – you can right-click on the site in the Server Explorer as a short-cut).

2. Create a new custom list named Customers. 

3. Configure the list workflow settings as follows:

 

image

4. Create a new customer list item with the Title of Contoso. A new document library of the same name should be created automatically.

image

 

Exercise Summary

In this walkthrough you built a new Workflow activity for use in SharePoint Designer workflows. You built a reusable workflow in SharePoint Designer and used the custom activity. You then imported that reusable workflow into Visual Studio 2010 and deployed the final workflow back into SharePoint.

  

February 10th, 2010 Neal McFee 3 comments

Walkthrough 2: Building a Web Part for a Sandboxed Solution

 

Exercise Duration: 20 minutes

Exercise Overview

This exercise demonstrates creating a web part that renders and updates list data that is deployed as a Sandboxed Solution.

Feature Overview  

A sandboxed solution can be deployed to a site by a site administrator, without requiring intervention from the farm administrator. The solution has full access to the immediate site and restricted access to system resources and other sites.

Task 1: Create Sandboxed Solution Project with a webpart.

1. Open Visual Studio 2010 from the Start | Programs | Visual Studio 2010 menu.

2. Create a new project by using File | New Project.

3. Pick the SharePoint | 2010 templates.

4. From the SharePoint | 2010 templates select the Empty Project project template.

5. Use SBSolutionDemo as the name.

6. Set the location to be C:\SPHOLs.

7. Press OK to create the project.

image

8. When the SharePoint Customization Wizard dialog appears, select the site you want to deploy the Web Part to.

9. Select the Deploy as a sandboxed solution radio button

10. .Press the Finish button to complete the project creation process.

image

 

11. Right-click on the SBSolutionDemo project in the Solution Explorer and choose Add | New Item.

12. Select the Web Part (not the Visual Web Part) template from the SharePoint | 2010 templates in the Add New Item dialog.  Name it SBWebPart.  

image

13. Press OK to close the dialog and add the item to the project.

 

Task 2: Add code to provide querying and rendering functionality.

1. In the Solution Explorer, double-click on the SBWebPart.cs file to open it in the editor window.

2. Add the following using statement after the other using statements.

 

 

using System.Web.UI.HtmlControls;

 

3. Add the following variables to the class declaration.

 

DropDownList _ddlProjects = new DropDownList();

TextBox _tbDescription = new TextBox();

TextBox _tbDueDate = new TextBox();

 

4. Add the following new methods within the class declaration.

 

protected override void OnLoad(EventArgs e)

{

    base.OnLoad(e);

    if (!Page.IsPostBack)

        GetProjectDetails();

}

 

/* Populate the text boxes with the selected project details */

private void GetProjectDetails()

{

    EnsureChildControls();

    if (_ddlProjects.SelectedValue != "– Select a Project –")

    {

        SPList pList = SPContext.Current.Web.Lists["Projects"];

        int nProjectID = Convert.ToInt32(_ddlProjects.SelectedValue);

        SPListItem spliProject = pList.GetItemById(nProjectID);

        _tbDescription.Text = spliProject["Description"].ToString();

        DateTime dueDate = Convert.ToDateTime(spliProject["Due_x0020_Date"]);

        _tbDueDate.Text = dueDate.ToShortDateString();

    }

    else

    {

        _tbDescription.Text = String.Empty;

        _tbDueDate.Text = String.Empty;

    }

}

 

5. Add the following CreateChildControls implementation beneath the previous code (replace the existing CreateChildControls method).

 

/* Build the UI and setup events */

protected override void CreateChildControls()

{

    base.CreateChildControls();

    Panel parent = new Panel();

    parent.Style.Add("border", "solid 1px Navy");

    parent.Style.Add("background-color", "#EEEEEE");

    parent.Style.Add("width", "250px");

    _ddlProjects.ID = "ddlProjects";

    _ddlProjects.AutoPostBack = true;

    _ddlProjects.SelectedIndexChanged += new 

    EventHandler(ddlProjects_SelectedIndexChanged);  

    PopulateProjects();

    parent.Controls.Add(_ddlProjects);

 

    Panel panel = new Panel();

    Label label = new Label();

    label.Text = "Description";

    panel.Controls.Add(label);

    parent.Controls.Add(panel);

    panel = new Panel();

    panel.Controls.Add(_tbDescription);

    parent.Controls.Add(panel);

 

    label = new Label();

    label.Text = "Due Date";

    panel = new Panel();

    panel.Controls.Add(label);

    parent.Controls.Add(panel);

 

    panel = new Panel();

    panel.Controls.Add(_tbDueDate);

    parent.Controls.Add(panel);

 

    panel = new Panel();

    Button bUpdateProject = new Button();

    bUpdateProject.Text = "Update Project";

    bUpdateProject.Click += new EventHandler(bUpdateProject_Click);

    panel.Controls.Add(bUpdateProject);

    parent.Controls.Add(panel);

    Controls.Add(parent);

}

 

6. Add the following code beneath the CreateChildControls method:

 

 

/* Populate the projects drop down */ 

private void PopulateProjects()

{

    SPList splProjects = SPContext.Current.Web.Lists["Projects"];

    _ddlProjects.Items.Add("– Select a Project –");

    foreach (SPListItem spli in splProjects.Items)

    {

        _ddlProjects.Items.Add(new ListItem(spli.Title, spli.ID.ToString()));

    }

}

 

7. Add the following event handling code beneath the PopulateProjects method:

 

 

/* Change projects handler */

void ddlProjects_SelectedIndexChanged(object sender, EventArgs e)

{

    GetProjectDetails();

}

 

/* Update the current project */

void bUpdateProject_Click(object sender, EventArgs e)

{

    EnsureChildControls();

    int nProjectID = Convert.ToInt32(_ddlProjects.SelectedValue);

    SPListItem spliProject = 

    SPContext.Current.Web.Lists["Projects"].GetItemById(nProjectID);

    spliProject["Description"] = _tbDescription.Text;

    spliProject["Due_x0020_Date"] = _tbDueDate.Text;

    spliProject.Update();

}

 

Task 3: Build and Deploy the Sandboxed Solution.

1. Right-click on your project in the Solution Explorer and select Deploy. 

2. Browse to your server. Click Site Actions | Site Settings  .  Then click on  Solutions (under Galleries), you will see your sandboxed solution deployed and activated. 

 

image

 

3. Add the webpart to a webpart page.

Click the Edit button to put the page in edit mode. 

Click Insert

Click Web Part

Click Miscellaneous

Click the SBWebPart Title

Click Add 

 

image

 

4. Now you will see the web part running in the Sandboxed Solution. Click the drop down to select a project. The description and due date fields are both updatable.

 

image

 

Exercise Summary

In this walkthrough you built and deployed a Web Part that runs in the context of a Sandboxed Solution.

  

February 10th, 2010 Neal McFee No comments

Walkthrough 1: Using LINQ to SharePoint from within a Visual web part

Exercise Duration: 10 minutes

Exercise Overview

This example demonstrates how to use the SharePoint LINQ provider to read data from a SharePoint list and render the data using the SPGrid web control. It shows these created in the Visual Web Part designer in Visual Studio 2010.

Task 1: Create a new Empty Project and add a Visual Web Part

1. Open Visual Studio 2010 from the Start | Programs | Visual Studio 2010 menu.

2. Create a new project by using File | New Project.

3. Pick the SharePoint | 2010 templates.

4. From the SharePoint | 2010 templates select the Visual Web Part project template.

5. Use SPLinqSolutionDemo as the name of the project.

6. Use C:\SPHOLs as the location.

7. Press OK to create the project.

image

 

8. When the SharePoint Customization Wizard dialog appears, select the site you want to deploy the Web Part to. Click the Finish button to complete the project creation process.

image

 

9. Within Solution Explorer expand VisualWebPart1 and open VisualWebPart1.webpart.

a. Set the title element to: SPLinqDemoPart Title

b. Set the description element to: SPLinqDemoPart Description

image

 

Task 2: Generate LINQ to SharePoint proxy class to access list data.

1. Start a Visual Studio 2010 Command Prompt from the Start | All Programs | Visual Studio 2010 | Visual Studio Tools |Visual Studio Command Prompt (2010) menu

2. Change the directory to C:\SPHOLS\SPLinqSolutionDemo  

cd C:\SPHOLS\SPLinqSolutionDemo

3. spmetal.exe is a command line tool that can generate C# or VB.NET classes from a SharePoint site’s list definitions. It is similar to wsdl.exe that generates a proxy from a Web Service’s WSDL file. 

4. Run the following command to generate the LINQ proxy code.

spmetal /web:http://<YourServerName> /namespace:Projects /code:Projects.cs

5. Go back to Visual Studio 2010.

6. Right-click on the SPLinqSolutionDemo project in the Solution Explorer and select Add | Existing Item.

7. Browse to C:\SPHOLS\SPLinqSolutionDemo and select the Project.cs file that was generated when you ran spmetal.

8. Right-click on the SPLinqSolutionDemo in the Solution Explorer and select Add Reference.

 

9. Click on the Browse tab, navigate to the C:\Program Files\Common Files\Microsoft Shared\Web Server Extension\14\ISAPI folder, and select Microsoft.SharePoint.Linq.dll and select OK.

 

image

  

Task 3: Write the code for the Visual WebPart User to access the list data.

1. In Visual Studio 2010 open the SPLinqDemoPartUserControl.ascx file from the Solution Folder by double-clicking on it.

2. Add the following markup to SPLinqDemoPartUserControl.ascx under the <%@ Control… declaration

 

<%@ Import Namespace="Microsoft.SharePoint.WebControls" %>

 

<SharePoint:SPGridView id="spGridView" runat="server" AutoGenerateColumns="false">

  <HeaderStyle HorizontalAlign="Left" ForeColor="Navy" Font-Bold="true" />

  <Columns>

    <SharePoint:SPBoundField  DataField="Title" HeaderText="Title"></SharePoint:SPBoundField>

    <SharePoint:SPBoundField DataField="JobTitle" HeaderText="JobTitle"></SharePoint:SPBoundField>

    <SharePoint:SPBoundField DataField="ProjectTitle" HeaderText="ProjectTitle"></SharePoint:SPBoundField>

    <SharePoint:SPBoundField DataField="DueDate" HeaderText="DueDate"></SharePoint:SPBoundField>

  </Columns>

</SharePoint:SPGridView>

 

3. In the Solution Explorer, expand the carat icon next to the SPLinqDemoPartUserControl.asx, and then double-click on the SPLinqDemoPartUserControl.ascx.cs file to open it.

 

image

4. Add the following using statements to SPLinqDemoPartUserControl.ascx.cs  file after the existing using statements.

 

using System.Linq;

using Projects;

using Microsoft.SharePoint;

using Microsoft.SharePoint.Linq;

 

 

5. Add the following code to the SPLinqDemoPartUserControl.ascx.cs  file (replace the existing Page_Load method).

 

protected void Page_Load(object sender, EventArgs e)

{

    ProjectsDataContext dc = new

    ProjectsDataContext(SPContext.Current.Web.Url);

 

    EntityList<EmployeesItem> Employees = 

    dc.GetList<EmployeesItem>("Employees");

 

    var empQuery = from emp in Employees

                   where emp.Project.DueDate <                    DateTime.Now.AddMonths(6)

                   select new { emp.Title, emp.JobTitle, 

                   ProjectTitle = emp.Project.Title, 

                   DueDate =                    emp.Project.DueDate.Value.ToShortDateString() };

 

    spGridView.DataSource = empQuery;

    spGridView.DataBind();

}

 

Task 4: Deploy and Test the WebPart

1. Right click on your project and select Deploy. 

2. Add the web part to a web part page:

Click the Edit button to put the page in edit mode. 

Click Insert

Click Web Part

Click Custom

Click SPLinqDemoPart Title

Click Add 

 

image

The rendered web part will look like this.

image

Exercise Summary

In this walkthrough you built and deployed a Visual Web Part that uses LINQ to SharePoint to gather data from a SharePoint list.

  

February 10th, 2010 Neal McFee 1 comment