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.