Skip to content

Latest commit

 

History

History
547 lines (481 loc) · 20.9 KB

File metadata and controls

547 lines (481 loc) · 20.9 KB

Office 365 APIs for Yammer Services

In this lab, you will use the Office 365 APIs for to read and write social data to your Yammer networks.

Prerequisites

  1. You must have an Office 365 tenant and Windows Azure subscription to complete this lab. If you do not have one, the lab for O3651-7 Setting up your Developer environment in Office 365 shows you how to obtain a trial.
  2. You must have your default social experience set to Yammer for your Office 365 tenant. This was accomplished in the lab for O3651-7 Setting up your Developer environment in Office 365. Note that it can take up to 30 minutes to change the SharePoint social experience.
  3. You must have created and joined a Yammer network with your Organizational account at https://www.yammer.com/msacademy.onmicrosoft.com/?show_signup=true.

Exercise 1: Yammer code, app parts, and apps in SharePoint online

In this exercise, you will add Yammer code, web parts amd apps to your SharePoint site.

  1. Log into Yammer and get the feed embed information.
  2. Navigate to Yammer [https://www.yammer.com] and log in with your Organizational Account.
  3. Click the All Company group.
  4. In the Access Options click Embed this group in your site.
  5. Copy the code and save it for use later.
  6. Embed a Yammer feed into SharePoint online.
  7. Log into your SharePoint online site with your Organizational Account.
  8. Place the home page in Edit mode.
  9. Click Insert/Embed Code.
  10. Paste the code you copied from Yammer.
  11. Click Insert.
  12. Verify the Yammer feed displays.
  13. Use the Yammer web part.
  14. Click Site Contents.
  15. Click Add an App.
  16. Click SharePoint Store.
  17. Type Yammer App for SharePoint in the search box and search the available apps.
  18. Click on the Yammer App for SharePoint app.
  19. Click Add It.
  20. Click Trust It.
  21. Go to the home page of your SharePoint site.
  22. CLick Insert/App Part.
  23. Select the Yammer Feed app part.
  24. Click Add.
  25. Click Home Feed.
  26. Enter your network name.
  27. Click Save.
  28. Save the changes to the home page.
  29. Use the Social Nucleus app.
  30. Click Site Contents.
  31. Click Add an App.
  32. Click SharePoint Store.
  33. Type Nucleus in the search box and search the available apps.
  34. Click on the Social Nucleus app.
  35. Click Add It.
  36. Click Trust It.
  37. When the app installs, launch it.
  38. Pick Yammer as your social platform for the app.
  39. If prompted, log into Yammer with your Organizational Account.
  40. Use the app to navigate your relationships in Yammer.

Exercise 2: JavaScript SDK

In this exercise, you will use the Yammer JavaScript SDK to search Yammer data.

  1. Create a new ASP.NET Web Forms application.
  2. Start Visual Studio 2013.
  3. Select File/New/Project.
  4. In the New Project dialog, select Templates/Visual C#/Web.
  5. Name the new project YammerSDKApp.
  6. Click OK.
  7. In the New ASP.NET Project dialog: 1. Click Web Forms. 2. Click Change Authentication. 3. Select No Authentication. 4. Click OK.
    5. Click OK.
  8. In the Solution Explorer, click the YammerSDKApp project and note the value of the URL in the Properties window. Save this value for later when you register a new app with Yammer.
  9. Register a new app
  10. Open a browser to https://www.yammer.com/client_applications
  11. Click Register New App.
  12. Fill out the form with information about the new app.
  13. Click Continue.
  14. Copy the Client ID and save it for later use.
  15. Click Basic Info.
  16. Enter the URL of the YammerSDKApp you saved earlier into the Redirect URI field.
  17. Also, enter the URL of the YammerSDKApp you saved earlier into the JavaScript Origins field.
  18. Click Save.
  19. Build the authentication code.
  20. In the Solution Explorer, double click Default.aspx to open the file.
  21. Replace the code in the BodyContent placeholder with the following:
  <div style="margin: 50px">
      <div class="row">
          <div class="col-md-12">
              <span id="yammer-login"></span>
          </div>
      </div>
  </div>
  1. In the Solution Explorer, right click the Scripts folder and select Add/JavaScript File.
  2. Name the new file App.js.
  3. Click OK.
  4. Add the following code to support the Yammer login button.
yam.connect.loginButton("#yammer-login", function (response) {

    if (response.authResponse) {
        $("#yammer-login").text("Welcome to Yammer!");
    }
    else {
        $("#yammer-login").text("Not logged in.");
    }

});
  1. In the Solution Explorer, right click the Site.Master.
  2. Add the following script references just before the closing head tag.
  <script type="text/javascript" data-app-id="YOUR CLIENT ID" src="https://c64.assets-yammer.com/assets/platform_js_sdk.js"></script>
  <script src="Scripts/App.js"></script>
  1. Test the login functionality.

NOTE: Internet Explorer places Yammer.com URLs in the Intranet zone by default. This can cause log in failures if your app is in a different zone. For this exercise, either place Yammer.com in the Trusted zone or use a browser, like Chrome, that does not have security zones.

  1. Press F5 to debug your application.
  2. When the application starts, click Login with Yammer.
  3. Click Allow.
  4. Verify that you receive the "Welcome to Yammer!" message.
  5. Stop debugging.
  6. Build the Search Code
  7. In the Solution Explorer, double click Default.aspx to open the file.
  8. Add the following code inside the main div in the BodyContent placeholder:
  <div class="row">
      <div class="col-md-4"></div>
      <div class="col-md-2">
          <input type="text" id="searchText" />
      </div>
      <div class="col-md-2">
          <input type="button" id="searchButton" value="Search Yammer" />
      </div>
      <div class="col-md-4"></div>
  </div>
  <div class="row" id="searchResults">
  </div>
  1. Add the following code to the App.js file to perform search:
jQuery(function () {

  $("#searchButton").click(function () {

      yam.getLoginStatus(function (response) {

          if (response.authResponse) {

              yam.platform.request({
                  url: "https://api.yammer.com/api/v1/search.json",
                  method: "GET",
                  data: {
                      "search": $("#searchText").val(),
                      "page": 1,
                      "num_per_page": 20
                  },
                  success: function (data) {
                      $("#searchResults").html("<div class='col-md-12'><h3>Search Results</h3></div>");
                      for (var i = 0; i < data.messages.messages.length; i++) {
                          $("#searchResults").append("<div class='col-md-12'>" + data.messages.messages[i].body.rich + "</div>");
                      }
                  },
                  error: function (err) {
                      alert(JSON.stringify(err));
                  }
              })

          }
          else {
              alert("You are logged out of Yammer");
          }

      });

  });

});
  1. Test the search functionality.
  2. Press F5 to debug your application.
  3. Enter a search term.
  4. Click Search Yammer.
  5. Verify that results are returned.

Exercise 3: OpenGraph Protocol

In this exercise, you will create an application that uses the OpenGraph protocol to create activities in Yammer.

  1. Create a new ASP.NET Web Forms application.
  2. Start Visual Studio 2013.
  3. Select File/New/Project.
  4. In the New Project dialog, select Templates/Visual C#/Web.
  5. Name the new project YammerOGApp.
  6. Click OK.
  7. In the New ASP.NET Project dialog: 1. Click Web Forms. 2. Click Change Authentication. 3. Select No Authentication. 4. Click OK.
    5. Click OK.
  8. In the Solution Explorer, click the YammerOGApp project and note the value of the URL in the Properties window. Save this value for later when you register a new app with Yammer.
  9. Right click the References node and select Add Reference.
  10. Add references to the following assemblies:
System.Runtime.Serialization
System.Net.Http
  1. Register a new app
  2. Open a browser to https://www.yammer.com/client_applications
  3. Click Register New App.
  4. Fill out the form with information about the new app.
  5. Click Continue.
  6. Copy the Client ID and save it for later use.
  7. Click Basic Info.
  8. Enter the URL of the YammerOGApp you saved earlier into the Redirect URI field.
  9. Click Save.
  10. Code the Yammer Authentication
  11. In the Solution Explorer, open Default.aspx for editing.
  12. In the Page directive, add the Async attribute to support asynchronous operations as shown
  13. In the Solution Explorer, open Default.aspx.cs for editing.
  14. Add the following using statements at the top of the file:
using System.Text;
using System.Xml;
using System.Xml.Linq;
using System.Runtime.Serialization.Json;
using System.Net.Http;
using System.Net.Http.Headers;
  1. Add the following constants to the top of the class file.
      public const string ClientId = "YOUR APP CLIENT ID";
      public const string RedirectUri = "YOUR APP REDIRECT URI";
      public const string ClientSecret = "YOUR APP SECRET";
  1. Add the following helper functions
      private static XElement Json2Xml(string json)
      {
          using (XmlDictionaryReader reader = JsonReaderWriterFactory.CreateJsonReader(
              Encoding.UTF8.GetBytes(json),
              XmlDictionaryReaderQuotas.Max))
          {
              return XElement.Load(reader);
          }

      }

      public static void SaveInCache(string name, object value)
      {
          System.Web.HttpContext.Current.Session[name] = value;
      }

      public static object GetFromCache(string name)
      {
          return System.Web.HttpContext.Current.Session[name];
      }

      public static void RemoveFromCache(string name)
      {
          System.Web.HttpContext.Current.Session.Remove(name);
      }
  1. Replace the Page_Load method with the following code to retrieve an access token when the application starts.
      protected async void Page_Load(object sender, EventArgs e)
      {
          if (!Page.IsPostBack)
          {
              string accessToken = null;
              try
              {
                  accessToken = GetFromCache("AccessToken").ToString();
              }
              catch
              {
                  accessToken = null;
              }

              if (accessToken == null)
              {
                  string code = Request.QueryString["code"];

                  if (code == null)
                  {
                      Response.Redirect(
                          String.Format("https://www.yammer.com/dialog/oauth?client_id={0}&redirect_uri={1}",
                          ClientId, RedirectUri), false);
                  }
                  else
                  {

                      string requestUri = String.Format(
                          "https://www.yammer.com/oauth2/access_token.json?client_id={0}&client_secret={1}&code={2}",
                          ClientId, ClientSecret, code);


                      HttpClient client = new HttpClient();
                      HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, requestUri);
                      request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
                      HttpResponseMessage response = await client.SendAsync(request);
                      XElement root = Json2Xml(await response.Content.ReadAsStringAsync());
                      accessToken = root.Descendants("token").First().Value;
                      SaveInCache("AccessToken", accessToken);
                  }
              }

          }
      }
  1. Code the creation of a new activity.
  2. In the Solution Explorer, open Default.aspx for editing.
  3. Replace all of the content in the BodyContent with the following code:
  <div style="margin: 50px">
      <div class="form-horizontal">
          <div class="form-group">
              <div class="col-md-2">Actor Name</div>
              <div class="col-md-10">
                  <asp:TextBox ID="actorName" runat="server" Width="250" Text="Your name" />
              </div>
          </div>
          <div class="form-group">
              <div class="col-md-2">Actor E-mail</div>
              <div class="col-md-10">
                  <asp:TextBox ID="actorEmail" runat="server" Width="250" Text="Your e-mail" />
              </div>
          </div>
          <div class="form-group">
              <div class="col-md-2">Message</div>
              <div class="col-md-10">
                  <asp:TextBox ID="activityMessage" runat="server" Width="250" Text="Check out this great video on Microsoft Virtual Academy" />
              </div>
          </div>
          <div class="form-group">
              <div class="col-md-2">Object URL</div>
              <div class="col-md-10">
                  <asp:TextBox ID="objectUrl" runat="server" Width="250" Text="http://www.microsoftvirtualacademy.com/training-courses/introduction-to-office-365-development" />
              </div>
          </div>
          <div class="form-group">
              <div class="col-md-2">Object Title</div>
              <div class="col-md-10">
                  <asp:TextBox ID="objectTitle" runat="server" Width="250" Text="Introduction to Office 365 Development" />
              </div>
          </div>
          <div class="form-group">
              <div class="col-md-offset-2 col-md-10">
                  <asp:Button ID="createActivity" runat="server" CssClass="btn btn-default" Text="Create Activity" OnClick="createActivity_Click" />
              </div>
          </div>
      </div>
  </div>
  1. Right click the YammerOGApp project and select Add/Class.
  2. Name the new class ActivityEnvelope.cs.
  3. Add the following using statements to the top of the file
using System.IO;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Json;
  1. Replace the class definition with the following code that defines the appropriate JSON message for adding an activity using the OpenGraph protocol.
  [DataContract]
  public class ActivityEnvelope
  {

      public ActivityEnvelope()
      {
          Activity = new Activity();
      }

      [DataMember(Name = "activity")]
      public Activity Activity { get; set; }

      public string GetJSON()
      {
          MemoryStream ms = new MemoryStream();
          DataContractJsonSerializer s = new DataContractJsonSerializer(typeof(ActivityEnvelope));
          s.WriteObject(ms, this);
          ms.Position = 0;
          StreamReader sr = new StreamReader(ms);
          return sr.ReadToEnd();
      }
  }
  [DataContract(Name = "activity")]
  public class Activity
  {
      public Activity()
      {
          Actor = new Actor();
          Action = YammerOGApp.Action.create.ToString();
          OG_Object = new OG_Object();
          Message = string.Empty;
          users = new List<Actor>();
      }
      private List<Actor> users;

      [DataMember(Name = "actor")]
      public Actor Actor { get; set; }

      [DataMember(Name = "action")]
      public string Action { get; set; }

      [DataMember(Name = "object")]
      public OG_Object OG_Object { get; set; }

      [DataMember(Name = "message")]
      public string Message { get; set; }

      [DataMember(Name = "actors")]
      public Actor[] Users
      {
          get { return users.ToArray(); }
          set { users = value.ToList<Actor>(); }
      }

  }
  [DataContract(Name = "actor")]
  public class Actor
  {
      public Actor()
      {
          
          Name = string.Empty;
          Email = string.Empty;
      }

      [DataMember(Name = "name")]
      public string Name { get; set; }

      [DataMember(Name = "email")]
      public string Email { get; set; }
  }

  [DataContract(Name = "object")]
  public class OG_Object
  {

      public OG_Object()
      {
          Url = string.Empty;
          Title = string.Empty;
      }

      [DataMember(Name = "url")]
      public string Url { get; set; }

      [DataMember(Name = "title")]
      public string Title { get; set; }
  }
  public enum Action
  {
      create,
      update,
      delete,
      follow,
      like
  }
  1. In the Solution Explorer, open Default.aspx.cs for editing.
  2. Add the following code to post the new activity
      protected async void createActivity_Click(object sender, EventArgs e)
      {
          string accessToken = GetFromCache("AccessToken").ToString();

          string requestUri = "https://www.yammer.com/api/v1/activity.json";

          HttpClient client = new HttpClient();
          HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, requestUri);
          request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
          request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);

          ActivityEnvelope envelope = new ActivityEnvelope();
          envelope.Activity.Actor.Name = actorName.Text;
          envelope.Activity.Actor.Email = actorEmail.Text;
          envelope.Activity.Action = "create";
          envelope.Activity.Message = activityMessage.Text;
          envelope.Activity.OG_Object.Title = objectTitle.Text;
          envelope.Activity.OG_Object.Url = objectUrl.Text;
              
          string json = envelope.GetJSON();

          StringContent requestContent = new StringContent(json);
          request.Content = requestContent;
          request.Content.Headers.ContentType = new MediaTypeHeaderValue("application/json");

          HttpResponseMessage response = await client.SendAsync(request);
          XElement root = Json2Xml(await response.Content.ReadAsStringAsync());

      }
  1. Test the application.
  2. Start Fiddler to trace the calls made by your app.
  3. In Visual Studio 2013, press F5 to start debugging your app.
  4. When the application starts, look for the call to the access_token.json endpoint in Fiddler.
  5. Review the response to see the returned access token.
  6. Edit the form data in the application to use your name and your Yammer e-mail account.
  7. Click Create Activity.
  8. When the post completes, look for the call to the activity.json endpoint in Fiddler.
  9. Review the request to see the activity data.
  10. Log into https://www.yammer.com
  11. Examine your Recent Activity to see the new activity post.
  12. Hover over the activity and open it from the link in the corresponding flyout.

Congratulations! You have completed working with the Yammer APIs.