Wednesday, 25 January 2012

How to setup alerts on User Information List in Sharepoint

Hi,

I got a request where a site collection administrator wanted to track the changes in "User Information List" without using any custom code. The very first way is to enable auditing under site collection administration for "Editing users and permissions". However this will fill the database and will result in performance issues. So this was not acceptable to the site administrators. Moreover his requirement was to track only when a user is added or removed from site collection. Hence we approached to setup the alerts.

When we reached to the User Information List we do not find any option to setup alerts or go to setting etc as normal lists.

Now we used the following method to get it through:
1. Our first requirement was to get the GUID. To get this we queried dbo.Lists table in the content database holding this site collection.
2. The query should be:
Select tp_ID From Lists with(NoLock)where tp_Title = 'User Information List'
3.Make a note of this ID.
4. Now go to any other list in the top site in your site collection and click on Alert Me under Actions.
5. In the next page in URL remove the contents after ?List= and add the GUID noted in step 3.
6. Press enter and now you will find that the fields are populated with User Information List and you can create the alerts.

I hope this will help you out.

Thanks,
Rahul Rashu

Sunday, 8 January 2012

Access Denied By Business Data Connectivity Error in Using External Content Type List in Sharepoint 2010

Hi,

Recently an issue was reported to me where a site administrator tried to use a table in sql server as an external content source. He was able to create the external content type based on this and had defined all CRUD operations. He also created a list based on this external content type however when he was trying to access this list he got this error:











This was throwing an access denied error message by Business Data Connectivity. It was a clear indication of the problem and I resolved this by following steps:

1. Login into central administrator and click on "Manage Service Applications"











2.  Now click on Business Data Connectivity Services :












3. Now check the External Content Type that was created and click on Set Object Permissions:











4. Now add the user and grant permissions as shown and click OK and you are ready to go:



I hope this will help you out:

Thanks,
Rahul Rashu

How to upload a folder and containing files into a sharepoint document library using client object model

Hi All,

I received a recent request to provide a tool to upload documents from a local machine to sharepoint document library using client object model in SPS 2010. I have selected the managed code model to do it.
This tool takes 3 inputs:
1. The URL of the sharepoint site where the library is located.
2. The name of the document library.
3. Path of the folder in your local machine.

If the folder does not exists it will create a new folder and if the files already exists it will overwrite them.
Here is the code:

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

namespace TestClientManagedCode
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("This tool will copy the entire folder from your local machine to the sharepoint document library");
            Console.WriteLine("Please enter the url of the site");
            String siteUrl = Console.ReadLine();
            Console.WriteLine("Please enter the name of the document library");
            String dLibraryName = Console.ReadLine();
            Console.WriteLine("Please enter the full path of the folder containing the files without the filname");
            String folderPath = Console.ReadLine();
            try
            {
                using (ClientContext ctx = new ClientContext(siteUrl))
                {
                    Web web = ctx.Web;
                    ctx.Load(web);
                    ctx.ExecuteQuery();
                    List dUplaod = web.Lists.GetByTitle(dLibraryName);
                    String[] fileNames = Directory.GetFiles(@folderPath);
                    bool exists = false;
                    DirectoryInfo dInfo = new DirectoryInfo(@folderPath);
                    FolderCollection folders = dUplaod.RootFolder.Folders;
                    char[] sep = { '\\' };
                    ctx.Load(folders);
                    ctx.ExecuteQuery();
                    foreach (Folder eFolder in folders)
                    {
                        if (eFolder.Name.Equals(dInfo.Name))
                        {
                            foreach (String fileName in fileNames)
                            {

                               
                                String[] names = fileName.Split(sep);
                                FileCreationInformation fCInfo = new FileCreationInformation();
                                fCInfo.Content = System.IO.File.ReadAllBytes(fileName);
                                fCInfo.Url = names[names.Length - 1];
                                eFolder.Files.Add(fCInfo);
                                exists = true;
                            }

                        }
                    }

                    if (!exists)
                    {
                        Folder tFolder = folders.Add(siteUrl + "/" + dLibraryName + "/" + dInfo.Name);
                        foreach (String fileName in fileNames)
                        {


                            String[] names = fileName.Split(sep);
                            FileCreationInformation fCInfo = new FileCreationInformation();
                            fCInfo.Content = System.IO.File.ReadAllBytes(fileName);
                            fCInfo.Url = names[names.Length - 1];
                            tFolder.Files.Add(fCInfo);
                        }
                    }
                   
                    ctx.ExecuteQuery();
                    Console.WriteLine("The Execution is completed");
                    Console.ReadLine();

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

        }
    }
}


I hope this will help you out.

Thanks,
Rahul Rashu


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