Pages

Search This Blog

Showing posts with label Event Handlers. Show all posts
Showing posts with label Event Handlers. Show all posts

Thursday, March 22, 2012

Access denied on SPJobDefinition RunNow()

Recently I faced strange issue while executing a timer service through my web part. Since it was possible in MOSS 2007, but I know SharePoint 2010 does not support executing any timer job through code. I have already written a solution for setting up the property : RemoteAdministratorAccessDenied. This property allows modification of the SPPersistedObject from content web applications.  The post can be viewed at: http://www.directsharepoint.com/2011/04/access-denied-while-activating-feature.html. However when I tried to execute the timer, It gave an error as:

"Operation is not valid due to the current state of the object"

To resolve this, I cleared the HttpContext.Current property to null as:


SPSecurity.RunWithElevatedPrivileges(delegate()
                {
                    using (SPSite elevatedSite = new SPSite("Site URL"))
                    {
                        foreach (SPJobDefinition job in  elevatedSite.WebApplication.JobDefinitions)
                        {
                            if (job.Title.Equals("Your job name") && job.Status == SPObjectStatus.Online)
                            {
                                HttpContext.Current = null;
                                job.RunNow();
                                break;
                            }
                        }
                    }
                });



Wednesday, February 22, 2012

Assign default page of Publishing site to custom page during site provisioning

In my previous post, I have highlighted how to create pages in Pages library using CAML when a site is being provisioned.
We had created Home.aspx custom page.
 

Requirement:
We need to set Home.aspx as the default welcome page of the site, when the site is being provisioned.

Solution:
We can achieve this by putting a piece of code in the feature receiver.


//Get the Publishing Web object
PublishingWeb objPublishingWeb = PublishingWeb.GetPublishingWeb(web);
//Get the Home.aspx file from Pages library
SPFile objHomePageFile = web.GetFile(objPublishingWeb.PagesListName + "/Home.aspx");            

//Set default page of publishing web
objPublishingWeb.DefaultPage = objHomePageFile;
objPublishingWeb.Update();
web.Update();
  
If we browse the site now, Home.aspx opens up as the default page.

Wednesday, November 30, 2011

Create and Assign Custom Permission Levels programmatically in SharePoint

Sometimes, we come across a business requirement, where in:
-     We need to create SharePoint sites on the fly (maybe using a site definition), which have their own unique permission and groups.
-     We might need to create a custom permission level for the contributors for this site, say which does not have the delete rights but all other Contributor rights as is.
-     Then we need to assign this custom permission level to Contributor group and remove the default ‘Contribute’ permission level from the site.

        /// *************************************************************************
        /// <summary>
        /// Creating & Assigning custom permission
        /// level to Contributor group of root site
        /// </summary>
        /// <param name="spWeb">SpWeb object</param>
        /// <param name="myGroup">Group on which the custom permission
        /// has to be applied</param>
        /// ************************************************************************
        private void CreateAssignCustomPermissionLevel(SPWeb spWeb, SPGroup myGroup)
        {          
            spWeb.AllowUnsafeUpdates = true;
            //Get the role definition collection for this SPWeb
            SPRoleDefinitionCollection sprdcoll = spWeb.RoleDefinitions;
           
            //Define the new custom RoleDefinition
            SPRoleDefinition roleDefinition = new SPRoleDefinition();
            roleDefinition.Name = "MyCustomRoleDefinition";
           
            //And then start giving all permisions that you want to give.
            roleDefinition.BasePermissions =
            SPBasePermissions.AddListItems
            | SPBasePermissions.EditListItems
            //| SPBasePermissions.DeleteListItems //Delete permission removed from this definition.
            | SPBasePermissions.ViewListItems
            | SPBasePermissions.OpenItems
            | SPBasePermissions.ViewVersions
            | SPBasePermissions.DeleteVersions
            | SPBasePermissions.CreateAlerts
            | SPBasePermissions.ViewFormPages
            | SPBasePermissions.BrowseDirectories
            | SPBasePermissions.ViewPages
            | SPBasePermissions.BrowseUserInfo
            | SPBasePermissions.UseRemoteAPIs
            | SPBasePermissions.UseClientIntegration
            | SPBasePermissions.Open
            | SPBasePermissions.EditMyUserInfo; 

            //Add role definition to spweb
            if (!spWeb.RoleDefinitions.Xml.ToString().Contains("MyCustomRoleDefinition"))
            {
                spWeb.RoleDefinitions.Add(roleDefinition);
                spWeb.Update();
            }          

            //Assign custom role definition to the contributor group
            SPRoleAssignment assignment = new SPRoleAssignment(myGroup);
            //Add custom role definition to the SPRoleAssignment
            assignment.RoleDefinitionBindings.Add(roleDefinition);
            //Add the custom RoleAssignment to the SPWeb.
            spWeb.RoleAssignments.Add(assignment);          

            //Once we have the custom permission level assigned to contributors group,
            //we need to remove the default 'Contribute' permission level from this web
            spWeb.RoleDefinitions.Delete("Contribute");
            spWeb.Update();
            spWeb.AllowUnsafeUpdates = false;
        }

This method can be placed in feature receiver, where this feature is activated when the site is created on the fly.

Friday, May 6, 2011

Creating Site Programmatically


If we want to create a site in our site collection programmatically, so here is the code for it. I have created a console application, you can use it according to your convenience wherever required say Feature Receiver or Event handler
Code snippet
SPSecurity.RunWithElevatedPrivileges(delegate()
{
using (SPSite objSite = new SPSite("SiteUrl"))
{
using (SPWeb objWeb = objSite.OpenWeb())
{
objWeb.AllowUnsafeUpdates = true;
SPWebCollection objWebColl = objWeb.Webs;
objWebColl.Add("MyTestSite", "TestSite", "this is a test Site", 1033,
"STS#0", true, false);
objWeb.AllowUnsafeUpdates = false;
}
}
});
· The First argument is the Name of your subsite
· Second Argument is the Name of your SubSite.
· Third argument is the Description of you subsite.
· Fouth argument is the LocalId in which you want to create the Site
· Fifth Argument is the Type of Site Template.Since there are many Templates,So here is the code for some of it:
o STS#0 Team Site
o STS#1 Blank Site
o STS#2 Document Workspace
o MPS#0 Basic Meeting Workspace
o MPS#1 Blank Meeting Workspace
o MPS#2 Decision Meeting Workspace
o MPS#3 Social Meeting Workspace
o MPS#4 Multipage Meeting Workspace
o WIKI#0 Wiki
o BLOG#0 Blog
And these are additional web template IDs
o BDR#0 Document center—A central document management location for an enterprise
o OFFILE#0 Records center—A central location in which records
o OFFILE#1 managers can define routes for incoming files
o CMSPUBLISHING#0 Publishing site
o BLANKINTERNET#0 Publishing site—A site for publishing web pages on a schedule with workflow features enabled
o BLANKINTERNET#1 Press releases site
o BLANKINTERNET#2 Publishing site with workflow—A publishing site for web pages using approval workflows
o SPSNHOME#0 A site for publishing news and articles
SPSREPORTCENTER#0 Report center—A site for creating, managing, and delivering web pages, dashboards, and Key Performance Indicators (KPIs)
o SPSPORTAL#0 A starter hierarchy for an intranet divisional portal
o PROFILES#0 A profile site that includes page layouts with zones
o BLANKINTERNETCONTAINER#0 Publishing portal—a site collection preconfigured for revision-controlled, secure content creation and publication
o SPSMYSITEHOST#0 My Site host—keep in mind that only one of these can be provisioned per Shared Services Provider
o SRCHCENTERLITE#0 Search center—A site designed to deliver the search query and results experience
SRCHCENTERLITE#1 Search center—A superset of the previous; does not appear in navigation bars

Monday, March 14, 2011

Event Impersonation in Sharepoint 2010

In earlier versions of SharePoint Foundation, events that occurred when a request was being processed ran in the context of the user whose action raised the event. Generally, this was acceptable; furthermore, if this created a problem, a developer could either revert to using the system account context, or create a new SPSite object for use with a particular user.

In some scenarios, for example, when an active workflow has code that is running with elevated privileges, the code runs in the context of the system account. But in this scenario, when event receiver code needs to run with the credentials of the originating user, SharePoint Foundation 2010 added a new property called “OriginatingUserToken” on the “SPEventPropertiesBase” class that returns the ID of the originating user. Event code should check for this user by ID, and, optionally, perform behaviors that can potentially cause unexpected effects by using an impersonated site collection with the token of that originating user.

public override void ItemUpdating(SPItemEventProperties properties)
       {
           base.ItemUpdating(properties);
           SPUserToken objSPUserToken = properties.OriginatingUserToken;
           if (objSPUserToken != null)
           {
               using (SPSite objSPSite = new SPSite(properties.SiteId, objSPUserToken))
               {
                   using (SPWeb objSPWeb = objSPSite.OpenWeb())
                   {
                       //You can perform user context specific changes here...
                   }
               }
           }

       }