Getting user login from the PeopleEditor via Code

October 4th, 2007 1 comment

Assuming you have a people editor control defined like below:

<wssawc:PeopleEditor AllowEmpty=”false”  ID=”myPeopleEditorControl” runat=server SelectionSet=”User” MaximumEntities=”1″ MultiSelect=”false” AllowTypeIn=”false” Width=’500px’ />

The following code sample will get you the currently logged on user’s login from the PeopleEditor control:

  ArrayList peEntities = myPeopleEditorControl.Entities;
  PickerEntity pickEn = (PickerEntity)peEntities[0];
  stringLogIn = pickEn.Key;

This comes handy when you want to create an SPUser context out of the entities kept in the PeopleEditor control. For example:

 private SPUser GetUser(string logIn)

        {
             SPUser user = this.workflowProperties.Web.SiteUsers[logIn];
             return user;
        }

Don’t forget Required Field Validation on your people editor control if you want the code not to break on you.

Categories: MOSS 2007 Tags:

Toronto SharePoint Camp 2007 Count down

September 30th, 2007 No comments

The Toronto SharePoint Camp 2007 is just around the corner, 20th of October in Toronto. Register Today, Space is limited! Remember, this is a *Free* event and no matter how expert you are in SharePoint, there should be something there for you to learn. For those of you who keep sending me emails asking for events and opportunities to learn MOSS 2007, there you are! Here is a great opportunity to meet a lot of SharePoint guys, learn for top-notch industry experts plus a lot of fun and PRIZES!!! I have two demos prepared one targeting the advanced audience and the other one for beginners. I probably have to choose one of them if there are many speakers lined up.Please keep an eye on my blog, Eli’s blog and SharePoint Buzz blog for updates and  announcements.

Categories: UG/CodeCamp Tags:

Item Level Permission in workflow CreateTaskXXX activities

September 27th, 2007 11 comments

Both CreateTask and CreateTaskWithContentType  activities  have a property called ” SpecialPermissions ” that takes a hashtable of key-value pairs of type string and SPRoleType. Setting the SpecialPermissions property  in your code will strip out all existing permissions inherited from the parent list(Workflow Task List) and only adds permissions for each pair you added to the hashtable .

   private void createTask(object sender, EventArgs e)
{
…….
CreateTask task1 = sender as CreateTask;
HybridDictionary permsCollection = new HybridDictionary();
permsCollection.Add(taskProps.AssignedTo, SPRoleType.Administrator);
task1.SpecialPermissions = permsCollection;
}

Alternatively, If you are using “CreateTaskWithContentType” activity, you have one other option : The event handler bound to your content type. Here is how I’d do it:

1) I create the Task using “CreateTaskWithContentType” activity from my workflow. Obviously, I already have a content type in place.

2) I have also attached an event handler to the content type I use above. Oops! I forgot to say that there is no way you can visually do that (except this one), so I use a programmatic approach to assign an event handler to my content type when the feature that contains my content type get activated.

3) So I have to create a Feature that contains the content type (MyTaskContentType.xml is content type definition which I will skip for the sake of code brevity)

<?xml version=”1.0″ encoding=”utf-8″ ?>
<Feature Id=”5FED1202-C6B8-453e-9EC0-F328655ED4DC”
Title=”My Workflow Task Content Types”
Description=”….”
Version=”12.0.0.0″
Scope=”Site”
xmlns=”http://schemas.microsoft.com/sharepoint/
ReceiverAssembly=”DevHorizon.SharePoint.Workflows, Version=1.0.0.0, Culture=neutral, PublicKeyToken=207a12b7817b805c”
ReceiverClass=” “DevHorizon.SharePoint.Workflows.AddConentTypesEventHanlders”>
<ElementManifests>
<ElementManifest Location=”DivRepTask.xml” />
<ElementManifest Location=”HRAdminTask.xml” />
</ElementManifests>
</Feature>

4) I create a feature receiver class for this feature, I get a reference to the content type and attach the event handler to it programmatically:

public override void FeatureActivated(SPFeatureReceiverProperties properties)
{
using (SPSite siteCollection = (SPSite) properties.Feature.Parent)
{
using (SPWeb web = siteCollection.OpenWeb())
{
System.Reflection.Assembly a = System.Reflection.Assembly.GetExecutingAssembly(); SPContentType ctMyTask = web.ContentTypes[“My Conent Type”];
ctMyTask.EventReceivers.Add(SPEventReceiverType.ItemAdded, a.FullName,”MyTaskItemEventReceiver”);
ctMyTask.Update();
web.Update();

}
}
}

5) Now,I need to create an event handler class named “MyTaskItemEventReceiver” that inherits from SPItemEventReceiver.Make sure you decorate this class with the right attributes to target to the featureId that contains your content type and the content type Id that you are writing this event handler for. You also need a unique GUID for your event handler

[TargetContentType(“feature id goes here”, “content type id goes here”)]
[Guid(“and here is the unique id for your enevnt handler”)]

6) In ItemAdded method of your event handler add the following code:

DisableEventFiring();
SPListItem listItem = properties.ListItem;
try
{
listItem.BreakRoleInheritance(false);
listItem.Update();
listItem =SetItemLevelPermissions(listItem.Web, listItem, SPRoleType.Contributor, listItem[“Assigned To”].ToString());
listItem.Update();
}
catch (Exception ex)
{
//Add error handling code here
}
EnableEventFiring();

7) And finally add this helper method somewhere accessible from within your event handler

public static SPListItem SetItemLevelPermissions(SPWeb setSPWeb, SPListItem setListItem, SPRoleType setRoleType, string assignedTo)
{
int index = assignedTo.IndexOf(‘;’);
int id = Int32.Parse(assignedTo.Substring(0, index));
SPUser user = setSPWeb.SiteUsers.GetByID(id);
SPRoleDefinition roleDefinition = setSPWeb.RoleDefinitions.GetByType(setRoleType);
SPRoleAssignment roleAssignment = new SPRoleAssignment(user.LoginName, string.Empty, string.Empty, string.Empty);
roleAssignment.RoleDefinitionBindings.Add(roleDefinition);
setListItem.RoleAssignments.Add(roleAssignment);
return setListItem;
}

Now when your workflow creates a task, its item level permission will be broken and set to “assigned to” field.Happy ending!

Categories: MOSS 2007 Tags:

Programming under the influence

September 26th, 2007 2 comments

Let’s say you have a list (i.e.task list ) for which you need to capture ItemAdded event using an event handler and You have to do something unusual like the following:

[SharePointPermission(SecurityAction.LinkDemand, ObjectModel = true)]
public override void ItemAdded(SPItemEventProperties properties)

        {
            SPListItem testtask = properties.ListItem.ParentList.Items.Add();
            testtask[“Title”] = “You are fired!::” + DateTime.Now.ToString();
            testtask[“Due Date”] = DateTime.Now;
            testtask[“Priority”] = “(1) High”;
            testtask.Update();
        }

Well,You are trapped in a loop. How? Somebody adds  a task and your event handler fires and adds another task and  so on and so forths. I know this may sound stupid to do, by my point is something else here. Event handler OM is now smart enough not to let you get trapped in an infinite loop ,so recursion depth in such case is set to 10 (for itemAdded) and looping only occurs 10 times. It is really cool! Look at the picture below:

 If you really have to do such a thing then at least use DisableEventFiring() and EnableEventFiring(); to stop the event handler from firing 10 times. 

[SharePointPermission(SecurityAction.LinkDemand, ObjectModel = true)]
public override void ItemAdded(SPItemEventProperties properties)
    {
       DisableEventFiring();
       SPListItem testtask = properties.ListItem.ParentList.Items.Add();
       testtask[“Title”] = “You are fired!::” + + DateTime.Now.ToString();
       testtask[“Due Date”] = DateTime.Now;
       testtask[“Priority”] = “(1) High”;
       testtask.Update();
       EnableEventFiring();
     }

Categories: MOSS 2007 Tags:

Plan your three Must-Attend conferences in 2008

September 17th, 2007 No comments

1) Microsoft Office System Developer Conference 2008 | San Jose, California | Feb 10-13 2008
I was just informed that the official site for this has gone live. I think this is the first time ever this conference is open to the public, so everyone is invited. This is a fantastic opportunity for architects, developers, industry experts, and Microsoft insiders to come together to discuss various developing solutions in Office System.
2) SharePoint 2008 conference | Seattle,WA | March 3-6,2008 Take advantage of  the “early bird” special discount. Register Today
3) Tech·Ed | Orlando, FL | June 9-13, 2008
Be among the first to get conference information, session agendas, and preregistration details by signing in the Tech·Ed 2008 Guestbook.If you live in Greater Toronto Area, I’d highly recommend you to mark your calendar for 20th of October for Toronto SharePoint Camp. I can’t wait to see you all there! 

Categories: General, MOSS 2007 Tags: