Thursday, May 10, 2012

Link to a Document in another folder in document library

Link to a document in a document library when the document is stored/Updated in document library

Follow the below steps to do Link to a document using OOTB.

We use the Content Type “Link to a Document” to link to a document that could be stored in another document library.
If the document library where you want to use the “Link to a Document” hasn’t been setup to use Content Types, you’ll have to click Settings, Document Library Settings, there you’ll need to access the Advanced Settings.


We need to add a Content Type, but before we can do this we’ll have to tell our Document Library that it can make use of different Content Types. Select “Yes” for the “Allow management of Content Types“.


When you return to the Document Library Settings, you’ll see a new section called Content Types, this is where we’ll add a new Content Type, click “Add from exisiting Content Type“.


The content type we need is “Link to a Document“, add it here.


When you return to your Document Library and click new, you’ll see that you have a new option to choose from, “Link to a Document“.


Let’s make a link to a Document in another Document Library, click “Link to a Document”. You’ll have to enter a name for the Link and enter the path to the Document you want to link to.


After confirming this is what your link looks like.


We made link to a document that’s saved in another document library, whenever you make a change to the master document, you don’t need to worry about the link, it will point to the changed document.



In the same way we can put "link to a document" links in another folder with in the Documnet library using Object Mode, Here i am using Event handler to Create Link to document when new item is Added in Document Library

using System;
using System.Security.Permissions;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Security;
using Microsoft.SharePoint.Utilities;
using Microsoft.SharePoint.Workflow;
using System.Text;

namespace LinkdocumentUrl.linktodocs
{
    /// <summary>
    /// List Item Events
    /// </summary>
    public class linktodocs : SPItemEventReceiver
    {
       /// <summary>
       /// An item was added.
       /// </summary>
       public override void ItemAdded(SPItemEventProperties properties)
       {
           base.ItemAdded(properties);
           base.DisableEventFiring();
           SPSecurity.RunWithElevatedPrivileges(delegate
           {
               using (SPSite site = new SPSite(properties.SiteId))
               {
                   using (SPWeb web = site.AllWebs[properties.RelativeWebUrl])
                   //using (SPWeb web = site.OpenWeb(properties.RelativeWebUrl))
                   {                      
                       SPListItem _item = properties.ListItem;
                       //SPField field = properties.ListItem.Fields.GetFieldByInternalName("Make a Link");
                       SPFieldBoolean boolField = _item.Fields["Make a Link"] as SPFieldBoolean;
                       bool CheckBoxValue = (bool)boolField.GetFieldValue(_item["Make a Link"].ToString());

                       //if (_item["Make a Link"].ToString() == "true")
                       if (CheckBoxValue== true)
                       {
                                        
                      
                           string documentUrl = web.Url + "/" + properties.ListItem.Url;
                           string documentName = properties.ListItem.DisplayName.ToString();
                           SPList list = web.Lists["TestDocs"];

                           if (list is SPDocumentLibrary)
                           {
                               SPDocumentLibrary docLib = (SPDocumentLibrary)list;
                               //string libraryRelativePath = list.RootFolder.ServerRelativeUrl;
                               //string libraryPath = site.MakeFullUrl(libraryRelativePath);

                               SPFolder folder = web.GetFolder(site.MakeFullUrl(list.RootFolder.ServerRelativeUrl) + "/Public");
                               SPFileCollection filecoll = folder.Files;

                               if (docLib.ContentTypesEnabled)
                               {
                                   SPContentType myCType = list.ContentTypes["Link to a Document"];
                                   if (myCType != null)
                                   {
                                       //replace string template with values
                                       string redirectAspx = RedirectAspxPage();
                                       redirectAspx.Replace("{0}", documentUrl);

                                       SPFile file = folder.Files.Add(documentName + ".aspx", UTF8Encoding.UTF8.GetBytes(redirectAspx));

                                       SPListItem item = file.Item;
                                       item["ContentTypeId"] = myCType.Id;
                                       SPFieldUrlValue fieldUrl = new SPFieldUrlValue() { Description = documentName, Url = documentUrl };
                                       item["URL"] = fieldUrl;
                                       item.Update();
                                       item.UpdateOverwriteVersion();
                                       folder.Update();
                                       base.EnableEventFiring();

                                   }
                               }

                           }
                          
                       }

                   }
               }
           });
           base.ItemAdded(properties);
       }

       public static string RedirectAspxPage()
       {
           //StringBuilder builder = new StringBuilder();

           const string format = @"<%@ Assembly Name='Microsoft.SharePoint, Version=14.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c' %>
                                                <%@ Register TagPrefix='SharePoint' Namespace='Microsoft.SharePoint.WebControls' Assembly='Microsoft.SharePoint' %>
                                                <%@ Import Namespace='System.IO' %>
                                                <%@ Import Namespace='Microsoft.SharePoint' %>
                                                <%@ Import Namespace='Microsoft.SharePoint.Utilities' %>
                                                <%@ Import Namespace='Microsoft.SharePoint.WebControls' %>

                                                <html xmlns:mso='urn:schemas-microsoft-com:office:office' xmlns:msdt='uuid:C2F41010-65B3-11d1-A29F-00AA00C14882'>
                                                <Head> <META Name='progid' Content='SharePoint.Link'>
                                                <!--[if gte mso 9]><xml>
                                                <mso:CustomDocumentProperties>
                                                <mso:URL msdt:dt='string'>{0}, {0}</mso:URL>
                                                <mso:ContentType msdt:dt='string'>Link to a Document</mso:ContentType>
                                                </mso:CustomDocumentProperties>
                                                </xml><![endif]-->
                                                </head>
                                                    <body>
                                                        <form id='Form1' runat='server'>
                                                            <SharePoint:UrlRedirector id='Redirector1' runat='server' />
                                                        </form>
                                                    </body>
                                                </html>";
           StringBuilder builder = new StringBuilder(format.Length + 400);          
           builder.AppendFormat(format, typeof(SPDocumentLibrary).Assembly.FullName);          
           return builder.ToString();
       }
    }
}


Reference from http://www.sharepointology.com/general/link-to-a-document-in-another-document-library/

Monday, April 16, 2012

Creating multiple site collections in seperate databases and Managed Paths with PowerShell

The Below PowerShell Script to usefull to create Site Collection with diffrent Content Db also each site collection has a managed path (explicit inclusion) and some site collections are using diffrent Web templates.

************************************************************************
$ErrorActionPreference = "Stop"

# Creating site collections.
$WebApps = "http://siva:9999" # enter web aplication name Example http://<server>:<port>
$WebApps_url = "http://siva:9999" # enter web aplication URL Example http://<server>:<port>
$db_server = "siva\sharepoint" # Pass the Server name
$owner_alias = "siva\siva.reddy" #Pass the User Name
$sitecoll_templates = @("STS#0","STS#1","STS#2","MPS#1","BLOG#0")
# Foreach loop to create site collections in array.

$SitesToCreate = @("siva1","siva2","siva3","Spblog","Meeting")
$ID = 0
foreach ($site in $SitesToCreate)
{
    $ID += 1  
    Write-Host "Creating site" $site "( ID =" $ID ")"
    $site_collection_db = "Test_Content_"+$site 
    Write-Host "Site Collectie Database = "$site_collection_db
  
    # The sitename will be converted to lowercase for the managedpath. 
    $siteToLower = $site.ToLower()
    $SiteColl_URL = $WebApps_url + '/' + $siteToLower
    Write-Host "Site Collectie URL =" $SiteColl_URL
    Write-Host " "
 
    # Creating content database for each site.
    New-SPContentDatabase $site_collection_db -DatabaseServer $db_server -WebApplication $WebApps
    Write-Host -ForegroundColor Yellow "Content database" $site_collection_db "has been created."
 
    # Creating managed path for each site collection.
    New-SPManagedPath -RelativeURL $site -WebApplication $WebApps -Explicit
    Write-Host -ForegroundColor Yellow "Managed path" $siteToLower "has been created."
 
    Switch ($site)
    {
        "Meeting" { $sitecoll_templates = "MPS#1"}
        "Spblog" { $sitecoll_templates = "BLOG#0"}
        default { $sitecoll_templates = "STS#1" }
    }
 
    # Creating site collection with the name defined by the Switch
  
    New-SPSite $SiteColl_URL -OwnerAlias $owner_alias -ContentDatabase $site_collection_db -Name $sitename -Template $sitecoll_templates -Language 1033
    Write-Host -ForegroundColor Yellow "Site collection" $site "has been created with the name" $sitename
 
    # Change status of content database to Disabled so the next site collection can be created in a new Online database.
    Set-SPContentDatabase -Identity $site_collection_db -Status Disabled
    Write-Host -ForegroundColor Yellow "The status of content database" $site_collection_db "is Disabled."
  
}

# Change the status of all created content databases to Online.
foreach  ($site in $SitesToCreate)
{
    $site_collection_db = "SP_Content_"+$site
    Set-SPContentDatabase -Identity $site_collection_db -Status Online
    Write-Host -ForegroundColor Yellow "Status of database" $site_collection_db "is Online."
}