Monday, December 17, 2012

Error Type: Content database needs to be upgraded to support this operation


Users of SharePoint 2007 will have noticed that Microsoft had removed the Storage Management page when SharePoint 2010 was released.  Well, the good news is this has made a return in Service Pack 1 with a new look, showing the top 100 largest files or containers across a site collection.

I get to the Storage Metrics page by selecting Site Actions –> Site Settings and then choosing Storage  Metrics under the Site Collection heading.  But, before being able to use the new Storage Metrics feature I had to upgrade my content database.  The error message reads: “Content database needs to be upgraded to support this operation”.


I wasn’t entirely sure how to upgrade the content database, as I’d not done this before and drew a blank with Google, so after a bit of investigation on the server I discovered it took a few minutes using the following command:

C:\Program Files\Common Files\Microsoft Shared\Web ServerExtensions\14\bin\psconfig.exe –cmd upgrade

After successfully ran the command, now am able to see the results in metrics page.


If the configuration stall and got the error some thing like "The farm is being upgraded in the timer service process. The task is XX% completed."

Then have a look the follwoing post.


Reference is here.

Sunday, December 16, 2012

Error Type: The farm is being upgraded in the timer service process. The task is 10% completed.


I am trying to enable the Enterprise Features in SharePoint 2010.  I have turned on the setting in Central Admin and I have run the PSConfig.exe command to set the upgrade going.
The psconfig command runs but stalls at the following message "The farm is being upgraded in the timer service process. The task is 10% completed."

And Log file shows as


PSCONFIG] [SPManager] [INFO] [12/8/2012 5:11:10 AM]: psconfig: Spawing off the upgrade job
[PSCONFIG] [SPManager] [DEBUG] [12/8/2012 5:11:10 AM]: Creating exclusive upgrade reg key


I have tried stopping and restarting the SharePoint 2010 Product Configuration wizard. But no use.

Then finally i got solved it after spending 8 hours.

Here the steps to solve the error,

Step 1: I found with regedit that WSS_ADMIN_WPG and WSS_WPG's permission for "HKEY_LOCAL_MACHINE\Software\Microsoft\Shared Tools\Web Server Extensions\14.0\Secure" registry was somehow lost. I granted permission as described in post.

i. open run command and enter "regedit".
 and go to the path "HKEY_LOCAL_MACHINE\Software\Microsoft\Shared Tools\Web Server Extensions\14.0\Secure"
ii. and set WSS_ADMIN_WPG and WSS_WPG's permission for that registry.




Step 2: Clear PSConfig file's cache using the following batch file.
just download the following bat file from the following location and run it. Download here.

Step 3: Now run the following command
"PSConfig.exe -cmd upgrade -inplace b2b -force -cmd applicationcontent -install -cmd installfeatures"



Thats its.. enjoy....

and reference are here
http://social.technet.microsoft.com/Forums/en-CA/sharepointadminprevious/thread/8fa42032-e93e-464a-ad2c-8ac57d06fcf1

http://technet.microsoft.com/en-us/library/cc678863(v=office.14).aspx

http://social.technet.microsoft.com/Forums/en/sharepointadminprevious/thread/67c26d87-f725-4ce3-92c0-07b6aec526ff

http://www.toro-solutions.com/complete-installation-by-running-psconfig-utility/

Sunday, December 2, 2012

Programmatically how to create custom role and assign the role to a group

Create Custom Role with Custom permissions and assign role to group:

In this example i wanna create custom role with custom permission and assign that role to a group.

            using (SPSite site = new SPSite("http://UKREDDY:6969/"))
            {
                using (SPWeb web = site.OpenWeb())
                {
                    SPRoleDefinition network_role = new SPRoleDefinition();
                    network_role.BasePermissions = SPBasePermissions.AddListItems |
                        SPBasePermissions.BrowseDirectories |
                        SPBasePermissions.EditListItems |
                        SPBasePermissions.DeleteListItems;
                    network_role.Name = "CustomRole";
                    network_role.Description = "Provides permissions required for a member of a project.";

                    web.RoleDefinitions.Add(network_role);
                    // you can't just return definition because SharePoint gives you
                    //    "You cannot grant a user a permission level that is not
                    //    attached to a web" when you attempt to use it, so
                    //    you need to return it again
                    SPRoleDefinition newlyaddedef = web.RoleDefinitions["CustomRole"];
                    SPRoleAssignment assign = new SPRoleAssignment(web.SiteGroups["UdayGroup"]);
                    assign.RoleDefinitionBindings.Add(newlyaddedef);
                    web.RoleAssignments.Add(assign);
                    web.Update();
                }
            }





Delete custom role definition:


            using (SPSite site = new SPSite("http://UKREDDY:6969/"))
            {
                using (SPWeb web = site.OpenWeb())
                {
                    web.RoleDefinitions.Delete("CustomRole");
                }
            }

Get all groups,roles and users details in SharePoint

Get All Groups, Users and Roles in SharePoint:

In this example i wanna show how to get all groups , users and roles in SharePoint site.

            StringBuilder sb = new StringBuilder();
            using (SPSite site = new SPSite("http://ukreddy:6969/"))
            {
                using (SPWeb web = site.OpenWeb())
                {
                    SPGroupCollection groupCollection = web.SiteGroups;
                    foreach (SPGroup group in groupCollection)
                    {
                        SPUserCollection userCollection = group.Users;
                        sb.Append("Group Name :" + group.Name + "\n");
                        foreach (SPUser user in userCollection)
                        {
                            sb.Append("User Name: " + user.Name + " ; Email: " + user.Email + " ; Login: " + user.LoginName);
                            sb.Append("\n");
                        }
                        SPRoleCollection sprolecol = group.Roles;
                        foreach (SPRole role in sprolecol)
                        {
                            sb.Append("Role Name: " + role.Name + " ; Role Desc: " + role.Description + "\n");
                        }
                        sb.Append("\n");
                    }
                   MessageBox.Show(sb.ToString());
                }
            }

Programmatically how to assign user to SharePoint group

Assign a user to group:

In this example, i wanna show how to create group, assign role to the group and assign a user to the group.

            using (SPSite site = new SPSite("http://UKREDDY:6969/"))
            {
                using (SPWeb web = site.OpenWeb())
                {
                    web.AllowUnsafeUpdates = true;
                    web.SiteGroups.Add("UdayGroup", web.CurrentUser, web.CurrentUser, "This is Test Group for adding users to group.");
                    SPGroup group = web.SiteGroups["UdayGroup"];
                    SPRoleDefinition roleDefinition = web.RoleDefinitions.GetByType(SPRoleType.Contributor);
                    SPRoleAssignment roleAssigment = new SPRoleAssignment(group);
                    roleAssigment.RoleDefinitionBindings.Add(roleDefinition);
                    web.RoleAssignments.Add(roleAssigment);
                    web.Update();
                    SPUser spUser = web.EnsureUser("ukreddysykam\\urkeddy");
                    group.Users.Add(spUser.LoginName, spUser.Email, spUser.Name, spUser.Notes);
                    web.AllowUnsafeUpdates = false;
                }
            }





Programmatically how to assign,change and delete pred-defined roles to groups in SharePoint 2010

In my previous post shown how to create and delete groups. Now, i wanna show how to assign role to groups.

Create group and assign pre-defined role to SharePoint group:

Here am creating sample Test Group and assign contributor role to this group.

            using (SPSite site = new SPSite("http://UKREDDY:6969/"))
            {
                using (SPWeb web = site.OpenWeb())
                {
                    web.SiteGroups.Add("TestGroup", web.CurrentUser, web.CurrentUser, "This is Test Group created.");
                    //Getting newly created group
                    SPGroup group = web.SiteGroups["TestGroup"];
                    //Getting Pre-Defined Roles
                    SPRoleDefinition rDefination = web.RoleDefinitions.GetByType(SPRoleType.Contributor);
                    SPRoleAssignment rAssignment = new SPRoleAssignment(group);
                    //adding role definition to role assignment
                    rAssignment.RoleDefinitionBindings.Add(rDefination);
                    web.RoleAssignments.Add(rAssignment);
                    web.Update();
                }
            }



How add roles to existing groups:

In this example , showing how to assign roles to existing groups.

            using (SPSite site = new SPSite("http://UKREDDY:6969/"))
            {
                using (SPWeb web = site.OpenWeb())
                {
                    SPGroup group = web.SiteGroups["TestGroup"];
                    //Getting Pre-Defined Roles
                    SPRoleDefinition rDefination = web.RoleDefinitions.GetByType(SPRoleType.WebDesigner);
                    SPRoleAssignment rAssignment = new SPRoleAssignment(group);
                    //adding role definition to role assignment
                    rAssignment.RoleDefinitionBindings.Add(rDefination);
                    web.RoleAssignments.Add(rAssignment);
                    web.Update();
                }
            }

How  to delete a role from the group:

In this example, wanna show how to remove a role from the group.


            using (SPSite site = new SPSite("http://UKREDDY:6969/"))
            {
                using (SPWeb web = site.OpenWeb())
                {
                    SPGroup group = web.SiteGroups["TestGroup"];
                    SPRoleDefinition roleDef = web.RoleDefinitions.GetByType(SPRoleType.Contributor);
                    SPRoleAssignment roleAss = web.RoleAssignments.GetAssignmentByPrincipal((SPPrincipal)group);
                    roleAss.RoleDefinitionBindings.Remove(roleDef);
                    roleAss.Update();
                }
            }


How to delete all roles to a group:

In this example, i wanna show how to remove all roles from a group.

            using (SPSite site = new SPSite("http://UKREDDY:6969/"))
            {
                using (SPWeb web = site.OpenWeb())
                {
                    SPGroup group = web.SiteGroups["TestGroup"];
                    web.RoleAssignments.Remove(group);
                    web.Update();
                }
            }





Programmatically how to create and delete group in SharePoint 2010


Here i want to show how to create and delete groups using visual studio 2010.

Create Group:

            using (SPSite site = new SPSite("http://UKREDDY:6969/"))
            {
                using (SPWeb web = site.OpenWeb())
                {
                    web.SiteGroups.Add("TestGroup", web.CurrentUser, web.CurrentUser, "This is Test Group created by Uday.");
                    web.Update();
                }
            }


Delete Group:

Delete newly created group.

            using (SPSite site = new SPSite("http://UKREDDY:6969/"))
            {
                using (SPWeb web = site.OpenWeb())
                {
                    web.SiteGroups.Remove("TestGroup");
                    web.Update();
                }
            }



Saturday, October 27, 2012

Programmatically how to create backup and restore a sitecolletion in SharePoint 2010

In previous post, have seen how to take backup and restore a site collection using power shell commands.

Here will take back up and restore a site collection using SharePoint API.

There are two methods to create back up and restore a site collection.

1. Backup and
2. Restore.

Here i want to maintain one log file for tracing backup and restore creation details, so for that created the following method.

here we need to create two folder in D drive for saving backup file and log file.
D:\SiteBackupLog and D:\SiteBackUp


        public static void siteBackupLog(string message)
        {
            string PathName = "D:\\SiteBackupLog\\";
     PathName = PathName + "Backuplog-" + DateTime.Now.ToString("dd-MM-yyyy") + ".log";
            StreamWriter sw = new StreamWriter(PathName, true);
            sw.WriteLine(message + " - " + DateTime.Now);
            sw.Flush();
            sw.Close();
        }

Now , for taking backup of a site collection , used the following method.

        private void btnBackup_Click(object sender, EventArgs e)
        {
            string sourceSiteCollURL = "http://ukreddy:6969";
            string time = DateTime.Now.ToString("dd-MM-yyyy");
            string backupfilename = "D:\\SiteBackup\\SharePointSiteBackup_" + time + ".bak";
            siteBackup(sourceSiteCollURL, backupfilename);
        }
        public static void siteBackup(string siteURL, string fileName)
        {
            try
            {
                SPSecurity.RunWithElevatedPrivileges(delegate()
                {
                    SPWebApplication webApplication = null;
                    webApplication = SPWebApplication.Lookup(new Uri(siteURL));
                    SPSiteCollection sitecols = webApplication.Sites;
                    string backupName = fileName;
                    sitecols.Backup(siteURL, backupName, true);//true is used for if already bak file created with the same name , it will overwrite
                });
                siteBackupLog("Site Collection backup created succuessfully");
            }
            catch (Exception ex)
            {
                siteBackupLog(ex.Message);
            }
        }  

in the above code we are try to create backup file and saving it in the specified location and also writing log also.

And the following code is used to restore site collection in new web application i.e http://ukreddy:2727 and restore it as root site collection.


        private void btnRestore_Click(object sender, EventArgs e)
        {
            string sitecollectionURL = "http://ukreddy:2727";
            string backupfilename = "D:\\SiteBackup\\SharePointSiteBackup_27-10-2012.bak";
            SiteRestore(sitecollectionURL, backupfilename);
        }

        private void SiteRestore(string siteURL, string fileName)
        {
            try
            {
                SPSecurity.RunWithElevatedPrivileges(delegate()
                {
                    SPWebApplication webApplication = null;
                    webApplication = SPWebApplication.Lookup(new Uri(siteURL));
                    SPSiteCollection sitecols = webApplication.Sites;
                sitecols.Restore("/", fileName, true);// overwrite sitecollection if already exists
                });
                siteBackupLog("Site collection restored successfully");
            }
            catch (Exception ex)
            {
               siteBackupLog(ex.Message);
            }
        }

here the screen shot of actual site collection i.e http://ukreddy:6969 and restored site collection i.e http://ukreddy:2727 respectively.






Thats it...


pls let me know if u have questions/suggestions.




Friday, October 19, 2012

How to move site collection from one web application to another web application using powershell


There are some situations where you want to move your site collection from one web application to another web application or where you want to change site collection port number or site collection path.

1. Take a backup of site collection from old webapplication
2. Restore backup in new web application.
3. Remove site collection from old web application
4. Delete backup file.

Here is my requirement, i have two web applications

1. http://ukreddy:2727 in this i have one root site collection
2. http://ukreddy:3636 This is my new web application 

now i want to move site collection from http://ukreddy:2727 web application to http://ukreddy:3636 web application or i want to change site collection port number.

In my site collection i have added some documents to document library, added events to calendar and add tasks to task list for testing.





1. Take backup of site collection 

Take backup of site from old web application(i.e http://ukreddy:2727).

Backup-SPSite -Identity http://ukreddy:2727 -Path "C:\\MoveSiteCollection.bak" 

or

Backup-SPSite -Identity http://ukreddy:2727 -Path "C:\\MoveSiteCollection.bak" -force

Note: -force is swicht parameter and it is used to create/overwrite if .bak file already exist.

This cmdlet will create .bak file in  "C:\\" path with the given name in cmdlet.



2. Restore backup file to new web application(i.e http://ukreddy:3636):

Here assuming that http://ukreddy:3636 web application created and root site collection not yet created.

Restore-SPSite -Identity http://ukreddy:3636 -Path "C:\\MoveSiteCollection.bak" 




or 

Restore-SPSite -Identity http://ukreddy:3636 -Path "C:\\MoveSiteCollection.bak"  -Confirm:$false



if you use -Confirm:$false parameter then it wont ask your confirmation for restore of site collection. Simply restore site collection.

This cmdlet will create root site collection in http://ukreddy:3636 as is it which in http://ukreddy:2727





3. Remove site collection 

Remove site collection from old web application.

Remove-SPSite -Identity http://ukreddy:2727 -Confirm:$false




4. Remove backup file

Remove the backup file from the path where we given path for backup.

Remove-Item "C:\\MoveSiteCollection.bak"




Here the code snippet copy the snippet and save it as .ps1 and run the .ps1 file in powershell....

###############################################################################

#Get the from Site Collection URL
$fromURL = "http://ukreddy:2727"
#Get the to Site Collection URL 
$toURL = "http://ukreddy:3636"

#Location to the backup file directory to store Site Collection backup files
$backupPath = "C:\\test.bak"

#Backing up Site Collection prior to moving
Write-Host "Backing Up Site Collection…."
Backup-SPSite $fromURL -Path C:\test.bak -force

#Removing Site Collection from old web application path
Write-Host "Removing Site Collection from old managed path location…"
Remove-SPSite -Identity $fromURL -Confirm:$false

#Restoring Site Collection to new Managed Path
Write-Host "Restoring Site Collection to new managed path location…"
Restore-SPSite -Identity $toURL -Path c:\test.bak -Confirm:$false

#Remove backup files from the backup dirctory
Remove-Item c:\test.bak

###############################################################################


Wednesday, October 17, 2012

How to create,get and delete managed path in SharePoint 2010 using PowerShell

In this article we will see 

1. How to get all managed paths 
2. How to create managed path
3. How to delete defined managed path

1.Get all managed paths in a web application:

a. Click On the Start menu, click All Programs.
b. Click Microsoft SharePoint 2010 Products.
c. Click SharePoint 2010 Management Shell.
Type the following command.

Get-SPManagedPath -WebApplication http://ukreddy:8998



and press enter.




2. Create managed path in a web application :

Now type the following command.

New-SPManagedPath "/newmanagedpath" -WebApplication http://ukreddy:8998



and press enter.



Now we can use get all managedpaths command to see all existing managed paths in a web application.

3. Delete managed path in a web application:

we can also delete managed path in a web application using the following command,

Remove-SPManagedPath -Identity "/newmanagedpath" -WebApplication http://ukreddy:8998



The above command will promt a message, asking end user confirmation to delete managed path.


if u dont want to prompt confirmation message use the following command.


Remove-SPManagedPath -Identity "/newmanagedpath" -WebApplication http://ukreddy:8998 -Confirm:$false




Monday, October 15, 2012

Programmatically How to create,get and delete managed path in SharePoint 2010


Introduction:

Managed Paths - We can specify which paths in the URL namespace of a Web application are used for site collections. We can also specify that one or more site collections exists at a specified path.

Types of Managed Paths:

Explicit inclusion.
Wildcard inclusion.

Explicit inclusion:

An explicitly named path is used for a single site collection.

Example: http://server/sites/team.

Wildcard inclusion:

A wildcard path of "sites" indicates that child URLs of the path are site collections. An wildcard named path is used for a multiple site collections.

Example: http://server/sites/

In this article we will be seeing the following

Programmatically create managed paths for a web application,
Programmatically get all the managed paths for a web application, and
Programmatically delete a managed path from a web application.

1. Creating a managed path:

string path = "NewManagedPath";
SPWebApplication webApp = SPWebApplication.Lookup(new Uri("http://ukreddy:6969/"));
SPPrefixCollection prefixColl = webApp.Prefixes;
if (prefixColl.Contains(path) == false)
   {
      SPPrefix newPrefix = webApp.Prefixes.Add(path, SPPrefixType.ExplicitInclusion);
      MessageBox.Show(path + " is successfully added to the web application");
   }
else
  {
       MessageBox.Show(path + " already existe in the web application");
  }


the above code is used to create managed path in http://ukreddy:6969 web application.

the following screen shot show managed paths before executing the above code.
to get the list of managed path we use the step 2 code.



Once the above code is executed, it will create managed path in the web application.

the following screen show shows the message after successfuly creation of managed path.

Once the path is created once again retrieving list of managed path in the web application.


2. Get all managed paths:

SPWebApplication webApp = SPWebApplication.Lookup(new Uri("http://ukreddy:6969/"));
SPPrefixCollection prefixColl = webApp.Prefixes;
string str = "";
foreach (SPPrefix prefix in prefixColl)
  {
      str += "Managed Path :" + prefix.Name + ", Prefix Type :" + prefix.PrefixType + "\n";
  }
MessageBox.Show(str);

the following screen show showing list of managed path in the web application i.e http://ukreddy:6969.



3. Delete a managed path:

string path = "NewManagedPath";
SPWebApplication webApp = SPWebApplication.Lookup(new Uri("http://ukreddy:6969/"));
SPPrefixCollection prefixColl = webApp.Prefixes;
if (prefixColl.Contains(path) == true)
  {
      webApp.Prefixes.Delete(path);
      MessageBox.Show(path + " is successfully deleted from the web application");
  }
else
  {
      MessageBox.Show(path + " managed path not exist in the web application");
  }

The above code is used to delete a managed path from the web application.

Once we sucessfully execute the above code it will display message,




after deletion of managed path , the following screen shows list of managed paths.



here the complete source code...

Reference to this link.

Error Type: This operation can be performed only on a computer that is joined to a server farm by users who have permissions in SQL Server to read from the configuration database. To connect this server to the server farm, use the SharePoint Products Configuration Wizard, located on the Start menu in Microsoft SharePoint 2010 Products.

When i was creating SharePoint 2010 windows application on windows server 2008 R2 i got the following error ...

"This operation can be performed only on a computer that is joined to a server farm by users who have permissions in SQL Server to read from the configuration database. To connect this server to the server farm, use the SharePoint Products Configuration Wizard, located on the Start menu in Microsoft SharePoint 2010 Products."



The reason for the error is my windows application's platform target is (by default) set to "x86" in application properties window.


but SharePoint applications runs on x64. so , i changed platform target to x64 or u can set to any cpu.

Then my application runs without any error.


Wednesday, October 10, 2012

How to remove web application using PowerShell 2010


Method 1:

Remove-SPWebApplication -Identity http://ukreddy:6789

This cmdlet will ask for user's confirmation.


Remove-SPWebApplication -Identity http://ukreddy:6789 -Confirm:$false

This cmdlet won't ask for user's confirmation.



This cmdlet permanently removes the Web application at http://ukreddy:6789. This command does not remove the content databases or the IIS Web site.

Method 2:


Remove-SPWebApplication -Identity http://ukreddy:6789 -DeleteIISSite -RemoveContentDatabase


This cmdlet will ask for user's confirmation.


Remove-SPWebApplication -Identity http://ukreddy:6789  -Confirm:$false -DeleteIISSite -RemoveContentDatabase

This cmdlet won't ask for user's confirmation.




This cmdlet permanently removes the Web application at http://ukreddy:6789. This command also remove the content databases or the IIS Web site.