Condividi tramite


Code Sample: Send a Link to Your Colleagues Activity Event

Applies to: SharePoint Server 2010

In this article
Introduction to SharePoint Activities
Creating and Publishing Activity Events
Building and Running the Sample

This sample demonstrates how to create ActivityType objects and ActivityEvent objects, and how to insert new ActivityEvent objects into the newsfeeds of users. It creates a simple form that enables users to share links with their colleagues in a few simple steps. The user interface includes a pop-up box that users can use to insert URLs and comments in their colleagues' newsfeeds.

Sample code provided by:MVP Contributor Mathew McDermott, Catapult Systems | MVP Contributor Andrew Connell, Critical Path Training, LLC

Install this code sample on your own computer by downloading the Microsoft SharePoint 2010 Software Development Kit (SDK) or by downloading the sample from Code Gallery. If you download the SharePoint 2010 SDK, the sample is installed in the following location on your file system: C:\Program Files\Microsoft SDKs\SharePoint 2010\Samples\Social Data and User Profiles.

Introduction to SharePoint Activities

Microsoft SharePoint Server 2010 provides for the consolidation of monitored events and notifications through the Newsfeed on the My Site Host. This new page and new feature enables the user to focus on a single location for updates from around the enterprise. The user can "opt in" to the news and the friendly display of information, formatted with the picture of the user and links to the associated information. This makes the Newsfeed a useful location for additional application notification. Each Newsfeed item displays the contents of an ActivityEvent object.

Activity Templates

The design for the activity begins with a simple sentence. For example, if we create a new ActivityType object that indicates that a colleague wants to share a link with you, the sentence looks similar to the following:

Jim Brown has sent you the following link of interest: Great SharePoint Article

The variable portion of the activity is Jim Brown and the link text is Great SharePoint Article. In the development of an activity type template, you substitute the variable portions with a token, as in the following sample template:

{Publisher} has sent you the following link of interest: {Link}

The custom application that you develop populates the tokens with the necessary information. The template text is deployed to the servers as a resource file, to facilitate localization into your desired target languages. For more information about creating and using resource files, see Working with Resource Files.

Deploying This Solution

Table 1 details the components that are required for this activity feed solution.

Table 1. Required components of the activity feed solution

Project Asset

Destination

Project Assembly (*.dll)

Global Assembly Cache

Activity Template Resource Files (*.resx)

Resources Directory

Application Page (*.aspx)

Template/Layouts/MSDN

After the activity assets are deployed, the new ActivityType object and the associated ActivityTemplate object must be created by an event receiver that associates the ActivityType object and the ActivityTemplate object with the resource file. The sample project performs this action when the solution is deployed.

private void SetupCustomActivity(SPSite site)
{
  try
  {
    //Get a Service Context from the site.
    SPServiceContext context = SPServiceContext.GetContext(site);
    //We need a User Profile Manager to work with Activities.
    UserProfileManager upm = new UserProfileManager(context);
    //Grab the current user's profile.
    UserProfile p = upm.GetUserProfile(true);

    Debug.WriteLine("Got the User Profile for: " + p.DisplayName);
    //Grab an activity manager.
    ActivityManager am = new ActivityManager(p, context);
    //Ensure that we have permission to do this.
    bool hasrights = am.PrepareToAllowSchemaChanges();
    Debug.WriteLine("Does installer have Admin rights to change the schema? " + hasrights);

    // Create our activity application.
    Debug.WriteLine("Create our Activity Application");
    ActivityApplication app = am.ActivityApplications["Send Link to Colleague"];
    if (app == null)
    {
      app = am.ActivityApplications.Create("Send Link to Colleague");
      app.Commit();
    }
    Debug.WriteLine("Send Link to Colleague App id: " + app.ApplicationId);

    //Create our Colleagues Activity Type, but first check to see whether it already exists.
    Debug.WriteLine("Activity Type: SendColleagueUrlNote");
    ActivityType activityType = app.ActivityTypes["SendColleagueUrlNote"];
    if (activityType == null)
    {
      activityType = app.ActivityTypes.Create("SendColleagueUrlNote");
      activityType.ActivityTypeNameLocStringResourceFile = resFile;
      activityType.ActivityTypeNameLocStringName = "ActivityFeed_SendColleagueUrlNote_Type_Display";
      activityType.IsPublished = true;
      activityType.IsConsolidated = true;
      activityType.Commit();
    }
    //SendColleagueUrlNote Activity Template.
    Debug.WriteLine("SendColleagueUrlNote Activity Single Value Template");
    ActivityTemplate urlTemplateSV = activityType.ActivityTemplates[ActivityTemplatesCollection.CreateKey(false)];
    if (urlTemplateSV == null)
    {
      urlTemplateSV = activityType.ActivityTemplates.Create(false);
      urlTemplateSV.TitleFormatLocStringResourceFile = resFile;
      urlTemplateSV.TitleFormatLocStringName = "ActivityFeed_SendColleagueUrlNote_SV_Template";
      urlTemplateSV.Commit();
     }

Creating and Publishing Activity Events

The design goal of the sample application is to provide users with a simple form that enables them to share links with their colleagues in a few simple steps. Modeled after the Tags and Notes feature, the Send Link to Colleagues feature adds a menu item to the personal menu, as shown in Figure 1.

Figure 1. Send link to Colleagues menu detail

Send link to Colleagues menu detail

After the user selects this menu item, the Send link to my Colleagues form displays.

Figure 2. Send Link to Colleague page

Send Link to Colleague page

The ECMAScript (JavaScript, JScript) used to start the form supplies the URL of the current window and passes it as a parameter to the form, which displays in the debug section the values that it is passing. To send the custom activity to colleagues, the user adds a note in the text box and clicks Post.

Creating Activities

The sample application creates activities for the user in the CreateActivity method. This method takes as arguments the User Profile of the activity owner and the User Profile of the activity publisher. It then creates a MinimalPerson object for each user, and then passes both of these objects to the CreateActivityEvent method. The activity link is constructed from the URL and the note that the user supplied.

public ActivityEvent CreateActivity(UserProfile ownerProfile, UserProfile publisherProfile, ActivityType activityType, string linkText, string linkUrl)
{
  //Get the Owner and Publisher Profile.
  Entity ownerMP = new MinimalPerson(ownerProfile).CreateEntity(activityManager);
  Entity publisherMP = new MinimalPerson(publisherProfile).CreateEntity(activityManager);

  //Create the activity and set some properties.
  ActivityManager am = new ActivityManager();
  ActivityEvent activityEvent = ActivityEvent.CreateActivityEvent(am, activityType.ActivityTypeId, ownerMP, publisherMP);

  Debug.WriteLine("Got my ActivityEvent");
  activityEvent.Name = activityType.ActivityTypeName;
  activityEvent.ItemPrivacy = (int)Privacy.Public;
  activityEvent.Owner = ownerMP;
  activityEvent.Publisher = publisherMP;
           
  //Create the link for the activity.
  Link link = new Link();
  link.Href = linkUrl;
  link.Name = linkText;
  activityEvent.Link = link;
  //Save your work.
  activityEvent.Commit();

  Debug.WriteLine("End of Activity event: " + activityType.ActivityTypeName);
  return activityEvent;
}

Sending the Activity Event to the User’s Colleagues

This solution uses the batch methods supplied by the ActivityFeedGatherer object to multicast the activity to all of the user’s colleagues.

//Send activity to the Owner’s Colleagues.
//Create Dictionary objects that will be output parameters for the batch gatherer methods.
  Dictionary<long, MinimalPerson> owners;
  Dictionary<long, List<MinimalPerson>> colleaguesOfOwners;
//Create List objects that contain the ActivityEvent and its publisher.
  List<ActivityEvent> events = new List<ActivityEvent>();
  events.Add(activityEvent);
  List<long> publishers = new List<long>();
  publishers.Add(activityEvent.Owner.Id);
  ActivityFeedGatherer.GetUsersColleaguesAndRights(activityManager, publishers, out owners, out colleaguesOfOwners);
  Dictionary<long, List<ActivityEvent>> eventsConsolidatedPerOwner;
  ActivityFeedGatherer.MulticastActivityEvents(activityManager, events, colleaguesOfOwners, out eventsConsolidatedPerOwner);
  List<ActivityEvent> eventsConsolidated;
  ActivityFeedGatherer.CollectActivityEventsToConsolidate(eventsConsolidatedPerOwner, out eventsConsolidated);
  ActivityFeedGatherer.BatchWriteActivityEvents(eventsConsolidated, 0, events.Count);

Building and Running the Sample

The following steps demonstrate how to test this project on your development or test site.

To build the sample

  1. Create a folder named Microsoft.SDK.Server.Samples, and then unzip the MSDN SharePoint 2010 Activity Feeds - Code.zip file in it.

  2. Start Visual Studio 2010, and then open the SendColleagueURLNote.sln file that is in the folder that you created in step 1.

  3. In the Properties window, specify the site URL value of the absolute address of your development or test site (for example, http://mysite/. Ensure that you include the closing forward slash.

  4. In the SendColleagueURLNote.EventReceiver.cs file, in the SendColleagueURLNoteEventReceiver method, specify the URL for your SharePoint Central Administration site.

  5. If they are not already present, add references to the following assemblies to the project:

    • Microsoft.SharePoint.dll

    • Microsoft.Office.Server.dll

    • Microsoft.Office.Server.UserProfiles.dll

  6. Add the resource files in the Resources directory (URLNote.en-US.resx and URLNote.resx) to your \Program Files\Common Files\Microsoft Shared\Web Server Extensions\14\Resources directory.

  7. On the Build menu, select Deploy Solution. After the build is complete, the application page is installed on your development or test site.

To run the sample

  1. After the solution is built and deployed, go to a page on your SharePoint Server 2010 site. On the drop-down menu located at the top-right of the page, select Send Link to Colleagues.

  2. Type an optional note in the text box, and then click Post to insert the note and the link in your colleagues’ newsfeeds.

See Also

Reference

Microsoft.Office.Server.ActivityFeed

Concepts

Using Activity Feeds with the Object Model