Saturday 24 December 2011

Application Page to check effective permissions of a user in an entire site collection in Sharepoint 2007

Hi,

I have recently published two tools on to check effective permissions of a user in an entire site collection. I provided console application and powershell script for this.
http://rahulrashu.blogspot.com/2011/12/how-to-check-effective-permissions-of_11.html
http://rahulrashu.blogspot.com/2011/12/how-to-check-effective-permissions-of.html

However these options were available for only server administrators. Hence to provide these options to other users I created an application page and a feature to shown the link under site collection adminstration. To deploy the same I have created a wsp file and a batch file to deploy the same.
Here are the codes
For application page:


<%@ Page Language="C#" MasterPageFile="application.master" Inherits="Microsoft.SharePoint.WebControls.LayoutsPageBase" %>
<%@ Assembly Name="Microsoft.Office.Server.SecurityReport, Version=12.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c"%>
<%@ Assembly Name="System.Data, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"%>
<%@ Assembly Name="Microsoft.Office.Server, Version=12.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c"%>
<%@ Assembly Name="Microsoft.SharePoint.ApplicationPages, Version=12.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c"%>
<%@ Register Assembly="Microsoft.SharePoint, Version=12.0.0.0, Culture=neutral,PublicKeyToken=71e9bce111e9429c" Namespace="Microsoft.SharePoint.WebControls" TagPrefix="cc1" %>
<%@ Register Tagprefix="SharePoint" Namespace="Microsoft.SharePoint.WebControls" Assembly="Microsoft.SharePoint, Version=12.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>
<%@ Import Namespace="Microsoft.SharePoint" %>
<%@ Import Namespace="Microsoft.Office.Server.UserProfiles" %>
<%@ Import Namespace="Microsoft.Office.Server" %>
<%@ Import Namespace="System.Data" %>
<%@ Import Namespace="System.Collections.ObjectModel" %>
<script runat="server" >
void Page_Load(object sender, EventArgs e)
{

}
void Change_Title(object sender, EventArgs e)
{
SPWeb web1 = this.Web;
if(UserPicker.ResolvedEntities.Count > 0)
{
PickerEntity selectedEntity = (PickerEntity)UserPicker.ResolvedEntities[0];
ServerContext serverContext = ServerContext.GetContext(web1.Site);
UserProfileManager userProfileManager = new UserProfileManager(serverContext);
UserProfile userProfile = userProfileManager.GetUserProfile(selectedEntity.Key);
String userLogin = userProfile[PropertyConstants.AccountName].Value.ToString();
SPWebCollection webs = web1.Site.AllWebs;
DataTable userTable = new DataTable();
userTable.Columns.Add("WebUrl");
userTable.Columns.Add("Permission");
userTable.Columns.Add("GivenVia");
 foreach (SPWeb web in webs)
 {
 SPPermissionInfo permissionInfo = web.GetUserEffectivePermissionInfo(userLogin);
 Collection<SPRoleAssignment> roles = permissionInfo.RoleAssignments;

 SPUser user = web.AllUsers[userLogin];
 if (user.IsSiteAdmin)
 {
 label1.Text = "The user "+userLogin+" is a site collection administrator";
 }

  for (int i = 0; i < roles.Count; i++)
 {
 SPRoleDefinitionBindingCollection bRoles = roles[i].RoleDefinitionBindings;
 foreach (SPRoleDefinition roleDefinition in bRoles)
 {
 if (roles[i].Member.ToString().Contains("\\"))
 {
  userTable.Rows.Add(web.Url,roleDefinition.Name,"Directly Given");

 }
  else
  {

  userTable.Rows.Add(web.Url,roleDefinition.Name,roles[i].Member.ToString());

  }
  }
 }

 }
 SPBoundField fldPropertyName = new SPBoundField();
fldPropertyName.HeaderText = "Web Url";
fldPropertyName.DataField = "WebUrl";
rahulGrid.Columns.Add(fldPropertyName);
SPBoundField fldPropertyName1 = new SPBoundField();
fldPropertyName1.HeaderText = "Permission";
fldPropertyName1.DataField = "Permission";
rahulGrid.Columns.Add(fldPropertyName1);
SPBoundField fldPropertyName2 = new SPBoundField();
fldPropertyName2.HeaderText = "GivenVia";
fldPropertyName2.DataField = "GivenVia";
rahulGrid.Columns.Add(fldPropertyName2);
rahulGrid.DataSource = userTable;
rahulGrid.DataBind();

rahulGrid.Dispose();
}
}

</script>
<asp:Content contentplaceholderid="PlaceHolderPageTitle" runat="server">
<SharePoint:EncodedLiteral runat="server" text="Check Permissions in Entire Site Collection" EncodeMethod='HtmlEncode'/>
</asp:Content>
<asp:Content contentplaceholderid="PlaceHolderPageTitleInTitleArea" runat="server">
<SharePoint:EncodedLiteral runat="server" text="Check Permissions in Entire Site Collection" EncodeMethod='HtmlEncode'/>
</asp:Content>
<asp:Content ContentPlaceHolderID="PlaceHolderMain" runat="server">
<SharePoint:PeopleEditor id="UserPicker"  runat="server"
SelectionSet="User,DL,SecGroup,SPGroup"
ValidatorEnabled="false"
AllowEmpty = "false"
MultiSelect = "false"
/><asp:Button runat="server" Text="Submit" OnClick="Change_Title" id="Button1"></asp:Button>
<br>
<asp:Label ID="label1" runat="server" ></asp:Label>
<br>
<SharePoint:SPGridView
  runat="server"
  ID="rahulGrid"
  AutoGenerateColumns="false"
  RowStyle-BackColor="#DDDDDD"
  AlternatingRowStyle-BackColor="#EEEEEE" />


</asp:Content>






For batch file:


@ECHO Off




"C:\Program Files\Common Files\microsoft shared\Web Server Extensions\12\BIN\STSADM.exe" -o addSolution -filename RahulCheckEntireSitePermission.wsp

pause

"C:\Program Files\Common Files\microsoft shared\Web Server Extensions\12\BIN\STSADM.exe"% -o deploySolution -name RahulCheckEntireSitePermission.wsp -immediate -

allowgacdeployment

pause

"C:\Program Files\Common Files\microsoft shared\Web Server Extensions\12\BIN\STSADM.exe" -o installfeature -name RahulSitePermListing -force

pause

"C:\Program Files\Common Files\microsoft shared\Web Server Extensions\12\BIN\STSADM.exe" -o activatefeature -name RahulSitePermListing -url YourSiteUrl - force

In the batch file you need to change YourSiteUrl to the site where you want to activate the same.
The wsp file as well as the batch file can be downloaded here:

http://gallery.technet.microsoft.com/Check-Permissions-in-4a8f2b91
I hope this will help you out.

Thanks,
Rahul Rashu




Sunday 11 December 2011

How to Check Effective Permissions of a User in Each Site in a Site Collection in Sharepoint 2007 and Sharepoint 2010 using Powershell

Hi,

I have observed that one of a tedious task for a sharepoint site administrator to check permissions of a user in each site in a site collection. Microsoft Admin Toolkit has provided a functionality that can be used to check effective permissions. This can be downloaded at http://www.microsoft.com/download/en/details.aspx?displaylang=en&id=14227 for MOSS 2007 but it provides the way to check permissions only at a site, list and list item level. There is no way to use this at a single run for all sites in a site collection.
Hence to do this I have prepared the following powershell script. It works with both MOSS 2007 and SPS 2010. This takes 2 input values. The first is the url of the site collection and the second one is the userlogin. The user login should be in the form of Domain\Username



param([switch]$help)
[void][System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SharePoint")
[void][System.Reflection.Assembly]::LoadWithPartialName("Microsoft.Office.Server")
[void][System.Reflection.Assembly]::LoadWithPartialName("Microsoft.Office.Server.UserProfiles")
[void][System.Reflection.Assembly]::LoadWithPartialName("System.Web")
function GetHelp() {
$HelpText = @"
DESCRIPTION:
This script will enumerate the permissions of the user in all webs under a site collection. This takes two input the user of the site collection and the username.The
username should be given in Domain\username format.
"@
$HelpText
}
function RahulCheckEffectivePermissionsInAllWebs() {
write-host "This script will chcek the effective permissions of a user"
write-host "Please enter the url of the site collection"
$url = read-host
write-host "Please enter the username of the user"
$userName = read-host
$site = New-Object Microsoft.SharePoint.SPSite($url)
$serverContext = [Microsoft.Office.Server.ServerContext]::GetContext($site)
$userProfileManager = New-Object Microsoft.Office.Server.UserProfiles.UserProfileManager($serverContext)
$userProfile = $userProfileManager.GetUserProfile($userName)
$userLogin = $userProfile[[Microsoft.Office.Server.UserProfiles.PropertyConstants]::AccountName].Value.ToString()
$webs = $site.AllWebs
foreach ($web in $webs)
{
$permissionInfo = $web.GetUserEffectivePermissionInfo($userLogin)
$roles = $permissionInfo.RoleAssignments
write-host "Now checking the permissions of the user "  $userLogin  " " "in the site " $web.Url
for ($i = 0; $i -lt $roles.Count; $i++)
{
$bRoles = $roles[$i].RoleDefinitionBindings
foreach ($roleDefinition in $bRoles)
{
 if ($roles[$i].Member.ToString().Contains('\'))
{
write-host "The User "  $userLogin  " has direct permissions "  $roleDefinition.Name
}
else
{
write-host "The User "  $userLogin  " has permissions "  $roleDefinition.Name  " given via "  $roles[$i].Member.ToString()
                                }
}
}
}
$site.Dispose()
}
if($help) { GetHelp; Continue }
else { RahulCheckEffectivePermissionsInAllWebs }

I hope this will help you out.

Thanks,
Rahul Rashu

How to find out the user who deployed or updated a solution in sharepoint

Hi All,

I have observed a very growing requirement is to find out which user has deployed a solution or updated in sharepoint. This is of high importance when there are many administrators assigned to do such activities in sharepoint farm. So upon some research and help I am mentioning a way that is very useful in this regard.
In this article I am defining the steps based on a feature definition and a wsp file. Here are the steps needs to be followed:
1. Login to the database.
2. Go to the config database and select new query.
3. Now we will find out the information about a solution solution1.wsp so we will execute this query:
Select * From Objects With(NoLock)where Name = 'solution1.wsp'
4. In the result returned our focus will be on the column "Properties" .
5.Copy the contents and paste it somewhere in notepad. There are many properties exposed through this however we will focus on these 3:


<sFld type="String" name="m_LastUpdatedUser">
<sFld type="String" name="m_LastUpdatedMachine">
<sFld type="DateTime" name="m_LastUpdatedTime">
6. As their names are already clear the first one shows the user name who has last updated it.The second one is the server where it was last updated. The third one shows the time when it was last updated. The last two information is available through UI as well.

In case of feature definitions we need to know the guid of the same. So this can be taken from the feature.xml file under the features folder. Then the following query can be executed:

Select * From Objects With(NoLock) where ID='Guid'

The output and next steps can be followed in the same way.

I hope this will help you out.

Thanks,
Rahul Rashu

Wednesday 7 December 2011

How to check effective permissions of a user in each site in a site collection in Sharepoint 2007 and Sharepoint 2010

Hi,

I have observed that one of a tedious task for a sharepoint site administrator to check permissions of a user in each site in a site collection. Microsoft Admin Toolkit has provided a functionality that can be used to check effective permissions. This can be downloaded at http://www.microsoft.com/download/en/details.aspx?displaylang=en&id=14227 for MOSS 2007 but it provides the way to check permissions only at a site, list and list item level. There is no way to use this at a single run for all sites in a site collection.
Hence to do this I have prepared the following code. It works with both MOSS 2007 and SPS 2010. This takes 2 input values. The first is the url of the site collection and the second one is the userlogin. The user login should be in the form of Domain\Username.


using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Web;
using Microsoft.SharePoint;
using Microsoft.Office.Server;
using Microsoft.Office.Server.UserProfiles;

namespace RahulCheckEffectivePermissionsInAllWebs
{
    class Program
    {
        static void Main(string[] args)
        {

            try
            {
                Console.WriteLine("This tool will chcek the effective permissions of a user");
                Console.WriteLine("Please enter the url of the site collection");
                String url = Console.ReadLine();
                Console.WriteLine("Please enter the username of the user");
                String userName = Console.ReadLine();
                using (SPSite site = new SPSite(url))
                {
                    ServerContext serverContext = ServerContext.GetContext(site);
                    UserProfileManager userProfileManager = new UserProfileManager(serverContext);
                    UserProfile userProfile = userProfileManager.GetUserProfile(userName);
                    String userLogin = userProfile[PropertyConstants.AccountName].Value.ToString();
                    SPWebCollection webs = site.AllWebs;
                    foreach (SPWeb web in webs)
                    {
                        SPPermissionInfo permissionInfo = web.GetUserEffectivePermissionInfo(userLogin);


                        Collection<SPRoleAssignment> roles = permissionInfo.RoleAssignments;
                        Console.WriteLine("Now checking the permissions of the user " + userLogin + " " + "in the site " + web.Url);
                        for (int i = 0; i < roles.Count; i++)
                        {

                            SPRoleDefinitionBindingCollection bRoles = roles[i].RoleDefinitionBindings;

                            foreach (SPRoleDefinition roleDefinition in bRoles)
                            {

                                if (roles[i].Member.ToString().Contains('\\'))
                                {
                                    Console.WriteLine("The User " + userLogin + " has direct permissions " + roleDefinition.Name);
                                }
                                else
                                {
                                    Console.WriteLine("The User " + userLogin + " has permissions " + roleDefinition.Name + " given via " + roles[i].Member.ToString());
                                }


                            }

                        }


                    }
                    Console.WriteLine("Execution Completed");
                    Console.ReadLine();
                }
            }
             catch(Exception e)
            {
                Console.WriteLine(e.Message);
                Console.WriteLine(e.StackTrace);
             }
        }
     
   
    }
    }
I hope this will help you out.

Thanks,
Rahul Rashu

Sunday 4 December 2011

Profile Synchronisation Jobs not updating user details in Sharepoint 2007 sites

Hi,

I have seen that many site admins periodically reports the issue of Profile Synchronisation jobs not updating the details of their users in the sharepoint site. In all the cases people have reported that the user details were updated in AD and the details were updated in SSP as well after profile import. However the same was not updated in site.
So I am mentioning some points here about this issue:

1. The profile synchronisation jobs responsible for updating these details from SSP to sites only updates details for the active users.
2. The active users are considered as the users who have carried out any change in the site ever in any form of add, update or delete.
3. The active users are marked at the database level. In the content database there is a table UserInfo used to store details of all site users.
4. In this table there is a column named as "tp_IsActive". This column is a type of bit column and will carry the values 0 or 1. the value 1 stands for an active user and 0 for an inactive user.  Refer this:
http://msdn.microsoft.com/en-us/library/c6244ace-4199-450d-a215-d37fa591159d(v=PROT.13)#active_user

Now to get this to work following steps can be taken:

1. Ask the user to carry out any changes in the site collection.
2. Try resolving his correct name by adding him to any any user group.
3. If the first way is not feasible because of your security policies and second is not working out to you then delete the user from site collection and add him once again.

I hope this will help you out.

Thanks,
Rahul Rashu

Friday 2 December 2011

How to Remove the option of changing views in a list in Sharepoint

Hi,

Recently someone asked me to provide a way to hide the option of navigating between views in a list.
This can be done by following the simple steps defined below:

1. Open the site in sharepoint designer.
2. Navigate down to the list in question.
3. Check out the AllItems.aspx page which you want to modify and double click on it.
4. Now in the list viewer webpart right click and select "Convert to XSLT dataview".















5. Now select the portion that shows the views dropdown. It will be the Sharepoint view selector Menu as shown











6. Add the attribute visible="false" as shown.
7. Check in the page and you are good to go.

I hope this will help you out.

Thanks,
Rahul Rashu

Wednesday 30 November 2011

Can Not Open pdf files in Browser in Sharepoint 2010

Hi,

Recently someone expressed his requirements to open pdf files in browsers in the same way as excel files opens up when we use excel services. Although the settings was to open the file in web browser in advanced settings of the document library it was opening in the client application. After some digging into this issue I managed to get it done. Hence here are the steps I am sharing to get this done:

1. Open the document library where you have stored the .pdf file.
2. Go to the advanced settings and make sure that you have selected "Open in web browser" and not in client application.
3. Login to Central Administrator--> Application management --> Web Application general settings and select your web application.
4. Then select your web applicaion --> general settings.and change browser file handling to Permissive from strict as shown below















5. Click on OK and you are OK to go.

I hope this will help you out.

Thanks,
Rahul Rashu

Saturday 26 November 2011

How to list out workflows designed by sharepoint designer in sharepoint 2007 site

Hi,
Recently I have received many requests from many site administrators that they want to track the sharepoint designer workflows created in their sites. Hence I have developed this application. This works in Sharepoint 2007. This takes an input of site url and then it enumerates each and every list and find out the workflows associated with that list. Then it checks for their base template. The base template for a SPD workflow is null since these workflows are not created with any base template. In this way I have listed out the lists and the workflows designed by SPD associated with them.


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

namespace RahulListOutSPDWorkflows
{
    class Program
    {
        static void Main(string[] args)
        {
            try
            {
                Console.WriteLine("This tool will provide you the list of SPD workflows and asociated lists in a site");
                Console.WriteLine("Please enter the url of the site");
                String webUrl = Console.ReadLine();
                using (SPSite site = new SPSite(webUrl))
                {
                    using (SPWeb web = site.OpenWeb())
                    {
                        SPListCollection lists = web.Lists;
                        foreach (SPList list in lists)
                        {
                          SPWorkflowAssociationCollection wAssociations = list.WorkflowAssociations;
                          foreach (SPWorkflowAssociation wAssociation in wAssociations)
                          {
                              if (wAssociation.BaseTemplate == null)
                              {
                                  Console.WriteLine("The List " + list.Title + " has SPD workflow " + wAssociation.Name);
                              }
                          }
                        }
                    }
                }
                Console.WriteLine("Execution Completed");
                Console.ReadLine();
            }
            catch (Exception e)
            {
                Console.WriteLine(e.StackTrace);
                Console.ReadLine();
            }
           
        }
    }
}

I hope this will help you out.

Thanks,
Rahul Rashu

Saturday 19 November 2011

The search application 'Guid' on server ServerName did not finish loading. View the event logs on the affected server for more information.

Hi,
In our new SPS 2010 environment we were trying to configure search. When we logged into the search service via central administration and clicked on content sources we got this error message "The search application 'Guid' on server ServerName did not finish loading. View the event logs on the affected server for more information." In the event viewer I was able to get this message:

Log Name:      Application
Source:        Microsoft-SharePoint Products-SharePoint Foundation
Date:          20-11-2011 01:45:35
Event ID:      6398
Task Category: Timer
Level:         Critical
Keywords:    
User:          NETWORK SERVICE
Computer:      rahul-HP
Description:
The Execute method of job definition Microsoft.Office.Server.Search.Administration.IndexingScheduleJobDefinition (Guid threw an exception. More information is included below.

The search application Guid on server ServerName did not finish loading. View the event logs on the affected server for more information.
Event Xml:
<Event xmlns="http://schemas.microsoft.com/win/2004/08/events/event">
  <System>
    <Provider Name="Microsoft-SharePoint Products-SharePoint Foundation" Guid=Guid />
    <EventID>6398</EventID>
    <Version>14</Version>
    <Level>1</Level>
    <Task>12</Task>
    <Opcode>0</Opcode>
    <Keywords>0x4000000000000000</Keywords>
    <TimeCreated SystemTime="2011-11-19T20:15:35.334377700Z" />
    <EventRecordID>48170</EventRecordID>
    <Correlation ActivityID="Guid" />
    <Execution ProcessID="2884" ThreadID="2996" />
    <Channel>Application</Channel>
    <Computer>rahul-HP</Computer>
    <Security UserID="S-1-5-20" />
  </System>
  <EventData>
    <Data Name="string0">Microsoft.Office.Server.Search.Administration.IndexingScheduleJobDefinition</Data>
    <Data Name="string1">Guid</Data>
    <Data Name="string2">The search application Guid on server ServerName did not finish loading. View the event logs on the affected server for more information.</Data>
  </EventData>
</Event>

So to come out of it I went to create a new search service instance. I went to Central Administration--> ManageServiceApplications --> new --> Search service Application.

A modal window opened as shown below:












Provide values and make sure that the account you are using as search service account must have at least read access to your web applications.

Now I was able to configure my content sources and get my items crawled.
I hope this will help you out.

Thanks,
Rahul Rashu

Sunday 13 November 2011

How to show ID field in EditForm.aspx and DispForm.aspx in Sharepoint

Hi,

We do not get ID field in DispForm.aspx and EditForm.aspx pages out of the box. However many times business needs this field to show up in this form because of their uniqueness. To accomplish it a javascript is most easy option and it can be applied via content editor webpart. To do this follow these steps

1. Go to the list
2. Click view item with any existing item or if you do not have any item then in the URL after listname add /DispForm.aspx .
3. In the next page add ?ToolPaneView=2 . This will open the page in editable form and the add a content editor webpart. Edit it to add the HTML content.
4. Paste the below script

<script language="javascript" type="text/javascript">

_spBodyOnLoadFunctionNames.push("showID");

function showID()
{

var querystring = location.search.substring(1, location.search.length);
var ids = querystring.split("&")[0];
var id = ids.split("=")[1];
var Td1 = document.createElement("td");
Td1.className = "ms-formlabel";
Td1.innerHTML ="<h3 class ='ms-standardheader'>ID</h3>";
var Td2 = document.createElement("td");
Td2.className =  "ms-formbody";
Td2.innerHTML = id;
var Tr1 = document.createElement("tr");
Tr1.appendChild(Td1);
Tr1.appendChild(Td2);
var Location = GetSelectedElement(document.getElementById("idAttachmentsRow"),"TABLE").getElementsByTagName("TBODY")[0];
Location.insertBefore(Tr1,Location.firstChild);
}

</script>


5. save it and exit.

The same process you need to follow in case of EditForm.aspx as well. The ID field will be shown in read only mode in both the forms.

For Sharepoint 2010 content editor webparts can be edited in the following way  http://rahulrashu.blogspot.com/2011/10/how-to-add-html-content-into-content.html . You can use same script here as well but in sharepoint 2010 these forms open in form of modal windows so if you want to edit them you need to use direct URL here.

I hope this will help you out.

Thanks,
Rahul Rashu

Saturday 12 November 2011

How to copy list permissions in Sharepoint Using Web Services

Hi All,

I have seen administrators working hard to copy permissions from one list to other list. This is a very important task from the security perspective as well. To ease this process I received various requests to develop something that will allow this via web service call since the tool will be used by site administrators and not server and farm administrators.

Hence I have created the following tool, it works in both versions of sharepoint MOSS 2007 and SPS 2010.



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

namespace RashuChangeListPermissionWebService
{
    class Program
    {
        static void Main(string[] args)
        {
            try
            {
                Console.WriteLine("This tool will copy the permissions of a list to the other one using web services");
                RahulPerm1.Permissions sourcePermissions = new RashuChangeListPermissionWebService.RahulPerm1.Permissions();
                RahulPerm2.Permissions destinationPermissions = new RashuChangeListPermissionWebService.RahulPerm2.Permissions();
                Console.WriteLine("Please enter the url of the source site");
                String sourceSiteUrl = 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 destinationSiteUrl = Console.ReadLine();
                Console.WriteLine("Please enter the name of the destination list");
                String destinationListName = Console.ReadLine();
                sourcePermissions.UseDefaultCredentials = true;
                destinationPermissions.UseDefaultCredentials = true;
                sourcePermissions.Url = sourceSiteUrl + "/_vti_bin/Permissions.asmx";
                destinationPermissions.Url = destinationSiteUrl + "/_vti_bin/Permissions.asmx";
                XmlNode nodeSource = sourcePermissions.GetPermissionCollection(sourceListName, "List");
                XmlNode nodeDest = destinationPermissions.GetPermissionCollection(destinationListName, "List");
                XmlDocument deleteXml = new XmlDocument();
                XmlDocument createXml = new XmlDocument();
             
                XmlElement rootS = createXml.CreateElement("Permissions");
                XmlElement rootUsers = createXml.CreateElement("Users");
                XmlElement rootGroups = createXml.CreateElement("Groups");
                createXml.AppendChild(rootS);
                rootS.AppendChild(rootUsers);
                rootS.AppendChild(rootGroups);
               
                XmlNodeList nodeDLists = nodeDest.ChildNodes;
             
                String userIdentification;
                foreach (XmlNode nodeDFirst in nodeDLists)
                {
                   
                    foreach (XmlNode nodeDSecond in nodeDFirst.ChildNodes)
                    {
                        userIdentification = nodeDSecond.Attributes["MemberIsUser"].Value;
                        if(userIdentification.Equals("True"))
                        {
                            destinationPermissions.RemovePermission(destinationListName, "List", nodeDSecond.Attributes["UserLogin"].Value, "user");
                        }
                        else
                        {
                            destinationPermissions.RemovePermission(destinationListName, "List", nodeDSecond.Attributes["GroupName"].Value, "group");
                        }

                    }
                }

             
                XmlNodeList nodeListsSource = nodeSource.ChildNodes;
                XmlAttribute sourceAttribute;
                foreach (XmlNode nodeF1 in nodeListsSource)
                {
                    foreach (XmlNode nodeF2 in nodeF1.ChildNodes)
                    {
                        sourceAttribute = nodeF2.Attributes["MemberIsUser"];
                        if (sourceAttribute.Value.Equals("True"))
                        {
                            XmlElement userD = createXml.CreateElement("User");
                            userD.SetAttribute("LoginName", nodeF2.Attributes["UserLogin"].Value);
                            userD.SetAttribute("PermissionMask", nodeF2.Attributes["Mask"].Value);
                            rootUsers.AppendChild(userD);


                        }
                        else
                        {
                            XmlElement groupD = createXml.CreateElement("Group");
                            groupD.SetAttribute("GroupName", nodeF2.Attributes["GroupName"].Value);
                            groupD.SetAttribute("PermissionMask", nodeF2.Attributes["Mask"].Value);
                            rootGroups.AppendChild(groupD);
                        }
                    }
                }
                destinationPermissions.AddPermissionCollection(destinationListName, "List", createXml);
                Console.WriteLine("Execution Completed");
                Console.ReadLine();



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



There are few points about input parameters.

1. Source Site-- This will be the URL of the site where the list whose permissions we are going to copy resides. This should be only till site url and should not contain any page or list's url .
2. Destination Site- This should be also entered in the same format as above.This indicates the URL of the site that contains the list to which we are going to insert permissions after removing the existing one.

This tool first read the permissions of the destination list and then removes it one by one for all users and groups. Then it reads the permissions of the source list and then copies it to destination. It works no matter whether the source list or destination list inherit permissions from the parent site. After tool execution as expected the destination list will have its own permission values.

I hope this will help you out.

Thanks,
Rahul Rashu

Monday 7 November 2011

Check Effective Permissions of a User in a Sharepoint Site

Hi,

One of a tedious task for site administrators is to check all permissions provided to a user. I have seen administrators checking each and every user group to find out the permissions. To minimize efforts in this direction I have created this application. This will enlist all permissions for a user at the site level. I will soon extend this for the list, libraries and even item level for more ease in this direction. I am sharing my code here it works in both Sharepoint 2007 and Sharepoint 2010. This takes 2 input values during site execution. The first one is the URL of the site where you want to check the permissions and the next one is user ID.


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.SharePoint;
using System.Collections;
using Microsoft.Office.Server.UserProfiles;
using Microsoft.Office.Server;

namespace RahulCheckSitePermission
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("This tool will check the permissions of a user in the site specified");
            Console.WriteLine("Please enter the URL of the site where you want to check the permissions");
            String webUrl = Console.ReadLine();
            Console.WriteLine("Please enter the userName");
            String userName = Console.ReadLine();
            try
            {
                using (SPSite site = new SPSite(webUrl))
                {
                    using (SPWeb web = site.OpenWeb())
                    {
                        ServerContext serverContext = ServerContext.GetContext(site);
                        UserProfileManager userProfileManager = new UserProfileManager(serverContext);
                        UserProfile userProfile = userProfileManager.GetUserProfile(userName);
                        String userLogin = userProfile[PropertyConstants.AccountName].Value.ToString();
                        SPUserCollection groupUsers;
                        ArrayList userInGroups = new ArrayList();
                        userInGroups.Add(userLogin);
                        SPPrincipal userPrincipal;
                        SPGroupCollection groups = web.Groups;
                        foreach (SPGroup group in groups)
                        {
                            groupUsers = group.Users;
                            foreach (SPUser groupUser in groupUsers)
                            {
                                if (groupUser.Name.Equals(userLogin))
                                {
                                    userInGroups.Add(group.Name);
                                    break;
                                }
                            }
                        }
                        SPRoleAssignmentCollection roleCollection = web.RoleAssignments;
                        foreach (SPRoleAssignment role in roleCollection)
                        {
                            userPrincipal = role.Member;
                            for (int i = 0; i < userInGroups.Count; i++)
                            {
                                if (userInGroups[i].ToString().Equals(userPrincipal.Name))
                                {
                                    SPRoleCollection roles = userPrincipal.Roles;
                                    foreach (SPRole userrole in roles)
                                    {
                                        Console.WriteLine("The user " + userLogin + " has permissions of " + userrole.Name + " given via " + userPrincipal.Name);
                                    }
                                }
                            }

                        }
                        Console.WriteLine("The execution completed");
                        Console.ReadLine();
                    }
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
                Console.ReadLine();
            }
        }
    }
}

The output will flash the message about each permissions. 
I hope this will help you out.

Thanks,
Rahul Rashu

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.