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

The workflow could not update the item, possibly because one or more columns for the items require a different type of information

a problem when working with SharePoint Designer building a workflow to update the list item with some changed values.  Following my normal good practise of using a ‘Reusable Workflow’ and publishing this to the site I started to get the following problems.

Symptoms:

The workflow was published and added to the Document Library which appeared to be working correctly.  The updates were updated but after a few times of running errors occurred and the workflow failed.  These were reported as:

"The workflow could not update the item, possibly because one or more columns for the items require a different type of information"

Resolution:

After investigating why this was happening including checking my field names and types as well as building on a separate test environment and replicating the problem the resolution came about with building the workflow in a different way.

The failed workflow step we were using was ‘Update List Item’ option and this is when the error occurred.  I was updating a number of fields in my current item as once which seemed the logical way to do this.  But changing this to separating out the update steps and using the ‘Set Field in Current Item’ for each update resolved the error.
This may seem obvious but the logic says ‘Update List Item’ should work although it seems to put a lock that causes further updates to fail whereas ‘Set Field in Current Item’ works in a more sequential way preventing problems.

Friday 17 February 2012

Scroll any Sharepoint list in minutes

Step One: take a list, any list (in fact any web part or other content)

links list

Step Two: prepare a site page on which you'll have the list displayed

press "Edit Page" > "Insert" > "Existing List" and select your list

site page?

Step Three: Adjust list web part appearence

select wanted view, disable list toolbar, remove web part frame..

prepare the list visual appearence

list properties

 

Step Four: Open SharePoint Designer

open the site, which contains your page and edit it

edit page

 

Step Five: Find list's web part in code view

code view

Step Six: Add marquee object

in a brief: html marquee object let's you scroll it's content on a web page.

Main attributes:

now you need to "wrap" the list's web part with the marquee element, so:

 

marquee

save the page and you're all done, let it scroll !!!

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:

 

C# - Select XML Nodes by Name

To find nodes in an XML file you can use XPath expressions. Method XmlNode.Selec­tNodes returns a list of nodes selected by the XPath string. Method XmlNode.Selec­tSingleNode finds the first node that matches the XPath string.

Suppose we have this XML file.

[XML]
<Names>
<Name>
<FirstName>John</FirstName>
<LastName>Smith</LastName>
</Name>
<Name>
<FirstName>James</FirstName>
<LastName>White</LastName>
</Name>
</Names>

To get all <Name> nodes use XPath expression /Names/Name. The first slash means that the <Names> node must be a root node. SelectNodes method returns collection XmlNodeList which will contain the <Name> nodes. To get value of sub node <FirstName> you can simply index XmlNode with the node name: xmlNode["FirstName"].InnerText. See the example below.

[C#]
XmlDocument xml = new XmlDocument();
xml.LoadXml(myXmlString); // suppose that myXmlString contains "<Names>...</Names>"

XmlNodeList xnList = xml.SelectNodes("/Names/Name");
foreach (XmlNode xn in xnList)
{
string firstName = xn["FirstName"].InnerText;
string lastName = xn["LastName"].InnerText;
Console.WriteLine("Name: {0} {1}", firstName, lastName);
}

The output is:
Name: John Smith
Name: James White

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.

    Submitting InfoPath to a SharePoint List

    As you know, submitting to a Microsoft Windows SharePoint form library from an InfoPath form is quite simple: just add a “submit” type of data connection to InfoPath and away you go. However, submitting to a SharePoint List is another matter. In this post, we will take a look at the steps necessary to enable this functionality.

    Step 1: Create the list

    1. Create a new custom list named: MyContacts
    2. From the Settings button choose List Settings
    3. Click Create Column
    4. Add the following columns/data types:

    • FirstName, Single line of text

    • LastName, Single line of text

    • Email, Single line of text

    • Phone, Single line of text


    The next step is to create a Collaborative Application Markup Language (CAML) template that contains the same XML nodes as the columns we added to our list – this will be used as a secondary data connection in the InfoPath Form Template.

    Step 2: Create the CAML template

    1. Launch Notepad (or any text editor)
    2. Copy and paste the following code to the Notepad document:
    <?xml version="1.0" encoding="UTF-8"?>
    <Batch OnError="Continue">
    <Method ID="1" Cmd="New">
    <Field Name='Title'></Field>
    <Field Name="FirstName"></Field>
    <Field Name="LastName"></Field>
    <Field Name="Email"></Field>
    <Field Name="Phone"></Field>
    </Method>
    </Batch>

    3. Save this as: Add List Item Template.xml

     

    Step 3: Create the InfoPath Form Template

    1. Create a new, blank, browser-compatible form template
    2. Add a “Receive” type secondary data connection to the Add List Item Template.xml file created in Step #2. (Make sure the options “Include the data as a resource file in the form template” and “Automatically retrieve data when the form is opened” are enabled.)
    3. Add a “Receive” type secondary data connection to the “MyContacts” SharePoint List created in Step #1 and make sure the option “Automatically retrieve data when the form is opened” is enabled.
    NOTE: Be sure to include the “Title” field along with the custom fields we created.

    Each SharePoint list is created with a unique identifier called a GUID. In order to submit items to a SharePoint list, you must know the unique GUID for that list. These next steps will enable you to identify the GUID for your “MyContacts” list.

    Step 4: Identify the list GUID

    1. Open a browser and navigate to the MyContacts list
    2. From the Settings menu choose List Settings
    3. In the browser’s address bar you will see the URL appended with “List=”



     

    4. Copy everything after the equals sign and paste this into a text editor as we will need this value later on.

    NOTE: We will need the list GUID to be formatted as “{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}”. If your GUID appears as above with the hyphens and braces “escaped” (i.e. %7B for the braces and %2D for the hyphens) then you will need to replace the escaped characters with the braces and hyphens so when we use this GUID later, it will appear as: {1E76517B-2C36-4473-A420-A737D98589BC}

    Step 5: Add controls to the InfoPath Form Template

    1. Open the Data Source Task Pane
    2. From the Data Source dropdown box choose the “MyContacts” connection



    3. Right-click on “MyContacts” and choose Repeating Table – this will add a repeating table bound to that connection to your View
    4. From the Data Source dropdown box choose Main
    5. Add a text box to the “myFields” node named: ListName and set the Default Value property to the GUID value of your list – we will use this node to specify the list when we perform the Submit operation



     

    To update the SharePoint list we will be using the “UpdateListItems” method of the SharePoint “lists.asmx” web service. This web method requires a couple of parameters (the list name and what gets updated) – now that we have added the “ListName” node which contains the GUID and we have the Add List Item Template XML data connection which describes our data structure we have all the necessary information to add the “UpdateListItems” web method!

    Step 6: Add the “lists.asmx” web service

    1. Add a new “Submit” type of web service data connection to the “lists.asmx” web service – this is typically located at: http://servername/_vti_bin/lists.asmx
    2. Select the “UpdateListItems” operation
    3. Double-click the “listname” parameter and assign the “my:ListName” node as the value



    4. Double-click the “updates” parameter, select the “Add list Item Parameter” data source, select “Batch” and click OK
    5. For the “Include” option select “XML subtree, including selected element”



    6. Complete the Data Connection Wizard

    Now that we have all the connections that are required, we now need to add the “submit” functionality to the form template.

    Step 7: Add Submit functionality

    1. Display the Data Source Task Pane
    2. From the Data Source dropdown box choose the Add List Item Template data connection
    3. Drill down through the data source, right-click on the Field node and choose Repeating Table



     

    We need to change the text box control in the “Name” column to Read-only – if these values were to be changed it would affect the CAML and the submit would fail.
    • Double-click on the text box in the Name column of the Repeating Table
    • Select the Display tab
    • Enable the Read-only property and click OK
    • Add a new Button control to the View
    • Double-click the button to display the Properties
    • Click the Submit Options button
    • Enable the option “Allow users to submit this form”
    • Enable the option “Perform custom action using Rules” and click the Rules button
    • Click the Add button
    • Click the Add Action button
    • From the Action dropdown box choose “Submit using a data connection”, select the “Web Service Submit” data connection and click OK
    • Click the Add Action button
    • From the Action dropdown box choose “Query using a data connection”, select the “MyContacts” data connection and click OK (this will automatically refresh the list in InfoPath so you can see the newly added record)



    • Click OK until you are back to your form

    NOTE: If you want to automatically clear out the submitted values, add another action to this Rule to “Set a field’s value” and the only option you need to specify is the “Field” option – select the “Field” node from the “Add List Item Template” data connection and then simply leave the Value option blank.

    Step 8: Test!

    1. Click the Preview button to preview the form
    2. Fill in values for each of the fields: Title, First Name, Last Name, E-mail and Phone



    3. Click the Submit button – the contact information should be submitted successfully and the “MyContacts” list automatically updated!

    SharePoint Designer Reminder Email Workflow

    design a workflow to extend the out of the box functionality to email meeting attendees 2 weeks before the meeting is due to start. Firstly create a SharePoint calendar list called ‘Events’.

    The out of the box editable calendar columns are displayed below:

    image

    For the workflow you need to create two additional columns for the events list:

    • Calculated field called Reminder (Date and Time)

    • Person or Group called Attendees


    The calculated column settings can be seen below basically offsetting the Start Time by 14 days (2 weeks) as [Start Date] – 14.

    image

    Then create the Person or Group column as shown below making sure that the ‘Allow multiple selections’ option is set to ‘No’:

    image

    If you create a new event now you will see an additional field for the Person or Group

    image

    Notice that the calculated field does not appear here as this is not an editable field and will automatically calculate in the background.

    Next step is to open SharePoint Designer and create a new workflow (I’m assuming if your reading this post you have some level of understanding of SPD and will not be covering this step for step).

    You will need 2 steps for the workflow. The first is to check date and pause the workflow if the date is not equal to Start Time – 14. The second step is once the Start Time does equal 14 days before event then send the email.

    On the new workflow set the values as shown below:

    image

    Step 1 – Check Date

    image

    So the above basically checks if Reminder (14 days before event) is equal to today. If not then it pauses until the Reminder does equal today.

    Step 2 – Send Email

    image

    In this step the action is again to check for the Reminder date equals today. Then send the email.

    image

    The email is where another blog post of mine discovered an issue. The  workflow sends an email to the the current items Attendees. The subject is also the title of that specific meeting. I also added some text to the main body where you could customise the email further by adding lookup references specific to that event such as start time etc.

    Once you’ve created the 2 steps click finish and navigate to the event list and enter a new event 2 weeks away and make sure you set it for 5 minutes ahead so you have time to save the event.

    NOTE: MAKE SURE YOU DO NOT CREATE THE TASKS AS A SYSTEM ACCOUNT OTHERWISE THE WORKFLOW WILL NOT WORK SEE KB ARTICLE: http://support.microsoft.com/kb/947284

    image

    image

    (This is not my actual diary!)

    If you select the new entry created and select workflows you should see:

    image

    And if you click on ‘InProgress’ this will show you that the workflow is paused for 5 minutes and will then send the email:

    image

    That's it job done and expect to see an email in your inbox reminding you.

    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: Download, Upload file from Document Library

    ownload from Document Library


    If you need download a file from document library you can do so easily. First you need to get the SPFile object from the file url. then you need to create a file stream for local file. Finally you need to write the SPFile object to the strem. The following code snippet shows how easy it is
    SPFile spFile = currentWeb.GetFile(docLibFileUrl); 
    FileStream outStream = new FileStream(localFileName, FileMode.Create);
    byte[] fileData = spFile.OpenBinary();
    outStream.Write(fileData, 0, fileData.Count());
    outStream.Close();

     

    Upload to Document Library


    If you ever need to overwrite a file in document library then first you need to get the SPFile. After that you need to checkout the file and finally call the SaveBinary method to save data to the spfile.

     
    SPFile spFile = currentWeb.GetFile(docLibFileUrl);
    spFile.CheckOut();
    byte[] binaryData=File.ReadAllBytes(localFileName);
    spFile.SaveBinary(binaryData, true);
    spFile.CheckIn(string.Empty);

    Using quick-parts to automatically update fields in a Microsoft Office document, from the metadata in a SharePoint document library

    Sometimes you find yourself in the scenario where you need to capture metadata as part of a document (for instance a Quote or a legal documnet, which then populates throughout the document where ever the field is placed. Sure, this doesn’t happen a lot, but when it happens, making use of quick parts is an easy way to do it.

    Step 1: Create a SharePoint document library as you usually would

    Step 2: If the document template is reusable, create a Site Content type as you usually would and add the site columns to it you would like to associate with it

    image

    Otherwise you could simply create list level custom columns and upload the document we’ll be creating in a minute under advanced settings

    image

    image

    Step 3 (I will assume you are using a custom content type):

    Create a new document of the content type you just created (for this demo I based it on a Medical Report required by one of our local banks for Insurance purposes)

    image

    Step 4: After creating a new document, save it first, or it won’t allow you to insert the metadata values from the document library. Call it anything, this is a temporary document.

    Step 5: With the document open, click the Insert tab –> Quick-Parts –> Document Property –>
    and select the property you would like to insert

    image

    Step 6: Repeat step 5 for all the properties you want to see on your document. You will immediately see the property fields fill them selves as you fill in the metadata at the top

    image

    Step 7: Once you’ve finished updating the document template with all the required fields, save it offline – i.e. to your desktop.

    Step 8: Upload the document you saved offline as the template to be used for your content type

    image

    And that’s it! You will notice that if you change the metadata in the column on SharePoint, the values will be changed as soon as you open the document again.

    Using Document Templates with Lists and Content Types in SharePoint

    While the concept of document templates has been in SharePoint for a very long time, and content types since SharePoint 2007, I often find that many organizations don’t take complete advantage of their power, or don’t use them at all. In many cases, this is because they are unaware of how to properly do so.

    This post is an attempt at demonstrating how templates can work with both libraries and document templates, taking full advantage of the metadata contained within SharePoint in the document. It will also describe an approach that we use to help with their maintenance.

    I have described 3 walkthrough scenarios, each complete in its own right, but when taken together form a comprehensive template management strategy. These 3 scenarios are:


    1. Using a Library Template

    2. Using a Content Type Template

    3. Use A Library to Manage Your Document Templates



    All of the examples here are shown using the 2010 suite of tools (Office 2010, SharePoint 2010). However, almost all of this capability is available in the 2007 family of products. Some of the menu locations are different with 2007 (Particularly with Word) , but the capabilities are there.

    A – Using a Library Template


    The simplest way of working with templates is to modify the default template for a document library. In the example below, we’ll create a new library, create metadata, display and use the metadata, and finally, create a new document based on this template. Several of the steps used in this example will be used in the other examples.

    1. Create a new Document library


    From your destination site, click either “Libraries” or “All site content” from the Quick Action pane on the left (note – the menu options that appear will vary according to the site template used, and the options that have been chosen by the site administrator). If neither option is available, select “Site Actions” then View All Site Content”.

    Finally, from the resultant dialog, select “Document Library”, give the new library a name, and click the “Create” button. In this case, we’ll use “Letters”.

    image

    2. Add metadata to the library


    Now we need to add some metadata to this library. When the Library is first created, the Library ribbon tab will be open. From there click the “Library Settings” button.

    image

    On the following screen, in the columns section, select “Create Column” (or add from existing site columns, and add the metadata fields that you want to use with this library. In this case, we’ll add a few (pretty boring) fields that you might want to use when tracking letters.

    Side note – as a best practice, I try to never use spaces in the names when creating fields, lists, sites, etc. When spaces are used, SharePoint converts these spaces to _x0020_ in the internal field names. Once the field is created, the name can be changed, and that will only affect the display name, not the internal field name.

    image

    3. Edit the default template


    Once we have our metadata fields in place, it is time to edit the default template. This example is using a word template, but the same approach works for other Office content (Excel, Powerpoint, etc).

    Without leaving the list settings screen, select Advanced Settings (in the General Settings section).

    image

    On the next screen, there is a section for the library’s document template.  in that section, select the “(Edit Template)” link. Word should open (you may be prompted for credentials) and then you will be editing the library template.

    4. Show the Document Information Panel


    Since we want to incorporate the document metadata into the body of the document, we will want to use the document information panel. The document information panel will show the user editable metadata for a document. When the document is stored in a SharePoint library, or is a template for one, you can also expose the metadata from the library itself (or from a content type….more on that later). The nice part is that it can be displayed right at the top of the document, so if the properties are used throughout the document, you only need to edit them in one place. Unfortunately, it is turned off by default, and it really has to be one of the best hidden features in Word 2010. It was hard enough to find in 2007 – you had to add the developer tab to your ribbon, and then select “show information panel” there. In 2010, it’s hidden in the backstage.

    Click File, and then click on the info tab. To the right of the screen you’ll see the section for properties. You might think that “Show All Properties” at the bottom would do it, but no. You need to hover your mouse over the “Properties” title, and select the dropdown arrow. You will be rewarded with two options, and  we want the first one, “Show Document Panel.

    image

    The good part is, you only need to set it once, and it sticks. If you’re setting it for a template, it’ll stick there too. Once selected, you will be returned to the document and the document information panel will be displayed.

    SNAGHTML1bbdb5c8

    You should see all of the metadata fields that you created for the list, in their proper column order, using the appropriate controls for their data type. Any metadata changes made in SharePoint will be reflected here, and conversely, SharePoint will be updated with any of the changes entered here. This is helpful, but it’s really powerful when you use the metadata to help form the document.

    5. Quick Parts – Put the Metadata to work


    To use a metadata field in the document, position your cursor where you would like the field to be displayed (or edited), click the “Insert” ribbon tab, select the “Quick Parts” button, select “Document Property” from the dropdown, and finally select the field that you want to use.

    image

    Repeat the procedure for each field that you want to use. When finished, your document will look something like the following:

    SNAGHTML1bcd54d5

    Finally, Save your template, and exit Word. You’re pretty much done.

    6. Test the Template


    After you close Word, you should be returned to your library. To test your template, you’ll want to try creating a new document. Go ahead and do so – click on the Documents tab in the toolbar, and the click on the new document button.

    image

    Go ahead and enter in the metadata values. Notice how the document updates as you do so. When complete, your document should look something like the image below:

    SNAGHTML1cd0018d

    Finally, save the document, and exit Word (or just exit). You’ll likely be prompted for a name – give it one. After Word closes refresh the library view, and you should see your document, with all of the relevant metadata in the library view.

    image

    B – Using A Content Type Template


    Modifying a library template is relatively straightforward, but it does entail several limitations. Firstly, by using library defined metadata (and template) you are limiting yourself to only that library. Neither these fields nor this template can be used elsewhere in the site or site collection. In addition, all of the documents in the library must use this metadata definition.

    In order to move beyond this limitation, SharePoint 2007 introduced the concept of Content Types. A detailed discussion of content types is beyond the scope of this article, but simply put, a content type is a collection of metadata fields that can be applied to a document. A content type is loosely analogous to a class in object oriented programming.

    Luckily, content types contain not only metadata, but also documents. That means that we can define a content type in a similar fashion to the way we modified a list in the example above, but we can then take that content type and apply it to any library in the site collection. With the content type syndication features available in SharePoint 2010, we can apply it to any library in our organization (it’s no longer limited to even the farm). In addition, by using content types, any given library is no longer limited to a single set of metadata fields.

    The process for creating a content type template is similar to creating a library template, but there are a few important differences. Where identical, I will reference the library template procedure.

    1. Create The Content Type


    Content types can be created at the site level or the site collection level. They will be available to their containing site and all sites below. If the content type is created at the root of the site collection, it will be available to the entire site collection.

    To do this, navigate to the root site and select “Site Actions”  and then Site Settings

    image

    You will then be presented with the Site Settings page. The Content types are stored in the Content Type Gallery, so next we will select “Site Content Types”.

    image

    We are going to create the “Letter” Content Type, so go ahead and click the “Create” button. You will then be taken to the Content type creation screen. This is similar to creating the new list as we did in the example above, but this time, there are additional options that control how the content type works.

    image

    We’ll be calling this content Type Letter, and it will inherit all of the properties (things like Name, and title) from the “Document” content type, which is in the “Document Content Types” category. Finally, we’ll want to group all of our content types in the same group, and since we don’t already have one, we’ll create the “My Custom Types” group.

    Once created, we can add all of our custom fields to the content type. We’ll use the same fields that we did in the example above.

    2. Add Metadata to the Content Type


    Upon creation of the content type, you should be taken to the Content Type Information page for it. From here, go ahead and add the same columns that added to the list above.If you bump into a reserved or in use column name (i.e. First Name) either use a different name (ie  Recipient First) or use the existing site column. Also, don’t forget to put all of the new columns into a group for later maintenance). When complete, the information page should look similar to the screen shown below.

    image

    Content types have some additional controls that allow you to control how the Document Information Panel appears within Word. In the settings section, Click on the “Document information Panel settings” link. On the next screen, ensure that the “Show Always” option is selected.

    image

    You should also note that this is where you can control precisely what appears in the Document Information Panel. Should you choose to do so, you can replace the default panel with an InfoPath form, but I won’t be covering that in this post.

    Once you are ready, click OK.

    3. Create an Word File and Upload it


    When a document library is created, a document template is normally created along with it, unless specified otherwise. This is not true for content types. Therefore, We need to create a document to use as the template for this content type. Initially the process is very straightforward. Start Word, create a new document. If you want to add content to the document at this point, that will work, but it’s not necessary. When ready, save the document to your file system and remember its name/location.

    Once done, go back to the content type definition window, and click the “Advanced Settings” link. in the resulting window, click the browse button, and navigate to the file that you just created.

    image

    Click OK, and then navigate back to the site. The content type is complete – for the moment.

    4. Add a Library for Template Customization


    Although we can edit the template once it’s been added to the content type, we can’t do anything with the metadata fields. That’s because Word can only reach back into the library that contains a document to see the metadata fields (the columns), and the content type gallery does not contain the columns that the content type itself does. We therefore need to create a document library that will use our content type. We will then create a new document that uses this content type, configure it the way we wish, and then replace the content type template with this document.

    Firstly, add a new document library to a site (ideally the root site). We will be using it again below, and ultimately to house other document templates, so give it a logical name, something like “Document Templates”. Once created, we need to enable content types, and choose the our content type.

    To enable content types, first navigate to the new library, and from the Ribbon, click the Library Tab, and then click the Library Settings button. From the Library Settings page, click the “Advanced Options” link. Once on the Advanced settings page, set “Allow management of content types?” to “Yes”.

    image

    Notice that the document template setting is greyed out. That’s because the content type will control the template. Click OK to close the advanced options screen.

    You will now notice that we have a content types section, and the Document content type is being used. We want to add our content type, and then remove the generic Document content type. Since a library must have at least one content type, we must first add ours, and then remove the Document type.

    First, click the “Add from existing site content types” link.

    image

    The “Add Content Types” dialog is loaded. Select your group from the dropdown, and add your content type to the Add list.

    image

    Click OK when ready. You will be returned to Library Settings, and you should now see your content type as number 2 in the list. We now want to remove the Document type, but there’s a slight catch. It is the first item in the content type list. The first item is the default content type, and the default content type cannot be deleted. We must first therefore make our content type the default, and then we can delete the Document content type. To do this, we click the “Change new button order and default content type” link.

    image

    From the next page, set the order of the Document content type to anything other than 1.

    image

    Click OK, and then click on the “Document” link in the Content Types list.  You are then taken to the List Content Type settings screen. From here, click the “Delete this content type” link, and confirm. Note that you are NOT deleting the Document content type itself, but only its association with this document library.

    image

    You should be returned to the Library Settings page, and see only one content type. Return to the library to perform the next step.

    5. Create a New Document in the Library


    From the library, click the Documents tab on the ribbon, and the the New Document button.

    image

    Accept the confirmation, and Word will open.  You will not need to turn on the Information Panel, as that is controlled by the content type itself. Recreate the letter following the procedure laid out in step 5 above.

    Once you finish using Quick Parts, save the letter back into the library (this isn’t absolutely necessary for what we’re doing right now, but will help us in the last example). Once saved to the library, save it once again, but this time to your file system, and take note of the location/name.

    6. Replace the Existing Content Type Template


    The content type template that you had originally created was blank, but was necessary for the content type to work at all. We now need to replace it with our formatted letter template. To do so, we need to navigate back to our site content gallery (Site Actions – Site Settings – Site Content Types). Locate and click on the site content type created above (Letter in this case), and the content type information screen appears. Click on advanced settings, and replace the existing template with the new one by uploading the new one.

    image

    Close this window and return to your site. We’re ready to test this out.

    7. Consume the New Content Type


    Create a new library to test this. Configure it to use content types, add the new content type and remove the default Document content type. I’ve already outlined the procedure for doing this above with the template library, so I won’t repeat it here. Create a new document, change some of the metadata values and save it.

    If you will not be using the procedure outlined below for template maintenance, you can delete the template library at this point.

    In order to make changes to the template at this point, you will need to repeat the procedures in steps 5 and 6, immediately above, but you will be able to do this from any library configured to use this content type. There are a few down sides to maintaining the template in this way. For one, it is cumbersome, and for another, the ability to modify site content types, particularly at the root level is very high (or at least it should be….). This is a problem because you don’t necessarily want to charge farm administrators with the task of keeping document templates current.

    Below, I will outline the last example which allows you to edit the template simply by editing a document in a library.

    C – Using A Library to Manage Your Document Templates


    So far, we have set up our template using our library metadata and stored it within our content type definition. We can use that content type throughout our site collection, but what happens when the requirements change for the site collection? In that case, someone with authority to do so must locate the content type definition, and repeat some of the steps above to update it.

    If we centralize our document templates into a single, or even multiple document libraries, it makes for easier maintenance. It will be necessary for the template library to use all of the content types that it also contains, in order to do metadata maintenance.

    The good news it that if you have been following along, you have already completed steps 1 and 2 below when you created the template library. Given that we’ve already been through many of the key concepts, I’ll keep the below examples brief.

    1. Create a Template Library


    If you have not already done so, create a new library for containing document templates. Go into advanced settings and enable content type. Add the content type of the template that you wish to manage. If necessary, delete the default “Document” content type.

    The detailed procedure for doing this can be found above.

    2. Add the Template to the Library


    Either upload or create the document to be used as a template. Edit the document to suit your purposes.

    3. Use the Document Directly as the Content Type Template


    Here is where we deviate from where we have been before. First, you’ll want to take note of the URL of the file that you used in step 2. I make it a practice to always use relative URLS, which is everything to the right of the web application in the URL of the document. If your site collection is not at the root of the application, you will need to include the site collection path (i.e. /sites/mysitecoll).

    The easiest way to get the document URL is by opening it in Word and getting it from the document information panel (File-Info).

    image

    Navigate to the site content type gallery (Site Actions, Site Settings, Site Content Types), and open your custom content type. When the information screen opens, click the Advanced Options link. The document Template URL will be set to the file name of the current template (if one has been created). Replace that with the URL of your document in the library.

    image

    Click OK, and return to your site.

    4. Test it Out


    If you don’t already have one, go ahead and create a new document library and have it use this content type. Create a few documents. As an added bonus, go back to the content type and add a mew metadata field. Edit the template in the template library to use this new field somewhere in the body of the document. Finally, edit one of the documents that use this template, and you should see the new metadata field appear in the Document Information Panel. If you create a new document, you should see the changes that were made to the template itself.

    If you’ve made it this far, congratulations! Hopefully this demonstrates the power of content types combined with document templates, and helps provide some guidance on their use.