Wednesday 26 October 2011

How to upload documents to sharepoint sites using Web Services

Hi ,

Recently someone requested me to prepare something that will allow uploading of files to sharepoint document libraries from their machine using web services.  Hence I have created the following application. It works in both versions of sharepoint MOSS 2007 and SPS 2010. This takes following 3 input values during runtime:
1. FilePath -- This is the first input value to be provided. This is the complete file path including your file name and extension.
2.Site URL- Here you need to provide the URL of the site where you want to upload your document. A point to remember here is that while providing URL make sure that you enter a valid URL and do not enter "/" at the end of the site. For example it should in the format http://webApplication/Site/Web and not in http://webApplication/Site/Web.
3. DocumentLibrary -- Here you need to enter the name of the document library in the site where you want to upload the document. If you want to upload it in any folder inside the document library then it should be in the format dLibrary/FolderName.

At the end of the execution you will get a message regarding the process completion.


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;

namespace RahulUploadFileInSharepointWebService
{
    class Program
    {
        static void Main(string[] args)
        {
            try
            {
                Console.WriteLine("This tool will upload the file from your PC to the Site");
                Console.WriteLine("Please enter the path of your file includin file name and extension");
                String sourceFilePath = Console.ReadLine();
                Console.WriteLine("Please enter the URL of the Site where you want to uplaod this file");
                String destinationSite = Console.ReadLine();
                Console.WriteLine("Please enter the Name of the document library where you want to upload the file");
                String destinationLibrary = Console.ReadLine();
                RahulCopy.Copy rahulCopy = new RahulUploadFileInSharepointWebService.RahulCopy.Copy();
                rahulCopy.UseDefaultCredentials = true;
                rahulCopy.Url = destinationSite + "/" + "_vti_bin/" + "Copy.asmx";


                FileInfo fInfo = new FileInfo(sourceFilePath);
                String dest = destinationSite + "/" + destinationLibrary + "/" + fInfo.Name;
                RahulCopy.CopyResult result1 = new RahulUploadFileInSharepointWebService.RahulCopy.CopyResult();
                RahulCopy.CopyResult result2 = new RahulUploadFileInSharepointWebService.RahulCopy.CopyResult();
                RahulCopy.CopyResult[] ResultCopy = { result1, result2 };
                RahulCopy.FieldInformation FieldInformation = new RahulCopy.FieldInformation();
                RahulCopy.FieldInformation[] fieldsInformation = { FieldInformation };
                String[] destinationURLS = { dest };
                FileStream fileStream = new FileStream(sourceFilePath, FileMode.Open, FileAccess.Read);
                byte[] fileContent = new byte[fileStream.Length];
                int length = (Int32)fileStream.Length;
                fileStream.Read(fileContent, 0, length);
                fileStream.Close();
                int outcome = (int)rahulCopy.CopyIntoItems(sourceFilePath, destinationURLS, fieldsInformation, fileContent, out ResultCopy);
                if (outcome == 0)
                {
                    Console.WriteLine("The Operation is completed successfully");
                }
                else
                {
                    Console.WriteLine("The Operation is not completed successfully");
                }
                Console.ReadLine();

            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
                Console.ReadLine();
            }
        }
    }
}

I hope this will help you out.

Sunday 23 October 2011

Powershell script to copy documents between sites in Sharepoint 2007 or Sharepoint 2010

Hi,

I have observed that now a days a very common and cumbersome task for the administrators is to copy documents between sites. I have observed that workflows are used to do the same. To provide more flexibility I have written the following script. This scrip is executed in two modes in the first mode it copies all the files from source folder and copied it to the destination folder. These folders can be the document library or the folders within them. When you will be asked for the folders URL you need to provide that in the following format.
http://site/library or http://site/library/Foldername . In the second way you can choose to copy one file among all files in the source folder to copy to destination folder. This works in MOSS 2007 as well as in SPS 2010.


param([switch]$help)

[void][System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SharePoint")

function GetHelp() {


$HelpText = @"

DESCRIPTION:
This script can be executed in two modes in the first mode it will copy all files from the source folder to the destination folder, in the second mode it will copy the

specific file from the source folder to destination folder. This folder can be a document library or a folder inside the document library.
This will also check in the file so that it will be visible to authorized users. If the file already exists in the destination location this tool will overwrite the

file.
"@
$HelpText

}

function RahulCopyDocumentsInSharepoint() {

write-host "Hello, This tool will copy the the files between the folders specified. It will overwrite the file if it exists at the destination location"
        write-host "Please enter the URL of the source folder"
        $sourceURL = read-host
        write-host "Please enter the URL of the destination folder"
        $destinationURL = read-host
        write-host "do you want to copy a specific file?if yes then type y or else type anything else"
        $fileDecision = read-host
        $cFile = [String]::Empty
        if($fileDecision -eq "y")
                {
                    write-host "Please enter the filename with extension of the file"
                    $cFile = read-host
                }
        $sourceSite = New-Object Microsoft.SharePoint.SPSite($sourceURL)
        $sourceWeb = $sourceSite.OpenWeb()
        $destinationSite = New-Object Microsoft.SharePoint.SPSite($destinationURL)
        $destinationWeb = $destinationSite.OpenWeb()
        $sList = [Microsoft.Sharepoint.SPFolder]$sourceWeb.GetFolder($sourceURL)
        $dList = [Microsoft.Sharepoint.SPFolder]$destinationWeb.GetFolder($destinationURL)
        $dLibrary = $destinationWeb.Lists[$dList.ContainingDocumentLibrary]
        $files = $sList.Files
        if ($fileDecision -ne "y")
        {
        foreach ($ctFile in $files)
        {
        $sbytes = $ctFile.OpenBinary()
        $dListFiles = $dList.Files
        foreach ($dListFile in $dListFiles)
        {
        if($dListFile.Name.Equals($ctFile.Name))
         {
         $dListFile.CheckOut()
         }
         }
        $dFileName = $dList.Files.Add($ctFile.Name, $sbytes, $true)
        if ($dFileName.CheckOutStatus -ne [Microsoft.Sharepoint.SPFile]::SPCheckOutStatus::None)
           {
           $dFileName.CheckIn("Checking in")
            }
            }
            }
            else
            {
            $desFile = $sList.Files[$sourceURL +"/" + $cFile]
            $sbytes = $desFile.OpenBinary()
             $dListFiles = $dList.Files
            foreach ($dListFile in $dListFiles)
             {
            if($dListFile.Name.Equals($desFile.Name))
               {
          $dListFile.CheckOut()
              }
                                        }
            $dFileName = $dList.Files.Add($desFile.Name, $sbytes, $true)
            if ($dFileName.CheckOutStatus -ne [Microsoft.Sharepoint.SPFile]::SPCheckOutStatus::None)
            {
          $dFileName.CheckIn("Checking in")
             }
            }
                                $destinationWeb.Update()
                                write-host "The operation completed successfully"
                               

$sourceSite.Dispose()
$sourceWeb.Dispose()
$destinationSite.Dispose()
$destinationWeb.Dispose()
       
}

if($help) { GetHelp; Continue }
else { RahulCopyDocumentsInSharepoint }

I hope this will help you out.

Thanks,
Rahul Rashu

Powershell Script To Remove the columns "Barcode", "Barcode Value", "Exempt from Policy" when removing IRM policy in a list in Sharepoint 2007 and Sharepoint 2010

Hi,

Recently someone expressed his issue of unable to remove the columns "Barcode", "Barcode Value" and "Exempt from Policy" from the list even after the policy is removed. These columns can be simply removed from the view by going into the view settings and checking these columns. However the requester expressed his concerns as why these columns where still there and why there were not removed when there the policy was removed. Hence to solve this I created the following script. It takes the site URL and list name as input values.

There was no option to delete these columns through the UI.
When initially I tried removing them from script, I got this:

Exception calling "Delete" with "0" argument(s): "Operation is not valid due to the current state of the object."

I modified my script and now it is working fine. This has been tested in both Sharepoint 2007 and Sharepoint 2010



If you are executing this make sure you have removed the policy otherwise you will face some other issues

param([switch]$help)

[void][System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SharePoint")

function GetHelp() {


$HelpText = @"

DESCRIPTION:
This script will remove the columns "Barcode", "Barcode Value" and "Exempt from Policy" from a list. These columns are added when Barcodes are enabled using IRM

policy. Even after the policy is withdrwan these columns stay in the list of columns under view settings.
"@
$HelpText

}

function RahulDeleteBarcodeIRMPolicyColumns() {

write-host "This script will remove barcode related columns from your list. Before executing this tool make sure that you have removed the policy otherwise it

will take you to some other issues"
        write-host "Please enter your site url"
        $siteURL = read-host
        write-host "Please enter your List Name"
        $listName = read-host
        $site = New-Object Microsoft.SharePoint.SPSite($siteURL)
        $Web = $site.OpenWeb()
        $web.AllowUnsafeUpdates = $true
        $listSource = $web.Lists[$listName]
        $columnNames = @("Barcode", "Barcode Value", "Exempt from Policy")
        for ($i = 0; $i -lt $columnNames.Length; $i++)
        {
           $fieldtoBedeleted = $listSource.Fields[$columnNames[$i]]
           $fieldtoBedeleted.AllowDeletion = $true
           $fieldtoBedeleted.Sealed = $false
           $fieldtoBedeleted.Delete()
                   
        }
        $web.AllowUnsafeUpdates = $false
        write-host "The columns are deleted successfully"
$site.Dispose()
$web.Dispose()
}



if($help) { GetHelp; Continue }
else { RahulDeleteBarcodeIRMPolicyColumns }


I hope this will help you out.

Thanks,
Rahul Rashu

Friday 21 October 2011

Cannot Open Database dbName Requested By The Login in Powershell scripts

Hi,

Recently while executing a powershell script that creates a Form library in a Sharepoint 2010 site I faced this error "Cannot Open database dbName requested by the login in powershell". The error is shown below:













I tried various troubleshooting steps all the way from google search but I was no where to the solution. I even started powershell window as administrator but had no luck. I passed DB name as switch to the script but again no luck.

I finally went to my SQL Server management studio and connected the instance I was using. I then tried to access my content db of the site where this script was trying to add the form library. I was shocked that I was not able to even access the properties of the db. I tried to assign security role to my login ID but had no luck.

After various troubleshooting steps I finally managed to get it through. Here are the steps I followed:

1. I opened Sql Server Management studio as administrator.
2. I then added by ID through with I was executing powershell in security roles and granted DB owner rights.

Thats it and now my scripts are executing fine without any issues.

I hope this will help you out.

Thanks,
Rahul Rashu

How to Create a Form Library using Powershell script in Sharepoint 2007 and Sharepoint 2010

Hi,

Someone expressed his needs to have a powershell script to create FormLibrary.
Hence I have written the below script and it works in both Sharepoint 2007 and Sharepoint 2010.
This code can be further modified to create other types of libraries as well.
Hence I am sharing my code here:

param([switch]$help)

[void][System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SharePoint")

function GetHelp() {


$HelpText = @"

DESCRIPTION:
This script will create a form library.
"@
$HelpText

}

function RahulFormLibraryCreation() {

write-host "This script will create a form library for you"
        write-host "Please enter your site url"
        $siteURL = read-host
        write-host "Please enter name of the form library"
        $library = read-host
        write-host "Please enter description of your form library"
        $desctiption = read-host
        $site = New-Object Microsoft.SharePoint.SPSite($siteURL)
        $web = $site.OpenWeb()
        $template = [Microsoft.Sharepoint.SPListTemplateType]::XMLForm
        $web.Lists.Add($library,$description,$template)
        $site.Dispose()
        $web.Dispose()
     

}
if($help) { GetHelp; Continue }
else { RahulFormLibraryCreation }

I hope this will help you out.

Thanks,
Rahul Rashu

Thursday 20 October 2011

How To Remove the columns "Barcode", "Barcode Value", "Exempt from Policy" when removing IRM policy in a list in Sharepoint 2007 and Sharepoint 2010

Hi,

Recently someone expressed his issue of unable to remove the columns "Barcode", "Barcode Value" and "Exempt from Policy" from the list even after the policy is removed. These columns can be simply removed from the view by going into the view settings and checking these columns. However the requester expressed his concerns as why these columns where still there and why there were not removed when there the policy was removed. Hence to solve this I created the following application. It takes the site URL and list name as input values. There was no option to delete them through the UI.
When initially I tried removing them from code, I got this:




Microsoft.SharePoint.SPException was unhandled
  Message="You cannot delete a sealed column."
  Source="Microsoft.SharePoint"
  ErrorCode=-2130575213
  StackTrace:
       at Microsoft.SharePoint.Library.SPRequest.RemoveField(String bstrUrl, String bstrListName, String bstrFieldName)
       at Microsoft.SharePoint.SPFieldCollection.Delete(String strName)
       at Microsoft.SharePoint.SPField.Delete()
       at SSPProfile.Form1..ctor() in D:\Users\Rahul\Documents\Visual Studio 2008\RahulTeamsite\SSPProfile\SSPProfile\Form1.cs:line 115
       at SSPProfile.Program.Main() in D:\Users\Rahul\Documents\Visual Studio 2008\RahulTeamsite\SSPProfile\SSPProfile\Program.cs:line 18
       at System.AppDomain._nExecuteAssembly(Assembly assembly, String[] args)
       at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
       at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
       at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
       at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
       at System.Threading.ThreadHelper.ThreadStart()
  InnerException: System.Runtime.InteropServices.COMException
       Message="You cannot delete a sealed column."
       Source=""
       ErrorCode=-2130575213
       StackTrace:
            at Microsoft.SharePoint.Library.SPRequestInternalClass.RemoveField(String bstrUrl, String bstrListName, String bstrFieldName)
            at Microsoft.SharePoint.Library.SPRequest.RemoveField(String bstrUrl, String bstrListName, String bstrFieldName)
       InnerException:

I modified my code and now it is working fine. This has been tested in both Sharepoint 2007 and Sharepoint 2010



If you are executing this make sure you have removed the policy otherwise you will face some.other issues


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.SharePoint;

namespace DeleteBarcodeIRMPolicyColumns
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("This tool will remove barcode related columns from your list. Before executing this tool make sure that you have removed the policy otherwise it will take you to some other issues ");
            Console.WriteLine("Please enter your site url");
            String siteUrl = Console.ReadLine();
            Console.WriteLine("Please enter your List Name");
            String listName = Console.ReadLine();
            try
            {
                using (SPSite site = new SPSite(siteUrl))
                {

                    using (SPWeb web = site.OpenWeb())
                    {
                        web.AllowUnsafeUpdates = true;
                        SPList listSource = web.Lists[listName];
                        String[] columnNames = { "Barcode", "Barcode Value", "Exempt from Policy" };
                        for (int i = 0; i < columnNames.Length; i++)
                        {
                            SPField fieldtoBedeleted = listSource.Fields[columnNames[i]];
                            fieldtoBedeleted.AllowDeletion = true;
                            fieldtoBedeleted.Sealed = false;

                            fieldtoBedeleted.Delete();
                            listSource.Update();
                        }
                        web.AllowUnsafeUpdates = false;
                        Console.WriteLine("The columns are deleted successfully");
                        Console.ReadLine();
                    }
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
                Console.ReadLine();
            }
        }
    }
}

I hope this will help you out.

Thanks,
Rahul Rashu


Sunday 16 October 2011

How to copy documents between sites in Sharepoint 2007 and Sharepoint 2010

Hi,

I have received a request from a site administrator to provide a way to copy documents between sharepoint sites. The requirement was to copy the files between different site collections as well as as sites created in other web applications. This tool can be executed in two modes in the first mode it will copy all files from the source folder to the destination folder, in the second mode it will copy the specific file from the source folder to destination folder. This folder can be a document library or a folder inside the document library.
This will also check in the file so that it will be visible to authorized users. If the file already exists in the destination location this tool will overwrite the file. I have tested this in both Sharepoint 2007 and Sharepoint 2010.

I am sharing the code below:



using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.SharePoint;
namespace CopyDocumentLibrariesRashu
{
    class Program
    {
        static void Main(string[] args)
        {
            try
            {
                Console.WriteLine("Hello, This tool will copy the the files between the folders specified. It will overwrite the file if it exists at the destination location");
                Console.WriteLine("Please enter the URL of the source folder");
                string sourceURL = Console.ReadLine();
                Console.WriteLine("Please enter the URL of the destination folder");
                string destinationURL = Console.ReadLine();
                Console.WriteLine("do you want to copy a specific file?if yes then type y or else type anything else");
                String fileDecision = Console.ReadLine();
                String cFile = string.Empty;
                if(fileDecision == "y")
                {
                    Console.WriteLine("Please enter the filename with extension of the file");
                     cFile = Console.ReadLine();
                }
                using (SPSite sourceSite = new SPSite(sourceURL))
                {
                    using (SPWeb sourceWeb = sourceSite.OpenWeb())
                    {
                        using (SPSite destinationSite = new SPSite(destinationURL))
                        {
                            using (SPWeb destinationWeb = destinationSite.OpenWeb())
                            {
                                SPFolder sList = (SPFolder)sourceWeb.GetFolder(sourceURL);
                                SPFolder dList = (SPFolder)destinationWeb.GetFolder(destinationURL);
                                SPList dLibrary = destinationWeb.Lists[dList.ContainingDocumentLibrary];
                                SPFileCollection files = sList.Files;
                                if (fileDecision != "y")
                                {
                                    foreach (SPFile ctFile in files)
                                    {
                                        byte[] sbytes = ctFile.OpenBinary();
                                        SPFileCollection dListFiles = dList.Files;
                                        foreach (SPFile dListFile in dListFiles)
                                        {
                                            if(dListFile.Name.Equals(ctFile.Name))
                                            {
                                                dListFile.CheckOut();
                                            }
                                        }
                                       
                                        SPFile dFileName = dList.Files.Add(ctFile.Name, sbytes, true);
                                        if (dFileName.CheckOutStatus != SPFile.SPCheckOutStatus.None)
                                        {
                                            dFileName.CheckIn("Checking in");
                                        }
                                    }
                                }
                                else
                                {
                                    SPFile desFile = sList.Files[sourceURL +"/" + cFile];
                                    byte[] sbytes = desFile.OpenBinary();
                                    SPFileCollection dListFiles = dList.Files;
                                    foreach (SPFile dListFile in dListFiles)
                                        {
                                            if(dListFile.Name.Equals(desFile.Name))
                                            {
                                                dListFile.CheckOut();
                                            }
                                        }
                                    SPFile dFileName = dList.Files.Add(desFile.Name, sbytes, true);
                                    if (dFileName.CheckOutStatus != SPFile.SPCheckOutStatus.None)
                                    {
                                        dFileName.CheckIn("Checking in");
                                    }

                                }
                                destinationWeb.Update();
                                Console.WriteLine("The operation completed successfully");
                                Console.ReadLine();

                            }
                        }
                    }
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
            }
        }
   
 
    }
}



I hope this will help you out.

Friday 14 October 2011

Powershell Script to list out webparts used in publishing site pages in Sharepoint 2007 and Sharepoint 2010

Hi,

This powershell script will enlist all webparts used in all publishing pages in a site.
This script does not take any argument at the time of invoking it. This requires an input value for the site URL. This will be asked during the execution time and a message will be flashed to provide the same.

I have included the help text to explain the purpose of this script and it can be reached by adding -help as a argument while invoking this script. This script is tested in both MOSS 2007 and SPS 2010.

param([switch]$help)

[void][System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SharePoint")
[void][System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SharePoint.Publishing")

function GetHelp() {


$HelpText = @"

DESCRIPTION:
This script will list out the webparts type along with the names in publishing pages in any site .

"@
$HelpText

}

function RahulPublishingPageWebParts() {

write-host "This tool will enlist the webparts used in all publishing pages in this site"
        write-host "Please enter theURL of the site"
        $siteURL = read-host
        $site = New-Object Microsoft.SharePoint.SPSite($siteURL)
        $web = $site.OpenWeb()
        $webPublish =  [Microsoft.SharePoint.Publishing.PublishingWeb]::GetPublishingWeb($web)
        $pages = $webPublish.GetPublishingPages()
        foreach($page in $pages)
        {
          $manager = $web.GetLimitedWebPartManager($page.Url,[System.Web.UI.WebControls.WebParts.PersonalizationScope]::Shared)
          $webCollection = $manager.WebParts
          if($webCollection.Count -ne 0)
{
write-host "The page "  $page.Title  " contains these webparts"
for($i =0;$i -lt $webCollection.Count; $i++)
{
write-host ($i + 1).ToString()  " "  $webCollection[$i].GetType().Name  " "  $webCollection[$i].Title
}

}
         
        }

$site.Dispose()
$web.Dispose()

       
}

if($help) { GetHelp; Continue }
else { RahulPublishingPageWebParts }

The sample output will be in this form:

I hope this will help you out.
Thanks,
Rahul Rashu

Thursday 13 October 2011

How to list out webparts used in publishing site pages in Sharepoint 2007 and Sharepoint 2010

Hi,

I got a request from someone to provide a way to enlist webparts used in all publishing pages of a publishing site.
After some initial work I came with this solution. This solution takes a command line parameter that is the URL of the site from where you want to get the data. There is no dependency of library name used to store these pages. It will enlist all publishing pages and corresponding webparts.

Remember :- A command line parameter has to be given as site url to invoke this tool otherwise this will fail.



using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Publishing;
using Microsoft.SharePoint.WebPartPages;
using System.Web.UI.WebControls.WebParts;

namespace ListOutWebParts
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("This tool will enlist the webparts");
            String siteURL = args[0];
            try
            {
                using (SPSite site = new SPSite(siteURL))
                {
                    using (SPWeb web = site.OpenWeb())
                    {
                        PublishingWeb webPublish = PublishingWeb.GetPublishingWeb(web);
                        PublishingPageCollection pages = webPublish.GetPublishingPages();
                        foreach (PublishingPage page in pages)
                        {
                            SPLimitedWebPartManager manager = web.GetLimitedWebPartManager(page.Url, PersonalizationScope.Shared);
                            SPLimitedWebPartCollection webCollection = manager.WebParts;
                            if (webCollection.Count != 0)
                            {
                                Console.WriteLine("The page " + page.Title + " contains these webparts");
                                for (int i = 0; i < webCollection.Count; i++)
                                {
                                    Console.WriteLine((i + 1).ToString() + " " + webCollection[i].GetType().Name + " " + webCollection[i].Title);
                                }
                            }
                         
                        }
                                           }
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
            }
        }
    }
 
}



I am showing the sample output:

This tool will enlist the webparts
The page Home contains these webparts
1 ContentByQueryWebPart Press Releases
The page Xslttest contains these webparts
1 ListViewWebPart Content and Structure Reports
2 DataFormWebPart Content and Structure Reports (1)

Hence first it displays the page title then in the serial order it lists first type of the webpart and then the title as used in that page.

I hope this will help you out.

Thanks,
Rahul Rashu

Sunday 9 October 2011

How to hide quick launch in a publishing page in sharepoint 2007 site

Hi,
I was asked to provide a way to hide quick launch in publishing pages in sharepoint 2007 sites.
As a very simple solution I modified the master page to not show quick launch but again I was informed about a requirement where the user group want to do this in only some of the pages and not in all pages of the site using that master page. So after working on this for some time I have managed to do this via page UI using content editor webpart and also programmatically. i am shareing both the ways here. An important point to note here is the CSS classes you are using in your master page to display quick navigation. If you are using different CSS classes then you need to use them instead of what I am using here.

In the below section I will explain how to do this with page UI and content editor webpart.

1. The first step will be to identify the CSS classes used by quick launch. Hence open the site in sharepoint designer.
2. Navigate down to the master page you are using. You do not need to check it out or to do any kind of editing. In the split mode just select the quick launch part and this in turn will select the code portion.Note down the CSS classes from here.


3. Now open the page that is using this master page and you want to hide this quick launch.
4. Edit the page and add a content editor webpart. In the source editor add the following script. If you have different CSS classes then you need to use the same for them.

<style>
.leftNav
{
display:none;
}
.leftNav1, .leftNav2, .leftNav3
{
display: none;
}
</style>

Thats it the page is now without quick launch. In the next section I am showing how to do this via object model. I have hard coded the script but as I have already mentioned above you need to change it according to your master page. Hence instead of embedding it within the code you can take this as an input string as well. I have displayed some messages to give an idea of exactly what inputs are needed while running this application.


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebPartPages;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI;
using Microsoft.SharePoint.Publishing;
using System.Xml;

namespace HideQuickLaunch
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("This will hide the quick launch of a page");
            Console.WriteLine("Please enter the full URL of the page");
            String page = Console.ReadLine();
            String webPartName = String.Empty;
            using (SPSite site = new SPSite(page))
            {
                using (SPWeb web = site.OpenWeb())
                {
             
                  String pageRelativeUrl = page.Remove(0, web.Url.Length+1);
                  ContentEditorWebPart contentEditor = new ContentEditorWebPart();
                  contentEditor.Title = String.Empty;
                  PublishingWeb webPublish = PublishingWeb.GetPublishingWeb(web);
                  PublishingPage pagePublish = webPublish.GetPublishingPages()[pageRelativeUrl];
                  pagePublish.CheckOut();
                  SPWebPartCollection webPartCollection = web.GetWebPartCollection(page, Storage.Shared);
                  webPartCollection.Add(contentEditor);
                  webPartCollection.SaveChanges(contentEditor.StorageKey);
                  ContentEditorWebPart webPartToBeEdited = (ContentEditorWebPart) webPartCollection[contentEditor.StorageKey];
                  XmlDocument xmlDoc = new XmlDocument();
                  XmlElement elementContent = xmlDoc.CreateElement("script");
                  elementContent.InnerText = "<style>\n.leftNav\n{\ndisplay:none;\n}\n.leftNav1, .leftNav2, .leftNav3\n{\ndisplay: none;\n}\n</style>";
                  webPartToBeEdited.Content = elementContent;
                  webPartToBeEdited.AllowHide = true;
                  webPartToBeEdited.Hidden = true;
                  webPartCollection.SaveChanges(webPartToBeEdited.StorageKey);
                  pagePublish.CheckIn("Approved");
                  web.Update();
                  Console.WriteLine("The quick launch is hidden now");
                  Console.ReadLine();
                }
            }
        }
    }
}

I hope this will help you out.

Thanks,
Rahul Rashu


How to copy a list using powershell script in Sharepoint 2007 and Sharepoint 2010

Hi,

I recently published an article on copying sharepoint lists programmatically. Someone asked to provide powershell scripts to carry out the same. Hence I created this script. This works with Sharepoint 2007 and Sharepoint 2010 as well.


param([switch]$help)

[void][System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SharePoint")

function GetHelp() {


$HelpText = @"

DESCRIPTION:
This script copies a list within the same site collection as per the parameters.

"@
$HelpText

}

function RahulCopyListSameSiteCollection() {

write-host "This script copies a list within the same site collection"
        write-host "Please enter the URL of the Source Site"
        $sourceSite = read-host
        write-host "Please enter the name of the source list"
        $sourceListName = read-host
        write-host "Please enter the URL of the Destination Site"
        $destinationSite = read-host
        write-host "Please enter the name of the Destination list"
        $destinationListName = read-host
        write-host "Please enter the description of the Destination list"
        $destinationListDescription = read-host
        $site = New-Object Microsoft.SharePoint.SPSite($sourceSite)
        $web =  $site.OpenWeb()
        $sourceList = $web.Lists[$sourceListName]
        $templateName = $sourceList.Title
        $templateFileName = $sourceList.Title
        $sourceList.SaveAsTemplate($templateFileName, $templateName, $sourceList.Description, $true)
        $listTemplate = $site.GetCustomListTemplates($web)[$templateName]
        $destinationWeb = $destinationSite.Remove(0, $site.Url.Length + 1)
        $destWeb = $site.OpenWeb($destinationWeb)
        $destWeb.Lists.Add($destinationListName, $destinationListDescription, $listTemplate)
        $destWeb.Update()
        $listTemplates = $site.RootWeb.Lists["List Template Gallery"]
        $listTemplateItems = $listTemplates.Items
        foreach($listTemplateItem in $listTemplateItems)
        {
          if($listTemplate.Name.Equals($listTemplateItem["Title"]))
                          {
                              $listTemplateItem.Delete()
                              break
                          }

        }
        write-host "the List is copied"
        $web.Dispose()
        $destWeb.Dispose()
        $site.Dispose()
       
        }

if($help) { GetHelp; Continue }
else
 { RahulCopyListSameSiteCollection }

I hope this will help you out.

Thanks,
Rahul Rashu

How to copy a list programmatically in sharepoint 2007 and Sharepoint 2010 within same site collection

Hi,

Recently someone expressed his requirements to copy sharepoint lists within the same site collection. Hence to automate this process at a single place I have developed this console application. This code can be further modified as per the requirement. This needs to be executed from any WFE and the input values are self explanatory. This works with sharepoint 2007 and sharepoint 2010 as well. This tool is internally creating a template from the source list then using this template to create the destination list. Once the list is created the template created in the previous step is getting deleted so that next time this can be executed without any issues with the same source list.


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.SharePoint;

namespace CopyListInSameSiteCollection
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("This tool copies a list within the same site collection");
            Console.WriteLine("Please enter the URL of the Source Site");
            String sourceSite = Console.ReadLine();
            Console.WriteLine("Please enter the name of the source list");
            String sourceListName = Console.ReadLine();
            Console.WriteLine("Please enter the URL of the Destination Site");
            String destinationSite = Console.ReadLine();
            Console.WriteLine("Please enter the name of the Destination list");
            String destinationListName = Console.ReadLine();
            Console.WriteLine("Please enter the description of the Destination list");
            String destinationListDescription = Console.ReadLine();
            try
            {
                using (SPSite site = new SPSite(sourceSite))
                {
                    using (SPWeb web = site.OpenWeb())
                    {
                        SPList sourceList = web.Lists[sourceListName];
                        String templateName = sourceList.Title;
                        String templateFileName = sourceList.Title;
                        sourceList.SaveAsTemplate(templateFileName, templateName, sourceList.Description, true);
                        SPListTemplate listTemplate = site.GetCustomListTemplates(web)[templateName];
                     
                        String destinationWeb = destinationSite.Remove(0, site.Url.Length + 1);
                        using (SPWeb destWeb = site.OpenWeb(destinationWeb))
                        {
                            destWeb.Lists.Add(destinationListName, destinationListDescription, listTemplate);
                            destWeb.Update();
                       
                         
                        }
                        SPList listTemplates = site.RootWeb.Lists["List Template Gallery"];
                        SPListItemCollection listTemplateItems = listTemplates.Items;
                     foreach (SPListItem listTemplateItem in listTemplateItems)
                     {
                       
                          if(listTemplate.Name.Equals(listTemplateItem["Title"]))
                          {
                              listTemplateItem.Delete();
                              listTemplates.Update();
                              break;
                          }
                       }
                    }
                }
             
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
            }
            Console.WriteLine("The List is copied");
        }
    }
}


I hope this will help you out.

Thanks,
Rahul Rashu

Saturday 8 October 2011

How To Add HTML content into content editor webpart in Sharepoint 2010.


Hi,
Recently someone asked me how to add HTML content into Content Editor webpart since they were unable to find this option in SPS 2010 as they were used to MOSS 2007.
I am sharing these steps here as well since it may help others as well.
If you add a content editor webpart in a page and then if you try to edit it you will find this

Unlike MOSS 2007 you will not get the option of adding HTML in a source editor.
To add HTML content you need these steps:
1.       Select the text area in the webpart as shown in the screenshot below:



2.       Now have a look into the ribbon under editing tools. You will get an option to insert HTML.


3.       Now you will get a screen like this.


4.       Now you can proceed further.
 I hope this will help you out.
Thanks,
Rahul Rashu

Tuesday 4 October 2011

How to export and import a site using powershell script in sharepoint 2007 and sharepoint 2010

Hi,

I recently published an article about exporting and importing a site using sharepoint object model. Someone recently asked me for doing the same via powershell scripts. Hence I have done that in this article. This scripts first exports a site and then ask for the decision to go for import or not. If you type "y" it will go or else it will not go, hence in this way it gives you to analyze the file sizes and all other factors before going to import a site.
Here is the script for this:

param([string]$Sourceurl,[string]$Destinationurl, [string]$FileName, [string]$Location, [switch]$help)

[void][System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SharePoint")

function GetHelp() {


$HelpText = @"

DESCRIPTION:
This script export a site from source site and then imports that at a destination url.

"@
$HelpText

}

function RahulExportImport-SPSite([string]$Sourceurl,[string]$Destinationurl, [string]$FileName, [string]$Location) {

if(Test-Path $Location) {

} else {
new-item -path $Location -type directory | Out-Null
}

$SPExport = New-Object Microsoft.SharePoint.Deployment.SPExport
        $SPImport = New-Object Microsoft.SharePoint.Deployment.SPImport
        $SPExportSettings = $SPExport.Settings
$SPExportSettings.SiteUrl= $Sourceurl
$SPExportSettings.BaseFilename = $FileName
$SPExportSettings.FileLocation = $Location
        $SPExportSettings.CommandLineVerbose = $true
        $SPExportSettings.ExportMethod = [Microsoft.SharePoint.Deployment.SPExportMethodType]"ExportAll"
        $SPExportSettings.LogFilePath =$Location +"\logExport.log"

$SPExport.Run()
        write-host "The export is completed. Do you want to go for Import? If Yes then type y or else type anything else"
        $Decision = read-host
        if($Decision -eq "y")
        {
$SPImportSettings = $SPImport.Settings
        $SPImportSettings.SiteUrl= $Destinationurl
        $SPImportSettings.BaseFilename = $FileName
$SPImportSettings.FileLocation = $Location
        $SPImportSettings.CommandLineVerbose = $true
        $SPImportSettings.LogFilePath =$Location +"\logImport.log"
        $SPImport.Run()
         }

$SPExport.Dispose()
        $SPImport.Dispose()
       
}

if($help) { GetHelp; Continue }
if($Sourceurl -AND $Destinationurl -AND $FileName -AND $Location) { RahulExportImport-SPSite -Sourceurl $Sourceurl -Destinationurl $Destinationurl -FileName $FileName -Location $Location }

I hope this will help you out.

Thanks,
Rahul Rashu

Saturday 1 October 2011

Deleting completed workflow instances in Sharepoint 2007 and Sharepoint 2010 lists

Hi,

Few days back someone requested me to write a tool that will cleanup completed workflow instances from a list. Hence I have developed this tool, it takes site url and list name as input and then it spans through all items in the list and clears up all completed workflow instances.This works for sharepoint 2007 as well as sharepoint 2010 The code is as below:


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Workflow;

namespace CompletedWorkflowCleanUp
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Please enter the site url");
            String siteUrl = Console.ReadLine();
            Console.WriteLine("Please enter the list title");
            String listName = Console.ReadLine();
            using (SPSite site = new SPSite(siteUrl))
            {
                SPWorkflowManager workflowManager = site.WorkflowManager;
                using (SPWeb web = site.OpenWeb())
                {
                    SPList list = web.Lists[listName];
                    SPListItemCollection listItems = list.Items;
                    foreach (SPListItem listItem in listItems)
                    {
                        SPWorkflowCollection wCollection = listItem.Workflows;
                 
                        for (int i = 0; i < wCollection.Count; i++)
                        {
                            if (wCollection[i].IsCompleted)
                            {
                                workflowManager.RemoveWorkflowFromListItem(wCollection[i]);
                                listItem.Update();
                            }

                        }
                     
                    }
                    Console.WriteLine("Completed workflow instances are deleted for the list" +list);
                    Console.ReadLine();
                }
            }
        }
    }
}

I hope this will help you out.

Thanks,
Rahul Rashu