Friday, April 20, 2012

Write text log entry inside 14 Hive logs from SharePoint Timer job

Leave a Comment
This blog will demonstrate, how to create/write log file in text format inside 14\Hive folder. Idea behind this is to register error in text format inside 14\Hive folder.

Lets consider this problem statement : Get list of Organization Profiles where  value of property "OrganizationMotto" is null or Empty. "OrganizationMotto" is custom property, created through UI. To create custom property follow this steps.
  1.  Go to User profile application
  2.  Under Organizations --> Click Manage Organizations Properties
  3.  From Top bar click "New Property"
  4. Specify Name  and Display Name. Name cannot be changed but display name can be. So make sure you giving correct name.
  5. Specify Type and length.
  6. Hit Save. There are other settings you can do while create property. Such as replicating property to user information list , showing in profile page etc.
After saving you can see custom property in Manage Organizations properties section.

Now you need to create SharePoint , which will be deployed to the share point webapplication level.
Below article showcase step by step guide to create timer job. Kindly review that if audience is new to SharePoint.

Now after creating timer job, you can find Execute method which will contain core body for logic.  Below is the code reference

 public override void Execute(Guid targetInstanceId)
SPWebApplication webApplication = this.Parent as SPWebApplication;
using (var rootSite = new SPSite(webApplication.Sites[0].Url))

// Get reference for Service Context
SPServiceContext serviceContext = SPServiceContext.GetContext(spSite);

//Get reference of OrganizationProfileManager which contains all Organization Profile objects
OrganizationProfileManager orgProfileManager = new OrganizationProfileManager(serviceContext);

//Now we want to create file under 14\Hive, so this path can be easily retrieved using GetGenericSteupPath method of SPSUtility. This will get path Program files\Common Files\Microsoft Shared\Web Service Extensions\14\Logs

      string logsPath = SPUtility.GetGenericSetupPath("Logs");
      string filepath = logsPath + @"\OrganizationProfileLog.txt";

// Get object of StreamWriter to create and write file
      StreamWriter streamWriter = File.CreateText(filepath);
      string orgDisplayName = string.Empty;

//iterate each object of OrganizationProfile to check OrganizationMotto value.
      foreach (OrganizationProfile orgProfile in orgProfileManager)
          orgDisplayName = orgProfile.DisplayName;
          if (orgProfile["OrganizationMotto"].Value == null)
            //WriteLine method will write string to the new line.
            streamWriter.WriteLine("OrganizationMotto property value of "+ orgDisplayName +" is empty");
            if (!string.IsNullOrEmpty(orgProfile["OrganizationMotto"].Value.ToString()))
              streamWriter.WriteLine("OrganizationMotto property value of " + orgDisplayName + " is empty");
        catch (Exception exception)

After adding this code. Deploy timer job and execute it.  Then go to 14\Logs folder and search for OrganizationProfileLog.txt file.  Open this file to see if there is any issue registered . 

Cheers !


Tuesday, April 17, 2012

Few Web Part operations using PowerShell

Leave a Comment

To create this script, open notepad or any other text editor and save it as .ps1

            1.   Firstly lets show up list of web parts from web on power shell Console

$site = Get-SPSite("site  url");
$web = $site.RootWeb;
$list = $web.Lists["Web Part Gallery"]
$listItems = $list.GetItems()

$listitems | ForEach-Object{ Write-Host $_.Title -Foregroundcolor red -Backgroundcolor green};

2.  Lets get list of web parts on page using Power shell

$site = Get-SPSite("site url");
$web = $site.RootWeb;
$webpartManager = $web.GetLimitedWebPartManager("SitePages/MyPage.aspx",[System.Web.UI.WebControls.WebParts.PersonalizationScope]::Shared)
$webparts = $webpartManager.Webparts

           $webparts | ForEach-Object { Write-Host $_.DisplayTitle }

             3.   Remove WebPart from Page

 $site = Get-SPSite("site url");
 $web = $site.RootWeb;

// Get instance of WebPart Manager on the page
 $webpartManager = $web.GetLimitedWebPartManager("SitePages/MyPage.aspx",[System.Web.UI.WebControls.WebParts.PersonalizationScope]::Shared)

// Get all the webparts on page
$webparts = $webpartManager.Webparts

//Get id of webpart to be deleted.
$webpartID = $webparts[1].ID


Tuesday, April 10, 2012

Delete File from SharePoint document library using Client context

Leave a Comment
Following blog spot shows how to delete file from sharepoint site document library using client context. To demonstrate this, we will delete first file from file collection.

To start with the code, we will create console application.
Add 2 assemblies to the sharepoint project
(1) Microsoft.Sharepoint.Client
(2) Microsoft.SharePoint.Client.Runtime

Both assemblies resides inside 14 hive\ISAPI Folder

Inside Main Function write following code.

         // Get Web object

          ClientContext clientContext = new ClientContext("site url");
          Web web = clientContext.Web;

          // Get List Object
          List list = web.Lists.GetByTitle("ListName");
          // Get Root Folder for the List
          Folder folder = list.RootFolder;

          // Get File Collection
          FileCollection files = folder.Files;

         //Delete first file from the collection
          File file = files[1];          


Saturday, April 7, 2012

Get Root Organization from Organization Profile

Leave a Comment

When user profile service application is created. Organization profile architecture creates Default organization which is Root Organization.  Logically every organization needs to have at least one department. So having Root Organization makes easy to extend by creating child organization or immediate members

To get Root Organization  one can use following code block

SPSite site = new SPSite("site url");
SPServiceContext serviceContext = SPServiceContext .GetContext(site);
OrganizationProfileManager organizationProfileManager = new OrganizationProfileManager(serviceContext);
OrganizationProfile orgProfile = organizationProfileManager .RootOrganization;

But when you modify name of the Root Organization, property returns null.

So when Root Organization returns null, how to get the Root Organization. ?

OrganizationProfileManager has method GetOrganizationProfile .  Root Organization is default organization which has ID 1. So you can get OrganizationProfile instance by ID 1.

OrganizationProfile orgProfile = organizationProfileManager GetOrganizationProfile(1);

Other way to get Organization Profile would be to Search all the ProfileBase .

For a case I want to search Organization Profile "SharePoint"
 var results = organizationProfileManager.Search("SharePoint");

      OrganizationProfile orgProfile;
      foreach (var profile in results)
        if(profile is OrganizationProfile)
          if(profile.DisplayName == "SharePoint")
            orgProfile = profile as OrganizationProfile;


Tuesday, April 3, 2012

Get SiteUsers and SiteGroups in PowerShell

Leave a Comment
To create this script, open notepad or any other text editor and save it as .ps1

Script to get SiteUsers. 

$site = Get-SPSite("site url");
$web = $site.OpenWeb();
$users = $web.SiteUsers;

$users | ForEach-Object{ Write-Host $_.Name -Foregroundcolor red};

After saving this file, open powershell and run this ps1 file.

Script to get SiteGroups

$site = Get-SPSite("site url");

$web = $site.OpenWeb();
$groups = $web.SiteGroups

$groups | ForEach-Object{ Write-Host $_.Name -Foregroundcolor red};


Monday, April 2, 2012

Get all SharePoint document library objects in descending order using ClientContext

Leave a Comment

To demonstrate this task we will create Console Application in Visual  Studio 2010. 
Add Microsoft.SharePoint.Client and Microsoft.SharePoint.Client.Runtime assemblies to the references.
This assemblies resides inside 14 hive ISAPI folder.

Refer Web from ClientContext

 ClientContext clientContext = new ClientContext("siteurl");
 Web web = clientContext.Web;

Get list collection from web

 ListCollection listCollection = web.Lists;

Iterate through listcollection to get lists of Base Type: document library

System.Collections.Generic.List documentlists = new List();
          foreach (List list in listCollection)
            if(list.BaseType == BaseType.DocumentLibrary)

Using linq extension get all the objects in descending order.

      var sortedlist = documentlists.OrderByDescending(p => p.Title);

sortedlist will contain list of sorted document library in descending order by its title. 

Sunday, April 1, 2012

Create local active directory group and add it to sharepoint site.

Leave a Comment

This post will explain how to  create security group  and assign permission to the group in SharePoint Site.

So before we proceed forward to create security group, we will create a user in local active directory

Firstly we need to get object for the computer on which user is going to be created

 var directoryEntry= new DirectoryEntry("WinNT://" + Environment.MachineName + ",Computer");

Now lets create user with name "TestUser"

DirectoryEntry newUser= directoryEntry.Children.Add("TestUser", "User");

This will create user in local active directory. Now you have to assign values to the properties. For example we will assign password to the user.

newUser.Password = "Password";

Next Step will be to create security group.

We already have directoryEntry object so now we can add new object of type Group to create security group

DirectoryEntry  groupEntry = directoryEntry.Children.Add("TestGroup", "Group");

Now we will add newuser to the new Group

groupEntry .Invoke("Add", new object[] { newUser.Path });

We have now created new user and group,  also added new user to the new group. So we are all set to add this group  to the SharePoint. By adding this security group will automatically assign the group permission to the each and every user inside this security group.  We will create a new Group in Sharepoint and add this security group to that group. This way we can control broad level SharePoint group entity.

SPSite site = new SPSite("site url");
SPWeb web = site.RootWeb;
web.AllowUnsafeUpdates = true;
 web.SiteGroups.Add("MyGroup", web.CurrentUser,web.CurrentUser,"MyGroup users");

SPGroup gGroup = web.SiteGroups["MyGroup"];
SPRoleDefinition roleDefinition = web.RoleDefinitions.GetByType(SPRoleType.Contributor);
var roleAssignment = new SPRoleAssignment(gGroup);

SPUser spUser = web.EnsureUser(SecurityGroupName);
gGroup.Users.Add(spUser.LoginName, "", "", "");
web.AllowUnsafeUpdates = false;

This will assign permission to the group in SharePoint Site

OrganizationProfile.AddMember throws Attempted to perform an unauthorized operation error

Leave a Comment

Organization Profile is the new feature of SharePoint 2010. This feature is part of SharePoint 2010 server edition.  We had task to create organization profile and add member through timer job. But even after writing down code correctly , Organization Profile.Addmember method throwed "Attempted to perform an unauthorized operation error."

Not much reference was available on web to track down problem. Only one technet forum thread  was closely related to the issue, which gave clue on the problem 

As suggested  in  above forum thread we gave Manage profile permissions to the account but error remained same. I tried luck by giving FULL Control but  error was same.

Timer job executes under the SPTimerV4 service account.  And same user need to have access to the content database.  SPTimerV4 user account was already db owner at content database but still error remain same.

This made me to change the local admin user account  as SPTimerV4 user account and Adding same user account as db owner in content database.. This made OrganizationProfile.Add member code working correctly.
Reference technet forum thread