Nik Patel's SharePoint World

An adventure in SharePoint and Microsoft in general.

Archive for the ‘Code Snippets’ Category

Code Snippet – Programmatically Access Root Site Collection in Multi-Site Collection Heirarchy

Posted by nikspatel on December 21, 2011

It’s fairly common need in multi-site collection environment to access root site collection programmatically from the current sub site collection or sub site. It’s kind of ironic that one of my colleagues asked me same question while working on our multi-site collection environment this week.

To access the root site collection from the sub site or sub site collections in given web application, you have to somehow access the SPWebApplication object. It’s easy to access SPWebApplication object using SPSite object’s WebApplication property. Once you have access to the SPWebApplication object, you can access first site collection from SPWebApplication.Sites collection to get the handle of the root site collection.

From the sub site, use the following line of code to access root site collection and its URL.

string rootSiteCollectionURL = SPContext.Current.Web.Site.WebApplication.Sites[0].Url;

Posted in Code Snippets | Leave a Comment »

Code Snippet – Programmatically Create Web Application Managed Paths in SharePoint 2010

Posted by nikspatel on December 5, 2011

While creating site collections, it is fairly common to create site collections at the more user friendly URLs. By default, each web application has two managed paths – Explicitly named single site collection managed path “(root)” which would allow only 1 site collection at the root path, http://<WebAppURL>/ and Wildcard managed path “sites” to host multiple site collections which would allow users to create multiple site collections at the http://<WebAppURL>/sites/ path.

To automate hundreds or thousands of site collections creation process for a given web application, you can create either explicit or wildcard managed path programmatically. Following code snippets shows two different ways to create managed paths. Both ways shows different ways to access the SPWebApplication application object – using URI or SPSite to create managed path.


using System;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Administration;

namespace CodeSnippets
{
    class Program
    {
        static void Main(string[] args)
        {
            //Retrieve the Input Arguments
            string url = string.Empty;
             if (args.Length > 0)
            {
                Console.WriteLine("Input Web App URL: " + args[0].ToString());
                url = args[0].ToString();
            }
            else
            {
                url = "<a href="http://sp2010vm:1000/">http://sp2010vm:1000</a>";
            }

            //Create Managed Path
            CreateManagedPathUsingWebAppURI(url, "teamsUri", true);
            CreateManagedPathUsingWebAppURI(url, "salesUri", false);
            CreateManagedPathUsingSPSite(url, "teamsSpSite", true);
            CreateManagedPathUsingSPSite(url, "salesSpSite", false);
        }

        ////Method 1 - Create Web App object using URI
        private static void CreateManagedPathUsingWebAppURI(string webAppURL, string NewSiteCollectionName, bool isWildCardInclusion)
        {
            SPWebApplication spWebApp = SPWebApplication.Lookup(new Uri(webAppURL));
            SPPrefixCollection prefixColl = spWebApp.Prefixes;
            if (prefixColl.Contains(NewSiteCollectionName) == false)
            {
                if (isWildCardInclusion)
                {
                    SPPrefix prefix = spWebApp.Prefixes.Add(NewSiteCollectionName, SPPrefixType.WildcardInclusion);
                }
                else
                {
                    SPPrefix prefix = spWebApp.Prefixes.Add(NewSiteCollectionName, SPPrefixType.ExplicitInclusion);
                }
            }
        }

        //Method 2 - Reference Web App Object from SPSite
        private static void CreateManagedPathUsingSPSite(string webAppURL, string NewSiteCollectionName, bool isWildCardInclusion)
        {
            using (SPSite spSite = new SPSite(webAppURL))
            {
                SPWebApplication spWebApp = spSite.WebApplication;
                SPPrefixCollection prefixColl = spWebApp.Prefixes;
                if (prefixColl.Contains(NewSiteCollectionName) == false)
                {
                    if (isWildCardInclusion)
                    {
                        SPPrefix prefix = spWebApp.Prefixes.Add(NewSiteCollectionName, SPPrefixType.WildcardInclusion);
                    }
                    else
                    {
                        SPPrefix prefix = spWebApp.Prefixes.Add(NewSiteCollectionName, SPPrefixType.ExplicitInclusion);
                    }
                    spWebApp.Update(true);
                }
            }
        }
    }
}

Posted in Code Snippets | Leave a Comment »

Code Snippet – How to Check if SharePoint Site Collection or Sub Site Exists

Posted by nikspatel on November 30, 2011

Recently I have been focusing on building site provisioning tool for one of my clients and one of the most important code snippets was to check whether given site collection or sub site exists whenever end-user requests new site collection or sub site. Even though SharePoint 2010 (or even SharePoint 2007) has been released for a while, I was surprised to see that there isn’t any complete code snippets on web. There are many MS and Non-MS forum questions and responses but I couldn’t find exactly what I was looking for as far as code snippets.

Here is the code snippet to check if site collection exists in given web application. Notice that following code uses SPSite.Exists method to check if site collection exists at given path.

//Check if site collection exists at given web application
private static bool isSiteCollectionExists(SPWebApplication spWebApp, string siteCollectionRelativeUrl)
{
    bool returnVal = false;
    string webAppURL = string.Empty;
    foreach(SPAlternateUrl spWebAppAlternateURL in spWebApp.AlternateUrls)
    {
        if (spWebAppAlternateURL.UrlZone == SPUrlZone.Default)
        {
            webAppURL = spWebAppAlternateURL.Uri.AbsoluteUri;
        }
    }

    if (webAppURL.ToString().Length != 0)
    {
        Uri siteCollectionUri = new Uri(webAppURL + siteCollectionRelativeUrl);
        returnVal = SPSite.Exists(siteCollectionUri);
    }           
    return returnVal;
}

//To Check if site collection - "Sales" exists at the Web Application's Explicit inclusion Managed Path - "Sales" - <a href="http://niks.sharepoint.local/Sales">http://niks.sharepoint.local/Sales</a>
using (SPSite spRootSite = new SPSite("<a href="http://niks.sharepoint.local/">http://niks.sharepoint.local</a>"))
{
     //Get the reference of the web application of the root site collection
     SPWebApplication spWebApp = spRootSite.WebApplication;
     if (!isSiteCollectionExists(spWebApp, "Sales"))
     {
           //Create New Site Collection
     }
}

//More Samples
//To Check if site collection - "Sales" exists at the Web Application's Wildcard Inclusion Managed Path - "Sites" - <a href="http://niks.sharepoint.local/Sites/Sales">http://niks.sharepoint.local/Sites/Sales</a>
isSiteCollectionExists (spWebApp, "Sites/Sales")
//To Check if site collection - "Sales" exists at the Web Application's Wildcard Inclusion Managed Path - "Depts" - <a href="http://niks.sharepoint.local/Depts/Sales">http://niks.sharepoint.local/Depts/Sales</a>
isSiteCollectionExists (spWebApp, "Depts/Sales")

Here is the code snippet to check if sub site exists in given site collection. Notice that following code uses SPWeb object’s Exists property to check if sub site exists at given path. Additionally, it opens the web using OpenWeb(String, Boolean) overloaded method where second parameter “true” means exact URL is supplied.

//Check if sub site exists at given site collection
private static bool isWebExists(SPSite spSite, string webRelativeUrl)
{
    bool returnVal = false;
    using (SPWeb currentWeb = spSite.OpenWeb(webRelativeUrl, true))
    {
        returnVal = currentWeb.Exists;
    }
    return returnVal;
}
//To Check if sub site- "Chicago" exists at Site Collection - <a href="http://niks.sharepoint.local/HR">http://niks.sharepoint.local/HR</a>
using (SPSite spSite = new SPSite("<a href="http://niks.sharepoint.local/HR">http://niks.sharepoint.local/HR</a>"))
{
     if (!isWebExists(spSite, "Chicago"))
     {
         //Create New Web
     }
}

You can also use following code snippet to check if sub site exists in given site collection. Instead of using SPWeb.Exists property, this code trying to access one of the SPWeb object property to check whether object was instantiated. If there is no sub site, it would throw and exception and silently return the false.


private static bool isWebExists(SPSite spSite, string webRelativeUrl)
{
     bool returnVal = false;
     using (SPWeb currentWeb = spSite.OpenWeb(webRelativeUrl))
     {
          try
          {
              //Try to access the site property. If it doesn't throw an error, means site already exists.
              string siteTitle = currentWeb.Title;
              returnVal = true;
           }
           catch
           {
               //Do nothing
           }
     }
     return returnVal;
}

Posted in Code Snippets | Leave a Comment »

Code Snippet – Add Images on SharePoint Web Part Pages Programmatically

Posted by nikspatel on October 24, 2011

There are multiple ways you can add images programmatically on the SharePoint web part pages from the code. This article will provide you couple of code snippets to add images using Image Web Part and Content Editor Web Part. One of the benefits of adding images using web parts are end-users can specify different images.

Image Web Part
If you want to add non-clickable image as a place holder on the web part pages, use “ImageWebPart” to add image programmatically using following code snippet.

SPFile page = spWeb.GetFile("Home/Home.aspx");
using (SPLimitedWebPartManager lwpm = page.GetLimitedWebPartManager(PersonalizationScope.Shared))
{
    try
    {
        lwpm.AddWebPart(
            new Microsoft.SharePoint.WebPartPages.ImageWebPart()
            {
                Title = "News & Events",
                AllowEdit = false,
                AllowClose = false,
                AllowHide = false,
                AllowMinimize = false,
                AllowConnect = false,
                AllowZoneChange = false,
                HorizontalAlignment = HorizontalAlignment.Left,
                ImageLink = "Images/industryNews.gif",
                ChromeType = PartChromeType.None
            },
            "Zone4",
            3);
    }
    finally
    {
        if (lwpm.Web != null)
        {
            lwpm.Web.Dispose(); // SPLimitedWebPartManager.Web object Dispose() called manually
        }
    }
}

Content Editor Web Part with Hyperlink HTML
If you want to add clickable image on the web part pages, unfortunately “ImageWebPart” wouldn’t work. As a workaround, you can add “ContentEditorWebPart” programmatically and add hyperlink HTML as shown in following code snippet.

SPFile page = spWeb.GetFile("Home/Home.aspx");
using (SPLimitedWebPartManager lwpm = page.GetLimitedWebPartManager(PersonalizationScope.Shared))
{
    try
    {
        // create a new XmlElement and put the results there
        XmlDocument xmlDoc = new XmlDocument();
        XmlElement xmlElement = xmlDoc.CreateElement("ContentElement");
        xmlElement.InnerText = "<a href='../Docs/MyDocs.aspx'><img src='Images/myDocs.gif'/></a>";

        lwpm.AddWebPart(
            new Microsoft.SharePoint.WebPartPages.ContentEditorWebPart()
            {
                Title = "My Documents",
                AllowEdit = false,
                AllowClose = false,
                AllowHide = false,
                AllowMinimize = false,
                AllowConnect = false,
                AllowZoneChange = false,
                Content = xmlElement,
                ChromeType = PartChromeType.None
            },
            "Zone3",
            1);
    }
    finally
    {
        if (lwpm.Web != null)
        {
            lwpm.Web.Dispose(); // SPLimitedWebPartManager.Web object Dispose() called manually
        }
    }
}

Posted in Code Snippets | Leave a Comment »

Code Snippet – Programmatically Modify the Properties of the SharePoint Web Parts

Posted by nikspatel on February 23, 2011

Here is the quick code snippet to update the web part properties on the SharePoint 2007/2010 Web Part Pages and SharePoint 2010 Wiki Pages. Please note that adding web parts on the web part pages and wiki pages has different process but updating web part properties has similar process.

In the following code snippet, we are looping through all the webs in the site collection and update the “Shared Documents” web part title to the “Project Documents” on the Projects site home page. Please note that we are looping through the page web parts using the SPLimitedWebPartManager and use the web part manager’s SaveChanges method to apply the changes made to the web parts.

class Program
{
    static void Main(string[] args)
    {
        using (SPSite spSite = new SPSite("http://sp2010vm"))
        {
            foreach (SPWeb spWeb in spSite.AllWebs)
            {
                if (spWeb.Name == "Projects")
                {
                    spWeb.AllowUnsafeUpdates = true;

                    SPFile wikiFile = spWeb.GetFile("SitePages/Home.aspx");
                    using (SPLimitedWebPartManager wpm = wikiFile.GetLimitedWebPartManager(System.Web.UI.WebControls.WebParts.PersonalizationScope.Shared))
                    {
                        try
                        {
                            foreach (System.Web.UI.WebControls.WebParts.WebPart wp in wpm.WebParts)
                            {
                                if (wp.Title == "Shared Documents")
                                {
                                    wp.Title = "Project Documents";
                                    wpm.SaveChanges(wp);
                                }
                            }
                        }
                        catch
                        {
                            if (wpm.Web != null)
                            {
                                wpm.Web.Dispose();
                            }
                        }
                    }

                    spWeb.AllowUnsafeUpdates = false;
                }
            }
        }
    }
}

Posted in Code Snippets | Leave a Comment »

Code Snippet – Programmatically Configure the Order By and Group By Properties of the SharePoint Lists and Document Libraries Views

Posted by nikspatel on November 9, 2010

If you want to set the Order By or Group By properties for the given list or document library views programmatically, you have to set the SPView Object’s Query property.


class Program
{
    static void Main(string[] args)
    {
        SPSite spSite = new SPSite("http://sp2010vm/");
        foreach (SPWeb spWeb in spSite.AllWebs)
        {
            spWeb.AllowUnsafeUpdates = true;

            SPListCollection lists = spWeb.Lists;
            for (int i = 0; i < lists.Count; i++)
            {
                if (lists[i] is SPDocumentLibrary)
                {
                    if (((SPDocumentLibrary)lists[i]).IsCatalog == false)
                    {
                        SPDocumentLibrary spList = (SPDocumentLibrary)lists[i];
                        if (spList.Title == "Classified Documents")
                        {

                            //Update the View
                            SPView view = spList.Views["All Documents"];

                           ////Reset the View
                           //string viewQuery = @" <OrderBy><FieldRef Name=""FileLeafRef"" /></OrderBy>> "; 

                          //Set the Group By Properties
                          string viewQuery = @" <GroupBy Collapse=""TRUE"" GroupLimit=""100""> <FieldRef Name=""Classified_x0020_Document_x0020_Type"" Ascending=""True""/> </GroupBy> <OrderBy> <FieldRef Name=""FileLeafRef"" /></OrderBy>";
                               
                            view.Query = viewQuery;
                            view.Update();
                            spList.Update();
                        }
                    }
                }
            }

            spWeb.AllowUnsafeUpdates = false;
            spWeb.Dispose();                  
        }

        spSite.Dispose();
    }
}

Tip: To find the syntax for the CAML Query order by and group by settings, you can download and use the free tool SharePoint Manager 2010 available on the codeplex. On the development machine, Set the group by settings in the browser interface for the views and visit the SharePoint Manager to find the syntax for the group by and order by CAML.

Posted in Code Snippets | Leave a Comment »

Code Snippet – Programmatically Add the Web Part on the SharePoint Web Part Page

Posted by nikspatel on November 9, 2010

Since MOSS 2007 days (including SharePoint 2010), users and developers can create the web part pages. I am sure it’s been blogged several different places but if you have web parts already deployed on the site collection web part gallery and if you want to add the web part on the web part page programmatically, please use the following code snippet. If you want to add the Web Part to a Web Part page, you have to simply tell the Web Part manager in which zone to add the web part. This code snippet is mainly for my personal reference but feel free to use it.


class Program
{
    static void Main(string[] args)
    {
        SPSite spSite = new SPSite("http://sp2010vm/");
        foreach (SPWeb spWeb in spSite.AllWebs)
        {
            spWeb.AllowUnsafeUpdates = true;

            // Add the web part to the web part page
            SPFile page = spWeb.GetFile("SampleWebPartPages/SampleWebPartPage.aspx");
            using (SPLimitedWebPartManager lwpm = page.GetLimitedWebPartManager(PersonalizationScope.Shared))
            {
                try
                {
                    lwpm.AddWebPart(
                        new SiteOwnersNameSpaceName.SiteOwnersClassName()
                        {
                            Title = "Sites List Web Part",
                            AllowEdit = false,
                            AllowClose = false,
                            AllowHide = false,
                            AllowMinimize = false,
                            AllowConnect = false,
                            AllowZoneChange = false,
                            ChromeType = PartChromeType.None
                        },
                        "Left",
                        1);
                }
                finally
                {
                    if (lwpm.Web != null)
                    {
                        lwpm.Web.Dispose(); // SPLimitedWebPartManager.Web object Dispose() called manually
                    }
                }
            }

            spWeb.AllowUnsafeUpdates = false;
            spWeb.Dispose();
        }

        spSite.Dispose();

    }
}

Posted in Code Snippets | Leave a Comment »

Code Snippet – Programmatically Update the SharePoint Web Part Properties on the List Forms

Posted by nikspatel on November 4, 2010

If you ever want to update the web part properties on the out of the box SharePoint List forms programmatically, use the following code snippet. Thanks to Fransisco’s article for the inspiration. I have updated his code with better memory check.

Typically you wouldn’t want to change List form web part properties but we came across very interesting situation where we had to update these web part properties. We had several document libraries created on the several sites which were further created based on the site template (user site templates stored in the site collection solution library). Whenever we add new custom content types on the document libraries on these sites, document library list form wasn’t displaying custom metadata attached to the custom content types in the edit form. By default, document library list form web part template name property is set to “DocumentLibraryForm”. Updating the template name property to the “ListForm” would fix this issue. This is one of the curious cases of SharePoint. We have tested the same scenario on the document libraries on the sites created based on site definition (out of box site templates) and we didn’t have these issues. This issue was affecting only document libraries in the sites where sites were created using user site templates.

The scenario I have here is I wanted to modify the ListFormWebPart’s TemplateName proprety on the Upload.aspx, EditForm.aspx, and DispForm.aspx pages of all the document libraries for all the sites in given site collection. This code snippet checks out the files, updates the list form web part properties, and checks in the files.

</pre>
&nbsp;

using Microsoft.SharePoint;
using Microsoft.SharePoint.WebPartPages;
using System.Web.UI.WebControls.WebParts;

class Program
{
    static void Main(string[] args)
    {
        SPSite spSite = new SPSite("<a href="http://sp2010vm">http://sp2010vm</a>");
        foreach (SPWeb spWeb in spSite.AllWebs)
        {
            spWeb.AllowUnsafeUpdates = true;

            SPListCollection lists = spWeb.Lists;
            for (int i = 0; i < lists.Count; i++)
            {
                if (lists[i] is SPDocumentLibrary)
                {
                    if (((SPDocumentLibrary)lists[i]).IsCatalog == false)
                    {
                        SPDocumentLibrary spList = (SPDocumentLibrary)lists[i];

                        // Update forms
                        foreach (SPForm spForm in spList.Forms)
                        {
                            if (spForm.Url.Contains("DispForm.aspx") || spForm.Url.Contains("EditForm.aspx") || spForm.Url.Contains("Upload.aspx"))
                            {
                                string fileURL = spWeb.Url + "/" + spForm.Url;
                                SPFile page = spWeb.GetFile(fileURL);

                                using (SPLimitedWebPartManager lwpm = page.GetLimitedWebPartManager(PersonalizationScope.Shared))
                                {
                                    try
                                    {
                                        // Enable the Update
                                        lwpm.Web.AllowUnsafeUpdates = true;

                                        // Check out the file, if not checked out
                                        SPFile file = lwpm.Web.GetFile(fileURL);
                                        if (file.CheckOutType == SPFile.SPCheckOutType.None)
                                            file.CheckOut();

                                        // Find the ListFormWebPart and Update the Template Name Property
                                        foreach (System.Web.UI.WebControls.WebParts.WebPart wp in lwpm.WebParts)
                                        {
                                            if (wp is Microsoft.SharePoint.WebPartPages.ListFormWebPart)
                                            {
                                                Microsoft.SharePoint.WebPartPages.ListFormWebPart lfwp =
                                                    (Microsoft.SharePoint.WebPartPages.ListFormWebPart)wp.WebBrowsableObject;
                                                lfwp.TemplateName = "ListForm";
                                                lwpm.SaveChanges(lfwp);
                                            }
                                        }

                                        // Update the file
                                        file.Update();
                                        file.CheckIn("System Update");

                                        // Disable the Unsafe Update
                                        lwpm.Web.AllowUnsafeUpdates = false;
                                    }
                                    finally
                                    {
                                        if (lwpm.Web != null)
                                        {
                                            lwpm.Web.Dispose(); // SPLimitedWebPartManager.Web object Dispose() called manually
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }

            spWeb.AllowUnsafeUpdates = false;
            spWeb.Dispose();                  
        }

        spSite.Dispose();
    }
}

Hope it is useful.

Posted in Code Snippets | Leave a Comment »

Code Snippet – Download and Upload the SharePoint Documents using the SharePoint Copy Web Service

Posted by nikspatel on April 12, 2010

I have been recently working on the Open XML SDK program where I needed to download the document from the SharePoint document library, update the data using the Open XML SDK, and upload the document back to the SharePoint document library. Eric White from the MSFT has an excellent article if you need to run the Open XML SDK program from the SharePoint Servers which downloads and uploads the document using the SharePoint Object Model.

http://blogs.msdn.com/ericwhite/archive/2010/03/24/modifying-an-open-xml-document-in-a-sharepoint-document-library.aspx

Although my scenario is similar to Eric White’s program as far as Open XML is concerned, I needed to run the Open XML Program on the Non-SharePoint servers where I can’t use the SharePoint Object Model to download and upload the documents on the SharePoint document library. Best way to accomplish this on the Non-SharePoint Servers is using the SharePoint Copy Web Service.

Here are the additional resources on how to upload and download the SharePoint documents from the document library. They have directly or indirectly helped me to come up with the working solution which follows later in this blog.

Following is the working code to download and upload the SharePoint document on the SharePoint document library.

To test the code, create the Console Program and Add the SharePoint Web Service Interface for the SharePoint Copy Web Service URL where document library is hosted. Following program is using the .NET Framework 2.0 based web services framework. Optionally you can use the WCF interface. To add the web service reference in the Visual Studio 2008 and Visual Studio 2010, Click on the Add Service References -> Advanced -> Add Web Reference -> Specify the SharePoint enviornment’s Copy Web Service URL (http://sp2010vm/_vti_bin/copy.asmx).


using ConsoleInterface.sp2010vmCopyService;

namespace ConsoleInterface
{
    class Program
    {
        public static void Main(string[] args)
        {
            // Doc URL
            string docUrl = "<a href="http://sp2010vm/Shared%20Documents/DocTemplate.docx">http://sp2010vm/Shared%20Documents/DocTemplate.docx</a>";

            // Step 1: Download the Document from the SharePoint Libary using the Copy Web Service
            byte[] byteArray = DownloadDoc(docUrl);
            Console.WriteLine("Document Downloaded from the SharePoint Library");

            // Step 2: Manipulate the document with the Open XML
            byteArray = OpenXMLDocProcessor.UpdateDocument(byteArray);
            Console.WriteLine("Document updated by the Open XML SDK");

            // Step 3: Download the Document from the SharePoint Libary using the Copy Web Service
            UploadDoc(docUrl, byteArray);
            Console.WriteLine("Document uploaded to the SharePoint Library");

            Console.WriteLine("Press any key too continue...");
            Console.ReadLine();
        }

        private static byte[] DownloadDoc(string sourceUrl)
        {
            // Instantiate the SP2010VM Copy Service
            ConsoleInterface.sp2010vmCopyService.Copy sp2010VmCopyService = new ConsoleInterface.sp2010vmCopyService.Copy();
            sp2010VmCopyService.Credentials = System.Net.CredentialCache.DefaultCredentials;

            // Define the variables that will store the output from the web service call
            ConsoleInterface.sp2010vmCopyService.FieldInformation myFieldInfo = new ConsoleInterface.sp2010vmCopyService.FieldInformation();
            ConsoleInterface.sp2010vmCopyService.FieldInformation[] myFieldInfoArray = { myFieldInfo };
            byte[] myByteArray;

            // Call the web service to get the desired item
            uint myGetUint = sp2010VmCopyService.GetItem(sourceUrl, out myFieldInfoArray, out myByteArray);

            // Convert into Base64 String
            string base64String;
            base64String = Convert.ToBase64String(myByteArray, 0, myByteArray.Length);

            // Convert to binary array
            byte[] docBinaryData = Convert.FromBase64String(base64String);

            return docBinaryData;
        }

        private static void UploadDoc(string sourceUrl, byte[] docBinaryData)
        {
            // Instantiate the SP2010VM Copy Service using Default Windows Credentials
            ConsoleInterface.sp2010vmCopyService.Copy sp2010VmCopyService = new ConsoleInterface.sp2010vmCopyService.Copy();
            sp2010VmCopyService.Credentials = System.Net.CredentialCache.DefaultCredentials;

            // Define the variables that will store the output from the web service call
            ConsoleInterface.sp2010vmCopyService.FieldInformation myFieldInfo = new ConsoleInterface.sp2010vmCopyService.FieldInformation();
            ConsoleInterface.sp2010vmCopyService.FieldInformation[] myFieldInfoArray = { myFieldInfo };

            // To receive the result Xml.
            ConsoleInterface.sp2010vmCopyService.CopyResult[] result;

            // List of desination Urls
            string[] destinationUrls = { Uri.EscapeUriString(sourceUrl) };

            // Upload the document to the SharePoint document library
            sp2010VmCopyService.CopyIntoItems(sourceUrl, destinationUrls, myFieldInfoArray, docBinaryData, out result);
            if (result[0].ErrorCode != ConsoleInterface.sp2010vmCopyService.CopyErrorCode.Success)
            {
                Console.WriteLine("Error occured during document upload process.");
                throw new Exception("Error Occured!");
            }
        }
    }
}

Posted in Code Snippets | Leave a Comment »

 
Follow

Get every new post delivered to your Inbox.