Showing posts with label SharePoint 2010. Show all posts
Showing posts with label SharePoint 2010. Show all posts

Friday, 30 March 2012

SharePoint 2010: Backup/Restore with PowerShell Command

If you want to backup/restore your site collection in SharePoint 2010, you can do with PowerShell command. I’ll spilt the post in two sections. One is on how to backup/restore in the same site collection and another is how to backup from one server/site collection to another. For the former (backup/restore in the same site collection), SharePoint provides nice easy GUI page in Central Administration page. However, for second one (backup/restore between different server) you need to run PowerShell scripts.

Backup/Restore in the same server and same site  collection


Sometimes you may want to backup from a site collection and your intention is to restore the backup in the same site collection. One example might be you have a site collection, say “http://myserver” and you are going to run code to test something against the site. However, you fear that running the code may break something and before you run the code, you want to backup the site so that in case running the code breaks something you can restore the backup taken before running the code. In the case, where you need to backup/restore is centered around same server and site collection, you can take SharePoint Central administration UI to do the backup/restore.
Backup Steps

1. Navigate to the Central Administration => Backup and Restore

2. Under “Farm Backup and Restore” section click “Perform a backup”.

3. Now you’ll be landed in the following page where you can select the site or site collection you want to take backup:

image

4. Click next and you’ll be navigated to the following page where you can select backup type (full or differential) and backup location:

image

 
Restoring Steps

To restore follow the steps:

1. Navigate to the Central Administration => Backup and Restore.

2. Under “Farm Backup and Restore” section click “Restore from a backup”. Follow the wizard to restore from a backup.

 

Backup/Restore from one server to another or from one Site Collection to another (with PowerShell command)


In some cases, you have developed a SharePoint site collection in your dev or stg machine and now you want to move the site with data from dev/stg to production. In such cases the process shown in the section “Backup/Restore in the same server and same site  collection” will not work. The recommended way is to use PowerShell command to take backup and restore the backup.
Backup a Site collection with PowerShell command

In SharePoint 2010, PowerShell command Backup-SPSite is used for taking backup. you can get details of the command from the msdn link. The following command will backup the site collection ‘http://myserver’.

Backup-SPSite -Identity http://myserver -Path "c:\backup\file.bak"
Restore a Site Collection with PowerShell command

To restore site collection you’ll use the following command. Use –Force if you want to overwrite the existing site collection

Restore-SPSite -Identity http://myserver -Path "c:\backup\file.bak"

However, once I had restored the backup I could not access the site. The problem was that I needed to deploy the custom SharePoint solution. So in case of site collection migration (with backup/restore) from one server to another or from one site collection to another, the steps should be:

  1. Restore the backup.

  2. If your source site collection (from where you taken backup) uses custom SharePoint solution, then deploy the solution in the destination site collection (where you are restoring the backup). If you try to access the site without deploying solution then you may get the site non-functional.

  3. Now you can try to access the site.


The important point here is that if you take backup from one server to another and restore it, the custom solution related to backup doesn’t go with backup. So after restoring backup you need to manually deploy the solution on the destination server. Then it’ll hopefully work.

Wednesday, 29 February 2012

How Do I Change the Icon on the Sign-In Page in SharePoint 2010?

Problem:

You’ve turned on claims-based authentication for a web application in SharePoint 2010, and you’ve also enabled the “Forms-based authentication” option in the authentication settings for one or more zones. The sign-in page SharePoint displays when you browse to the site has an error icon (red circle with a white X) on it, and you’d like to replace that with a different icon.

Solution:

First, for clarification, there are two default sign-in pages SharePoint might show you. Which one you see depends how you’ve configured claims-based authentication.

If you’ve enabled both Windows and forms-based authentication for a zone, you’ll see the sign-in page depicted in Figure 1. It contains a drop-down list that lets you choose how you’d like to log in. This version of the page is located at {SharePointRoot}\TEMPLATE\IDENTITYMODEL\LOGIN\default.aspx:
McDonough Fig1_2
Figure 1

On the other hand, if you’ve only enabled forms-based authentication (and not Windows), you’ll see the sign-in page depicted in Figure 2. It contains the standard user name and password fields you’d expect to see on a sign-in page. This version of the page is located at {SharePointRoot}\TEMPLATE\IDENTITYMODEL\FORMS\default.aspx:
McDonough Fig2_2
Figure 2

Both pages have the red error icon. Fortunately, the master page used by the sign-in pages places the icon inside an ASP.NET content placeholder, making it easy to change. Here are the steps:
Note: I describe how to do this manually so you can see what’s going on, but as always, I recommend you create a Solution Package (WSP file) for final deployment.

1. Go to the location of your current sign-in page (one of the two locations I described above).
2. Copy the “default.aspx” page to a new folder you’ve created (perhaps named after your company) under {SharePointRoot}\TEMPLATE\LAYOUTS. That way you’re not changing out-of-the-box files.
3. Open the copied file in a text editor and add the following ASP.NET content tag:
<asp:Content ContentPlaceHolderId="PlaceHolderIcon" runat="server">
<img src="/path/to/new/icon.gif" runat="server" />
</asp:Content>

 

4. Save the file.
5. Open Central Administration, and go to the Web Application Management page.
6. Select your web application, and click Authentication Providers in the ribbon.
7. In the dialog that pops up, click the link for the zone where you want your new sign-in page.
8. For the Sign-In Page URL setting, choose “Custom Sign-In Page,” and set the URL to ~/_layouts/YourFolder/default.aspx (or wherever you put your new page).

That’s it! Now your sign-in page should have your new icon (see Figure 3 below), and I hope it’s much more user-friendly than the big red X.

McDonough Fig3_2
Figure 3

Friday, 17 February 2012

How to use Form Templates for InfoPath Forms Services inside Project Server 2010/SharePoint 2010 Web Application

1- After you deploy your InfoPath form, you should see this screen form Central Administration -> General Application Settings -> Manage Form Templates
(then install it and you can enable it from your Site Collection Features as well)

3- So, you need to create new Form Library that will use InfoPath Form Template:

4- From Library Settings, Advanced Settings, Set Allow management of content types equal True

5- then add your Forms Services to form content and make it the default - Add Content Type and select your InfoPath Form Template:

6- Finally, you have a form library of content InfoPath Forms Services:

 

SharePoint 2010: Basics on how to apply branding

Step 1: The first thing that you have to consider is how the SharePoint site that you are branding is configured?

  • Is it SharePoint 2007 or 2010?

  • Is it WSS or Full SharePoint Server?

  • Will Publishing be enabled?

  • What site templates will be branded?


  • Publishing

  • Team Collaboration

  • Meeting Workspaces

  • Search Center

  • My Sites

  • Administration Pages “_layouts/”

  • Other?



Step 2: Be prepared and gather all design support files from your visual designer

  • Support Images optimized for web

  • Style Guide


  • Hex colors for all design elements


  • Text body colors

  • Text link colors

  • Text link hover colors

  • Text header colors

  • Background colors


  • Heights and widths of design elements


    • Ribbon

    • Header

    • Logo

    • Navigation Container

    • Navigation Links

    • Left Side Navigation

    • Content Area




    Step 3: Choose your implementation approach

    • Store all CSS and Images on the server


    • This approach allows you to store all of your CSS and images in a custom folder on the server within the 14 hive, 12 hive for 2007.

    • SharePoint 2010 - C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\14\TEMPLATE\LAYOUTS\1033\STYLES\customfolder

    • SharePoint 2007 - C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\12\TEMPLATE\LAYOUTS\1033\STYLES\customfolder

    • This approach allows you to have a single source for all of your CSS and images. Note that it is recommended to create a solution package with all of your files and deploy it especially if you have more than one web front end server. This will push all of the files to the correct location on each web front end so you do not have to do it manually.


  • The other option is to Store all CSS and Images within SharePoint Style Library (Publishing Infrastructure and Site Publishing Feature need to be enabled)


    • This approach allows you to have version control over your CSS and images. However these files will need to be added to each site collection the branding will be applied to so if you have a lot of site collections there will not be a single source for your files. AKA if you update one it will not update the branding globally.



    Step 4a: If you choose to go with storing all of your CSS and images on the server, below are the steps to get you started.
    I will walk you through the manual process of adding in the files, a solution would be created to add these files in normally. Please note that this should be done in a development environment first.

    • log into your web front end as a administrator

    • Navigate to C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\14\TEMPLATE\LAYOUTS\1033\STYLES

    • create a new folder within the styles library that is either your company name or project name or what ever makes sense

    • upload all of your optimized images into this folder

    • right click > new > text document

    • rename it custom.css

    • Open up the document in notepad and add in the following just to make sure you have it linked up correctly


    body #s4-leftpanel{display: none !important;}
    body .s4-ca{background-color: #CCC; margin-left: 0px !important;}
    body #s4-mainarea{width: 940px; margin: auto; float: none; clear:both;}

    • Save the custom CSS file


    Step 4b: If you choose to go with storing all of your CSS and images within SharePoint, below are the steps to get you started.

    • first you need to make sure that you have the publishing infrastructure and publishing feature activated within your site.

    • To verify click on Site Actions > Site Settings > Site Collection Administration > Site collection features


    image

    • Then to verify the site feature click on Site Actions > Site Settings > Site Actions > Manage site features


    image

    • by activating the publishing feature it creates a style library at the root of the site collection where you will be able to store and reference your custom CSS and images.

    • navigate to the new style library:
      http://sitename/Style%20Library/Forms/AllItems.aspx

    • you will normally see four folders


    • en-us

    • Images

    • Media Player

    • XSL Style Sheets


  • create a new folder at this root location that is either your company name or project name or what ever makes sense

  • upload all of your optimized images into this folder

  • on your local machine create a new text document in notepad

  • save it as “custom.css”, make sure you save as type “All Files” and Encoding “UTF-8”


  • image

    • Open up the document in notepad and add in the following just to make sure you have it linked up correctly


    body #s4-leftpanel{display: none !important;}
    body .s4-ca{background-color: #CCC; margin-left: 0px !important;}
    body #s4-mainarea{width: 940px; margin: auto; float: none; clear:both;}

    • Save the custom CSS file


    Step 5a: Apply your server side custom CSS to your site.
    You now have a few choices on how you want to apply your custom CSS to your site/page.

    • Approach 1: (Hardest) Creating a custom master page and referencing your custom CSS in the header.


    • For non-publishing Click on Site Actions > Site Settings > Galleries > Master pages

    • For publishing Click on Site Actions > Site Settings > Galleries > Master pages and page layouts

    • hover over v4.master and click on Send To > Download a Copy

    • Save this copy of v4.master onto your local machine

    • Rename it customv4.master

    • Open up the master page in notepad.

    • ** Do not try to open it locally with SharePoint designer, it will add in a bunch of weird references and your master page might get errors.**

    • at the end of the head tag add the following code

    • <SharePoint:CssRegistration name="custom/custom.css" After="corev4.css" runat="server"/>

    • Save the master page and upload it into the master page gallery.

    • Make sure that you publish it as a major version and approve it as needed.

    • to apply your custom master page when publishing has been enabled click on site actions > site settings > look and feel > master page

    • If Publishing is not enabled you will have to use SharePoint designer to set this custom master page, there will not be an option to do this through the UI.



    image


    • Change the Site Master page and the System Master page to your customv4.master and then click on ok

    • Now You will finally see that you branding has been applied.



    image

    • Approach 2: (Medium) With publishing enabled, specify your custom CSS as a Alternate CSS.


    • Click on site actions > site settings > look and feel > master page

    • Scroll down to the Alternate CSS URL section and click on “Specify a CSS file to be used by this publishing site and all sites that inherit from it:”

    • add in the following path:

    • _layouts/1033/styles/custom/custom.css

    • then click on ok

    • your site should now have the custom branding applied to this site and if you choose to any existing sub sites.

    • ** note that when new sites are created the branding will not get applied to the new sites. The “Reset all sub sites to inherit this alternate CSS URL” only applies to existing sites and not sites that get created in the future. **


  • Approach 3: (Easy) Add a content editor web part to the page and reference your custom CSS.


    • Add the content editor web part to the page

    • Click to add in content and then in the markup section within the ribbon click on HTML > Edit HTML Source

    • paste in the following:

    • <link href="/_layouts/1033/styles/custom/custom.css" rel="stylesheet" type="text/css"/>

    • Save/Publish the page. Just this page will now have the custom branding applied.



    Step 5b: Apply your Style library custom CSS to your site.
    You have the same options as above but with different URL paths.

    • Approach 1: (Hardest) Creating a custom master page and referencing your custom CSS in the header.


    • Use same method above to create your custom master page but use the following reference at the end of the HEAD section.

    • <SharePoint:CssRegistration name="<% $SPUrl:~sitecollection/Style Library/custom/custom.css %>" After="corev4.css" runat="server"/>


  • Approach 2: (Medium) With publishing enabled, specify your custom CSS as a Alternate CSS.


    • Click on site actions > site settings > look and feel > master page

    • Scroll down to the Alternate CSS URL section and click on “Specify a CSS file to be used by this publishing site and all sites that inherit from it:”

    • add in the following path:

    • /Style Library/custom/custom.css

    • then click on ok

    • your site should now have the custom branding applied to this site and if you choose to any existing sub sites.

    • ** note that when new sites are created the branding will not get applied to the new sites. The “Reset all sub sites to inherit this alternate CSS URL” only applies to existing sites and not sites that get created in the future. **


  • Approach 3: (Easy) Add a content editor web part to the page and reference your custom CSS.


    • Add the content editor web part to the page

    • Click to add in content and then in the markup section within the ribbon click on HTML > Edit HTML Source

    • paste in the following:

    • <link href="/Style Library/custom/custom.css" rel="stylesheet" type="text/css"/>

    • Save/Publish the page. Just this page will now have the custom branding applied.

    SharePoint 2010: Attach files to List/Library using Managed Client Object Model

    Client Objet Model (OM) is a great new addition in SharePoint 2010. I have discussed before how to manipulate lists and list items using Managed Object Model. Today I’ll discuss on how to attach file to list item or add file to library using Managed Client Object Model.

    Upload File in Library


    The following code snippet shows how to upload file in document library:
    public void UploadFileInLibrary(string siteUrl, string webName, string libraryName, string subfolderPath, string fileName)
    {
    using (ClientContext clientContext = new ClientContext(siteUrl))
    {

    string uploadLocation = Path.GetFileName(fileName);
    if (!string.IsNullOrEmpty(subfolderPath))
    {
    uploadLocation = string.Format("{0}/{1}", subfolderPath, uploadLocation);
    }
    uploadLocation = string.Format("/{0}/{1}/{2}", webName, libraryName, uploadLocation);
    var list = clientContext.Web.Lists.GetByTitle(libraryName);
    var fileCreationInformation = new FileCreationInformation();
    fileCreationInformation.Content = System.IO.File.ReadAllBytes(fileName);
    fileCreationInformation.Overwrite = true;
    fileCreationInformation.Url = uploadLocation;
    list.RootFolder.Files.Add(fileCreationInformation);
    clientContext.ExecuteQuery();
    }
    }

    In the above code snippet, I have constructed the full path to the update location by concatenating the subfolderpath with library location. The site url is the spsite location whereas web name is name of the web site. To upload a file I have use FileCreationInformation object which is part of Client Object Model. To use the above method you can call the method as shown below. The instance is the class instance which has the method. Here the subfolderpath is the folder location inside the library where the document will be uploaded.
    Instance.UploadFileInLibrary("http://mysite","mywebname", LibraryName,"folder1/folder2", @"c:\myfiles\LibraryItem.xlsx");


    Download File From Library


    The following code snippets shows how to download file from library:
    public void DownloadFileFromLibrary(string siteUrl, string webName, string libraryName, string subfolderPath, string fileName, string downloadPath)
    {
    using (ClientContext clientContext = new ClientContext(siteUrl))
    {
    string filePath = string.Empty;
    if (!string.IsNullOrEmpty(subfolderPath))
    {
    filePath = string.Format("/{0}/{1}/{2}/{3}", webName, libraryName, subfolderPath, fileName);
    }
    else
    {
    filePath = string.Format("/{0}/{1}/{2}", webName, subfolderPath, fileName);
    }

    var fileInformation = File.OpenBinaryDirect(clientContext, filePath);
    var stream = fileInformation.Stream;
    IList<byte> content = new List<byte>();
    int b;
    while ((b = fileInformation.Stream.ReadByte()) != -1)
    {
    content.Add((byte)b);
    }
    var downloadFileName = Path.Combine(downloadPath, fileName);
    System.IO.File.WriteAllBytes(downloadFileName, content.ToArray());
    fileInformation.Stream.Close();
    }
    }

    As above code shows, we can use Microsoft.SharePoint.Client.File.OpenBinaryDirect method to download file directly from SharePoint. However, SharePoint open the file as binary stream so you need read the full stream before processing the file. The subfolderpath is same as described in ‘Upload File in Library’ section.

     

    Delete File From Library


    The following code snippet shows how to delete file from library:
    public void DeleteFileFormLibrary(string siteUrl, string webName, string listName, string subfolder, string attachmentFileName)
    {
    using (ClientContext clientContext = new ClientContext(siteUrl))
    {
    string attachmentPath = string.Empty;
    if (string.IsNullOrEmpty(subfolder))
    {
    attachmentPath = string.Format("/{0}/{1}/{2}", webName, listName, Path.GetFileName(attachmentFileName));
    }
    else
    {
    attachmentPath = string.Format("/{0}/{1}/{2}/{3}", webName, listName, subfolder, Path.GetFileName(attachmentFileName));
    }
    var file = clientContext.Web.GetFileByServerRelativeUrl(attachmentPath);
    file.DeleteObject();
    clientContext.ExecuteQuery();
    }
    }

    As the above code , the DeleteObject method is invoked on file object to delete the file.

     

    Attach File to ListItem


    The following code snippet shows how to attach file to list item. The attachments in list are places in a folder whose location is like “http://siteurl/lists/[listname]/Attachments/[ListItemID]/[filename]”. So I have constructed the attchment location first and use Microsoft.SharePoint.Client.File.SaveBinaryDirect method to upload the file. Here in the method, Item id is the list item id that I want to attach the file to.
    public void AttachFileToListItem(string siteUrl, string webName, string listName, int itemId, string fileName, bool overwrite)
    {
    using (ClientContext clientContext = new ClientContext(siteUrl))
    {
    FileStream fileStream = new FileStream(fileName, FileMode.Open);
    string attachmentPath = string.Format("/{0}/Lists/{1}/Attachments/{2}/{3}", webName, listName, itemId, Path.GetFileName(fileName));
    File.SaveBinaryDirect(clientContext, attachmentPath, fileStream, overwrite);
    }
    }


    Download File from ListItem


    The following code snippet shows how to download file that is attached with list item.
    public void DownloadAttachedFileFromListItem(string siteUrl, string webName, int itemId, string attachmentName, string listName, string downloadLocation)
    {
    using (ClientContext clientContext = new ClientContext(siteUrl))
    {
    string attachmentPath = string.Format("/{0}/lists/{1}/Attachments/{2}/{3}", webName, listName, itemId, Path.GetFileName(attachmentName));
    var fileInformation = File.OpenBinaryDirect(clientContext, attachmentPath);
    IList<byte> content = new List<byte>();
    int b;
    while ((b = fileInformation.Stream.ReadByte()) != -1)
    {
    content.Add((byte)b);
    }
    var downloadFileName = Path.Combine(downloadLocation, attachmentName);
    System.IO.File.WriteAllBytes(downloadFileName, content.ToArray());
    fileInformation.Stream.Close();
    }
    }

    As said before, the attachment location is “http://siteurl/lists/[listname]/Attachments/[itemid]/[filename]”. So I have used Microsoft.SharePoint.Client.File.OpenBinraryDirect to download the file.

     

    Delete Attached File From ListItem


    The following code shows how to delete a file that is attached with list item.
    public void DeleteAttachedFileFromListItem(string siteUrl, string webName, int itemId, string attachmentFileName, string listName)
    {
    using (ClientContext clientContext = new ClientContext(siteUrl))
    {
    //http://siteurl/lists/[listname]/attachments/[itemid]/[filename]
    string attachmentPath = string.Format("/{0}/lists/{1}/Attachments/{2}/{3}", webName, listName, itemId, Path.GetFileName(attachmentFileName));
    var file = clientContext.Web.GetFileByServerRelativeUrl(attachmentPath);
    file.DeleteObject();
    clientContext.ExecuteQuery();
    }
    }

     

    Conclusion


    The code snippet above just provide you the gist. One point to notice that the File class used in the code not from System.IO. This is from Microsoft.SharePoint.Client and the full name is “Microsoft.SharePoint.Client.File”.

    SharePoint 2010 Fields Validation

    In SharePoint 2007 we have many issues with field validation when we add a new item to the list. So I solved it with JavaScript and I solved it with InfoPath Forms but it has never been easy.

    In SharePoint 2010 we have great tools to perform field validation on the page without spending hours.

    The first option is very intuitive. You can set the basic validation using the usual calculated fields functions during the creation of your field. You can use Excel functions just like I used it in the picture below to find out if some text appears in the field value or not. You can also build any other validation you want.



    The User description field will show your users explanation about the content you want to see in the field. It will appear in red text under your field, like the example below.



    Here are a few examples of field validation functions:

    E-mail validation:

    =AND((FIND(“@”,[E-mail filed])<>0),( FIND(“.”,[E-mail filed])<>0))

    The AND function allows you to check more than one condition.

    Today date validation:

    =[Date field]>Today()

    The second way to perform field validation is to edit the list forms using the InfoPath application.

    This gives you really powerful abilities to edit your list forms. If you choose this method you’ll have much more options to design and validate your fields. For example: you can change the color of your field if it has not passed validation.

    So, how do we do it?

    Enter your list and click the “Customize Form” link. This link will open the InfoPath application (so make sure InfoPath is installed at your machine first). This button will design the “New”, “Edit” and “Design” forms but you will need to design it only once.



    When the InfoPath form is opened you will see all the fields of your list at the left side of the window and you can add these fields to the form.

    Let’s create some validation! Choose the field you want to validate and click the “Add Rule” button on the Ribbon.



    Then click the “New” button and create a new Validation rule. You can also add a formatting rule to change the design of your fields that based on similar conditions. This is the “Conditional Formatting”, just a little redesigned.

    Add a new validation rule. Click on “None” link under the “Condition” title to create new conditions.







    Now it’s time to publish the form back to our SharePoint list. This is very easy to do. Just press the “File” option in the Ribbon and press the big “Quick Publish” button. That’s all. Now you have this validation in your SharePoint list forms.



    Developing with SharePoint 2010 Word Automation Services

    To build the application




    1. Start Microsoft Visual Studio 2010.

    2. On the File menu, point to New, and then click Project.

    3. In the New Project dialog box, in the Recent Template pane, expand Visual C#, and then click Windows.

    4. To the right side of the Recent Template pane, click Console Application.

    5. By default, Visual Studio creates a project that targets .NET Framework 4. However, you must target .NET Framework 3.5. From the list at the upper part of the File Open dialog box, select .NET Framework 3.5.

    6. In the Name box, type the name that you want to use for your project, such as FirstWordAutomationServicesApplication.

    7. In the Location box, type the location where you want to place the project.

      Figure 1. Creating a solution in the New Project dialog box

      Creating solution in the New Project box

    8. Click OK to create the solution.

    9. By default, Visual Studio 2010 creates projects that target x86 CPUs, but to build SharePoint Server applications, you must target any CPU.

    10. If you are building a Microsoft Visual C# application, in Solution Explorer window, right-click the project, and then click Properties.

    11. In the project properties window, click Build.

    12. Point to the Platform Target list, and select Any CPU.

      Figure 2. Target Any CPU when building a C# console application

      Changing target to any CPU

    13. If you are building a Microsoft Visual Basic .NET Framework application, in the project properties window, click Compile.

      Figure 3. Compile options for a Visual Basic application

      Compile options for Visual Basic applications

    14. Click Advanced Compile Options.

      Figure 4. Advanced Compiler Settings dialog box

      Advanced Compiler Settings dialog box

    15. Point to the Platform Target list, and then click Any CPU.

    16. To add a reference to the Microsoft.Office.Word.Server assembly, on the Project menu, click Add Reference to open the Add Reference dialog box.

    17. Select the .NET tab, and add the component named Microsoft Office 2010 component.

      Figure 5. Adding a reference to Microsoft Office 2010 component

      Add reference to Microsoft Office 2010 component

    18. Next, add a reference to the Microsoft.SharePoint assembly.

      Figure 6. Adding a reference to Microsoft SharePoint

      Adding reference to Microsoft SharePoint



    The following examples provide the complete C# and Visual Basic listings for the simplest Word Automation Services application.






    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using Microsoft.SharePoint;
    using Microsoft.Office.Word.Server.Conversions;

    class Program
    {
    static void Main(string[] args)
    {
    string siteUrl = "http://localhost";
    // If you manually installed Word automation services, then replace the name
    // in the following line with the name that you assigned to the service when
    // you installed it.
    string wordAutomationServiceName = "Word Automation Services";
    using (SPSite spSite = new SPSite(siteUrl))
    {
    ConversionJob job = new ConversionJob(wordAutomationServiceName);
    job.UserToken = spSite.UserToken;
    job.Settings.UpdateFields = true;
    job.Settings.OutputFormat = SaveFormat.PDF;
    job.AddFile(siteUrl + "/Shared%20Documents/Test.docx",
    siteUrl + "/Shared%20Documents/Test.pdf");
    job.Start();
    }
    }
    }





    To build and run the example




    1. Add a Word document named Test.docx to the Shared Documents folder in the SharePoint site.

    2. Build and run the example.

    3. After waiting one minute for the conversion process to run, navigate to the Shared Documents folder in the SharePoint site, and refresh the page. The document library now contains a new PDF document, Test.pdf.



    Monitoring Conversion Status




    In many scenarios, you want to monitor the status of conversions, to inform the user when the conversion process is complete, or to process the converted documents in additional ways. You can use the ConversionJobStatus class to query Word Automation Services about the status of a conversion job. You pass the name of the WordServiceApplicationProxy class as a string (by default, "Word Automation Services"), and the conversion job identifier, which you can get from the ConversionJob object. You can also pass a GUID that specifies a tenant partition. However, if the SharePoint Server farm is not configured for multiple tenants, you can pass null (Nothing in Visual Basic) as the argument for this parameter.

    After you instantiate a ConversionJobStatus object, you can access several properties that indicate the status of the conversion job. The following are the three most interesting properties.

    ConversionJobStatus Properties





















    PropertyReturn Value
    CountNumber of documents currently in the conversion job.
    SucceededNumber of documents successfully converted.
    FailedThe number of documents that failed conversion.

    Whereas the first example specified a single document to convert, the following example converts all documents in a specified document library. You have the option of creating all converted documents in a different document library than the source library, but for simplicity, the following example specifies the same document library for both the input and output document libraries. In addition, the following example specifies that the conversion job should overwrite the output document if it already exists.






    Console.WriteLine("Starting conversion job");
    ConversionJob job = new ConversionJob(wordAutomationServiceName);
    job.UserToken = spSite.UserToken;
    job.Settings.UpdateFields = true;
    job.Settings.OutputFormat = SaveFormat.PDF;
    job.Settings.OutputSaveBehavior = SaveBehavior.AlwaysOverwrite;
    SPList listToConvert = spSite.RootWeb.Lists["Shared Documents"];
    job.AddLibrary(listToConvert, listToConvert);
    job.Start();
    Console.WriteLine("Conversion job started");
    ConversionJobStatus status = new ConversionJobStatus(wordAutomationServiceName,
    job.JobId, null);
    Console.WriteLine("Number of documents in conversion job: {0}", status.Count);
    while (true)
    {
    Thread.Sleep(5000);
    status = new ConversionJobStatus(wordAutomationServiceName, job.JobId,
    null);
    if (status.Count == status.Succeeded + status.Failed)
    {
    Console.WriteLine("Completed, Successful: {0}, Failed: {1}",
    status.Succeeded, status.Failed);
    break;
    }
    Console.WriteLine("In progress, Successful: {0}, Failed: {1}",
    status.Succeeded, status.Failed);
    }





    To run this example, add some WordprocessingML documents in the Shared Documents library. When you run this example, you see output similar to this code snippet,





    Starting conversion job
    Conversion job started
    Number of documents in conversion job: 4
    In progress, Successful: 0, Failed: 0
    In progress, Successful: 0, Failed: 0
    Completed, Successful: 4, Failed: 0






    Identifying Documents That Failed to Convert




    You may want to determine which documents failed conversion, perhaps to inform the user, or take remedial action such as removing the invalid document from the input document library. You can call the GetItems method, which returns a collection of ConversionItemInfo objects. When you call the GetItems method, you pass a parameter that specifies whether you want to retrieve a collection of failed conversions or successful conversions.

    C#





    Console.WriteLine("Starting conversion job");
    ConversionJob job = new ConversionJob(wordAutomationServiceName);
    job.UserToken = spSite.UserToken;
    job.Settings.UpdateFields = true;
    job.Settings.OutputFormat = SaveFormat.PDF;
    job.Settings.OutputSaveBehavior = SaveBehavior.AlwaysOverwrite;
    SPList listToConvert = spSite.RootWeb.Lists["Shared Documents"];
    job.AddLibrary(listToConvert, listToConvert);
    job.Start();
    Console.WriteLine("Conversion job started");
    ConversionJobStatus status = new ConversionJobStatus(wordAutomationServiceName,
    job.JobId, null);
    Console.WriteLine("Number of documents in conversion job: {0}", status.Count);
    while (true)
    {
    Thread.Sleep(5000);
    status = new ConversionJobStatus(wordAutomationServiceName, job.JobId, null);
    if (status.Count == status.Succeeded + status.Failed)
    {
    Console.WriteLine("Completed, Successful: {0}, Failed: {1}",
    status.Succeeded, status.Failed);
    ReadOnlyCollection<ConversionItemInfo> failedItems =
    status.GetItems(ItemTypes.Failed);
    foreach (var failedItem in failedItems)
    Console.WriteLine("Failed item: Name:{0}", failedItem.InputFile);
    break;
    }
    Console.WriteLine("In progress, Successful: {0}, Failed: {1}", status.Succeeded,
    status.Failed);
    }





    To run this example, create an invalid document and upload it to the document library. An easy way to create an invalid document is to rename the WordprocessingML document, appending .zip to the file name. Then delete the main document part (known as document.xml), which is in the Word folder of the package. Rename the document, removing the .zip extension so that it contains the normal .docx extension.

    When you run this example, it produces output similar to the following.






    Starting conversion job
    Conversion job started
    Number of documents in conversion job: 5
    In progress, Successful: 0, Failed: 0
    In progress, Successful: 0, Failed: 0
    In progress, Successful: 4, Failed: 0
    In progress, Successful: 4, Failed: 0
    In progress, Successful: 4, Failed: 0
    Completed, Successful: 4, Failed: 1
    Failed item: Name:http://intranet.contoso.com/Shared%20Documents/IntentionallyInvalidDocument.docx





    Another approach to monitoring a conversion process is to use event handlers on a SharePoint list to determine when a converted document is added to the output document library.


    Deleting Source Files after Conversion









    Console.WriteLine("Starting conversion job");
    ConversionJob job = new ConversionJob(wordAutomationServiceName);
    job.UserToken = spSite.UserToken;
    job.Settings.UpdateFields = true;
    job.Settings.OutputFormat = SaveFormat.PDF;
    job.Settings.OutputSaveBehavior = SaveBehavior.AlwaysOverwrite;
    SPFolder folderToConvert = spSite.RootWeb.GetFolder("Shared Documents");
    job.AddFolder(folderToConvert, folderToConvert, false);
    job.Start();
    Console.WriteLine("Conversion job started");
    ConversionJobStatus status = new ConversionJobStatus(wordAutomationServiceName,
    job.JobId, null);
    Console.WriteLine("Number of documents in conversion job: {0}", status.Count);
    while (true)
    {
    Thread.Sleep(5000);
    status = new ConversionJobStatus(wordAutomationServiceName, job.JobId, null);
    if (status.Count == status.Succeeded + status.Failed)
    {
    Console.WriteLine("Completed, Successful: {0}, Failed: {1}",
    status.Succeeded, status.Failed);
    Console.WriteLine("Deleting only items that successfully converted");
    ReadOnlyCollection<ConversionItemInfo> convertedItems =
    status.GetItems(ItemTypes.Succeeded);
    foreach (var convertedItem in convertedItems)
    {
    Console.WriteLine("Deleting item: Name:{0}", convertedItem.InputFile);
    folderToConvert.Files.Delete(convertedItem.InputFile);
    }
    break;
    }
    Console.WriteLine("In progress, Successful: {0}, Failed: {1}",
    status.Succeeded, status.Failed);
    }











    Console.WriteLine("Starting conversion job")
    Dim job As ConversionJob = New ConversionJob(wordAutomationServiceName)
    job.UserToken = spSite.UserToken
    job.Settings.UpdateFields = True
    job.Settings.OutputFormat = SaveFormat.PDF
    job.Settings.OutputSaveBehavior = SaveBehavior.AlwaysOverwrite
    Dim folderToConvert As SPFolder = spSite.RootWeb.GetFolder("Shared Documents")
    job.AddFolder(folderToConvert, folderToConvert, False)
    job.Start()
    Console.WriteLine("Conversion job started")
    Dim status As ConversionJobStatus = _
    New ConversionJobStatus(wordAutomationServiceName, job.JobId, Nothing)
    Console.WriteLine("Number of documents in conversion job: {0}", status.Count)
    While True
    Thread.Sleep(5000)
    status = New ConversionJobStatus(wordAutomationServiceName, job.JobId, _
    Nothing)
    If status.Count = status.Succeeded + status.Failed Then
    Console.WriteLine("Completed, Successful: {0}, Failed: {1}", _
    status.Succeeded, status.Failed)
    Console.WriteLine("Deleting only items that successfully converted")
    Dim convertedItems As ReadOnlyCollection(Of ConversionItemInfo) = _
    status.GetItems(ItemTypes.Succeeded)
    For Each convertedItem In convertedItems
    Console.WriteLine("Deleting item: Name:{0}", convertedItem.InputFile)
    folderToConvert.Files.Delete(convertedItem.InputFile)
    Next
    Exit While
    End If
    Console.WriteLine("In progress, Successful: {0}, Failed: {1}",
    status.Succeeded, status.Failed)
    End While





     


    Integrating with the Open XML SDK




    The power of using Word Automation Services becomes clear when you use it in combination with the Welcome to the Open XML SDK 2.0 for Microsoft Office. You can programmatically modify a document in a document library by using the Welcome to the Open XML SDK 2.0 for Microsoft Office, and then use Word Automation Services to perform one of the difficult tasks by using the Open XML SDK. A common need is to programmatically generate a document, and then generate or update the table of contents of the document. Consider the following document, which contains a table of contents.

    Figure 7. Document with a table of contents

    Document with table of contentsLet’s assume you want to modify this document, adding content that should be included in the table of contents. This next example takes the following steps.

    1. Opens the site and retrieves the Test.docx document by using a Collaborative Application Markup Language (CAML) query.

    2. Opens the document by using the Open XML SDK 2.0, and adds a new paragraph styled as Heading 1 at the beginning of the document.

    3. Starts a conversion job, converting Test.docx to TestWithNewToc.docx. It waits for the conversion to complete, and reports whether it was converted successfully.




    C#
    Console.WriteLine("Querying for Test.docx");
    SPList list = spSite.RootWeb.Lists["Shared Documents"];
    SPQuery query = new SPQuery();
    query.ViewFields = @"<FieldRef Name='FileLeafRef' />";
    query.Query =
    @"<Where>
    <Eq>
    <FieldRef Name='FileLeafRef' />
    <Value Type='Text'>Test.docx</Value>
    </Eq>
    </Where>";
    SPListItemCollection collection = list.GetItems(query);
    if (collection.Count != 1)
    {
    Console.WriteLine("Test.docx not found");
    Environment.Exit(0);
    }
    Console.WriteLine("Opening");
    SPFile file = collection[0].File;
    byte[] byteArray = file.OpenBinary();
    using (MemoryStream memStr = new MemoryStream())
    {
    memStr.Write(byteArray, 0, byteArray.Length);
    using (WordprocessingDocument wordDoc =
    WordprocessingDocument.Open(memStr, true))
    {
    Document document = wordDoc.MainDocumentPart.Document;
    Paragraph firstParagraph = document.Body.Elements<Paragraph>()
    .FirstOrDefault();
    if (firstParagraph != null)
    {
    Paragraph newParagraph = new Paragraph(
    new ParagraphProperties(
    new ParagraphStyleId() { Val = "Heading1" }),
    new Run(
    new Text("About the Author")));
    Paragraph aboutAuthorParagraph = new Paragraph(
    new Run(
    new Text("Eric White")));
    firstParagraph.Parent.InsertBefore(newParagraph, firstParagraph);
    firstParagraph.Parent.InsertBefore(aboutAuthorParagraph,
    firstParagraph);
    }
    }
    Console.WriteLine("Saving");
    string linkFileName = file.Item["LinkFilename"] as string;
    file.ParentFolder.Files.Add(linkFileName, memStr, true);
    }
    Console.WriteLine("Starting conversion job");
    ConversionJob job = new ConversionJob(wordAutomationServiceName);
    job.UserToken = spSite.UserToken;
    job.Settings.UpdateFields = true;
    job.Settings.OutputFormat = SaveFormat.Document;
    job.AddFile(siteUrl + "/Shared%20Documents/Test.docx",
    siteUrl + "/Shared%20Documents/TestWithNewToc.docx");
    job.Start();
    Console.WriteLine("After starting conversion job");
    while (true)
    {
    Thread.Sleep(5000);
    Console.WriteLine("Polling...");
    ConversionJobStatus status = new ConversionJobStatus(
    wordAutomationServiceName, job.JobId, null);
    if (status.Count == status.Succeeded + status.Failed)
    {
    Console.WriteLine("Completed, Successful: {0}, Failed: {1}",
    status.Succeeded, status.Failed);
    break;
    }
    }




    After running this example with a document similar to the one used earlier in this section, a new document is produced, as shown in Figure 8.

    Figure 8. Document with updated table of contents

    Document with updated table of contents

    Conclusion




    The Open XML SDK 2.0 is a powerful tool for building server-side document generation and document processing systems. However, there are aspects of document manipulation that are difficult, such a document conversions, and updating of fields, table of contents, and more. Word Automation Services fills this gap with a high-performance solution that can scale out to your requirements. Using the Open XML SDK 2.0 in combination with Word Automation Services enables many scenarios that are difficult when using only the Open XML SDK 2.0.

    WCF: Building WCF Web Services for SharePoint 2010 Business Connectivity Services

    Summary:  Learn to authenticate users in Microsoft SharePoint Foundation 2010. Create Windows Communication Foundation (WCF) web services that you can consume as external content types from Microsoft Business Connectivity Services (BCS).

    Introduction




    This article shows how to create a very simple web service by using WCF. There is one special characteristic of the web service that I present in this article: Although it is very simple, it can be consumed as an external content type from Business Connectivity Services. In addition, the procedure presented in this article describes how to host this web service by using Internet Information Services (IIS).

    This web service contains only two methods: a finder method to retrieve a collection of items, and a specific finder method to retrieve a single item. The data behind the collection is an initialized list. The schema of this little database is very simple. It is a single flat table consisting of two fields—an integer field, CustomerID, and a string field, CustomerName. CustomerID is a unique ID. The following snippet shows the initialization of list that contains the data that are served by the web service.






    return new List<Customer>()
    {
    new Customer
    {
    CustomerID = 1,
    CustomerName = "Bob",
    },
    new Customer
    {
    CustomerID = 2,
    CustomerName = "Bill",
    },
    new Customer
    {
    CustomerID = 3,
    CustomerName = "Cheryl",
    },
    };





    After building and configuring this web service, you can use SharePoint Designer 2010 to create an external content type from it, and then view the data in a SharePoint list. The following figure shows a SharePoint external list.

    Figure 1. SharePoint 2010 external list

    SharePoint 2010 External ListAs you probably know, Business Connectivity Services in SharePoint Foundation 2010 and SharePoint Server 2010 is read/write. If you supply additional methods to create, update, and delete items, you can fully maintain the data in a list. I want this web service as simple as possible. Therefore this is a read-only implementation. My focus is on security and identity issues. How the database is stored, where it is stored, or the details of the schema are irrelevant to this topic.

    The procedure presented here is for Windows Server 2008 R2 and Windows Server 2008. You can build this web service by using either Microsoft Visual Studio 2010 or Visual Studio 2008.

    You can build, run, and test the web service presented in this article on any development computer that is running Internet Information Services. However, if you want to connect to this web service as an external content type by using Business Connectivity Services, build this example in a SharePoint 2010 development environment so that SharePoint Foundation 2010 or SharePoint Server 2010 and the example web service are running on the same computer. You can put this web service on a different server, and consume it as an external content type. However, in that situation, you must either remove security, or you must create a claims-aware web service.

    As I mentioned, the procedure that I present here shows how to host the web service under IIS. This is the way that most implementers of such a web service want to host it. Hosting it as a service of IIS gives lots of benefits such as process recycling, process health monitoring, and message based activation.


    Prerequisites




    This procedure is for Windows Server 2008 or Windows Server 2008 R2. In both cases, I started on a server that had a fresh, patched install of the operating system. Next, I installed the necessary roles and features so that IIS was installed and running. In addition, the procedures that are presented in this article require the .NET Framework 3.5.1, and either Visual Studio 2008 or Visual Studio 2010.


    Installing Windows Communication Foundation (WCF) and Internet Information Services




    Use Server Manager to install the Web Server (IIS) role and the .NET Framework 3.5.1 feature.

    To run this example, the only role that is Required is Web Server (IIS). The following figure shows the dialog in the Add Roles Wizard.

    Figure 2. Select Web Server Role in Add Roles Wizard

    Select Web Server in Add Roles WizardAfter adding the Web Server (IIS) role, the wizard asks you to select Role Services. Select Application Development. The following figure shows the dialog in the Add Roles Wizard.

    Figure 3. Select Application Development in Add Roles Wizard

    Select Application Development in Add Roles WizardTo install the .NET Framework, add the .NET Framework 3.5.1 Features. The following figure shows the dialog in the Add Roles Wizard.

    Figure 4. Select .NET Framework 3.5.1 Features in Add Roles Wizard

    Select .NET Framework 3.5.1When you install this feature on Windows Server 2008 (not R2), after you select the .NET Framework 3.0 Features, select WCF Activation. This is the default selection on Windows Server 2008 R2. The following figure shows the dialog in the Add Roles Wizard.

    Figure 5. Select WCF Activation

    Select WCF Activation on Windows Server 2008Both WCF and IIS must be installed for IIS-hosted WCF services to function correctly. The procedures for installing WCF (as part of .NET Framework 3.0) and IIS vary depending on the operating system that you are using. If you are installing on an operating system other than Windows Server 2008 or Windows Server 2008 R2, see Microsoft .NET Framework 3.0 Redistributable Package to download and install .NET Framework 3.0. See Installing IIS.


    Registering the Service Model




    To run this example, you must register this version of WCF and update script maps at the IIS metabase root.

    To register the service model




    1. Start a Visual Studio command prompt. Run as administrator. The following figure shows running the command prompt as administrator.

      Figure 6. Run the Visual Studio Command Prompt as administrator

      Run command prompt as administratorClick Start, click All Programs, click Visual Studio 2010, click Visual Studio Tools, right-click Visual Studio Command Prompt, and then click Run as Administrator.

      The Visual Studio command prompt is located in a similar location for Visual Studio 2008.

    2. Change the directory to the following:

      c:\Windows\Microsoft.NET\Framework\v3.0\Windows Communication Foundation

    3. In the command prompt, enter:

      ServiceModelReg -i

      The following figure shows ServiceModelReg running.

      Figure 7. Running ServiceModelReg

      Running ServiceModelReg










      note Note:
      This did not have to be a Visual Studio command prompt. However, the following step needs a Visual Studio command prompt. Therefore for efficiency, I created one in this step.

       





    Updating Script Maps



    To update script maps




    1. In the command prompt, enter:

      aspnet_regiis.exe -i

      The following figure shows updating script maps.

      Figure 8. Updating script maps

      Running aspnet_regiis




    Creating Web Services



    To create a web service




    1. Create a directory, C:\MyWebService, to contain the web service. If you use a different directory, you must change these procedures as appropriate.

    2. Start Visual Studio 2010 (or Visual Studio 2008).

    3. Click File, click New, and then click Project. For the installed template category, select WCF. For the template, select WCF Service Application. Target the .NET Framework 3.5. For the location of the project, browse to the directory that you created in step 1. Name the project CustomersService. Do not create a directory for the solution. The following figure shows what the New Project dialog box should look like.

      Figure 9. The New Project dialog box

      New Project dialog box










      note Note:
      Remember to change target to .NET Framework 3.5. By default, Visual Studio targets .NET Framework 4, and you must change it to .NET Framework 3.5 for the procedure presented here to work.

       


    4. In the project, rename IService1.cs to ICustomers.cs. Visual Studio 2010 offers to rename all references to the code element IService1 in this project. Click Yes. Actually, we will replace all code in all modules, so whether you click Yes or No has no affect.

    5. In the project, rename Service1.svc to Customers.svc. The following figure shows Solution Explorer after renaming these items.

      Figure 10. Solution Explorer after renaming the items

      Solution Explorer after renaming items

    6. Replace Customers.svc with the following single line of markup. Right-clickCustomers.svc, and then select View Markup. Copy the markup from this article, paste it into Visual Studio, and save.






      <%@ ServiceHost Language="C#" Debug="true" Service="CustomersService.Customers" CodeBehind="Customers.svc.cs" %>





    7. Replace Customers.svc.cs with the following code.






      using System;
      using System.Collections.Generic;
      using System.Linq;

      namespace CustomersService
      {
      public class Customers : ICustomers
      {
      // Finder
      public List<Customer> GetAllCustomers()
      {
      return new List<Customer>()
      {
      new Customer
      {
      CustomerID = 1,
      CustomerName = "Bob",
      },
      new Customer
      {
      CustomerID = 2,
      CustomerName = "Bill",
      },
      new Customer
      {
      CustomerID = 3,
      CustomerName = "Cheryl",
      },
      };
      }

      // Specific finder
      public Customer GetCustomerByID(int CustomerID)
      {
      return GetAllCustomers().FirstOrDefault(c => c.CustomerID == CustomerID);
      }
      }
      }





    8. Replace ICustomers.cs with the following code.






      using System;
      using System.Collections.Generic;
      using System.Linq;
      using System.Runtime.Serialization;
      using System.ServiceModel;

      namespace CustomersService
      {
      [ServiceContract]
      public interface ICustomers
      {
      [OperationContract] //finder
      List<Customer> GetAllCustomers();

      [OperationContract] //specificFinder
      Customer GetCustomerByID(int CustomerID);
      }

      [DataContract]
      public class Customer
      {
      [DataMember]
      public int CustomerID { get; set; }

      [DataMember]
      public string CustomerName { get; set; }
      }
      }





    9. Replace Web.config with the following markup. In Solution Explorer, right-click Web.config and select Edit. Copy, paste, and save.










      Important Important:
      This is the Web.config file that configures this specific web service. It resides at C:\MyWebService\CustomersService.

       








      <?xml version="1.0"?>
      <configuration>
      <system.serviceModel>
      <services>
      <service behaviorConfiguration="CustomersService.Service1Behavior"
      name="CustomersService.Customers">
      <endpoint address="" binding="wsHttpBinding" contract="CustomersService.ICustomers">
      <identity>
      <dns value="localhost" />
      </identity>
      </endpoint>
      <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange" />
      </service>
      </services>
      <behaviors>
      <serviceBehaviors>
      <behavior name="CustomersService.Service1Behavior">
      <!-- To avoid disclosing metadata information, set the value below to false and remove the metadata endpoint above before deploying the solution. -->
      <serviceMetadata httpGetEnabled="true"/>
      <!-- To receive exception details in faults for debugging purposes, set the value below to true. Set to false before deploying the solution to avoid disclosing exception information. -->
      <serviceDebug includeExceptionDetailInFaults="false"/>
      </behavior>
      </serviceBehaviors>
      </behaviors>
      </system.serviceModel>
      </configuration>





    10. Build the application.

    11. Add an application to the default web site. Start Internet Information Services (IIS) Manager. Click Start, click All Programs, click Administrative Tools, and then click Internet Information Services (IIS) Manager. In Internet Information Services (IIS) Manager, expand Sites, and right-click Default Web Site, and then select Add Application. The following figure shows how to add an application in Internet Information Services (IIS) Manager.

      Figure 11. Internet Information Services Manager

      Internet Information Services ManagerIn the Add Application dialog box, in the Alias field, type Customers. In the Physical Path field, browse to C:\MyWebService\CustomersService. Click OK twice. The following figure shows the directory that contains the web service.

      Figure 12. Directory with the web service

      Browse to directory that contains Web service

    12. Validate that the web service is running. Start Internet Explorer, and browse to http://localhost/Customers/Customers.svc. If the web service is running, you see the following:

      Figure 13. CustomersService web service in Internet Explorer

      Web service running in Internet Explorer




    Validating the Web Service




    Another approach to testing the web service is to use the WCF test client.

    To validate the Web Service by using the WCF Test Client




    1. Start a Visual Studio command prompt (or use the one that is open from the end of the preceding procedure).

    2. Type wcftestclient to run the WCF test client. Click File and then click Add Service.

    3. Type http://localhost/Customers/Customers.svc as the endpoint address, and then click OK.

      The following figure shows entering the endpoint into the WCF test client.

      Figure 14. WCF Test Client

      WCF test clientIf the service was added successfully, you see the methods that the service exposes. The following figure shows the web service methods in the WCF test client.

      Figure 15. WCF Test Client showing methods

      WCF test client showing methods

    4. Double-click GetAllCustomers. This opens a window that lets you configure the request and start the request.

    5. Click Invoke to see the response from the web service. The following figure shows the results of calling GetAllCustomers.

      Figure 16. WCF Test Client showing results from calling GetAllCustomers

      WCF test client showing data