In this lab, you will use the Office 365 APIs for to read and write social data to your Yammer networks.
- 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.
- 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.
- You must have created and joined a Yammer network with your Organizational account at https://www.yammer.com/msacademy.onmicrosoft.com/?show_signup=true.
In this exercise, you will add Yammer code, web parts amd apps to your SharePoint site.
- Log into Yammer and get the feed embed information.
- Navigate to Yammer [https://www.yammer.com] and log in with your Organizational Account.
- Click the All Company group.
- In the Access Options click Embed this group in your site.
- Copy the code and save it for use later.
- Embed a Yammer feed into SharePoint online.
- Log into your SharePoint online site with your Organizational Account.
- Place the home page in Edit mode.
- Click Insert/Embed Code.
- Paste the code you copied from Yammer.
- Click Insert.
- Verify the Yammer feed displays.
- Use the Yammer web part.
- Click Site Contents.
- Click Add an App.
- Click SharePoint Store.
- Type Yammer App for SharePoint in the search box and search the available apps.
- Click on the Yammer App for SharePoint app.
- Click Add It.
- Click Trust It.
- Go to the home page of your SharePoint site.
- CLick Insert/App Part.
- Select the Yammer Feed app part.
- Click Add.
- Click Home Feed.
- Enter your network name.
- Click Save.
- Save the changes to the home page.
- Use the Social Nucleus app.
- Click Site Contents.
- Click Add an App.
- Click SharePoint Store.
- Type Nucleus in the search box and search the available apps.
- Click on the Social Nucleus app.
- Click Add It.
- Click Trust It.
- When the app installs, launch it.
- Pick Yammer as your social platform for the app.
- If prompted, log into Yammer with your Organizational Account.
- Use the app to navigate your relationships in Yammer.
In this exercise, you will use the Yammer JavaScript SDK to search Yammer data.
- Create a new ASP.NET Web Forms application.
- Start Visual Studio 2013.
- Select File/New/Project.
- In the New Project dialog, select Templates/Visual C#/Web.
- Name the new project YammerSDKApp.
- Click OK.
- 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.
- 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.
- Register a new app
- Open a browser to https://www.yammer.com/client_applications
- Click Register New App.
- Fill out the form with information about the new app.
- Click Continue.
- Copy the Client ID and save it for later use.
- Click Basic Info.
- Enter the URL of the YammerSDKApp you saved earlier into the Redirect URI field.
- Also, enter the URL of the YammerSDKApp you saved earlier into the JavaScript Origins field.
- Click Save.
- Build the authentication code.
- In the Solution Explorer, double click Default.aspx to open the file.
- 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>
- In the Solution Explorer, right click the Scripts folder and select Add/JavaScript File.
- Name the new file App.js.
- Click OK.
- 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.");
}
});
- In the Solution Explorer, right click the Site.Master.
- 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>
- 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.
- Press F5 to debug your application.
- When the application starts, click Login with Yammer.
- Click Allow.
- Verify that you receive the "Welcome to Yammer!" message.
- Stop debugging.
- Build the Search Code
- In the Solution Explorer, double click Default.aspx to open the file.
- 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>
- 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");
}
});
});
});
- Test the search functionality.
- Press F5 to debug your application.
- Enter a search term.
- Click Search Yammer.
- Verify that results are returned.
In this exercise, you will create an application that uses the OpenGraph protocol to create activities in Yammer.
- Create a new ASP.NET Web Forms application.
- Start Visual Studio 2013.
- Select File/New/Project.
- In the New Project dialog, select Templates/Visual C#/Web.
- Name the new project YammerOGApp.
- Click OK.
- 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.
- 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.
- Right click the References node and select Add Reference.
- Add references to the following assemblies:
System.Runtime.Serialization
System.Net.Http
- Register a new app
- Open a browser to https://www.yammer.com/client_applications
- Click Register New App.
- Fill out the form with information about the new app.
- Click Continue.
- Copy the Client ID and save it for later use.
- Click Basic Info.
- Enter the URL of the YammerOGApp you saved earlier into the Redirect URI field.
- Click Save.
- Code the Yammer Authentication
- In the Solution Explorer, open Default.aspx for editing.
- In the Page directive, add the Async attribute to support asynchronous operations as shown
- In the Solution Explorer, open Default.aspx.cs for editing.
- 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;
- 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";
- 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);
}
- 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);
}
}
}
}
- Code the creation of a new activity.
- In the Solution Explorer, open Default.aspx for editing.
- 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>
- Right click the YammerOGApp project and select Add/Class.
- Name the new class ActivityEnvelope.cs.
- Add the following using statements to the top of the file
using System.IO;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Json;
- 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
}
- In the Solution Explorer, open Default.aspx.cs for editing.
- 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());
}
- Test the application.
- Start Fiddler to trace the calls made by your app.
- In Visual Studio 2013, press F5 to start debugging your app.
- When the application starts, look for the call to the access_token.json endpoint in Fiddler.
- Review the response to see the returned access token.
- Edit the form data in the application to use your name and your Yammer e-mail account.
- Click Create Activity.
- When the post completes, look for the call to the activity.json endpoint in Fiddler.
- Review the request to see the activity data.
- Log into https://www.yammer.com
- Examine your Recent Activity to see the new activity post.
- Hover over the activity and open it from the link in the corresponding flyout.
Congratulations! You have completed working with the Yammer APIs.