Skip to content

Commit

Permalink
Finish receive messages tutorial
Browse files Browse the repository at this point in the history
  • Loading branch information
tylerlong committed Apr 8, 2016
1 parent b7882dd commit 2af6ab7
Show file tree
Hide file tree
Showing 2 changed files with 153 additions and 2 deletions.
155 changes: 153 additions & 2 deletions docs/mac/receive-messages.md
Original file line number Diff line number Diff line change
Expand Up @@ -107,7 +107,10 @@ var response = platform.Get(request);
var syncToken = response.GetJson().SelectToken("syncInfo.syncToken").ToString();
```

In the code above, we sent a request to the `message-sync` endpoint together with two query string items: `dateFrom` and `syncType`. `dateFrom` is self-explanatory, it means the start date of the messages. `syncType` has at least two possible values: `FSync` and `ISync`. The former is short for "Full Synchronization", the latter is short for "Incremental Synchronization".
In the code above, we sent a request to the `message-sync` endpoint together with two query string items: `dateFrom` and `syncType`.

- `dateFrom` is self-explanatory, it means the start date of the messages.
- `syncType` has at least two possible values: `FSync` and `ISync`. The former is short for "Full Synchronization", the latter is short for "Incremental Synchronization".

The last line of code: `var syncToken = response.GetJson().SelectToken("syncInfo.syncToken").ToString();` is to extract the `syncToken` from the response. `syncToken` is important because we need it to do incremental synchronization:

Expand All @@ -127,6 +130,154 @@ foreach(var m in ExtractMessages(response.GetJson())) {
}
```

In the code snippet above, we sent another request to the `message-sync` endpoint. Unlike last time, it's an incremental synchronization(Please note that `syncType` is `ISync`). We also sent the `syncToken` we saved as a query parameter. The `syncToken` is mandatory because the server needs it to know when we did the sync last time.

The new response also contains a `syncToken`, we saved it. Because next time we do incremental synchronization, we'd have to include it as a parameter to tell the server when we did the sync last time.

At the end of the code snippet, there is a `foreach` statement. We extracted all the messages from the response, and append them to the `consoleTextView` UI element.

OK, up to now you should understand the fundamentals to receiving messages. Let's go back to Xamarin Studio and finish the demo. Edit "ViewController.cs" to make it look like the following:

```csharp
using System;
using System.Collections.Generic;
using RingCentral.SDK;
using UIKit;

namespace MyTestApp
{
public partial class ViewController : UIViewController
{
private string syncToken;

public ViewController (IntPtr handle) : base (handle)
{
}

private Platform platform;
    private const string appKey = "appKey";
    private const string appSecret = "appSecret";
    private const string username = "username";
    private const string extension = "extension";
    private const string password = "password";
    private const string sandboxServer = "https://platform.devtest.ringcentral.com";
    // private const string productionServer = "https://platform.ringcentral.com";
private void Authenticate ()
{
if (platform == null) {
var sdk = new SDK (appKey, appSecret, sandboxServer, "MyTestApp", "1.0.0");
platform = sdk.GetPlatform ();
}
if (!platform.IsAuthorized ()) {
platform.Authorize (username, extension, password, true);
}
}

private void PrintAuthenticationStatus ()
{
if (platform != null && platform.IsAuthorized ()) {
Console.WriteLine ("App is authenticated");
} else {
Console.WriteLine ("App is not authenticated");
}
}

public override void ViewDidLoad ()
{
base.ViewDidLoad ();
// Perform any additional setup after loading the view, typically from a nib.
// do the authentication
Authenticate ();

// make sure authentication is successful
PrintAuthenticationStatus ();


// get initial syncToken
var request = new RingCentral.SDK.Http.Request("/restapi/v1.0/account/~/extension/~/message-sync",
new List<KeyValuePair<string, string>> {
new KeyValuePair<string, string>("dateFrom", DateTime.UtcNow.AddHours(-1).ToString("o")),
new KeyValuePair<string, string>("syncType", "FSync"),
});
var response = platform.Get(request);
syncToken = response.GetJson().SelectToken("syncInfo.syncToken").ToString();


// subscribe
var sub = new RingCentral.Subscription.SubscriptionServiceImplementation () { _platform = platform };
sub.AddEvent ("/restapi/v1.0/account/~/extension/~/message-store");
sub.Subscribe (ActionOnNotification, null, null);
}

void ActionOnNotification (object message)
{
var request = new RingCentral.SDK.Http.Request("/restapi/v1.0/account/~/extension/~/message-sync",
new List<KeyValuePair<string, string>> {
new KeyValuePair<string, string>("syncToken", syncToken),
new KeyValuePair<string, string>("syncType", "ISync"),
});
var response = platform.Get(request);
syncToken = response.GetJson().SelectToken("syncInfo.syncToken").ToString();

foreach(var m in ExtractMessages(response.GetJson())) {
InvokeOnMainThread(() => {
consoleTextView.Text += "\n" + m;
});
}
}

private HashSet<string> ids = new HashSet<string> ();
private List<string> ExtractMessages(Newtonsoft.Json.Linq.JObject jo) {
var result = new List<string> ();

foreach (var jt in jo.SelectToken ("records")) {
var subject = jt.SelectToken ("subject").ToString ();
var direction = jt.SelectToken ("direction").ToString ();
var id = jt.SelectToken ("id").ToString ();
if (!ids.Contains (id)) {
result.Add (string.Format ("{0} : {1}", direction, subject));
ids.Add (id);
}
}
result.Reverse ();

return result;
}

public override void DidReceiveMemoryWarning ()
{
base.DidReceiveMemoryWarning ();
// Release any cached data, images, etc that aren't in use.
}

partial void SendMessage (Foundation.NSObject sender)
{
var requestBody = new Dictionary<string, dynamic> {
{ "text", messageTextField.Text },
{ "from", new Dictionary<string, string>{ { "phoneNumber", username } } }, {
"to",
new List<Dictionary<string, string>> { new Dictionary<string, string> { {
"phoneNumber",
receiverNumberTextField.Text
}
}
}
}
};
var jsonBody = Newtonsoft.Json.JsonConvert.SerializeObject (requestBody);
var request = new RingCentral.SDK.Http.Request ("/restapi/v1.0/account/~/extension/~/sms", jsonBody);
var response = platform.Post (request);
Console.WriteLine ("Sms sent, status code is: " + response.GetStatus ());
}
}
}
```

Let's run and test it. Please note that, you need two accounts to test both send and receive messages. If everything is all right, you should see something similar to this:

![Chat Testing](/screenshots/chat-testing.png)


[Source code](https://github.com/tylerlong/ringcentral-csharp-tutorials/tree/master/mac/receive-messages) for this tutorial is available.
OK, it's done. This tutorial contains quite a lot of content. If you cannot follow it, I suggest you to download the [source code](https://github.com/tylerlong/ringcentral-csharp-tutorials/tree/master/mac/receive-messages) and play with it inside Xamarin Studio.
Binary file added docs/screenshots/chat-testing.png
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.

0 comments on commit 2af6ab7

Please sign in to comment.