• Visual Studio SharePoint Development Blog

    Update Your Links - We’ve Moved!

    • 0 Comments

    To make it easy for developers to make sure they're getting all the latest technical information around developing SharePoint solutions, the SharePoint, Visual Studio and Office User Assistance teams have decided to combine their blogging efforts into the new SharePoint Developer Team Blog. Think of it as your one-stop shop for developer-centric SharePoint information, straight from the product teams and user assistance folk responsible for SharePoint Foundation, Server, SharePoint Online, and the SharePoint development tools in Visual Studio.

    Here's what you can expect from our new blog going forward:

    • Regular, detailed technical information on SharePoint development, such as walkthroughs and code samples, from the people who designed those product features and tools
    • Early, first-look versions of content being prepared for publication to MSDN
    • Cross-posts and pointers to SharePoint-centric developer content on other specialized blogs
    • Announcements of interest to SharePoint developers, such as content updates, service releases, or developer events.

    So we're hoping you'll subscribe, and pass the following easy-to-remember URL on to your SharePoint developer friends and colleagues:

    http://blogs.msdn.com/sharepointdev/

    And if there are particular things you'd like to see covered or discussed, by all means leave us a comment on our new consolidated blog!

  • Visual Studio SharePoint Development Blog

    Even More Resources for SharePoint Developers

    • 0 Comments

    Kemp first shared a lengthy list of SharePoint developer resources at http://blogs.msdn.com/b/vssharepointtoolsblog/archive/2010/08/12/resources-for-visual-studio-tools-for-sharepoint-developers.aspx. In addition to these, there are articles and videos that are published in the Technical Articles and Visual How Tos nodes. In addition to the documentation, technical articles, and visual how-tos, you can also read Book Excerpts and Quick Notes.

    Here is a list of recent visual how-to videos that demonstrate how to use the SharePoint developer tools in Visual Studio. Click on the screenshot to view the visual how-to.

    image     image

    image    image

     

    There are several more visual how-to articles and more posted each month, so be sure to check out the Technical Articles and Visual How Tos nodes regularly. Alternatively, you can visit the SharePoint Developer Center where there is an RSS feed called Recently Published Content, or even add the feed to your favorite RSS reader.

    Mary Lee, Programming Writer.

  • Visual Studio SharePoint Development Blog

    Check out the new SharePoint in Pictures blog

    • 0 Comments

    There is a new blog called SharePoint in Pictures that illustrates the platform and architecture of SharePoint Foundation 2010 and SharePoint Server 2010.  The blog is to be updated on a weekly basis with new diagrams, so feel free to check it out and leave feedback about what you’d like to see in the near future.

    Mary Lee, Programming Writer.

  • Visual Studio SharePoint Development Blog

    Resources for Visual Studio Tools for SharePoint Developers

    • 1 Comments

    Nearly all of the tools for SharePoint development included in Visual Studio 2010 are new, so learning about them and finding help and information can be a challenge. To help you in this quest, I’ve compiled a list of links to helpful resources, including product documentation, web sites, forums, and blogs. As new resources become available, I’ll add them to the list. If you know of any other sites you think others would find useful, feel free to add them to the comments and I’ll periodically update the list.

    Learning

    Blogs

    Forums and Newsgroups

    Other Resources

    Kemp Brown

  • Visual Studio SharePoint Development Blog

    Walkthrough of creating association between Sharepoint BDC entities using Visual Studio 2010

    • 3 Comments

    Up till now, we have published two blogs in this series about SharePoint 2010 external list, Walkthrough of creating a SharePoint 2010 external list using Visual Studio 2010 Beta and Walkthrough of enabling CRUD for SharePoint 2010 external lists using Visual Studio 2010. Now you are able to create external list and add basic CRUD functions. In this blog we will show how to create Association between Sharepoint BDC entities using Visual Studio 2010 and use Business Data Web Parts to display the data and the association in SharePoint page.

    The same as our second blog, we will use “Northwind” database as external data source, so if you do not have an existing “Northwind” database available, please download it here and install the sample database following the instruction of the installed package or our last blog here.

    If you have not read the first two blog entries, we recommend you read them before going through the following content, since this article is highly relevant with previous ones. The first several parts are very similar with the last blog, so they are simplified to only contain useful information. Please refer to the previous articles for any ambiguity.

    Create BDC Project

    First of all, let’s create a new C# BDC Model project and rename it “BdcAssociationSample.

    Connect to external data source

    Add a LINQ to SQL model and drag-and-drop both Customers and Orders tables of Northwind database from the Server Explorer. Right click on the LINQ to SQL item and click View Code, and insert the following code.

    C#:

    1 public partial class CustomersAndOrdersDataContext 2 { 3 private const string ConnectionString = @"Data Source=localhost\SQLEXPRESS;Initial Catalog=Northwind;Integrated Security=True;Pooling=False"; 4 5 public CustomerDataContext() : 6 base(ConnectionString, mappingSource) 7 { 8 OnCreated(); 9 } 10 }

    VB:

    1 Partial Public Class CustomersAndOrdersDataContext 2 Private Const ConnectionString As String = "Data Source=localhost\SQLEXPRESS;Initial Catalog=Northwind;Integrated Security=True;Pooling=False" 3 Public Sub New() 4 MyBase.New(ConnectionString, mappingSource) 5 OnCreated() 6 End Sub 7 End Class

    Design BDC Model

    Design the Customer and Order entities according to the LINQ to SQL model. To simply the problem, we only define Specific Finder method and Finder method for both of the entities.

    After this step, we get two entities as below.

    clip_image001

    The TypeDescriptors in BDC Explorer are like this:

    clip_image002clip_image003

    Add Association between Customer and Order

    Now we can create an association by selecting Association tool in the Visual Studio Toolbox, clicking the first entity Customer (called the source entity) and then clicking the second entity Order (called the destination entity). You can define the details of the association in the popped out Association Editor.

    By default, the Association Editor adds an Association Navigation method to the source and destination entities. An Association Navigation method in the source entity enables consumers to retrieve a list of destination entities. An Association Navigation method in the destination entity enables consumers to retrieve the source entity that relates to a destination entity.

    You can create two types of associations in the BDC designer: foreign key-based associations and foreign keyless associations. For detailed information, check out this on MSDN.

    Now we are creating a foreign key-based associations. So check Is Foreign Key Association checkbox and find ReadItem.order.Order.CustomerID in the left column of the Identifier Mapping gird, and then select CustomerID from the Source ID column on the right to map the identifier. Now the dialog looks like below:

    clip_image004

    Click OK to finish the association creation. On the design surface we get an association CustomerToOrderAssociation which connects two entities with a dotted line.

    clip_image005

    Add code behind to access external data source

    In Solution Explorer, find and open CustomerService.cs (.vb), and then replace the implementation with the following code snippet:

    C#:

    1 public static Customer ReadItem(string customerID) 2 { 3 CustomersAndOrdersDataContext context = new CustomersAndOrdersDataContext (); 4 Customer cust = context.Customers.Single(c => c.CustomerID == customerID); 5 6 return cust; 7 } 8 9 public static IEnumerable<Customer> ReadList() 10 { 11 CustomersAndOrdersDataContext context = new CustomersAndOrdersDataContext (); 12 IEnumerable<Customer> custList = context.Customers; 13 return custList; 14 } 15 16 public static IEnumerable<Order> CustomerToOrder(string customerID) 17 { 18 CustomersAndOrdersDataContext context = new CustomersAndOrdersDataContext(); 19 20 IEnumerable<Order> orderList = context.Orders.Where(o => o.CustomerID == customerID); 21 22 return orderList; 23 }

    VB:

    1 Public Shared Function ReadItem(ByVal customerID As String) As Customer 2 Dim context As New CustomersAndOrdersDataContext 3 4 Dim cust = (From c In context.Customers _ 5 Where c.CustomerID = customerID _ 6 Select c).Single() 7 Return cust 8 End Function 9 10 Public Shared Function ReadList() As IEnumerable(Of Customer) 11 Dim context As New CustomersAndOrdersDataContext 12 13 Return context.Customers 14 End Function 15 16 Public Shared Function CustomerToOrder(ByVal customerID As String) As IEnumerable(Of Order) 17 Dim context As New CustomersAndOrdersDataContext 18 19 Dim orderList = From o In context.Orders _ 20 Where o.CustomerID = customerID _ 21 Select o 22 Return orderList 23 End Function

    Then open and do the same for OrderService.cs (.vb).

    C#:

    1 public static Order ReadItem(int orderID) 2 { 3 CustomersAndOrdersDataContext context = new CustomersAndOrdersDataContext(); 4 5 Order order = context.Orders.Single(o => o.OrderID == orderID); 6 7 return order; 8 } 9 10 public static IEnumerable<Order> ReadList() 11 { 12 CustomersAndOrdersDataContext context = new CustomersAndOrdersDataContext(); 13 14 IEnumerable<Order> orderList = context.Orders; 15 16 return orderList; 17 } 18 19 public static IEnumerable<Customer> OrderToCustomer(int orderID) 20 { 21 CustomersAndOrdersDataContext context = new CustomersAndOrdersDataContext(); 22 23 string customerID = context.Orders.Single(o => o.OrderID == orderID).CustomerID; 24 25 IEnumerable<Customer> custList = context.Customers.Where(c => c.CustomerID == customerID); 26 27 return custList; 28 }

    VB:

    1 Public Shared Function ReadItem(ByVal orderID As Integer) As Order 2 Dim context As New CustomersAndOrdersDataContext 3 4 Dim order = (From o In context.Orders _ 5 Where o.OrderID = orderID _ 6 Select o).Single() 7 Return order 8 End Function 9 10 Public Shared Function ReadList() As IEnumerable(Of Order) 11 Dim context As New CustomersAndOrdersDataContext 12 13 Return context.Orders 14 End Function 15 16 Public Shared Function OrderToCustomer(ByVal orderID As Integer) As IEnumerable(Of Customer) 17 Dim context As New CustomersAndOrdersDataContext 18 19 Dim customerID = (From o In context.Orders _ 20 Where o.OrderID = orderID _ 21 Select o).Single().CustomerID 22 23 Dim custList = From c In context.Customers _ 24 Where c.CustomerID = customerID _ 25 Select c 26 Return custList 27 End Function

    Deploy the solution and create new page to see the associated data lists

    1. Go to the homepage of your SharePoint site. Typically http://localhost.

    2. On the top left corner of the site, select Site Actions -> New Page, name the new page BdcAssociationSample.

    3. On the ribbon, select Insert -> Web Part, and click on Business Data from the Categories panel, select Business Data List from the Web Parts panel. Click Add.

    clip_image006

    4. Repeat the step above, select Business Data Related List and click Add.

    5. Click Open the tool pane on Business Data List, then select Customer from External Content Type picker and click OK. Now you should able to see the customer information from the database is displayed in the list.

    clip_image007

    clip_image008

    6. Repeat the step above, select Order on Business Data Related List.

    7. On the top-right corner of the Business Data Related List, click on the drop down menu and select Edit Web Part. After the page refreshed, from the same drop down menu, select Connections -> Get Related Item From -> Customer. Click OK.

    clip_image009 clip_image010

    8. Click Save & Close on the ribbon of the new page.

    Now you can see a list of Customers on the SharePoint page, when you select a row in the Customer table, a list of orders related with this customer will showed in the second table.

    Select CustomerID ALFKI by clicking the small icon in the front of each line.

    clip_image011

    The second list will display the corresponding orders.

     clip_image012

    Yanchen Wu

  • Visual Studio SharePoint Development Blog

    Deploy your BDC model to a specific BCS Service using Visual Studio 2010

    • 0 Comments

    When deploying a BDC model in Visual Studio 2010, some people may see this error message “… There is no default Business Data Connectivity Service Proxy available for the given SPServiceContext…” or similar ones. This probably means the SiteUrl feature property is not appropriately set.

    SiteUrl is a SharePoint feature property that determines where a feature will be deployed. When a BCS feature is deployed, SharePoint server will look up a BCS service (if there are more than one BCS service connected to the site, it will select the default one) connected to the appointed SiteUrl. If the SiteUrl property is omitted, it assumes the value of SiteUrl is http://localhost:80. The SharePoint BDC project in VS2010 helps you customize the feature properties like SiteUrl. Let me show you how you can easily manage SiteUrl property here.

    Assume you have two BCS services, BCS1 and BCS2, and two web applications, one on port 80 (http://localhost:80) named WebApp80, and the other on port 90 (http://localhost:90) named WebApp90. In SharePoint 2010 Central Administration, you can link services up with web applications. Browse to the Web Application Management page, select the web application WebApp80 as shown in the screenshot below.

    clip_image001

    If you click the Service Connections button on the top ribbon, the Configure Service Application Associations dialog will be displayed. Now you can select BCS1 as the default BCS service for the current web application as shown in the screenshot below.

    clip_image002

    It is the same for adding BCS2 to WebApp90. Now BCS1 is the default BCS service for WebApp80 and BCS2 is the default BCS service for WebApp90.

    Now let’s create a new BDC project. SiteUrl by default is not set for a new project. So the solution will be deployed to BCS1. If we want to deploy the solution to the BCS service other than BCS1, how can we do that? Here are the steps.

    1. Select the BDC folder node in the Solution Explorer and view its properties in the Property Window. Click the […] at the end of Feature Properties row in the Property Window. See the screenshot below.

    clip_image003

    2. The Feature Properties dialog will be displayed. Now we can add the SiteUrl property and set its value to http://localhost:90 where BCS2 is the default BCS service.
    clip_image004

    3. Now if we deploy the solution again, it will be deployed to BCS2.

    Enjoy using this feature!

    Jeff Chen

  • Visual Studio SharePoint Development Blog

    Using Deployment Step events to add functionality to Deployment Configuration

    • 0 Comments

    With the help of the extensibility features in the SharePoint tools in Visual Studio, you can add functionality to deployment configurations by subscribing to the DeploymentStepStarted and DeploymentStepCompleted events.

    To learn more about deployment configurations and deployment steps in SharePoint projects, refer to the MSDN article here.

    In this blog post I will show you how to use the DeploymentStepCompleted event and add you own code that is executed when a SharePoint project is either deployed or retracted.

    Our scenario is the following: When retracting Web Parts we would like to delete the .webpart file from the SharePoint server. We will create a project item extension for the Visual Web Part project and from that extension we will subscribe to the DeploymentStepCompleted event. First we will need to create a SharePoint project item extension project.

    To do that we will need to:

    1)       Install the Visual Studio SDK from: http://www.microsoft.com/downloads/details.aspx?displaylang=en&FamilyID=47305cf4-2bea-43c0-91cd-1b853602dcc5

    2)      Create an empty VSIX project

    3)      Add a class library project which is project item extension project to the solution

    4)      Add the output from the project item extension project as MEF component content to the VSIX manifest in the VSIX project.

    For detailed information on how to create project item extensions you can refer to the walkthrough here or Bing ‘Visual Studio 2010 How to: Create a SharePoint Project Item Extensions.

    Let’s start by creating a project Item extension for Visual Web Part.

       

    [Export(typeof(ISharePointProjectItemTypeExtension))]

    [SharePointProjectItemType("Microsoft.VisualStudio.SharePoint.VisualWebPart")]

     internal class ItemExtension : ISharePointProjectItemTypeExtension

        {

            public void Initialize(ISharePointProjectItemType projectItemType)

            {

                projectItemType.DeploymentStepCompleted += new EventHandler<DeploymentStepCompletedEventArgs>(projectItemType_DeploymentStepCompleted);

            }

     

           

    void projectItemType_DeploymentStepCompleted(object sender, DeploymentStepCompletedEventArgs e)

            {

                ISharePointProjectItem SPProjectItem = e.ProjectItem;

                string webPartUrl = GetWebPartFileUrl(SPProjectItem);

     

                if (e.DeploymentStepInfo.Id == DeploymentStepIds.RetractSolution && !string.IsNullOrEmpty(webPartUrl))

                {

                    SPProjectItem.Project.SharePointConnection.ExecuteCommand<string>(DeleteWebPartFileCommand, webPartUrl);

                }

            }

     

    Notice in above code we created a new class called Item Extension that implements the ISharePointProjectItemTypeExtension interface. In order for this class to be recognized in Visual Studio we added two attributes. With the Export attribute we are telling Visual Studio that this class is a project item extension and with second attribute (SharePointProjectItemType) we are telling Visual Studio that this extension applies to the Visual Web Part projects. Extension developers can subscribe to deployment step events in the Initialize method of the project item extension.

     projectItemType.DeploymentStepCompleted += new EventHandler<DeploymentStepCompletedEventArgs>(projectItemType_DeploymentStepCompleted);

    The event we subscribed to is raised for all the deployment steps that are executed in the active deployment configuration. With the help of the event args parameter passed to the event handler we can check which step is being executed and decide what code to run.

    if (e.DeploymentStepInfo.Id == DeploymentStepIds.RetractSolution && !string.IsNullOrEmpty(webPartUrl))

    Since this includes deleting a file on the SharePoint server, the extension uses a custom SharePoint command to call into the SharePoint server object model. For detailed information on why to use SharePoint commands is discussed here.

     The line of code which uses the SharePoint command is:

    SPProjectItem.Project.SharePointConnection.ExecuteCommand<string>(DeleteWebPartFileCommand, webPartUrl);

     

    When this line of code is executed we create a new process named vssphost4.exe or use an existing one. The SharePoint command named DeleteWebpartFileCommand is executed inside this process during execution.

    To create a SharePoint command class we need to:

    1)      Add a class library project that targets the .NET Framework 3.5 to the same solution as the VSIX and project item extension projects.

    2)      Add references to Microsoft.SharePoint.dll and Microsoft.VisualStudio.SharePoint.Commands.dll.

    3)      Add the commands project output to the VSIX manifest in the VSIX project as a Custom Content Type with Type= “SharePoint.Commands.v4”. This will include the commands project in the VSIX as custom assembly which can be used by the SharePoint project extensions.   

     

    internal class Command

        {

            [SharePointCommand("DeleteWebPartFile")]

            private void DeleteWebPartFile(ISharePointCommandContext context, string webPartFileUrl)

            {

                //Append RootWeb Url

                string fullWebpartFileUrl = SPUrlUtility.CombineUrl(context.Web.Site.RootWeb.Url, webPartFileUrl);

                try

                {

                    SPFile file = context.Web.Site.RootWeb.GetFile(fullWebpartFileUrl);

                    if (file.Exists)

                    {

                        file.Delete();

                        context.Logger.WriteLine(string.Format("Visual Webpart Extension:Deleted file at {0}", fullWebpartFileUrl), LogCategory.Status);

                    }

                }

                catch (Exception ex)

                {

                    context.Logger.WriteLine(string.Format("Visual Webpart Extension:Exception occured when deleting file at: {0}", fullWebpartFileUrl), LogCategory.Status);

                    context.Logger.WriteLine(string.Format("Visual Webpart Extension:Exception occured when deleting file at: {0}; Exception:{1}", fullWebpartFileUrl, ex.Message  +       ex.StackTrace), LogCategory.Verbose);

                }

            }

        }

     

    Notice in the above code we are have an attribute SharePointCommand for the method name which will enable it to be recognized and used by the project item extension to call into. Also the first parameter should be ISharePointCommandContext which will have reference to ‘SPWeb’ to take advantage of Server object model.

     You will also see the logger object is also exposed in the context parameter with which we can log back messages to the output window of Visual Studio from vssphost4.exe.

    You can now install the extension located in the bin/output folder of the VSIX project after the solution is built. Once this extension is installed the DeploymentStepCompleted event will be raised each time a Visual Web Part project is being retracted after the ‘retractSolution’ step.

    To test and debug the extension:

    1)      Download and open the extension project from MSDN code gallery.

    2)      Place a breakpoint in the projectItemType_DeploymentStepCompleted event handler in ItemExtension.cs file and press F5 to start debugging. This will install the VSIX extension in the experimental instance of Visual Studio.

    3)      The experimental instance of Visual Studio will start. Create a Visual Web Part project (select the project template under the SharePoint 2010 node) and use default values in the wizard.

    4)       Once the project is created, press F5.

    5)      Close IE or stop debugging to start executing the retraction steps.

    6)      Once the retraction steps start executing, you will see the breakpoint being hit after “Retract Solution” step.

    7)      You will see the file being deleted after the code is executed.

    Output Window snapshot

    For more information on how to extend the SharePoint project system in Visual Studio you can refer to MSDN topic here or Bing Visual Studio 2010 Extending the SharePoint Project System“.

    Murali Madala.

  • Visual Studio SharePoint Development Blog

    Extending the SharePoint Tools in Visual Studio: An Overview

    • 0 Comments

    Since you’re reading this blog, you’re probably aware that Visual Studio 2010 includes an all-new set of tools for creating SharePoint solutions for Microsoft SharePoint Foundation 2010 and Microsoft SharePoint Server 2010. These tools include a set of project and item templates for developing various types of solutions, integrated Feature and packaging support (with designers), and the SharePoint Connections node in Server Explorer.

    However, you might not know that the SharePoint tools include a comprehensive extensibility model. This extensibility model is public and fully documented. In fact, all of the built-in tools were implemented by using same extensibility model that you can use to create your own extensions. A number of Visual Studio extensions that were built by using this extensibility API are already available, such as VSeWSSImport and vsixforsp.

    The purpose of this post is to provide a high-level overview of the different ways you can extend the SharePoint tools, with some pointers to relevant topics and code examples in the documentation.

    Introduction to the Extensibility Model

    To extend the SharePoint tools in Visual Studio 2010, you use types in three assemblies that are included with Visual Studio:

    • Microsoft.VisualStudio.SharePoint.dll
    • Microsoft.VisualStudio.SharePoint.Commands.dll
    • Microsoft.VisualStudio.SharePoint.Explorer.Extensions.dll.

    For the rest of the post I'll refer to these collectively as the SharePoint tools API. You can think of this API as an abstraction layer on top of the Visual Studio automation object model (DTE and related types) and integration object model (VSPackages and related types). When you create extension for the SharePoint tools, you always work directly with the SharePoint tools API, but you can also call into the automation and integration object models if you need to leverage functionality that is provided only in those object models.

    The SharePoint tools API consists of two main groups of types:

    • Extensibility interfaces that you implement as the basis for an extension of the SharePoint tools. To extend a particular feature of the SharePoint tools, you implement an interface that is defined by the SharePoint tools and apply the Export attribute (and additional attributes as necessary) to your interface implementation. There are a handful of extensibility interfaces provided by the SharePoint tools, including ISharePointProjectItemTypeExtension, ISharePointProjectItemTypeProvider, and ISharePointProjectExtension. The SharePoint tools use the Managed Extensibility Framework (MEF) to expose extensibility interfaces and to manage extensions.

    • Other types that represent components that you can modify or automate in extensions (such as ISharePointProject and ISharePointProjectItem, which represent a SharePoint project and project item, respectively), and other supporting types such as delegates, attributes, and enumerations. Most of the types in the SharePoint tools API fall into this category.

    There are two main feature areas that you can extend: the SharePoint project system and the SharePoint Connections node in Server Explorer.

    SharePoint Project System

    The SharePoint project system refers to the components and functionality that are available in a SharePoint project. At the highest level, this includes the project itself, each SharePoint project item in the project, and other contents of the project such as mapped folders, Feature definitions, and the package definition. A SharePoint project item (or SPI for short) represents a specific SharePoint customization - for example, a Web Part, an event receiver, or list definition. In a SharePoint project that is open in Solution Explorer, each SharePoint project item is represented by a node with an icon that identifies the item type. This node can contain additional files that are associated with the project item, such as Elements.xml files or code files.

    The Microsoft.VisualStudio.SharePoint namespace contains most of the main types in the SharePoint project system, such as ISharePointProject and ISharePointProjectItem. Other project system types are also provided in the Microsoft.VisualStudio.SharePoint.Deployment, Microsoft.VisualStudio.SharePoint.Features, Microsoft.VisualStudio.SharePoint.Packages, and Microsoft.VisualStudio.SharePoint.Validation namespaces.

    You can extend the SharePoint project system in the following ways:

    • Create an extension for a particular type of SPI, such as the built-in List Definition project item. Your extension is loaded only when an instance of the targeted SPI type is in a project that is open in Visual Studio. For more information and related code examples, see Extending SharePoint Project Items in the MSDN documentation.

    • Create your own new type of SPI, which you can associate with an item template or project template. You can even implement your own wizard that appears when a customer adds your SPI to a project, or creates a new project that includes your SPI. For more information and related code examples, see Defining Custom SharePoint Project Item Types in the MSDN documentation.

    • Create an extension for SharePoint projects. Your extension is loaded whenever any type of SharePoint project is open in Visual Studio. For more information and related code examples, see Extending SharePoint Projects in the MSDN documentation.

    • Extend the packaging and deployment behavior of a SharePoint project or SPI. For example, you can create your own deployment steps or deployment configurations, handle various deployment-related events, or create your own validation rules for Features and package definitions. For more information and related code examples, see Extending SharePoint Packaging and Deployment in the MSDN documentation.

    There are a number of tasks you can perform in extensions of the SharePoint project system. For example, you can add custom properties to SharePoint projects or particular types of SPIs (these properties appear in the Properties window when a project or SPI is selected in Solution Explorer), add your own context menu items to SharePoint projects or particular types of SPIs (these menu items appear when you right click the project or SPI in Solution Explorer), and you can handle many different events that are raised by SharePoint projects and SPIs in various scenarios. The MSDN topics I link to above provide how-to topics and walkthroughs that demonstrate all of these tasks.

    SharePoint Connections Node in Server Explorer

    The new SharePoint Connections node in Server Explorer is intended to be used to browse the contents of local SharePoint sites on your development computer. After you add a connection to a local SharePoint site, many (but not all) of the components of the site are displayed here in a hierarchical tree view. This can help provide a quick, comprehensive view of the site while you are working on a new SharePoint solution that you plan to deploy to it. For an overview of how this feature is used, see Browsing SharePoint Connections Using Server Explorer.

    The Microsoft.VisualStudio.SharePoint.Explorer and Microsoft.VisualStudio.SharePoint.Explorer.Extensions namespaces contain the types that you can use to extend the SharePoint Connections node.

    You can extend the SharePoint Connections node in the following ways:

    • Extend a node, such as the node that represents fields, lists, or content types. For a code example and step-by-step instructions, see How to: Extend a SharePoint Node in Server Explorer in the MSDN documentation.

    • Create a new type of node. For example, you might want to do this if you want to create an extension that can display components of SharePoint sites that the built-in SharePoint Connections node does not support, such as Web Parts. For a code example and step-by-step instructions, see How to: Add a Custom SharePoint Node to Server Explorer in the MSDN documentation.

    As with the project system, you can also add custom properties and context menu items to nodes, and there are a number of different events you can handle. The MSDN topics I link to above provide how-to topics and walkthroughs that demonstrate all of these tasks.

    Important Features

    The following features play an important role in most extensions of the SharePoint tools.

    SharePoint Commands

    Most extensions need to call into the SharePoint APIs to perform some work, such as determining whether a particular file exists on a SharePoint site or adding or deleting content from a site. Although the 2010 releases of SharePoint now include a client object model, most SharePoint tools extensions should use the "traditional" server object model, because the client object model was designed to be used to call into remote SharePoint installations, not local installations. However, the SharePoint server object model cannot be called directly from SharePoint tools extensions, because the SharePoint server object model can be called only from 64-bit processes that target the .NET Framework 3.5, but SharePoint tools extensions are run in the Visual Studio process, which is a 32-bit process that targets the .NET Framework 4.

    To bridge this gap, the Visual Studio tools include the concept of a SharePoint command. A SharePoint command is essentially an intermediary method that can call into the SharePoint server object model directly, and that can be called by your extension. For a nuts-and-bolts explanation of how this works, see Calling into the SharePoint Object Models, How to: Create a SharePoint Command, and How to: Execute a SharePoint Command in the MSDN documentation.

    SharePoint Service

    The Visual Studio tools provide a special service object, called the SharePoint service, which provides a number of different features such as the ability to convert some types in the SharePoint tools API to types in the Visual Studio automation and integration object models, execute a SharePoint command, and access any open SharePoint project or project item. For more information, see Using the SharePoint Project Service in the MSDN documentation.

    Related Walkthroughs

    For end-to-end walkthroughs that demonstrate how to implement, deploy, and test different types of SharePoint tools extensions, see the following walkthroughs in the MSDN documentation.

    Project System Extensions

    Extensions of the SharePoint Connections Node in Server Explorer

    McLean Schofield

     

  • Visual Studio SharePoint Development Blog

    Deploying documents with content types and associating content types with libraries (Part III)

    • 0 Comments

    Part III: Using Feature Event Receiver to create a library and associate a content type

    In previous post we showed how to use ContentTypeBinding to bind the content type to an existing document library. In this post, we will learn how to achieve similar results but using the feature event receiver. In this post we will create a new document library, remove all existing content types from the created library and then add our content type to the list. Instead of create a new library from the code, you could also reference an existing one that’s already on the SharePoint server. In this example we will use the same project we created in Part I. So, let's start by opening that project which contains the content type and a document. When project opens, expand the Features folder, right click the Feature1 folder and finally select the Add Event Receiver option to add a feature event receiver to the project. Next, uncomment the FeatureActivated method and add the following code:

    SPWeb web = properties.Feature.Parent as SPWeb;

    string libraryName = "Sample library name - " + DateTime.Now.Millisecond.ToString ();

     

    Guid listGuid = web.Lists.Add(libraryName, string.Empty, SPListTemplateType.DocumentLibrary);


    SPList list = web.Lists[listGuid];

    // Delete all content types from the list

    for (int i = 0; i < list.ContentTypes.Count; i++)

    {

      list.ContentTypes[i].Delete();

    }

    SPContentType myContentType = web.ContentTypes[new SPContentTypeId("0x010100a9fe27b0556b4de8a60d9e04c6db71de")];

    list.ContentTypes.Add(myContentType);

    list.ContentTypesEnabled = true;

    list.Update();

     
    In the above code we are adding a library to the SharePoint site. The Add method returns the Guid of the created list/library. In the for statement, we iterate through all the content types that are in the list (since we created a new document library there should be only 1 content type (Document) in the library) and we delete them.

    After we removed all content types from the list, we add a new content type to the list (similar as in Part II, we are referring to the content type by its ID). You can use the Server Explorer to get the content type ID. Finally, we enable the content type management in the list and we update the list to save the changes.

    If you press F5 you will notice that the "My New Document Library" is created on SharePoint. If you click the Documents tab and then open the New Document menu you will notice a document we associated with the content type shows up.

    Peter Jausovec

  • Visual Studio SharePoint Development Blog

    The Visual Studio 2010 SharePoint Power Tools are now available!

    • 5 Comments

    The Visual Studio team that brought you the SharePoint developer tools in Visual Studio 2010 is happy to announce we have created a set of power tools that make developing SharePoint 2010 sandboxed solutions even easier.  Below is the list of features included in the current release of the power tools.

     

    Sandboxed-compatible Visual Web Part
    This item template enables you to use a visual designer to create SharePoint web parts that can be deployed in a SharePoint 2010 sandboxed solution.

     

    Sandboxed Compilation
    This extension displays build errors when you use types or members in a SharePoint 2010 sandboxed project which are not allowed in the SharePoint sandbox environment.

                   

    The Visual Studio 2010 SharePoint Power Tools are available immediately on the Visual Studio Gallery.

    Mike Morton - Program Manager - Visual Studio

  • Visual Studio SharePoint Development Blog

    Deploying documents with content types and associating content types with libraries (Part II)

    • 0 Comments

    Using ContentTypeBinding to associate content types with lists

    In previous post we showed how to deploy a document and associate it with a content type. Even though the deploying and associating the document with content types was fairly easy we still had to manually associate the content type with desired document library. In this post I will show you how to use the ContentTypeBinding element to associate a content type to the existing document library.

    You can use the content type project we created in previous post. Currently, we are deploying the document and a content type and then with the help of the DocumentTemplate element we are associating it to the content type. In order to automatically associate or bind the content type with an existing document library we need to create an Empty Element project item.

    1.       Right click the project name and select AddàNew Item.

    2.       From the list of templates, select Empty Element.

    3.       Name the project item "ContentTypeBinding" and click OK to create it.

    A new folder with an empty Elements.xml file is added to the project. Double click the Elements.xml in the ContentTypeBinding folder we just added. As mentioned at the beginning, we are going to use the ContentTypeBinding element. This element can be used to bind a specific content type to an existing list or library. Let's create a new Document Library from the SharePoint home page and call it "My Documents". Switch back to the Visual Studio 2010 to add the ContentTypeBinding element to the empty Elements.xml file:

    <?xml version="1.0" encoding="utf-8"?>
    <Elements xmlns="http://schemas.microsoft.com/sharepoint/">
    <ContentTypeBinding ListUrl="My Documents" ContentTypeId="[CONTENT TYPE ID]"/>     
    </Elements>

    Explanation for the above snippet is very simple. We are pointing to the list and the content type ID we want to associate to that list. To get the content type ID you can either open the Elements.xml file inside the content type folder or use the Server Explorer:

    1.       In Visual Studio 2010, click Tools à Add SharePoint Connection item.

    2.       In the dialog that opens type the SharePoint URL and click OK to open the Server Explorer.

    3.       In the Server Explorer window expand the Team Site and Content Types node.

    4.       Locate the content type you want to associate (e.g. MyContentType - ContentType1).

    5.       With the desired content type selected, click F4 to open the Properties Window.

    6.       Locate the ID property - that's the content type ID we need for ContentTypeBinding.

    7.       Copy the ID and paste it to the empty elements' Elements.xml file to replace the [CONTENT TYPE ID] value.

    We are all done! Press F5 to start debugging and navigate to the "My Documents" library.  Click the Documents tab and then the New Document menu. You will notice the document we deployed with our solution now shows up in the menu which means that the content type was successfully associated with this document library. In the next post we will show how to achieve similar functionality (associate a content type with a document library) using feature event receivers.

    Peter Jausovec

  • Visual Studio SharePoint Development Blog

    Deploying documents with content types and associating content types with libraries (Part I)

    • 3 Comments

    Content type, document and a library

    In this series of posts I will show you how to create a content type project, deploy a Word document template together with the content type, and then associate the content type with document library on the SharePoint site. When developing content types, one common scenario is to deploy a document template along with the content type. The deployed document template appears on the New menu for the SharePoint library content type it is associated with. So, let’s start by creating a new C# SharePoint 2010 Content Type project.

    1. Start Visual Studio 2010 with administrator privileges.
    2. Click File à New Project and select the Content Type project under the SharePoint à 2010 node.
    3. Name the project MyContentType and click OK. 
    4. Select the Deploy as a farm solution option in the wizard and click Next. We are creating a farm solution because we want to deploy the document using mapped folders and mapped folder can be used only in farm solutions. 
    5. Select Document for the base content type.
    6. Click Finish to create the project.

    Once the content type project is created, we can add a document to the project. This document will be deployed as a part of our content type. As mentioned earlier we are going to use a mapped folder to deploy the document. Right-click the project name and select Add -> SharePoint "Layouts" Mapped folder. This command creates the Layouts and MyContentType subfolder in the project as shown below.

    Assuming your document is prepared and ready you can right-click the MyContentType folder (under the Layouts mapped folder in the project) and select Add à Existing Item. Browse to the document you want to use, select it and click Add to add it to the mapped folder. When you add a document to the mapped folder the deployment type and location properties are automatically to the required values.

    The next step is to associate this document with the content type. To do this, open the Elements.xml file under the ContentType1 folder and insert the DocumentTemplate element right after the FieldRefs closing tag:

    <DocumentTemplate TargetName="/_layouts/MyContentType/MyDocument.docx"/>

    Using the DocumentTemplate tag we are pointing to the document that is going to be deployed to the layouts folder. You can press F5 now to deploy the project and start debugging. By default the Site Content Types page opens. Click MyContentType - ContentType1 in the list to open the content type settings page which should look similar to the one below.

    Click the Advanced settings link. Notice that the URL for the Document Template is set to the document we deployed as shown below.

    Let's try to associate this content type with the new document library. Click the Libraries link on the SharePoint site and then click the Create link to create a new library. Select the Document Library item from the list and name it My Document Library as shown below.

    Click the Create button to create the document library. Now that we have the document library we need to associate the content type with it. Click the Library Settings button to open Document Library Settings page. The default content type for document libraries is Document content type - we need to change that in order to use the content type we deployed. But before we do that we have to allow the management of content types in this library. To do this, click the Advanced settings link and on the Advanced Settings page, click Yes to allow management of content types as shown below and click OK to save changes.

    We are redirected back to the Document Library Settings page and you will notice the Content Types section on the page is now visible. Click the Add from existing site content types link to add our content type to the library. Select the MyContentType - ContentType from the list and click Add to associate the content type with the library. Click OK to save the changes - the content types section on the settings page now shows our content type.

    However, the Document content type is still set to be the default. We can easily change that by clicking the Change new button order and default content type link. On the page that opens uncheck the Document content type and click OK to save changes. This hides the Document content type and makes our content type the default.

    Finally, navigate back to the My Document Library and click the Documents tab on the ribbon. If you click the New Document button you will notice the document we deployed shows in the list.

    Deploying and associating documents with content types is fairly easy. Associating the content type to a library however requires a bit more (manual) work. In the next post I will show you how to automatically allow management of content types in the library and make the content type a default one.

    Peter Jausovec

  • Visual Studio SharePoint Development Blog

    Surfacing Business Data in a Web Part that you Create by Using SharePoint Tools in Visual Studio

    • 2 Comments

    So you add a Visual Web Part to your SharePoint solution and you want the Web Part to show some data. No problem. I’ll show you three ways to do it. This post shows you how to surface data in your Visual Web Part by performing the following tasks:

    • Binding data to a GridView at design time.
    • Binding data to a GridView by using LINQ to SQL code.
    • Binding data to a GridView by querying the Business Data Catalog.

    I have also published a sample that shows these tasks here. For now, let’s make some data appear!

    Binding Data to a GridView at Design Time

    1. In Visual Studio, create a Visual Web Part project.

    2. From the Toolbox, drag a GridView to the designer.

    3. Attempt to configure a data source for the GridView. Wait! Where can I select Database? I only see XML File. Could this be a bug?

    original[1]

    Nope. This is not a bug. The ability to configure other data sources by using the Data Source Configuration Wizard is a feature that has not been implemented in the Visual Web Designer for SharePoint projects in Visual Studio. You have two options.

    · Write XML that defines the data source in the Source view of the designer (Not fun).

    · Configure your data source in an ASP.NET project and then copy over the data source object (fun).

    For this post, I’ll configure a SQLDataSource object in an ASP.NET project. Then, just copy control over to my Visual Web Part project. Then, I will bind the GridView to that control.

    1. In Visual Studio, create a new ASP.NET Web Application project.

    2. From the Toolbox, drag a SQLDataSource control to the designer of any page.

    original[1]

    3. Configure the control by using the Data Source Configuration Wizard (Shown earlier). Use the wizard to generate create, update, delete, and select commands.

    4. In the designer of the ASP.NET project, copy the SQLDataSource control.

    original[1]

    5. In the designer of the Visual Web Part project, paste the SQLDataSource control.

    6. Bind the GridView to that data source.

    original[1]

    7. In the GridView Tasks dialog box, select Enable Editing, and Enable Deleting. Selecting these options will add Edit and Delete links to the GridView.

    original[1]

    8. Finally, add the name of the primary key column of your database table to the DataKeyNames property of the GridView.

    original[1]

    9. Design the rest of the GridView (look and feel etc.).

    If you open the designer in Source view, your GridView should look something like this:

    GridView

    <asp:GridView ID="GridView1" runat="server" DataSourceID="SqlDataSource1" DataKeyNames="CustomerID" PageSize="3" EnableModelValidation="True">
    
      <Columns>
    
        <asp:CommandField ShowDeleteButton="True" ShowEditButton="True" />
    
      </Columns>
    
    </asp:GridView>
    

    SQLDataSource

    <asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:AdventureWorksConnectionString%>" ProviderName="System.Data.SqlClient"
    
      SelectCommand="SELECT TOP 3 [CustomerID], [FirstName], [MiddleName], [LastName] FROM [SalesLT].[Customer]"
    
      DeleteCommand="DELETE FROM [SalesLT].[Customer] WHERE [CustomerID] = @CustomerID"
    
      InsertCommand="INSERT INTO [SalesLT].[Customer] ([FirstName], [MiddleName], [LastName]) VALUES (@FirstName, @MiddleName, @LastName)"
    
      UpdateCommand="UPDATE [SalesLT].[Customer] SET [FirstName] = @FirstName, [MiddleName] = @MiddleName, [LastName] = @LastName WHERE [CustomerID] = @CustomerID">
    
      <DeleteParameters>
    
        <asp:Parameter Name="CustomerID" Type="Int32" />
    
      </DeleteParameters>
    
      <InsertParameters>
    
        <asp:Parameter Name="FirstName" Type="String" />
    
        <asp:Parameter Name="MiddleName" Type="String" />
    
        <asp:Parameter Name="LastName" Type="String" />
    
      </InsertParameters>
    
      <UpdateParameters>
    
        <asp:Parameter Name="FirstName" Type="String" />
    
        <asp:Parameter Name="MiddleName" Type="String" />
    
        <asp:Parameter Name="LastName" Type="String" />
    
        <asp:Parameter Name="CustomerID" Type="Int32" />
    
      </UpdateParameters>
    
    </asp:SqlDataSource>
    

    A Quick note about Connection Strings

    Notice the following line in the above source:

    ConnectionString="<%$ ConnectionStrings:AdventureWorksConnectionString%>"

    This line grabs the connection string from the web.config file of the root site. This is one way to persist a connection string. There are other ways to do this as well. You can read about them in the MSDN topic Managing Application Configuration.

    The sample contains code that adds the connection string to web.config by using code in the feature receiver of the Visual Web Part project.

    Bind Data to a GridView by using LINQ to SQL Code

    There are probably a dozen ways to structure this. Here is one way to do it.

    · Create a class library.

    · Generate objects to access the data.

    · Add methods that retrieve, edit, and delete the data.

    · Bind the GridView to those methods.

    Create a Class Library

    1. Add a Class Library project to your solution.

    2. Compile the project.

    3. Strong name sign the assembly of the project. You can read more about how to do that here.

    4. Add the assembly to the package manifest. You can read more about how to do that here.

    Generate objects to access the data

    1. Add a new data source to the Class Library project. You can read more about how to do that here.

    2. Add a LINQ to SQL Classes item to the Class Library project.

    original[1]

    3. In Server Explorer, drag a table onto the O/R Designer.

    This creates an Entity that represents the table. Your code will read, edit, and delete data by using the entity not the actual table.

    original[2]

    Add methods that retrieve, edit, and delete the data

    1. In the class file of the Class Library project, add code to retrieve, update and delete data.

    Example:

    public class DAL
    
    {
    
      public static AdventureWorksDataContext GetDataContext()
    
      {
    
        string strConnString = ConfigurationManager.ConnectionStrings["AdventureWorksConnectionString"].ConnectionString;
    
        return new AdventureWorksDataContext(strConnString);
    
      }
    
      public static IEnumerable<Customer> GetCustomers()
    
      {
    
        AdventureWorksDataContext dataContext = GetDataContext();
    
        IEnumerable<Customer> myCustomers = from customers in dataContext.Customers.Take(3)
    
                                            select customers;
    
        return myCustomers;
    
      }
    
      public static void UpdateCustomer(int customerID, string firstName, string middleName, string lastName)
    
      {
    
        AdventureWorksDataContext dataContext = GetDataContext();
    
        var CustomerToUpdate = (from Customers in dataContext.Customers
    
                                where Customers.CustomerID == customerID
    
                                select Customers).Single();
    
        
    
        CustomerToUpdate.CustomerID = customerID;
    
        CustomerToUpdate.FirstName = firstName;
    
        CustomerToUpdate.MiddleName = middleName;
    
        CustomerToUpdate.LastName = lastName;
    
        dataContext.SubmitChanges();
    
      }
    
      public static void DeleteCustomer(int CustomerID)
    
      {
    
        AdventureWorksDataContext dataContext = GetDataContext();
    
        Customer Customer =(from Customers in dataContext.Customers.AsEnumerable().Take(5)
    
                            where Customers.CustomerID == CustomerID
    
                            select Customers).Single();
    
        dataContext.Customers.DeleteOnSubmit(Customer);
    
        dataContext.SubmitChanges();
    
      }
    
    }

    Binding the GridView to your methods

    1. In the designer of your Visual Web part, create event handlers for the RowCancelingEdit, RowDeleting, RowEditing, and RowUpdating events of the GridView.

    original[2]

    2. Right-click the designer and then click View Code.

    3. Add code for each of the event handlers.

    Example:

    public partial class VisualWebPart1UserControl : UserControl
    
    {
    
      protected void Page_Load(object sender, EventArgs e)
    
      {
    
        if (!IsPostBack)
    
        {
    
          BindGridView(GridView2);
    
        }
    
      }
    
      private void BindGridView(GridView GridView)
    
      {
    
        GridView.DataSource = DAL.DAL.GetCustomers();
    
        GridView.DataBind();
    
      }
    
      protected void GridView_RowDeleting(object sender, GridViewDeleteEventArgs e)
    
      {
    
        GridView TempGridView = (GridView)sender;
    
        TableCell cell = TempGridView.Rows[e.RowIndex].Cells[1];
    
        DAL.DAL.DeleteCustomer(Convert.ToInt32(cell.Text));
    
        BindGridView(TempGridView);
    
      }
    
      protected void GridView_RowEditing(object sender, GridViewEditEventArgs e)
    
      {
    
        GridView TempGridView = (GridView)sender;
    
        TempGridView.EditIndex = e.NewEditIndex;
    
        BindGridView(TempGridView);
    
      }
    
      protected void GridView_RowUpdating(object sender, GridViewUpdateEventArgs e)
    
      {
    
        int CustomerID = 0;
    
        string FirstName ="";
    
        string MiddleName="";
    
        string LastName="";
    
      
    
        GridView TempGridView = (GridView)sender;
    
        GridViewRow gvr = TempGridView.Rows[e.RowIndex];
    
        for (int i = 0; i < gvr.Cells.Count; i++)
    
        {
    
          switch (TempGridView.HeaderRow.Cells[i].Text)
    
          {
    
            case "CustomerID":
    
              CustomerID = Convert.ToInt32(((TextBox)(gvr.Cells[i].Controls[0])).Text);
    
              break;
    
            case "FirstName":
    
              FirstName = ((TextBox)(gvr.Cells[i].Controls[0])).Text;
    
              break;
    
            case "MiddleName":
    
              MiddleName = ((TextBox)(gvr.Cells[i].Controls[0])).Text;
    
              break;
    
            case "LastName":
    
              LastName = ((TextBox)(gvr.Cells[i].Controls[0])).Text;
    
              break;
    
            default:
    
              break;
    
           }
    
        }
    
        DAL.DAL.UpdateCustomer(CustomerID, FirstName, MiddleName, LastName);
    
        TempGridView.EditIndex = -1;
    
        BindGridView(TempGridView);
    
      }
    
      protected void GridView_RowUpdated(object sender, GridViewUpdatedEventArgs e)
    
      {
    
        GridView TempGridView = (GridView)sender;
    
        e.KeepInEditMode = false;
    
        TempGridView.EditIndex = -1;
    
      }
    
      protected void GridView_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
    
      {
    
        GridView TempGridView = (GridView)sender;
    
        TempGridView.EditIndex = -1;
    
        BindGridView(TempGridView);
    
      }
    
    }

    Binding Data to a GridView by Querying the Business Data Connectivity Service

    Perhaps your organization has a bunch of data in the Business Data Connectivity Service in SharePoint. No problem. You can bind your GridView to that too.

    <Quick Shameless Plug>

    If you are not familiar with the Business Data Connectivity Services in SharePoint, it is the coolest thing since ice cubes. You can read more about it here. Visual Studio has a project template to help deploy data models to the service. You can read more about that here.

    </Quick Shameless Plug>

    1. Add a class to your Class Library project.

    2. Add a reference to the Microsoft.BusinessData assembly. Unfortunately, you won’t find that assembly in the .NET tab of the Add Reference dialog box. I found it by browsing to this location - C:\program files\common files\microsoft shared\web server extensions\14\ISAPI\Microsoft.BusinessData.dll.

    3. In your class, add the following using (or for VB Imports) statements:

    using Microsoft.SharePoint;

    using Microsoft.SharePoint.BusinessData.SharedService;

    using Microsoft.BusinessData.MetadataModel;

    using Microsoft.SharePoint.Administration;

    4. Add code.

    Example:

    class BDC_DAL
    
    {
    
      const string nameSpace = "AdventureWorksCustomers.BdcModel1";
    
      const string entityName = "Customer";
    
      
    
      private static IMetadataCatalog GetCatalog()
    
      {
    
        BdcService service = SPFarm.Local.Services.GetValue<BdcService>(String.Empty);
    
        IMetadataCatalog catalog = service.GetDatabaseBackedMetadataCatalog(
    
        SPServiceContext.Current);
    
        return catalog;
    
      }
    
      public static object GetCustomers()
    
      {
    
        IMetadataCatalog catalog = GetCatalog();
    
        IEntity entity = catalog.GetEntity(nameSpace, entityName);
    
        ILobSystemInstance LobSysteminstance = entity.GetLobSystem().
    
        GetLobSystemInstances()[0].Value;
    
        IMethodInstance methodInstance = entity.GetMethodInstance("ReadList", MethodInstanceType.Finder);
    
        object result = entity.Execute(methodInstance, LobSysteminstance);
    
        return result;
    
      }
    
      public static void UpdateCustomer(int CustomerID, string FirstName, string MiddleName, string LastName)
    
      {
    
        IMetadataCatalog catalog = GetCatalog();
    
        IEntity entity = catalog.GetEntity(nameSpace, entityName);
    
        ILobSystemInstance LobSysteminstance = entity.GetLobSystem().
    
        GetLobSystemInstances()[0].Value;
    
        IMethodInstance methodInstance = entity.GetMethodInstance ("Update", MethodInstanceType.Updater);
    
        object[] args = { CustomerID, FirstName, MiddleName, LastName };
    
        entity.Execute(methodInstance, LobSysteminstance, ref args);
    
      }
    
      public static void DeleteCustomer(int CustomerID)
    
      {
    
        IMetadataCatalog catalog = GetCatalog();
    
        IEntity entity = catalog.GetEntity(nameSpace, entityName);
    
        ILobSystemInstance LobSysteminstance = entity.GetLobSystem().
    
        GetLobSystemInstances()[0].Value;
    
        IMethodInstance methodInstance = entity.GetMethodInstance("Delete", MethodInstanceType.Deleter);
    
        object[] args = { CustomerID };
    
        entity.Execute(methodInstance, LobSysteminstance, ref args);
    
      }
    
    }

    5. Now, just call these methods from the event handlers of your GridView.

    Surfacing data in a Visual Web Part, application page, or a user control, is not a whole lot different than the way that you do this in a plain vanilla ASP.NET Web application. Here a few take-away points:

    · You can configure data sources visually by using an ASP.NET project and port over your data source object. – or – you can just write XML that describes the data source yourself.

    · If you use a separate assembly for your data access code, make sure to sign the assembly and add that assembly to the package manager.

    You can get to data described in the Business Data Connectivity service by using the Business Data Connectivity services object model.

    Norm Estabrook

  • Visual Studio SharePoint Development Blog

    Visual Studio 2010 SharePoint Developer Tools ‘Import’ Templates

    • 2 Comments

    With Visual Studio 2010, Microsoft has introduced in-the-box tools for SharePoint development. Included in those tools are various templates for you guys to start off with e.g. Visual Webparts, Content Type, List Instances, Workflows etc. There are two templates provided which support what our team has come to call the continuum between SharePoint Designer and Visual Studio. The two templates are the ‘Import SharePoint Solution Package’ template and the ‘Import Reusable Workflow’ template.

    There seems to be some confusion around when to use the Import SharePoint Solution Package vs. Import Reusable Workflow templates. This blog post will get into the details of the differences and when we would want to use each of the templates. The key difference between the Import Reusable Workflow and the Import Solution Package is that the Import Reusable Workflow project template actually converts your declarative SharePoint Designer workflow into a VS code workflow that we can then open in the Visual Studio workflow designer, make edits, add code activities, debug and even add association or initiation forms to. The Import SharePoint Solution Package template on the other hand allows us to import reusable workflows (like the Import Reusable Workflow template), but the key difference is that it does not convert the workflow to a code workflow. This means we won’t be make edits, code additions or debug the workflow.

    The primary scenarios for wanting to use the Import Solution Package template are:

    • Importing custom SharePoint items (lists, content types, fields etc.) from an existing site
    • Importing entire existing site into Visual Studio and customizing it

    The primary scenarios for wanting to use the import Reusable Worklfow templates are:

    • Importing and converting Reusable Workflows (made in SharePoint Designer) into code workflows for the purposes of customizing the Workflow with custom activities and code.
    • Adding initiation and association forms to your converted Workflow

    The rest of the blog shows the step by step of how the VS ‘import’ templates differ.

    We will be using a solution package which was exported from a SharePoint Foundation site. This solution package contains a very simple workflow and a custom list instance both created in SharePoint Designer (SPD).

    The workflow looks like the following in SharePoint Designer:

    image

    This is a very simple Workflow which checks if the title field contains the words ‘New task’ and if it does the task is then assigned to the person who created it.

    The list instance looks like the following in SharePoint Designer:

    image

    Once we have created the Workflow and the Custom List, we can export the entire site via SharePoint (Site Actions -> Site Settings -> Save Site as Template). SharePoint will save this site as a WSP (SharePoint Solution Package) file and we will be using this solution package with the aforementioned templates and pointing out how they differ and when to use them.

    Import SharePoint Solution Package

    We start off by creating a new project in Visual Studio 2010 and use the ‘Import SharePoint Solution Package’ template from new project dialog:

    image

    For this blog, we’ll be using Visual Basic, but all SharePoint development templates are available in both C# and VB. I just like VB better :).

    After naming the project (‘wspimportblog’ in this case) we press “OK” and we see the SharePoint Customization Wizard page:

    image

    This wizard, which is the same for every SharePoint project template in VS, gives us the option of selecting which local site we want to choose for debugging and the trust level of this particular SharePoint solution. After pressing “Next” we get to a wizard which is specific to the Import Solution Package template. This particular page allows us to select the solution package we want to import from the file system:

    image

    After selecting the solution package that we exported above, we are presented with a list of items that are available within.

    image

    The wizard parses through the entire solution package and lists out all available items in the solution package along with their types .

    We can select the items we want to import using the checkbox next to each item. The checked items will be imported into your Visual Studio 2010 project by default, which means that if we went ahead with the wizard without changing the default selection we would end up importing the entire exported site into your VS project. For the purposes of this blog we just selected custom list instance (Shopping List), and the workflow created in SharePoint Designer (the workflow appears as a module instead of a workflow, I’ll explain why this happens later on):

    image

    If we scroll through the list of items to be imported in the wizard we will notice that there is a Workflow list instance in the list as well. This list instance is created when SharePoint designer is installed on the SharePoint server and SharePoint designer is used to deploy a Workflow. This list is where all the workflows (declarative or code) are deployed to. If we did not have SharePoint designer deployed Workflows on the machine we were deploying to, we would have to import the Workflow list instance as well in order to successfully deploy the imported workflow module on the target site.

    Hint: We can press Ctrl+A (select all) when one of the items in the list is selected. This will select all the available entries in this list and allow us to select or unselect all of the items in the list with a single click; something which is very useful when we just want to select a few items from the list unless you want to go and select or unselect every item individually :).

    Once we press Finish we might be presented with a ‘Selection Dependency Warning’ dialog:

    image

    When we make the selection of items we want to import (previous image) the wizard detects the dependencies of the selected items and prompts the user to ask if they want the dependencies imported along with the actual items. If we are importing a solution package which was generated on a site different to where we will deploy it back (target site), then it will be probable that all the required dependencies are not available on the target site and importing them will enable successful deployment of the selected items. In this case, we want all the dependencies to come into the project, so we should press “Yes”. The wizard parses out the items that are to be imported and builds a Visual Studio 2010 project containing all those items. This is what the Solution explorer should look like once the solution package has been successfully imported:

    image

    Notice how Visual Studio 2010 recognizes what is being imported. List Instances, Fields and Modules are placed under the List Instances, Field and Module folders etc. Furthermore the required features are created (3 in this case). One feature would contain the List, the other the workflow and finally there will be one feature for the imported property bags. Property bags, which can be required while deploying, will always be brought in and handled by VS i.e. they will not show up in the dependency warning dialog or in the item selection dialog, but they will be imported.

    Previously I mentioned that the workflow we were importing was showing up as a Module, because of which, we can now see that the Workflow is under the “Modules” folder in the Solution Explorer. This is because of the difference between how we import workflows in the ‘Import SharePoint Solution Package’ template and the ‘Import Reusable Workflow’ template. For this template (Import SharePoint Solution Package) we bring the workflow in as a module to be able to deploy it back to SharePoint. The workflow cannot be customized or debugged (If you want to customize or extend your declarative Workflow, move on to the next section and we’ll discuss how that can be done). However other items (non-workflow) can be used. E.g. if we imported a content type, or imported a field, we could use those with other SharePoint Items that we create within the project.

    When importing an entire site into Visual Studio, there may be items in the solution package that we don’t recognize. These unrecognized items will be placed in an “Other elements” folder within your solution; however this “Other elements” folder is not deployed.

    Pressing F5 deploys both the List and the Workflow up to SharePoint. Since Visual Studio 2010 treats the imported workflow as a module with this template, there isn’t an option to associate this workflow to a list from within Visual Studio 2010. To use the recently deployed workflow we will have to go inside SharePoint and associate the workflow with an appropriate list.

    Import Reusable Workflow

    Onto using the ‘Import Reusable Workflow’ template! We use the same solution package that we used with the ‘Import SharePoint Solution Package’ template in the previous section. In the ‘New Project’ dialog we select the ‘Import Reusable Workflow’ template and give it a name (‘workflowimport’ in this case):

    image

    Upon pressing “OK” we get to the SharePoint Customization Wizard. For the ‘Import Reusable Workflow’ template the wizard always defaults to ‘Deploy as Farm Solution’. This is because code workflows can only be deployed as a farm solution and therefore ‘Deploy as sandboxed solution’ is greyed out. The second wizard page lets us choose the solution package file from the file system, similar to the ones in ‘Import SharePoint Solution Package’ template. Once we select the solution package we want and press “Next” the wizard parses through the solution package and finds all Workflows contained within:

    image

    In the previous template, the workflow was recognized as a module which keeps the workflow as a declarative workflow that can’t be edited or extended with code in VS, but in the case of the ‘Import Re-usable Workflow’ template, the wizard not only recognizes the custom Workflow (Workflow1) it also converts the declarative workflow to a code workflow, as evidenced by the screen shot above. Once we press finish the VS project containing the workflow is created and the solution explorer should look something like:

    image

    The workflow is now recognized and placed under the “Workflows” folder. For further customization we can also associate the workflow from within VS using the ‘Workflow debug settings’ which is available when we right-click the workflow in the solution explorer or we could add an initiation or association form for this Workflow (Right-click on the Workflow -> Add new item -> Initiation or Association form). Once the workflow has been converted into a code workflow, it can be opened up in the workflow designer. The workflow designer has a whole list of controls that can be used to modify the workflow and write code to customize it, put in breakpoints to debug and step through the code etc. (that is a blog for another day :))

    image image

    With the ‘Import Reusable Workflow’ template we don’t need to import the Workflow list instance regardless of whether there is a SharePoint Designer deployed Workflow on the SharePoint server we are deploying to. Upon conversion and association Visual Studio 2010 makes sure that all the requirements for successful deployment of the workflow are covered.

    Once the workflow has been customized and associated, we can press F5 and the converted workflow is then deployed out to the Workflow List in the target SharePoint site.

    Wrap up

    Hopefully this blog helps answer some questions regarding the difference between the two import templates.

    The ‘Import Reusable Workflow’ template parses reusable WFs out of a solution package and converts them into code workflows so that the developer can customize and debug the workflow.

    The ‘Import SharePoint Solution Package’ template gives the developer the opportunity to select some or all of the items available inside the solution package and then work with them.

    For more information around the importing workflows and entire solution packages please refer to the following MSDN documentation:

    Please let us know if there are any questions around this topic and we can hopefully help you out. Happy Importing!

     

    Saaid Khan

  • Visual Studio SharePoint Development Blog

    Walkthrough of enabling CRUD for SharePoint 2010 external lists using Visual Studio 2010

    • 0 Comments

    In our previous blog post of this series Walkthrough of creating a SharePoint 2010 external list using Visual Studio 2010 Beta, we introduced how to create a simple “Hello world” external list in SharePoint 2010 Beta using Business Data Connectivity Designer in Visual Studio 2010 Beta.

    In this blog, we will show you how to pull data from an external database into an external list and enable Create, Read, Update and Delete (CRUD) functions to the external list.

    First of all, you need to have SharePoint 2010 Public Beta and Visual Studio 2010 installed on your machine in order to complete this walkthrough. We’ll use “Northwind” database as external data source, so if you do not have an existing “Northwind” database available, we’ll walk you through to create a local database using SQL Server Express first (SQL Server Express comes with Visual Studio installation by default, in case you don’t yet have it, download it here).

    At the end of this post, we will complete with a BDC model project which has a “Customer” entity connects to “Customer” table in “Northwind” database, and have CRUD operations enabled. The finished project can also be downloaded from here.

    Prepare the data source

    If you already have a “Northwind” database, you can skip this section. Otherwise, please download SharePoint2010_BDCSamples.zip from here and extract the SQL script file CreateSampleNorthwindDB.sql.

    Open Visual Studio. Go to View->Server Explorer. Right click Data Connections in Server Explorer, and select Create New SQL Server Database.

    1. In the prompt dialog, type “localhost\sqlexpress” in Server Name text box, and give the new database name “SampleNorthwind”.

    * If you're using the SQL Express that comes with SharePoint Server, please replace “localhost\sqlexpress" with "localhost\sharepoint”.

    2. Start a Command Prompt. Go to Start->Run, type “Cmd” in the text box and click OK.

    3. In the Command Prompt, type in following command and press enter:

    sqlcmd -S localhost\sqlexpress -d samplenorthwind -i <Path of CreateSampleNorthwindDB.sql file>

    Create BDC Project

    Create a new C# BDC Model project and rename it “BdcSampleCSharp”. VB code snippets will also be provided, so you can create VB BDC Model project if you want. In this walkthrough, we will use C# project as an example. (Check this blog post on how to create a BDC project)

    Connect to external data source

    To use the SampleNorthWind database, we add a LINQ to SQL model to the project:

    1. On the Project menu, click Add New Item, in the prompt Add New Item dialog select Data in the Installed Templates pane, in the Templates pane select LINQ to SQL Classes, in the Name box, type “Customer”, and then click Add.

    2. In the Server Explorer, go to Data Connections->[hostname]\sqlexpress.SampleNorthWind.dbo->Tables->Customers, drag the Customers table and drop it on the Customer.dbml design surface.

    3. Add a new class file and rename it “CustomerDataContext.cs”. Replace the code of the class with the following code snippet.

    Note: We made the connection string a constant in the code only for demo purpose, if you’re using your own database, modify the connection string as needed. In our future post we will introduce how to set the connection string in a custom property on LobSystemInstance inside the BDC model and read the value through IContextProperty interface at runtime.

    C#:

    public partial class CustomerDataContext
    {
      private const string ConnectionString = @"Data Source=localhost\SQLEXPRESS;Initial Catalog=SampleNorthwind;Integrated Security=True;Pooling=False";
      public CustomerDataContext() : 
                base(ConnectionString, mappingSource)
      {
        OnCreated();
      }
    }

    VB:

    Partial Public Class CustomerDataContext
      Private Const ConnectionString As String = "Data Source=localhost\SQLEXPRESS;Initial Catalog=SampleNorthwind;Integrated Security=True;Pooling=False"
      Public Sub New() MyBase.New(ConnectionString, mappingSource)
        OnCreated()
      End Sub
    End Class

    Design BDC Model

    1. On the design surface, delete entity Entity1 which is created by default. On the View menu, click on Toolbox if it is not shown. Create a new entity by drag and drop the Entity icon from Toolbox onto design surface (see the screenshot below). In the Properties Browser, change the value of Entity’s Name property to “Customer”.

    clip_image001

    2. Create a new Identifier CustomerID on entity Customer. To do so, on the design surface, right click the entity, click Add->Identifier. A new identifier appears on the entity, and then rename it to “CustomerID”.

    3. Create a Specific Finder method for the entity. To do so, on the design surface, select entity Customer, you could find a <Add a Method> command in the Method Details Window. If the Method Details Window is not opened, you can find it in menu View->Other Windows->BDC Method Details. From the <Add a Method> drop-down list, select Create Specific Finder Method:

    clip_image002

    A method named ReadItem appears on entity Customer. In the Method Details Window, you will find that the method takes a In parameter and a Return parameter. In the next step we will define TypeDescriptors associated with these parameters.

    4. Add TypeDescriptors for the return parameter Customer. The edit need to be done in BDC Explorer. You can find it by going to View->Other Windows->BDC Explorer.

    a) In the Method Details Window, click <Edit> command in the drop down control from TypeDescriptor Customer as depicted below. After the click the BDC Explorer will get focused on the TypeDescriptor Customer.

    clip_image003

    b) In BDC Explorer right click the focused TypeDescriptor Customer and select Add Type Descriptor:

    clip_image004

    A new TypeDescriptor is created under TypeDescriptor Customer. In the Properties Browser, rename it to “CustomerID”. Next you need to set the Identifier property to “CustomerID” to tell the BCS runtime which identifier this TypeDescriptor represents. Here is a screenshot of Properties Browser after this step:

    clip_image005

    c) Continue to add following TypeDescriptors under Customer by repeating the operation described above: Address, City, CompanyName, ContactName, Country, Fax, Phone, PostalCode and Region, for each TypeDescriptor, you need to change its Type Name to make sure they match the type defined in the LINQ to SQL model. In this example, all the TypeDesriptors have a type of System.String which is the default one so we do not need to change them. After this step, we get the following TypeDescriptors in BDC Explorer:

    clip_image006

    d) Next we need to define the actual type of the TypeDescriptor Customer. Click TypeDescriptor Customer in BDC Explorer. You will find in the Properties Browser the value of Type Name property is System.String by default, we need to change it to “BdcSampleCSharp.Customer, BdcModel1” which is a LobSystem qualified type name. This specifies the actual the data type of the data structure that is represented by this TypeDescriptor Customer.

    5. Create the other types of methods by the same way described in step 6. After this step we will have five methods in the entity Customer: ReadItem, ReadList, Create, Update and Delete. If you check the ReadList method in Method Details Window, the TypeDescriptors of the return parameter have already been defined with the same structure as we just built above. This is because when creating a new method, BDC designer will search the possible TypeDescriptors defined in the other methods of this entity and copy them to the newly created methods. This saves the developers so much time to define them repetitively.

    Add code behind to access external data source

    Now it’s time to add code to implement the CRUD functions. In Solution Explorer, find and open CustomerService.cs, and then replace the implementation with the following code snippet:

    C#:

    public static Customer ReadItem(string customerID)
    {
      CustomerDataContext context = new CustomerDataContext();
      Customer cust = context.Customers.Single(c => c.CustomerID == customerID);
      return cust;
    }
    
    public static IEnumerable<Customer> ReadList()
    {
      CustomerDataContext context = new CustomerDataContext();
      IEnumerable<Customer> custList = context.Customers;
      return custList;
    }
    
    public static Customer Create(Customer newCustomer)
    {
      CustomerDataContext context = new CustomerDataContext();
      context.Customers.InsertOnSubmit(newCustomer); context.SubmitChanges();
      Customer cust = context.Customers.Single(c => c.CustomerID == newCustomer.CustomerID);
      return cust;
    }
    
    public static void Delete(string customerID)
    {
      CustomerDataContext context = new CustomerDataContext();
      Customer cust = context.Customers.Single(c => c.CustomerID == customerID);
      context.Customers.DeleteOnSubmit(cust);
      context.SubmitChanges();
    }
    
    public static void Update(Customer customer, string customerID)
    {
      CustomerDataContext context = new CustomerDataContext();
      Customer cust = context.Customers.Single(c => c.CustomerID == customer.CustomerID);
      cust.CustomerID = customer.CustomerID;
      cust.Address = customer.Address;
      cust.City = customer.City;
      cust.CompanyName = customer.CompanyName;
      cust.ContactName = customer.ContactName;
      cust.ContactTitle = customer.ContactTitle;
      cust.Country = customer.Country;
      cust.Fax = customer.Fax;
      cust.Phone = customer.Phone;
      cust.PostalCode =customer.PostalCode;
      cust.Region = customer.Region;
      context.SubmitChanges();
    }

    VB:

    Public Shared Function ReadItem(ByVal customerID As String) As Customer
      Dim context As New CustomerDataContext
      Dim cust = (From c In context.Customers _
      Where c.CustomerID = customerID _
      Select c).Single()
      Return cust
    End Function
    
    Public Shared Function ReadList() As IEnumerable(Of Customer)
      Dim context As New CustomerDataContext
      Return context.Customers
    End Function
    
    Public Shared Function Create(ByVal newCustomer As Customer) As Customer
      Dim context As New CustomerDataContext
      context.Customers.InsertOnSubmit(newCustomer)
      context.SubmitChanges()
      
      Dim cust = (From c In context.Customers _
      Where c.CustomerID = newCustomer.CustomerID _
      Select c).Single()
      Return cust
    End Function
    
    Public Shared Sub Delete(ByVal customerID As String)
      Dim context As New CustomerDataContext
      Dim cust = (From c In context.Customers _
      Where c.CustomerID = customerID _
      Select c).Single()
      
      context.Customers.DeleteOnSubmit(cust)
      context.SubmitChanges()
    End Sub
    
    Public Shared Sub Update(ByVal customer As Customer, ByVal customerID As String)
      Dim context As New CustomerDataContext
      Dim cust = (From c In context.Customers _
      Where c.CustomerID = customer.CustomerID _
      Select c).Single()
    
      cust.Address = customer.Address
      cust.City = customer.City
      cust.CompanyName = customer.CompanyName
      cust.ContactName = customer.ContactName
      cust.ContactTitle = customer.ContactTitle
      cust.Country = customer.Country
      cust.Fax = customer.Fax
      cust.Phone = customer.Phone
      cust.PostalCode = customer.PostalCode
      cust.Region = customer.Region
      context.SubmitChanges()
    End Sub

    Create an external list to test out the BDC Model!

    Now we are done! Let’s deploy the solution and create an external list to test it out (Check this blog to see how to create an external list). After the list is created, you will see the following page appears when you click on the list name:

    clip_image007

    All the data are pulled out to SharePoint successfully, now you can create, delete or edit customer records.

    To create a new Customer, find the List Tools->Items->New Item button on the ribbon shown in the following screenshot:

    clip_image008

    Click on the button, New Item dialog will pop out as below:

    clip_image009

    Fill in the dialog and click Save, you will find the item created in the list right away.

    To edit or delete the item, just click the down arrow at the right side of CustomerID, all the operations you need are there.

    clip_image010

    Yanchen Wu

  • Visual Studio SharePoint Development Blog

    Walkthrough of creating a SharePoint 2010 external list using Visual Studio 2010

    • 6 Comments

    There are a bunch of SharePoint features in Visual Studio 2010. You may have already heard about them from reading the blog Short Overview of SharePoint Features in Visual Studio 2010 or by other means. Today I want to introduce one of them, Business Data Connectivity (BDC) designer, which is available in the project template Business Data Connectivity Model. If BDC is new to you, here is a short description. BDC is one of two most important architectural components of Microsoft Business Connectivity Services (BCS) which enables users to read and write data from external systems—through Web and Windows Communication Foundation (WCF) services, databases, and Microsoft .NET Framework assemblies—from within Microsoft SharePoint 2010 and Microsoft Office 2010 applications. This MSDN webpage Business Data Connectivity (BDC) Service has a more descriptive version.

    Visual Studio 2010 helps a SharePoint developer to develop, debug and deploy .NET assemblies as external data sources to SharePoint. In the following paragraphs, I will walkthrough with you how to create your first SharePoint external list using Visual Studio 2010. In order to make this walkthrough work on your machine, you need to install SharePoint 2010* and Visual Studio 2010#.

    *: Please read Setting Up the Development Environment for SharePoint Server before the installation. If you are using SharePoint Foundation 2010 you will need to create a Feature Event Receiver to enable the import of BDC models. How to create a Feature Event Receiver will be covered in a future blog post.

    #: Please make sure Microsoft SharePoint Development Tools component is selected when installing. It is chosen by default if you choose Full installation.

    Let’s start the journey.

    1. Create a new BDC Model project. (Main menu: File -> New -> Project…). In the left column of the New Project dialog, you are able to find node 2010 under tree view Visual C# -> SharePoint. Similarly you can find same node under Visual Basic -> SharePoint. In the middle column of the dialog, you should be able to see Business Data Connectivity Model listed as one of the project templates. See the screenshot as follows. Here I am creating BDC Model project in Visual C#. You are able to do the same things in Visual Basic.

    2. After clicking [OK] button in the New Project dialog, the SharePoint Customization Wizard dialog will be displayed. In this dialog you can customize the local site you want to target and trust level for the SharePoint solution. Since a BDC model is deployed to a farm, a collection of one or more SharePoint servers and one or more SQL servers, only “Deploy as a farm solution” option is enabled. Here is the screenshot of the dialog.

    3. When you click [Finish] button in the SharePoint Customization Wizard dialog, the BDC Model project will be created. There are four main UI panes that help you manage the BDC model visually. They are the BDC Designer Surface, BDC Method Details Pane, BDC Explorer, and Properties Browser.

    a. The BDC Designer Surface allows editing entities, identifiers, methods, and associations between entities. And you can do that either from toolbox or context menus.

    b. The BDC Method Details pane, where its name is already self-explanatory, lets you edit everything related to a method, from the method itself, its parameters to its parameters’ type descriptors, from method instances to filter descriptors, etc.

    c. BDC Explorer lists and organizes metadata objects in the BDC model in a tree view. It lets you to browse and search metadata objects in a graphical way and allows you to copy/cut/paste type descriptors between different parameters or type descriptors.

    d. Properties Browser gives you a familiar way of editing components and attributes of BDC Models. We use it to supplement the functions offered by the other three panes and list all the attributes for a particular metadata object for editing. Here is a typical layout of a BDC Model project as described above.

    4. If you notice, there is already a default entity generated for you when the project is created. This default entity also has an identifier and two methods ReadItem and ReadList created. One is a Finder method that is to return a collection of data. The other is a Specific Finder method that is to return a specific entry based on the input parameter(s).

    5. Now let’s deploy to the SharePoint server. You can either click the deploy menu item in main menu (Build -> Deploy Solution), or in the context menu of the project or the solution. In the output you will see several activities happening including packaging, solution retraction/addition, deployment, etc.

    6. Let’s open the target site and see if our model has been successfully deployed. Open the target site with any browser supported by SharePoint, like Internet Explorer 8. Create an external list based on the model we just deployed. Here are the steps to create an external list in case you are new to it.

    a. In main menu: Click Site Actions -> More Options…

    b. On the Create dialog, select External List, click [Create] button in the right column

    c. On the next external list create form, type a name for the list. Check ‘Yes’ to display the list on the Quick Launch for easy access. Then click to select the model we just deployed in the External Content Type Picker form. Click [Create] on the external list create form. Now the Hello World list is displayed.

     

    In the main menu under List Tools -> Items, you may find only “View Item” option is enabled. Guess why? Yes, it is because the default entity only has a Finder method to view the entire list and a Specific Finder method to view a specific item. In our next blog in this series, we will show you how to add more functions like Add, Update and Delete to the list as well as pull data from external data sources.

    Jeff Chen

  • Visual Studio SharePoint Development Blog

    How to deploy a custom content master and use it in an application page

    • 6 Comments

    In SharePoint 2007, Application Pages would inherit from Application Master deployed to Layouts folder. The Site Pages would inherit from a different Site Master deployed to SharePoint Content database. Since there was no way for application pages to inherit from the same master as that of the site pages, the look and feel of the two kinds of pages in a SharePoint application would be different, by default. This problem is overcome in SharePoint 14 with the introduction of Dynamic Master Page feature.

    Application Pages that wants to inherit from site master will have to specify DynamicMasterPageFile attribute instead of the MasterPageFile attribute in the Page directive as

    <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="ApplicationPage1.aspx.cs" Inherits="SharePointProject15.Layouts.SharePointProject15.ApplicationPage1" DynamicMasterPageFile="~masterurl/default.master" %>

    DynamicMasterPageFile attribute can only take two tokens as values; ~masterurl/default.master or ~masterurl/custom.master. These tokens will be resoved by SharePoint at runtime to point to the site's default master and the site's custom master respectively.

    Deploying a custom content master page and using it in an application page involves three steps:

    1. Create and deploy a custom content master.
    2. Create and deploy a site definition that uses the content master created in step #1 and create a site based on it. [Creating a site definition is just for illustration and is not necessary if you are modifying an existing Site to point to a new content master.]
    3. Create an application page to be deployed to the site created in step #2

    1. Create and deploy a custom content master.

    1.1 Create a C# empty SharePoint project with all default selections and add a module element with name "MasterPage" to it.

     

    1.2 Delete the sample.txt by right clicking on it in the solution explorer and selecting delete

    1.3 In Solution Explorer, Right click the "MasterPage" module folder and add a file with name MyCustomContent.master (For example you can add a text file and change the extension from .txt to .master) and add the content to this file. Or you can start with SharePoint's existing content master and modify as needed. For simplicity let us choose an existing content master and proceed with it. To do this, go to master page gallery in SharePoint. Click on the dropdown of the master page you wish to save for example. Minimal.Master and select "Send To" and then "Download a Copy" and save the file.

     

    Right click the "MasterPage" module folder and select "Add Existing" to add the saved master page. Be sure to change the name of the master page (say for example MyCustomContent.master) to avoid overwriting the SharePoint created master page. Double click on the master page to open it in the default editor and make the necessary modifications to the master page. In order to demonstrate the active master page is the new custom master in a simple way, let us change the ContentPlaceHolder with Id "PlaceHolderMain" to "PlaceHolderMyCustomMain".

    1.4 Modify the element file associated with the module as follows:

    <?xml version="1.0" encoding="utf-8"?>

    <Elements xmlns="http://schemas.microsoft.com/sharepoint/">

    <Module Name="MasterPage" Url="_catalogs/masterpage">

    <File Path="MasterPage\MyCustomContent.master" Url="MyCustomContent.master" />

    </Module>

    </Elements>

    1.5 Right click the project in the solution explorer and select Deploy.

    1.6 Verify that the master page got deployed to the master page gallery.

     

    2. Create and deploy a site definition that uses the content master created in step #1 and create a site based on it.

    2.1 Create a C# SharePoint Site Definition project called "MyCustomSiteDefinition".

    In the onet.xml that gets created as part of the Site Definition project modify the configuration element so that the MasterUrl and CustomMasterUrl points to the newly deployed custom content master, as follows

    <Configuration ID="0" Name="MyCustomSiteDefinition" MasterUrl="/_catalogs/masterpage/MyCustomContent.master" CustomMasterUrl="/_catalogs/masterpage/MyCustomContent.master">

    Since we have changed the PlaceHolderMain to PlaceHolderMyCustomMain, we will also have to change it in the default.aspx. If we miss this step, SharePoint will throw error when we create a site based on this site definition.

    2.2 Open the default.aspx file in the Site Definition project and change the ContentPlaceHolderId attribute in the default.aspx file to "PlaceHolderMyCustomMain" as shown below.

     

    2.3 Right click the Site Definition project in the solution explorer and select Deploy.

    2.4 In SharePoint, Click Site Actions | New Site. Select SharePoint Customizations link on the left navigation, enter the title and Url name for your site (example MyCustomSite)

     

    2.5 Click on Create to create the site.

     

    3. Create an application page to be deployed to the site created in step #2.

    3.1 Create a C# Empty SharePoint project with local site used for debugging pointing to the site created in step #2 which is http://<machineName>/MyCustomSite.

    Choose the option to Deploy as a farm solution. This is required since application pages can only be deployed to layouts folder and not to content database.

     

    3.2 Click Finish and add an Application Page to the project. Right click on the Application Page and select "Set as Startup Item" to set it as startup item.

    By default, it shows a warning since the active master page does not have "PlaceHolderMain" defined. If you invoke the IntelliSense, the new placeholder can be seen.

     

    This application page inherits the newly deployed content master and the IntelliSense reflects the same. Press F5 to deploy it and view it in SharePoint. You can see that the look and feel of this page is inherited from the new custom content master.

    Pallavi Vajranabhaiah

     

  • Visual Studio SharePoint Development Blog

    Building Visual Studio SharePoint Projects using Team Foundation Build

    • 6 Comments

    With Microsoft’s introduction of the Visual Studio 2010 SharePoint Developer Tools and its continually growing support for team development, the SharePoint Developer Tools team has published an MSDN article on how to configure your Team Foundation Build server(s) to support both the building of Visual Studio SharePoint projects and the creation and validation of SharePoint deployment packages (.wsp).

    The article outlines the steps needed for setting up both Team Build 2008 and Team Foundation Build 2010 server configurations.

    Additionally, the team has also created a PowerShell script that will aid users in collecting and installing the required assemblies for build Visual Studio SharePoint projects. The steps to use the PowerShell script are quite simple.

    First, download the .ps1 file from the MSDN Code Gallery and copy it onto a SharePoint Tools developer’s machine or any machine that has Visual Studio 2010 and SharePoint 2010 installed. Before you can execute the script, you need to enable the correct permissions. To do so, run PowerShell under administrator privileges and enter the following command:

    Set-ExecutionPolicy RemoteSigned

    Next, navigate to the directory where you copied the .ps1 script and enter the following command

    .\ SharePointProjectToTfsBuildServer.ps1 –Collect

    This will gather all the necessary files from the developer’s machine and copy them into a sub folder named “Files”. Copy this subdirectory, along with the PowerShell script onto the build server(s).

    Finally, the last step is to tell the PowerShell script to install the files. Once again, we’ll need to enable the correct permissions to execute the script so again run PowerShell as an administrator and enter the following command:

    Set-ExecutionPolicy RemoteSigned

    Next we’ll do the same thing we did when we “collected” the required assemblies but instead of passing the “-Collect” parameter, we’ll pass it “-Install”, like so:

    .\ SharePointProjectToTfsBuildServer.ps1 –Install

    This moves all the files into the correct place and makes any other changes to the system, if needed.

    Now you’re all set to begin building your Visual Studio SharePoint projects on your Team Build server(s). Consult the MSDN article for more information on how to correctly set up your build definition in TFS.

    Scot Moorhead

  • Visual Studio SharePoint Development Blog

    Visual Studio 2010 & .NET Framework 4 RTM is Available

    • 0 Comments

    We are very excited to announce the availability of Visual Studio 2010 and .NET Framework 4 on April 12th.  This represents the biggest tools release from Microsoft in many years.

    As mentioned in Somasegar’s recent blog post, the new release of Visual Studio 2010 has plenty of compelling new features and updates that will make every developer more productive.

    • Visual Studio 2010 allows users target of the right platform for their application, including Windows 7, Windows Server 2008 R2, SQL Server 2008, SharePoint. Office, Windows Azure, and Windows Phone 7 applications using their existing skills.
    • Visual Studio 2010 is a rich, personalized development environment.  We know that software developers spend much of their time in the IDE, and features like the new editor and multi-monitor support make your time in Visual Studio more productive and enjoyable.
    • Teams are able to work more efficiently using Application Lifecycle Management tools.  We’ve done a great deal of work in Visual Studio 2010 to improve testing and debugging tools.  Features like IntelliTrace and easy project management help your team ensure high quality.

    In addition to these features, there are a number of new features available for building SharePoint 2010 solutions.  Here are some of those:

    • Complete integration of SharePoint projects within the Visual Studio Integrated Development Environment (IDE).
    • Project templates for creating the most common SharePoint 2010 solutions such as Visual Web Parts, Workflows, Business Connectivity Services (BCS) external content types, Event Receivers, List Definitions, site Definitions, and many more.
    • Project templates which enable declarative artifacts and reusable workflows that were created in SharePoint Designer (SPD) 2010 to be imported into Visual Studio 2010 and then be included in a SharePoint project.  These artifacts and workflows can be modified as needed after they are imported and/or added to existing projects.
    • SharePoint developers have first class access to source code control, code analysis, and many other application lifecycle management features of both Visual Studio 2010 and Team Foundation Server 2010.
    • Item templates for common SharePoint 2010 artifacts such as Web Parts, Application Pages, List Instances, Content Types, Workflow Association & Initiation Forms, Resource files and others.  There is also a generic Empty Element which can be used to create any SharePoint artifact that may be needed.
    • Visual designers for building Web Parts, Workflows, and BCS external content types.
    • Robust packaging and deployment is supported which allows you to add SharePoint items to your project and then press F5 to debug your solution without having to worry about how the items are packaged into features.  Designers are provided for when you want to change the default feature(s) and packaging, in addition to a Packaging Explorer which shows all of the packages, features, and items across all of the projects in the solution.
    • A number of wizards which make creating projects and adding items easier, including support for Sandboxed solutions.
    • Numerous project, item, and file properties which allow the developer to have precise control over how each item/file is packaged and deployed.
    • Connections can be added now to the Server Explorer for any of the site collections on your local SharePoint 2010 server which allows you to quickly see what artifacts exist on the server from within the Visual Studio IDE.
    • Configurable and extensible deployment options for complete control over deployment of the packaged solution.
    • Robust extensibility is available throughout the new SharePoint project system and tools.

    To purchase Visual Studio 2010 now, visit here.  If you are an MSDN subscriber, later in the day on April 12th you can download Visual Studio 2010 from MSDN.

    Mike Morton

  • Visual Studio SharePoint Development Blog

    Deploy a BDC Model project to SharePoint Foundation 2010 using Visual Studio 2010

    • 22 Comments

    Business Connectivity Services (BCS), one of the key components of SharePoint 2010, helps you to access external line-of-business (LOB) data. The SharePoint team posted a blog entry which demonstrates how to create your first BDC (Business Data Connectivity) model using Visual Studio 2010. As indicated in the post, you can use Visual Studio 2010 to deploy your BDC model to Microsoft SharePoint Server 2010.

    However, if you are using Microsoft SharePoint Foundation 2010 on your develop machine, or you want to make the model deployable to Microsoft SharePoint Foundation 2010 on other machines, you will need to write a Feature Event Receiver to enable the deployment of BDC models from within Visual Studio 2010. In this blog post, I’ll show you how to create a Feature Event Receiver to do so.

    Here are the detailed steps:

    1. In Visual Studio 2010, create a BDC project (read this post to learn how) or open your existing BDC project (e.g. “BdcModelProject1”).
    2. Add Feature Event Receiver to BDC project. In Solution Explorer, add a new Feature Event Receiver by right clicking on the feature (Feature1 in this sample) under Features folder and selecting Add Event Receiver.
    3. Write code for the Feature Event Receiver. In the generated code file (the default name is Feature1EventReceiver.cs/vb), replace the code with the sample code (Download here).
    4. Add reference.
      1. Copy Microsoft.BusinessData.dll assembly out of GAC. To do so: Start->Run, type in C:\Windows\assembly\gac_msil. Find Microsoft.BusinessData folder, and then copy Microsoft.BusinessData.dll to folder C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\14\ISAPI.
      2. Add the following two assembly references to your project:
        1. In .Net tab, select Component Name = System.Web, Version=2.0.0.0.
        2. In Browse tab, navigate to folder C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\14\ISAPI, and then add Microsoft.SharePoint.dll and Microsoft.BusinessData.dll.
    5. Set BDC SPI (SharePoint item) property. In Solution Explorer, select the SPI folder (e.g. “BdcModel1”), open Properties Window and update the following two Feature Receiver properties:
    6. C# Project -
      - Assembly = $SharePoint.Project.AssemblyFullName$
      - Class Name = BDCModelReceiver.Features.Feature1.ImportModelReceiver

      VB Project –
      - Assembly = $SharePoint.Project.AssemblyFullName$
      - *Class Name = BdcModelProject1.BDCModelReceiver.Features.Feature1.ImportModelReceiver
      * Replace “BdcModelProject1” with your own project name

    7. Set Feature property. In Solution Explorer, expand Features\Feature1 folder, double click on Feature1.Feature and open Properties window and update the following Feature property:

      C# Project -
      - Receiver Class = BDCModelReceiver.Features.Feature1.ImportModelReceiver
    8. VB Project -
      - *Receiver Class = BdcModelProject1.BDCModelReceiver.Features.Feature1.ImportModelReceiver
      * Replace “BdcModelProject1” with your own project name

    9. Now you can deploy the BDC project (Project->Deploy) or debug the BDC project (F5) to SharePoint Foundation 2010. You will find the external content type being deployed to the metadata store.

    For more information about Business Connectivity Services, please also check out BCS Team blog.

    Rong Lu

  • Visual Studio SharePoint Development Blog

    Importing fields using the Import SharePoint Solution Package project

    • 1 Comments

    A SharePoint Content Type project allows the user to create a content type based on the built-in SharePoint content types. But what about situations where one would want to re-use a built-in field(s) in SharePoint? One way to do this is to use the "Import SharePoint Solution Package" project. This article provides the simple step-by-step procedures on how to achieve this.

    To begin, let's first create a subsite. Imagine this as the site you want to copy the field from. This may or may not be on the same development machine that you're using.

    To create a subsite in SharePoint:

    1. Using Internet Explorer, browse to http://<machinename>
    2. Click on Site Actions | New Site.


    3. Fill-in the following values for the form:
      1. Title: SourceSite
      2. URL name: SourceSite
    4. Click the Create button.

    The “SourceSite” subsite is now created. Let's now use SharePoint's "Save site as template" feature to export the entire subsite to a .wsp file.

    To export a subsite to a .wsp file:

    1. Using Internet Explorer, browse to http://<machinename>/SourceSite
    2. Click on Site Actions | Site Settings.
    3. Click on Save site as template.
    4. Fill-in the following values for the form:
      1. File name: SourceSite
      2. Template name: SourceSite
    5. Click the Ok button.
    6. After the operation completes successfully, click the Solution Gallery link.
    7. Click SourceSite and save the wsp file to your disk.

    We're now ready to import the field into Visual Studio.

    To import a field into Visual Studio:

    1. Start Visual Studio in admin mode.
    2. Create a new C# Import SharePoint Solution Package project.


    3. In Page 1 of the wizard, leave all default values as-is. Click the Next button.
    4. In Page 2 of the wizard, click the Browse button and browse to the directory where you previously saved the SourceSite.wsp file. Click the Next button.
    5. In Page 3 of the wizard, unselect all SharePoint items (Tip: This can easily be done by typing "Ctrl+A" and then hitting the space bar).
    6. Look for the following fields and check them (Tip: This can easily be done by typing the fields you're looking for).
      1. Address
      2. City
      3. State/Province
      4. \Zip/Postal code
    7. Click the Finish button.

    A project will be created that contains the Fields project item. Double-clicking on this project item will show the contents of its Elements.xml:

    Let's now create a content type that will use these fields that we just imported.

    To add a Content Type project item:

    1. From the main menu of Visual Studio, select Project | Add New Item.
    2. In the Add New Item dialog, select Content Type and click Add.
    3. In Page 1 of the wizard, select "Issue" as the base content type. Click the Finish button.

    We now modify the content type to reference the imported fields.

    To reference the fields in the content type:

    1. In Solution Explorer, double-click the Fields project item.
    2. Copy the Fields:


    3. In Solution Explorer, double-click the Content Type.
    4. Paste the Fields into the Content Type so that it would look like this:
    5. Note:
      o Make sure you change the Field tags to FieldRef.
      o Only the ID, Name, and DisplayName attributes are needed.

    We are now ready to debug and deploy the content type and fields.

    To debug the content type and fields:

    1. Set the content type as the default startup item:
      1. Right-click the content type in Solution Explorer.
      2. Select "Set as Startup Item" in the context menu.
    2. Press F5 to start debugging.
    3. Click the content type under the "Custom Content Types" group.

    You'll see the Address, City, State/Province and Zip/Postal Code fields in the columns section.The next step is to create a List Definition and List Instance based on the Content Type.

    To create a List Definition and List Instance based on the Content Type:

    1. From the main menu of Visual Studio, select Project | Add New Item.
    2. In the Add New Item dialog, select the List Definition from Content Type and click the Add button.
    3. Use the defaults in the List Definition wizard. Visual Studio automatically detects the Content Type in your project and uses this.


    4. Click the Finish button.

    A List Definition and List Instance project item are added to the project.


    To debug the List Definition and List Instance:

    1. Set the List Instance as the default startup item:
      1. Right-click the List Instance in Solution Explorer.
      2. Select "Set as Startup Item" in the context menu.
    2. Press F5 to debug. The List Instance will be loaded in IE.
    3. Click the Add new item link.
    4. You'll find the fields at the bottom of the New Item form:


    5. Fill-up the form and click Save.

    You'll notice the Address, City, State, and Zip fields are not displayed in the list. To display them, follow these steps:

    To display certain fields in the list:

    1. Click the List tab under the List Tools tab.
    2. Click Modify View in the ribbon:


    3. Check the fields you want to be displayed in the list view.

    That's it! You've now inherited fields, referenced them in a content type, created a list definition based on the content type, and displayed the fields in the list instance. Hope this helps! :)

    Ian Ching

  • Visual Studio SharePoint Development Blog

    List Definition from Content Type using Event Receiver

    • 1 Comments

    As a SharePoint developer, you’ve probably heard of VSeWSS (Visual Studio extensions for Windows SharePoint Services). A co-worker wrote this post which is an example of how to use VSeWSS to implement a SharePoint solution. I’d like to take that example and show you how adapt it to use the new Visual Studio 2010 SharePoint Developer Tools. Thanks to Pranab for allowing us to use his walkthrough as a point of comparison. Take a moment to read over his introduction for further background on this walkthrough. In short, we will implement a transcript document library using a Content Type with custom fields. When the user uploads a file, it is parsed by an Event Receiver and the custom properties of the item are populated with data from the file. Before proceeding ensure you have the necessary prerequisites: http://msdn.microsoft.com/en-us/library/ee231582(VS.100).aspx.

    Start Visual Studio as administrator and create a SharePoint Content Type project. To do this, click File -> New -> Project… , select Visual C# -> SharePoint -> 2010, select the Content Type project template, name it “ContosoTranscriptDoc” and name the solution “ContosoTranscriptDocLib”, then click OK. In the first page of the project wizard set the Site URL field to match the site you’ll be using for deployment and debugging, then select Deploy as farm solution trust level and click Next (sandboxed trust is possible but requires changes to the sample code below). As shown below, choose the “Document” base Content Type and click Finish.

    clip_image002

    Next we’ll add fields to the Content Type. Expand the ContosoTranscriptDoc node in the Solution Explorer and open the Elements.xml file. Add the following lines within the <FieldRefs> tag.

          <FieldRef ID="{672B4E30-1FDD-48F3-AABC-546404D3D483}" Name="Patient" Required="TRUE" ShowInDisplayForm="TRUE" ShowInNewForm="FALSE" ShowInEditForm="TRUE" />
    
          <FieldRef ID="{3EC8A782-F667-4FB9-970D-D14372811E85}" Name="Doctor" Required="TRUE" ShowInDisplayForm="TRUE" ShowInNewForm="FALSE" ShowInEditForm="TRUE" />
    
          <FieldRef ID="{04D116F7-1381-4CB1-A60C-87A222FB86CB}" Name="PNumber" Required="TRUE" ShowInDisplayForm="TRUE" ShowInNewForm="FALSE" ShowInEditForm="TRUE" />
    
          <FieldRef ID="{25644618-1C4F-49EB-96DC-C1BD5BCD5253}" Name="ServiceDate" Required="TRUE" ShowInDisplayForm="TRUE" ShowInNewForm="FALSE" ShowInEditForm="TRUE" />
    

    I’ve generated the GUIDs using the Tools -> Create GUID feature in Visual Studio.

    Add the following lines before the </Elements> tag while making sure the GUIDs match what you used above:

    <Field ID="{672B4E30-1FDD-48F3-AABC-546404D3D483}" Type="Text" Name="Patient" DisplayName="Patient Name" Sealed="TRUE" StaticName="Patient"> 
    
    </Field> 
    
    <Field ID="{3EC8A782-F667-4FB9-970D-D14372811E85}" Type="Text" Name="Doctor" DisplayName="Attending Doctor" Sealed="TRUE" StaticName="Doctor"> 
    
    </Field> 
    
    <Field ID="{04D116F7-1381-4CB1-A60C-87A222FB86CB}" Type="Text" Name="PNumber" DisplayName="Patient Number" Sealed="TRUE" StaticName="PNumber"> 
    
    </Field> 
    
    <Field ID="{25644618-1C4F-49EB-96DC-C1BD5BCD5253}" Type="DateTime" Name="ServiceDate" DisplayName="Date of Service" Sealed="TRUE" StaticName="ServiceDate"> 
    
    </Field> 
    

    Our Content Type is ready for use; next up is to create the List Definition based on this Content Type. Right click the project node and select Add -> New Item, SharePoint -> 2010 and select the “List Definition from Content Type” project item template, name it “ContosoTranscriptDocLib”. The wizard opens and you can see that our Content Type is automatically selected (see screenshot below). Keep the default options and click Finish. A new List Definition using the custom Content Type is created, as well as a List Instance. Rename the ListInstance1 node in the Solution Explorer to “ContosoTranscripts”.

    clip_image004

    The final step of our implementation is to hook-up an event receiver which pulls data from the document and populates the custom fields of our “ContosoTranscriptDoc” list item. Right click the project node in the Solution Explorer and select Add -> New Item, SharePoint -> 2010, select the “Event Receiver” project item template and name it “ContosoTranscriptDocLibItemEventReceiver”. Note that the event source is already selected for the List Definition. Select both the “An item is being added” and “An item was added” events (see screenshot) and click Finish. This creates an Event Receiver class and hooks up the events you specified to the list.

    clip_image005

    The event receiver file opens automatically. Add the following code within the ContosoTranscriptDocLibItemEventReceiver class to drive the data extraction. Include the using statement “using System.IO;” at the top of the file and overwrite the generated ItemAdding and ItemAdded methods.

            /// <summary>
    
            /// String between MR# and DATE
    
            /// +4 is because "MR#:" itself has the length of 4 characters
    
            /// </summary>
    
            /// <param name="str"></param>
    
            /// <returns></returns>
    
            private string GetNo(string str)
    
            {
    
                int first = str.IndexOf("MR#:") + 4;
    
                int last = str.LastIndexOf("DATE:");
    
                string ouput = str.Substring(first, last - first);
    
                return ouput.Trim();
    
            }
    
            /// <summary>
    
            /// String between DOCTOR and SUBJECTIVE
    
            /// </summary>
    
            /// <param name="str"></param>
    
            /// <returns></returns>
    
            private string GetDoctor(string str)
    
            {
    
                int first = str.IndexOf("DOCTOR:") + 7;
    
                int last = str.LastIndexOf("SUBJECTIVE:");
    
                string ouput = str.Substring(first, last - first);
    
                return ouput.Trim();
    
            }
    
            /// <summary>
    
            /// String between DATE and DOCTOR 
    
            /// </summary>
    
            /// <param name="str"></param>
    
            /// <returns></returns>
    
            private string GetDate(string str)        
    
            {
    
                int first = str.IndexOf("DATE:") + 5;
    
                int last = str.LastIndexOf("DOCTOR:");
    
                string ouput = str.Substring(first, last - first);
    
                return ouput.Trim();
    
            }
    
            /// <summary>
    
            /// String between NAME and MR 
    
            /// </summary>
    
            /// <param name="str"></param>
    
            /// <returns></returns>
    
            private string GetPatient(string str)
    
            {
    
                int first = str.IndexOf("NAME:") + 5;
    
                int last = str.LastIndexOf("MR#:");
    
                string ouput = str.Substring(first, last - first);
    
                return ouput.Trim();
    
            }
    
           /// <summary>
    
           /// An item is being added.
    
           /// </summary>
    
           public override void ItemAdding(SPItemEventProperties properties)
    
           {
    
               base.ItemAdding(properties);
    
               string extension = properties.AfterUrl.Substring(properties.AfterUrl.LastIndexOf(".") + 1);
    
               if (extension != "txt")
    
               {
    
                   properties.Cancel = true;
    
                   properties.ErrorMessage = "Please upload only text files";
    
               }
    
           }
    
           /// <summary>
    
           /// An item was added.
    
           /// </summary>
    
           public override void ItemAdded(SPItemEventProperties properties)
    
           {
    
               base.ItemAdded(properties);
    
               int itemID = properties.ListItem.ID;
    
               string siteUrl = properties.WebUrl + "/";
    
               string listTitle = properties.ListTitle;
    
               // extract the content of the file in a string 
    
               TextReader tr = new StreamReader(properties.ListItem.File.OpenBinaryStream());
    
               string content = tr.ReadToEnd();
    
               tr.Close(); 
    
               string patient = GetPatient(content);
    
               string doctor = GetDoctor(content);
    
               string serviceDate = GetDate(content);
    
               string patientNo = GetNo(content);
    
               properties.ListItem["Patient Name"] = patient;
    
               properties.ListItem["Attending Doctor"] = doctor;
    
               properties.ListItem["Patient Number"] = patientNo;
    
               properties.ListItem["Date of Service"] = DateTime.Parse(serviceDate);
    
               properties.ListItem.Update();
    
           }
    

    That’s it! We’re ready to deploy and test the customization. Remember that our tools automatically add the SharePoint Items to the feature, which is by default included in the package. Here is a screenshot of the feature designer which shows the included SharePoint items and files for deployment. Feel free to update the feature title and description with more descriptive text as I’ve done below.

    clip_image007

    Let’s test our solution. Start debugging of the project (F5) and wait for the SharePoint site to appear. The new ContosoTranscriptDocLib – ContosoTranscript List should be visible in the quick-launch bar. Open the document library and then click the “Add new item” link. A zip file is attached to this post which contains sample input files (there are also some on Pranab’s original post). Browse to the sample file of your choice and click OK. The event receiver will execute and automatically populate the custom fields. Here is a screenshot with the results of the parsing. You can add breakpoints to the event receiver to step through the code.

    clip_image009

    As you can see, the new Visual Studio 2010 SharePoint Developer tools enable rapid implementation and deployment of SharePoint solutions. We’re excited to hear any feedback you have on our feature set.

    - Erik Cutts

  • Visual Studio SharePoint Development Blog

    Deploying files using Mapped Folders

    • 8 Comments

    With Visual Studio 2010 SharePoint Developer Tools, the concept of the Mapped Folder was introduced. A mapped folder is a convenient way for developers to specify a location for any files that need to be deployed on to the SharePoint file system, all from within in a Visual Studio solution. Mapped folders can be included as part of a deployment package (.WSP) and the files will get copied to the correct location when the WSP is installed on to the server.

    Let’s take a quick look at how a developer might use a mapped folder. Say a developer wants to develop a custom application page for their SharePoint site that will consume a custom image. The SharePoint server has a designated location for both application pages and images. With mapped folders, the developer can ensure that their files will be deployed to the correct location. Here’s an example:

    First we need to create a project. In this example, we will start by creating an Empty SharePoint project (Installed Templates->Visual Basic/C#->SharePoint->2010).

    Next, we’ll create our custom image that we want to display. First, let’s setup a mapped folder to the Images directory on the SharePoint farm. To do this, we simply right-click on the project node and select “Add->SharePoint “Images” Mapped Folder”:

    This will create a mapped folder named “Images” in our project. (You can also create it via the “Project->Add SharePoint “Images” Mapped Folder on the main menu bar”)

    In the Solution Explorer, mapped folders look very similar to normal folders but have a small green globe in the bottom right corner of the icon. You’ll notice that underneath the mapped folder there is a sub folder with the same name as the project. This is to help organize images specific to your project and keep developers from inadvertently overwriting another item with the same name.

    Also, if you select the mapped folder and open the property window (F4), you’ll see two entries: Folder Name and Deployment Location. The Deployment Location indicates the location relative to the SharePoint root directory ({SharePointRoot}) on the SharePoint farm.

    Now that we have our mapped folder, we can right-click on the project directory underneath it and add our image file (“Add->New Item’). In this example, I’ve added a bitmap image named ”Bob.bmp”.

    The next step is to create the application page and modify it to show our image. To start, right-click on the project node in the Solution Explorer and select “Add->New Item”. When the Add New Item dialog appears, the “2010” node under SharePoint will be selected. From the list of templates, select the “Application Page” item, give it the name you want, and click “Add”. You’ll notice that when the application page is added to the project, it automatically gets created under the “Layouts” mapped folder, which is the default location on the SharePoint file system for application pages:

    Following its creation, the .aspx file we just added should be opened in the designer. Locate the <asp:Content> element with the ID equal to “Main”. Within that element add an image element and set the ImageUrl attribute to point to the image in your product. It should look like this:

    <asp:Content ID="Main" ContentPlaceHolderID="PlaceHolderMain" runat="server">
    <asp:Label ID="Label1" runat="server" Text="Label" Font-Size="Medium">This is Bob.......</asp:Label>
    <asp:Image ID="Image1" runat="server" ImageUrl="~/_layouts/Images/SharePointProject1/Bob.bmp" />
    </asp:Content>

    The last thing we’ll want to do to make testing our project easier is to set the application page to be our startup item when we F5. To do this, select the project node in the Solution Explorer and open the property window (F4). In the property window, select the “Startup Item” property and choose our application page from the drop down list. Now when we F5, it will take us right to our application page:

    A couple of things to know about mapped folders. First, since mapped folders effectively deploy files onto the SharePoint file system, they are only allowed in farm level solutions. Sandboxed solutions are restricted to only deploying content to the content database on the server. In VS, when you try add a mapped folder to a sandboxed solution, the package validation will generate an error regarding this.

    Second, as you saw when we added the application page, some items go into certain mapped folders by default when they are added to the project. Another example is User Control items (.ascx) which are automatically placed into the User Control mapped folder. While these are the SharePoint “default” locations, there may be times you need to place one of these files in a different location, and this can be done by mapping the folder to a different location.

    Finally, you can create a mapped folder to any folder under the SharePoint root on the farm by opening the Add SharePoint Mapped Folder dialog (Project->Add SharePoint Mapped Folder… from main menu, Add->SharePoint Mapped Folder… from project context menu:

    For instance, if you had a custom web service you wanted to deploy to the SharePoint server, you could simply add a mapped folder that points to the ISAPI directory on the SharePoint file system and dropped the web service in there. Then, when the package gets deployed to the server, the web service will automatically be placed in the ISAPI directory and available for consumption.

    Additional Resources

    MSDN: How to: Add and Remove Mapped Folders

    Scot Moorhead

  • Visual Studio SharePoint Development Blog

    Publishing Silverlight Applications in SharePoint 2010

    • 7 Comments

    In this blog post I’ll walk you through how easy it is to publish Silverlight applications to SharePoint 2010 by using the Visual Studio 2010 tools for SharePoint development.

    This walkthrough requires: a local installation of either SharePoint Foundation 2010 or SharePoint Server 2010, Silverlight 3.0, and Visual Studio 2010. Please see http://msdn.microsoft.com/en-us/library/ee231582(VS.100).aspx for a full list of requirements. Once you have installed the prerequisites start Visual Studio as an administrator. (This is required to create SharePoint projects in VS.)

    To begin, let’s create a simple Silverlight (SL) application. Create a new Silverlight Application project named “MySilverlightApplication” and uncheck the Host the Silverlight Application in a new website option in the New Project wizard. Because we're hosting the SL application in a SharePoint Web part, that option isn't required. On the MainPage.xaml, add a text box, button, and label control. In the button's click event, add code to copy the textbox’s text to the label’s content field. It should look something like this:

    Next, we’ll create a SharePoint project to package and deploy the Silverlight app to our test server. To do this, click File -> Add -> New Project… , select Visual C# -> SharePoint -> 2010, select the Module project template, and then name it “DeploymentProject”. Leave the other settings at their defaults and click OK. In the wizard that is displayed click the Finish button to add this second project to the solution. Notice that a Module1 project item is included in this new project. Feel free to expand the Module1 node and delete the unnecessary sample.txt file. Next, we’ll want to add the output of the Silverlight application to our package. To do this, select the Module1 node in Solution Explorer, select Project Output References in the Properties window, and then click the ellipsis (…) button.

    Note: The Project Output References property of a SharePoint Item determines whether the output of a project is packaged as an element file, template file, root file, or other deployment type. These files will be packaged only if the item is included in the package. If you would rather include project output as an assembly to be deployed to the GAC or BIN folder, then use the Advanced tab in the Package Designer.

    In the Project Output References dialog, click the Add button on the left. The new project output reference is automatically selected in the list. Choose ElementFile in the Deployment Type drop-down list. Then select the Project Name drop-down and choose the Silverlight project you added to the solution earlier. Here’s how it should look.

    There are a number of places we can deploy our Silverlight XAP file to SharePoint. The web’s ClientBin folder is sometimes used, but we can’t use the WSP file or our tools to deploy it there. Another deployment location option is the SharePoint hive. The decision of where to place the file depends on the scope of your application. The most common and easily controlled location is a Document Library. Uploading your XAP files to this list makes it easy to control permissions to the application and keeps them all in one location that's easy to find and update.

    For debugging purposes, let’s create a list using our deployment project. Right-click the DeploymentProject node in Solution Explorer and then select Add -> New Item. Select the SharePoint -> 2010 List Instance project item template, name it “XAPLibrary” and choose a “Document Library” type of list. In the wizard, change the name to “XAPLibrary”, choose “Document Library” as the type of list, and the relative URL for this list to “Lists/XAPLibrary” and then click Finish. This project item will automatically be packaged and deployed with the module we created earlier.

    Now that we have a list to host the XAP file, we need to tell SharePoint where to deploy it. Expand the Module1 node in Solution Explorer and open the Elements.xml file. Add the File node to the Modules parent node using the following:

    <Module Name="Module1">
    <File Path="Module1\MySilverlightApplication.xap" Url="Lists/XAPLibrary/MySilverlightApplication.xap" Type="GhostableInLibrary"/>
    </Module>

    The GhostableInLibrary type attribute is necessary so that SharePoint will create a list item for our XAP file on deployment.

    That’s it! We’re ready to deploy. Right-click the DeploymentProject node in Solution Explorer and select “Set as StartUp Project”. Now, press F5 and the Silverlight application will be built, packaged into the DeploymentProject WSP, and then deployed to the SharePoint site. In addition, the browser will be opened to the home page of the site. For testing purposes, let’s add the Web part to this page. Click the Page tab in the ribbon and then click Edit to enable the page to be edited. Click the Insert tab on the ribbon which is now displayed and then click Web Part on the ribbon to bring up the Web part picker. In the Media and Content category select the Silverlight Web Part item and click Add. Enter the location of the XAP file in the URL text box (~site/Lists/XAPLibrary/MySilverlightApplication.xap) and click OK.

    Once added, the Web part should appear on your site. Enter some text in the text box and click the button, and your text should be copied. You can now modify the SL application and redeploy it quickly to the site so that your changes are promptly reflected.

    I hope this post helps you get started publishing Silverlight applications to SharePoint. For further information, please watch this informative video by Paul Stubbs “Developer Patterns to Integrate Silverlight with SharePoint 2010” in which he leverages the Visual Studio 2010 tools for SharePoint development.

    Erik Cutts

  • Visual Studio SharePoint Development Blog

    How to deploy a SharePoint Site Definition project to the correct location when the SharePoint language is different from VS Language

    • 0 Comments

    If a SharePoint site definition project is created in English (ENU) version of Visual Studio 2010 and deployed on Arabic – Saudi Arabia (Ar-Sa) SharePoint, the template does not show up in SharePoint when you navigate to the site creation page. The template file is deployed to the folder corresponding to ENU locale (1033) instead of the one associated with ar-sa locale (1025).

    To fix this, the deployment path of the webtemp_<projectname>.xml needs to be changed to point to the correct SharePoint locale. Right click the webtemp_<projectname>.xml in the Solution Explorer and select Properties. In the properties window, expand the Deployment Location property. By default the Path property will be <VS LCID>\xml\ where <VS LCID> is 1033 for ENU Visual Studio (refer to the figure below).

    Change the LCID part of the path property to match that of the SharePoint language. For Ar-Sa the LCID is 1025 and hence the path should be 1025\xml. Deploying this onto Ar-Sa SharePoint should show this template under the SharePoint customizations tab in the Site creation page.You can find the full locale ID chart at http://msdn.microsoft.com/en-us/library/0h88fahh(VS.85).aspx.

     

    Pallavi Vajranabhaiah

Page 1 of 2 (43 items) 12