In my recent project UniShare I also added Yammer, because some of users asked for it and we use it also at Telefónica.
This post is all about how to connect you Yammer. First, we need to prepare our app. Five steps are needed for preparation.
First, we need an uri scheme to launch our app. To add an uri scheme, right click on the WMAppManifest.xml and click on ‘Open With…’ and select ‘XML (Text) Editor with Encoding’. After the ‘Tokens’ section, add your custom uri scheme within the ‘Extensions’ tag, for example:
public class UriMapper : UriMapperBase
{
public override Uri MapUri(Uri uri)
{
if (uri.ToString().Contains("yourapp-yammercallback"))
{
string decodedUri = HttpUtility.UrlDecode(uri.ToString());
int redirectUriIndex = decodedUri.IndexOf("yourapp-yammercallback");
string redirectParams = new Uri(decodedUri.Substring(redirectUriIndex)).Query;
// Map the OAuth response to the app page
return new Uri("/MainPage.xaml" + redirectParams, UriKind.Relative);
}
else return uri;
}
}
If you want to learn more about uri schemes, you can read my blog post here.
After clicking on continue, click on ‘Basic Info’ and add your uri scheme in the field ‘Redirect Uri’ and click on ‘Save’.
The fourth step starts with downloading the Yammer oAuth SDK for Windows Phone from Github. Open the solution and built all projects. After that, you can close the solution. Go back into your project, and right click on ‘References’, followed by ‘Add Reference’. Browse to the folder ‘\WPYammer-oauth-sdk-demo-master\windows-phone-oauth-sdk-demo-master\Yammer.OAuthSDK\Bin\Release’ and add the file with the name ‘Yammer.OAuthSDK.dll’.
The last step is to add your keys and the redirect uri in your app’s resource dictionary:
Now that our app is prepared, we can finally launch the oAuth process. First, we need to read our values from our app’s resource dictionary. Add this to the constructor to do so:
To kick the user out to the oAuth process, which happens in the phone’s browser, just add these two lines to your starting event (for example a button click event).
You might notice the app gets terminated. We have to do this because only this way, the uri scheme we added earlier can do its work. If the app is not terminated, the values cannot be passed into our app. Technically, it would also be possible to use the WebAuthenticationBroker on 8.1 for this. Sadly, the Yammer authorization pages do not work well with the WAB. The best way to use it with this library, is to kick the user to the browser.
Once we are receiving the values of the authentication, we can continue the authentication process to get the final access token. Add this code to your OnNavigatedTo event:
With this, you are handling all errors and events properly. If the call ends successfully, we are finally able to get our user’s data:
public void GetYammerCurrentUserData()
{
ShowProgressIndicator("connecting to Yammer...");
var baseUrl = new Uri("https://www.yammer.com/api/v1/users/current.json", UriKind.Absolute);
OAuthUtils.GetJsonFromApi(baseUrl,
onSuccess: response =>
{
//do something with the result (json string)
HideProgressIndicator();
}, onErrorResponse: errorResponse =>
{
Dispatcher.BeginInvoke(() =>
{
MessageBox.Show(errorResponse.OAuthError.ToString(), "Invalid operation", MessageBoxButton.OK);
HideProgressIndicator();
});
}, onException: ex =>
{
Dispatcher.BeginInvoke(() =>
{
MessageBox.Show(ex.ToString(), "Unexpected error", MessageBoxButton.OK);
HideProgressIndicator();
});
}
);
}
As you can see above, the result is a json string that contains the current user’s data. You can either create a class/model to deserialize the values or use anonymous deserialization methods.
One important point: you cannot publish your app outside your home network until it got approved as a global app by Yammer. I am waiting for nearly two weeks now for UniShare to get approved and hope it will become available for all soon.
As always, I hope this post is helpful for some of you.
The WAB needs some other code to work properly in a Silverlight project, and this post will got through all steps that are needed for this. I will reference to the above blog post where the methods itself are the same. I am just highlighting the changes that are needed in an 8.1 Silverlight project.
Preparing our App
First, we need to set up the proper continuation event in App.xaml.cs. We are doing this by adding this line of code in the App class:
public WebAuthenticationBrokerContinuationEventArgs WABContinuationArgs { get; set; }
This event is used when we are coming back to our app after the WAB logged the user in. The next step we need to do, is to tell our app that we have performed an authentication, and pass the values back to our main code. Unlike in the Runtime project, we are using the Application_ContractActivated event for this:
private void Application_ContractActivated(object sender, Windows.ApplicationModel.Activation.IActivatedEventArgs e)
{
var _WABContinuationArgs = e as WebAuthenticationBrokerContinuationEventArgs;
if (_WABContinuationArgs != null)
{
this.WABContinuationArgs = _WABContinuationArgs;
}
}
If you are upgrading from a WP8 project, you might have to add this event manually. Our app is now prepared to get results from the WAB.
Preparing oAuth
I am going to show you the oAuth process of Twitter to demonstrate the usage of the WAB. First, we need again the GetNonce(), GetTimeStamp () and GetSignature(string sigBaseString, string consumerSecretKey, stringoAuthTokenSecret=null) methods from my former blog post.
Performing the oAuth process
In the oAuth authentication flow, we need to obtain a so called Request Token, which allows our app to communicate with the API (in this case Twitter’s API).
Add the following code to your “connect to Twitter”- Button event:
Like in a Runtime app, we are getting the request token first (code is also in my former blog post), once we obtained the request token, we are able to get the oAuth token that enables us to get the final user access tokens.
Once the user has authenticated our app, we’ll receive the above mentioned oAuth tokens. To use them, add the following code to your OnNavigatedTo event:
var appObject = Application.Current as App;
if (appObject.WABContinuationArgs != null)
{
WebAuthenticationResult result = appObject.WABContinuationArgs.WebAuthenticationResult;
if (result.ResponseStatus == WebAuthenticationStatus.Success)
{
await GetTwitterUserNameAsync(result.ResponseData.ToString());
}
else if (result.ResponseStatus == WebAuthenticationStatus.ErrorHttp)
{
MessageBox.Show(string.Format("There was an error connecting to Twitter: \n {0}", result.ResponseErrorDetail.ToString()), "Sorry", MessageBoxButton.OK);
}
else
{
MessageBox.Show(string.Format("Error returned: \n{0}", result.ResponseStatus.ToString()), "Sorry", MessageBoxButton.OK);
HideProgressIndicator();
}
}
The WebAuthenticationResult now holds all values that we need to perform the final actions. To complete the oAuth process on Twitter, you can use the GetTwitterUserNameAsync(string webAuthResultResponseData) method from my former blog post. If you are not using other methods to control the result of the WAB, don’t forget to set appObject.WABContinuationArgs to null after you finished obtaining all tokens and data from Twitter (or other services).
As you can see, there are some structural differences in using the WAB when creating a Silverlight app, but we are also able to use a lot of code from my Runtime project. I hope this post is helpful for some of you to get the oAuth dance going.
In my next post, I will show you how to authenticate your app with Yammer (Microsoft’s enterprise social network).
As you might guess, I am still working on that app I mentioned in my last blog post. As I was diving deeper into the functions I want, I recognized that Twitter does a very well url handling server side.
Like the official documentation says, every url will be shortened with a link that has 22 characters (23 for https urls).
I was trying to write a RegEx expression to detect all the links that can be:
http
https
just plain domain names like “msicc.net”
This is not as easy as it sounds, and so I was a bit struggling. I then talked with @_MadMatt (follow him!) who has a lot of experience with twitter. My first attempt was a bit confusing as I did first only select http and https, then the plain domain names.
I found the names by their domain ending, but had some problems to get their length (which is essential). After the very helpful talk with Matthieu, I finally found a very good working RegEx expression here on GitHub.
I tested it with tons of links, and I got the desired results and it is now also very easy for me to get their length.
Recovering the amount of time I needed for this, I decided to share my solution with you. Here is the method I wrote:
public int CalculateTweetCountWithLinks(int currentCount, string text)
{
int resultCount = 0;
if (text != string.Empty)
{
//detailed explanation: https://gist.github.com/gruber/8891611
string pattern = @"(?i)\b((?:https?:(?:/{1,3}|[a-z0-9%])|[a-z0-9.\-]+[.](?:com|net|org|edu|gov|mil|aero|asia|biz|cat|coop|info|int|jobs|mobi|museum|name|post|pro|tel|travel|xxx|ac|ad|ae|af|ag|ai|al|am|an|ao|aq|ar|as|at|au|aw|ax|az|ba|bb|bd|be|bf|bg|bh|bi|bj|bm|bn|bo|br|bs|bt|bv|bw|by|bz|ca|cc|cd|cf|cg|ch|ci|ck|cl|cm|cn|co|cr|cs|cu|cv|cx|cy|cz|dd|de|dj|dk|dm|do|dz|ec|ee|eg|eh|er|es|et|eu|fi|fj|fk|fm|fo|fr|ga|gb|gd|ge|gf|gg|gh|gi|gl|gm|gn|gp|gq|gr|gs|gt|gu|gw|gy|hk|hm|hn|hr|ht|hu|id|ie|il|im|in|io|iq|ir|is|it|je|jm|jo|jp|ke|kg|kh|ki|km|kn|kp|kr|kw|ky|kz|la|lb|lc|li|lk|lr|ls|lt|lu|lv|ly|ma|mc|md|me|mg|mh|mk|ml|mm|mn|mo|mp|mq|mr|ms|mt|mu|mv|mw|mx|my|mz|na|nc|ne|nf|ng|ni|nl|no|np|nr|nu|nz|om|pa|pe|pf|pg|ph|pk|pl|pm|pn|pr|ps|pt|pw|py|qa|re|ro|rs|ru|rw|sa|sb|sc|sd|se|sg|sh|si|sj|Ja|sk|sl|sm|sn|so|sr|ss|st|su|sv|sx|sy|sz|tc|td|tf|tg|th|tj|tk|tl|tm|tn|to|tp|tr|tt|tv|tw|tz|ua|ug|uk|us|uy|uz|va|vc|ve|vg|vi|vn|vu|wf|ws|ye|yt|yu|za|zm|zw)/)(?:[^\s()<>{}\[\]]+|\([^\s()]*?\([^\s()]+\)[^\s()]*?\)|\([^\s]+?\))+(?:\([^\s()]*?\([^\s()]+\)[^\s()]*?\)|\([^\s]+?\)|[^\s`!()\[\]{};:'.,<>?«»“”‘’])|(?:(?<!@)[a-z0-9]+(?:[.\-][a-z0-9]+)*[.](?:com|net|org|edu|gov|mil|aero|asia|biz|cat|coop|info|int|jobs|mobi|museum|name|post|pro|tel|travel|xxx|ac|ad|ae|af|ag|ai|al|am|an|ao|aq|ar|as|at|au|aw|ax|az|ba|bb|bd|be|bf|bg|bh|bi|bj|bm|bn|bo|br|bs|bt|bv|bw|by|bz|ca|cc|cd|cf|cg|ch|ci|ck|cl|cm|cn|co|cr|cs|cu|cv|cx|cy|cz|dd|de|dj|dk|dm|do|dz|ec|ee|eg|eh|er|es|et|eu|fi|fj|fk|fm|fo|fr|ga|gb|gd|ge|gf|gg|gh|gi|gl|gm|gn|gp|gq|gr|gs|gt|gu|gw|gy|hk|hm|hn|hr|ht|hu|id|ie|il|im|in|io|iq|ir|is|it|je|jm|jo|jp|ke|kg|kh|ki|km|kn|kp|kr|kw|ky|kz|la|lb|lc|li|lk|lr|ls|lt|lu|lv|ly|ma|mc|md|me|mg|mh|mk|ml|mm|mn|mo|mp|mq|mr|ms|mt|mu|mv|mw|mx|my|mz|na|nc|ne|nf|ng|ni|nl|no|np|nr|nu|nz|om|pa|pe|pf|pg|ph|pk|pl|pm|pn|pr|ps|pt|pw|py|qa|re|ro|rs|ru|rw|sa|sb|sc|sd|se|sg|sh|si|sj|Ja|sk|sl|sm|sn|so|sr|ss|st|su|sv|sx|sy|sz|tc|td|tf|tg|th|tj|tk|tl|tm|tn|to|tp|tr|tt|tv|tw|tz|ua|ug|uk|us|uy|uz|va|vc|ve|vg|vi|vn|vu|wf|ws|ye|yt|yu|za|zm|zw)\b/?(?!@)))";
//generating a MatchCollection
MatchCollection linksInText = Regex.Matches(text, pattern, RegexOptions.Multiline);
//going forward only when links where found
if (linksInText.Count != 0)
{
//important to set them to 0 to get the correct count
int linkValueLength = 0;
int httpOrNoneCount = 0;
int httpsCount = 0;
foreach (Match m in linksInText)
{
//https urls need 23 characters, http and others 22
if (m.Value.Contains("https://"))
{
httpsCount = httpsCount + 1;
}
else
{
httpOrNoneCount = httpOrNoneCount + 1;
}
linkValueLength = linkValueLength + m.Value.Length;
}
//generating summaries of character counts
int httpOrNoneReplacedValueLength = httpOrNoneCount * 22;
int httpsReplacedValueLength = httpsCount * 23;
//calculating final count
resultCount = (currentCount - linkValueLength) + (httpOrNoneReplacedValueLength + httpsReplacedValueLength);
}
else
{
resultCount = currentCount;
}
}
return resultCount;
}
First, we are detecting links in the string using the above mentioned RegEx expression and collect them in a MatchCollection.
As https urls have a 23 character length on t.co (Twitter’s url shortener), I am generating two new counts – one for https, one for all other urls.
The last step is to substract the the length of all Match values and add the newly calculated replaced link values lengths.
Add this little method to your TextChanged event, and you will be able to detect the character count on the fly.
As always, I hope this is helpful for some of you.
After playing around with WP8.1 for a few days (like everyone else), I decided to dig a bit into development of WP8.1.
As oAuth is the common authentication method nowadays for Apps and Websites, I was curios about the implementation of the WebAuthenticationBroker in a WINPRT app.
I used it before with Windows 8 for my TweeCoMinder app, but that’s a few month back (it didn’t make it into the Store yet (another goal, right – porting TweeCoMinder to Universal will be a lot of fun and learning for me ;-)).
Before we continue: This is a pretty huge topic. Be prepared that it may take you more than one time to read and understand what is going on.
Let’s dive into it. Unlike the Windows WebAuthenticationBroker, the Phone version does not use the AuthenticateAsync method. It uses AuthenticateAndContinue instead. This is related to the lifecycle on phone, as it is more likely that an WINPRT app is suspended than on Windows (at least that’s the official reason).
Preparing our App
But we are able to get it working, no worries. First, we need the so called ContinuationManager. This class brings the user back to the app where the fun begun.
You can download the complete class from here (it is a 1:1 copy from the official MSDN reference). The only thing you need to do is to add your app’s Namespace into it.
The next step we need to do: some modifications at the App.xaml.cs file.
1. Add an OnActivated event (it isn’t there in the Phone template) [updated: added missing continuationManager initialization]
protected async override void OnActivated(IActivatedEventArgs e)
{
continuationManager = new ContinuationManager();
CreateRootFrame();
// Restore the saved session state only when appropriate
if (e.PreviousExecutionState == ApplicationExecutionState.Terminated)
{
try
{
await SuspensionManager.RestoreAsync();
}
catch (SuspensionManagerException)
{
//Something went wrong restoring state.
//Assume there is no state and continue
}
}
//Check if this is a continuation
var continuationEventArgs = e as IContinuationActivatedEventArgs;
if (continuationEventArgs != null)
{
continuationManager.Continue(continuationEventArgs);
}
Window.Current.Activate();
}
First, we check the SuspensionManager and let him restore a saved state – if there is one. If you do not have a Folder ”Common” with the SuspensionManager, just add a new Basic page. This will generate the Common folder with the SuspenstionManager class for you.
After that, we are checking if the activation is a Continuation. We need this check there, otherwise the app will not be able to receive the Tokens after returning from the WebAuthenticationBroker. Note: declare the ContinuationManager globally in App.xaml.cs with this to avoid multiple instances (which will crash the app for sure).
public static ContinuationManager continuationManager { get; private set; }
2. Add a CreateRootFrame() method with some little changes to the default behavior
private void CreateRootFrame()
{
// Do not repeat app initialization when the Window already has content,
// just ensure that the window is active
if (rootFrame != null)
return;
// Create a Frame to act as the navigation context and navigate to the first page
rootFrame = new Frame();
//Associate the frame with a SuspensionManager key
SuspensionManager.RegisterFrame(rootFrame, "AppFrame");
// Set the default language
rootFrame.Language = Windows.Globalization.ApplicationLanguages.Languages[0];
rootFrame.NavigationFailed += OnNavigationFailed;
// Place the frame in the current Window
Window.Current.Content = rootFrame;
}
This simply creates the RootFrame for our app. Place this one in the OnLaunched and OnActivated events. Instead of creating the RootFrame in the OnLaunched method, declare it globally in App.xaml.cs with this:
public static Frame rootFrame { get; set; }
3. Handle the HardwareButtons_BackPressed event
private void HardwareButtons_BackPressed(object sender, BackPressedEventArgs e)
{
Frame frame = Window.Current.Content as Frame;
if (frame == null)
{
return;
}
if (frame.CanGoBack)
{
frame.GoBack();
e.Handled = true;
}
}
This just handles the BackButton press globally (you can still handle it on individual pages/frames/controls).
4. Handle Navigation Errors in the OnNavigationFailed event
private void OnNavigationFailed(object sender, NavigationFailedEventArgs e)
{
//change this code for your needs
throw new Exception("Failed to load Page " + e.SourcePageType.FullName);
}
5. Add the Save method to the OnSuspending event
await SuspensionManager.SaveAsync();
This is just to save the current state of our app while the App gets suspended.
Preparing oAuth
Now, we have our app prepared to be continued after the WebAuthenticationBroker has finished. Pretty much to do so far, but now we are going to start with the real fun: The oAuth process. We are going to use Twitter in this case, as it is very popular to be added as a sharing option in apps (yes, I recently saw a lot of them).
Before we are able to connect to Twitter, we need some preparing methods. The first one is to get a random character chain. Twitter demands a 32 digit chain that contains random alphanumeric values, the so called oAuth-nonce. A lot of samples use a chain that is shorter, which will be fine for the initial authentication, but not for additional request. Here is my method:
string GetNonce()
{
StringBuilder builder = new StringBuilder();
Random random = new Random();
char ch;
for (int i = 0; i < 32; i++)
{
ch = Convert.ToChar(Convert.ToInt32(Math.Floor(26 * random.NextDouble() + 65)));
builder.Append(ch);
}
return builder.ToString().ToLower();
}
We also need a timestamp in Milliseconds, this one is pretty straight forward:
You will find a lot of samples that don’t use the oAuthTokenSecret in the basic method. We will need this for additional requests, so I am using a nullable string overload. This way, I need only one method after all.
Performing the Authentication process
To start the Authentication process, we are using this code in our Button_Click event:
First, we need a RequestToken that authenticates our request for the oAuthToken, that’s why we are awaiting the GetTwitterRequestTokenAsync(TwitterCallBackUri, TwitterConsumerKey) Task. The Task itself is this one:
If you think that’s all of our code, I need to disappoint you. The fun goes on. We prepared our app to be recognized as continued app. To effectifely continue our app, we need to use the ContinueWebAuthentication(WebAuthenticationBrokerContinuationEventArgs args) event from our ContinuationManager class:
public async void ContinueWebAuthentication(WebAuthenticationBrokerContinuationEventArgs args)
{
WebAuthenticationResult result = args.WebAuthenticationResult;
if (result.ResponseStatus == WebAuthenticationStatus.Success)
{
await GetTwitterUserNameAsync(result.ResponseData.ToString());
}
else if (result.ResponseStatus == WebAuthenticationStatus.ErrorHttp)
{
MessageDialog HttpErrMsg = new MessageDialog(string.Format("There was an error connecting to Twitter: \n {0}", result.ResponseErrorDetail.ToString()), "Sorry");
await HttpErrMsg.ShowAsync();
}
else
{
MessageDialog ErrMsg = new MessageDialog(string.Format("Error returned: \n{0}", result.ResponseStatus.ToString()), "Sorry");
await ErrMsg.ShowAsync();
}
}
The WebAuthenticationResult holds our accessToken and accessTokenSecret, that we are going to exchange for our final oAuthToken and oAuthTokenSecret (we need them for all further requests).
If all goes well, we are now able to call the final Authentication Task GetTwitterUserNameAsync(string webAuthResultResponseData):
At the end of this Task, we will have all Tokens and the ScreenName of our user and can save them for further usage.
The whole oAuth process is a pretty huge thing as you can see. I hope this blog post helps you all to understand how to use the WebAuthenticationBroker and get the required Tokens for all further requests.
Here are some useful links to the MSDN, if you want to dive deeper:
As always, this covers my experience. If anyone has tips or tricks to make this all easier (except of using already existing libraries), feel free to add a comment below.
This time, we will have look on how to integrate tickets from uservoice into your Windows Phone app.
Users love to see a history of their tickets they submitted to a customer service. They can review them again, and maybe help also other users by showing or telling them about it.
However, if you want to get a list of all tickets from a specific user, we need to slightly change our request. We need to login as owner of the account to be allowed to search all tickets.
Let’s have a look on how to log in as owner:
private void LoginAsOwner()
{
string loginAsOwnerPath = "/api/v1/users/login_as_owner";
var client = new RestClient(BaseUrl)
{
Authenticator = OAuth1Authenticator.ForRequestToken(ConsumerKey, ConsumerSecret, oAuthCallBackUri)
};
//works only with POST!
var request = new RestRequest(loginAsOwnerPath, Method.POST);
request.AddHeader("Accept", "application/json");
var response = client.ExecuteAsync(request, HandleLoginAsOwnerResponse);
}
private void HandleLoginAsOwnerResponse(IRestResponse restResponse)
{
var response = restResponse;
var ownerTokens = JsonConvert.DeserializeObject<UserViaMailClass.Token>(response.Content);
OwnerAccesToken = ownerTokens.oauth_token;
OwnerAccesTokenSecret = ownerTokens.oauth_token_secret;
}
The authorization request is pretty similar to the user’s authentication request. However, if we log in as owner, we are getting another AccessToken and another AccessTokenSecret. That’s why we are using the ‘ForRequestToken’-method with our RestClient.
Important to know is that the request itself works only with the HTTP-method ‘POST’, otherwise the login would be denied.
We are getting back the JSON string of our owner account, which can be deserialized with JSON.net to get our AccessToken and AccessTokenSecret. I attached my ‘UserViaMailClass‘ for easy deserialization (yes, it looks similar to the user class from my authentication post, but has some differences in there).
Now that we have our OwnerAccesToken and OwnerAccessTokenSecret, we are able to search for all tickets from a specific user:
public void GetAllTicketsFromUser()
{
string mailaddress = "<usersmailaddress>";
string getSearchTicketsPath = "/api/v1/tickets/search.json";
var client = new RestClient(BaseUrl)
{
Authenticator = OAuth1Authenticator.ForProtectedResource(ConsumerKey, ConsumerSecret, OwnerAccesToken, OwnerAccesTokenSecret)
};
var request = new RestRequest(getSearchTicketsPath, Method.GET);
request.AddParameter("query", mailaddress);
var response = client.ExecuteAsync(request, HandleGetAllTicketsFromUserResponse);
}
private void HandleGetAllTicketsFromUserResponse(IRestResponse restResponse)
{
var response = restResponse;
var tickets = JsonConvert.DeserializeObject<TicketDataClass.TicketData>(response.Content);
}
This request is again pretty similar to what we did to get a list of all suggestions. Please find attached my ‘TicketDataClass‘ for easy deserialization.
Of course, users want to be able to submit new tickets/support requests from our app, too. I will show you how to do that:
public void CreateNewTicketAsUser()
{
string ticketsPath = "/api/v1/tickets.json";
var client = new RestClient(BaseUrl)
{
Authenticator = OAuth1Authenticator.ForProtectedResource(ConsumerKey, ConsumerSecret, AccessToken, AccessTokenSecret)
};
var request = new RestRequest(ticketsPath, Method.POST);
request.AddParameter("ticket[subject]", "testing the uservoice API");
request.AddParameter("ticket[message]", "hi there, \n\nwe are just testing the creation of a new uservoice ticket.");
var response = client.ExecuteAsync(request, HandleCreateNewTicketAsUserResponse);
}
private void HandleCreateNewTicketAsUserResponse(IRestResponse restResponse)
{
var response = restResponse;
}
To submit a new ticket, we are using the user’s AccessToken and AccessTokenSecret. This way, the ticket gets automatically assigned to the ticket. We then need to pass the ‘ticket[subject]’ and ‘ticket[message]’ parameters to the request to make it being accepted by the uservoice API.
The response is a json string that contains the ticket id, which can be used to fetch the submitted ticket data. The Alternative is to call again the search method we created before to get the updated list.
Answering to already existing tickets as user seems to be not possible with the current API. Normally, if a user responds to the response mail we answer their support ticket with, it will get assigned to the existing ticket. If we create a new ticket with the same subject, it will be a new ticket that creates a new thread. I already reached out to uservoice if there is a way to do the same from the API. As soon as I have a response that enables me to do so, I will update this post.
Now that we have all important functions for our new support system, I am starting to make a small helper library for your Windows Phone 8 apps. I hope to have it finished by this weekend, and will of course blog about here.
As always, I hope this blog post is helpful for some of you. Until the next post,
As I described in my first blog post about uservoice, uservoice has a feedback forum where users are able to submit and vote for ideas.
This post is about how to get those ideas into your app. On the API side, the ideas are called suggestions. Now that we know how to authenticate our users for the API, we are able to get a list of suggestions into our app:
public void GetSuggestions()
{
string suggestionsPath = "api/v1/forums//suggestions.json";
var client = new RestClient(BaseUrl)
{
Authenticator = OAuth1Authenticator.ForProtectedResource(ConsumerKey, ConsumerSecret, AccessToken, AccessTokenSecret)
};
var request = new RestRequest(suggestionsPath, Method.GET);
var response = client.ExecuteAsync(request, HandleGetSuggestionResponse);
}
This is pretty straight forward. We are using the oAuth1Authenticator with our saved tokens as parameter to call the suggestions endpoint of the uservoice API. The result is a JSON string that holds all suggestions as a list.
In our response handler, we are able to deserialize our List of suggestions (best with JSON.net):
private void HandleGetSuggestionResponse(IRestResponse restResponse)
{
var response = restResponse;
var suggestionslist = JsonConvert.DeserializeObject<SuggestionsDataClass.SuggestionsData>(response.Content);
suggestionsListBox.ItemsSource = suggestionslist.suggestions;
}
To get the SuggestionsDataClass items, just go to json2csharp.com and pass in the json string we received with response.Content or download it from here: SuggestionsDataClass.
Now let’s have a look on how to submit a new idea on behalf of our user. To submit an idea, we are using the POST method after we authenticated our user again with the uservoice API:
public void PostSuggestion()
{
string suggestionsPath = "api/v1/forums//suggestions.json";
var client = new RestClient(BaseUrl)
{
Authenticator = OAuth1Authenticator.ForProtectedResource(ConsumerKey, ConsumerSecret, AccessToken, AccessTokenSecret)
};
var request = new RestRequest(suggestionsPath, Method.POST);
request.AddHeader("Accept", "application/json");
request.Parameters.Clear();
request.RequestFormat = DataFormat.Json;
var newSuggestion = new SuggestionsDataClass.Suggestion();
newSuggestion.title = "test suggestion number 2 from app development";
newSuggestion.text = "please ignore this suggestion as we are testing integration of ideas into our apps";
newSuggestion.vote_count = 3;
request.AddParameter("suggestion[title]", newSuggestion.title);
request.AddParameter("suggestion[text]", newSuggestion.text);
request.AddParameter("suggestion[votes]", newSuggestion.vote_count);
request.AddParameter("suggestion[referrer]", "uservoice test app");
var response = client.ExecuteAsync(request, HandlePostSuggestionResponse);
}
This call is a bit different from the previous one. We need to pass the idea data to as parameters to our request. The parameter “suggestion[title]” is the main one and always required. As you can see, “suggestion[text]” and “suggestion[votes]” are additional parameters that make the idea complete. All other date is generated by the uservoice server (like posted at, connect to the user who posted that, etc..). The parameter “suggestion[referrer]” is only visible in our admin console and can help you to track from where the suggestion was submitted.
In our response handler, we are receiving a complete set of suggestion data as a JSON string that we can use display to our users and enable sharing of this idea for example:
private void HandlePostSuggestionResponse(IRestResponse restResponse)
{
var response = restResponse;
//tbd: do something with the result (e.g. checking response.StatusCode)
}
The last important point I want to show you is how to let a user vote for an idea.
public void VoteOnSuggestion()
{
string postUserVotesPath = "/api/v1/forums//suggestions/{0}/votes.json";
string suggestionId = "";
var client = new RestClient(BaseUrl)
{
Authenticator = OAuth1Authenticator.ForProtectedResource(ConsumerKey, ConsumerSecret, AccessToken, AccessTokenSecret)
};
var request = new RestRequest(string.Format(postUserVotesPath, suggestionId), Method.POST);
request.AddHeader("Accept", "application/json");
request.Parameters.Clear();
request.RequestFormat = DataFormat.Json;
request.AddParameter("to", 3);
var response = client.ExecuteAsync(request, HandleVotingResponse);
}
Of course we need to authenticate our user again. We need to pass the suggestion id to the request path (which is part of the Suggestion class). This call accepts only one parameter (“to”). The value can be between 1 and 3 (tip: only offer this three options from your code already to avoid erroneous responses).
The response handler returns the suggestion’s JSON string the user voted on again:
private void HandleVotingResponse(IRestResponse restResponse)
{
var response = restResponse;
//tbd: do something with the result (e.g. checking response.StatusCode)
}
This was all about how to integrate the feedback forum of your uservoice account into your app. As always, I hope this will be useful for some of you.
I am really enjoying playing around with the uservoice API. It enables me to integrate a lot of cool new features that take the user experience to a new level, while helping me to improve my apps.
Today, I am going to write about how to authenticate a user with the uservoice API.
uservoice uses the oAuth authentication in version 1.0a. Therefore, we need a consumer key and a consumer secret for our app. Log into <yourname>.uservoice.com, and go to ‘Settings/Integration’, where you create a new API client for your app.
I recommend to set it up as a trusted client, as you will have more rights with a trusted client. After your set up your app, you should have an entry like this under integrations:
Now we have everything set up on the uservoice part. Let’s go to our app. I am using the RestSharp library that makes it a little easier to authenticate users. You should do the same if you want to follow along this post. In Visual Studio, right click the project name and select ‘Manage NuGet packages’, and search for RestSharp in the ‘Online’ section.
After we have integrated the RestSharp library in our app, we are going to set up some objects for authentication:
You might have noticed that I set the Visibility property to collapsed. With oAuth, we are typically authenticating users by referring them to the web site, that handles the login process for us. After the user has authorized our app, the website transfers the user to our callback url that we define with our API client.
As I told you already above, RestSharp helps us a lot when it comes to authentication.
There are several ways to use the RestSharp API, but for the moment, I am using it directly to authenticate my users.
This is the start method:
public void GetUserAuthenticated()
{
authBrowserGrid.Visibility = Visibility.Visible;
var client = new RestClient(BaseUrl)
{
Authenticator = OAuth1Authenticator.ForRequestToken(ConsumerKey, ConsumerSecret, oAuthCallBackUri)
};
var request = new RestRequest(requestTokenPath, Method.GET);
var response = client.ExecuteAsync(request, HandleRequestTokenResponse);
}
We are creating a new RestClient that calls our BaseUrl which we defined before. In the same call, we are telling our client that we want to use oAuth 1.0(a), passing the parameters ConsumerKey, ConsumerSecret and our callback url with the client. As we want to receive a RequestToken, we are generating a new RestRequest, passing the requestTokenPath and the ‘GET’ method as parameters.
Finally, we want to continue with the response, that should contain our RequestToken. Windows Phone only supports the ExecuteAsync method, which needs a specific response handler to be executed. That was the first lesson I had to learn with using RestSharp on Windows Phone. To handle the response, we are creating a new handler method that implements ‘IRestResponse’:
private void HandleRequestTokenResponse(IRestResponse restResponse)
{
var response = restResponse;
//tbd: write an extraction helper for all tokens, verifier, secrets
oAuthToken = response.Content.Substring((response.Content.IndexOf("oauth_token=") + 12), (response.Content.IndexOf("&oauth_token_secret=") - 12));
var tempStringForGettingoAuthTokenSecret = response.Content.Substring(response.Content.IndexOf("&oauth_token_secret=") + 20);
oAuthTokenSecret = tempStringForGettingoAuthTokenSecret.Substring(0, tempStringForGettingoAuthTokenSecret.IndexOf("&oauth_callback_confirmed"));
var authorizeUrl = string.Format("{0}{1}{2}",BaseUrl, authorizePath, response.Content);
authBrowser.Navigate(new Uri(authorizeUrl));
authBrowser.IsScriptEnabled = true;
authBrowser.Navigating += authBrowser_Navigating;
}
We now have an object that we are able to work with (the variable response). We need to extract the oauth_token and the oauth_token_secret and save them for later use.
After that, we can build our authorization url, that we pass to the WebBrowser control we created earlier. Important: you should set the ‘IsScriptEnabled’ property to true, as authentication websites often use scripts to verify the entered data. Last but not least, we are subscribing to the Navigating event of the browser control. In this event, we are handling the response to the authorization:
We only need the verification string for out next request we have to send, so we are extracting the parameter “oauth_verifier” and going over to get our AccessToken for all further requests:
private void GetAccessToken()
{
var client = new RestClient(BaseUrl)
{
Authenticator = OAuth1Authenticator.ForAccessToken(ConsumerKey, ConsumerSecret, oAuthToken, oAuthTokenSecret, oAuthVerifier)
};
var request = new RestRequest(accessTokenPath, Method.GET);
var response = client.ExecuteAsync(request, HandleAccessTokenResponse);
}
This time, we are telling our RestClient that we want to get the AccessToken, and we need also the oAuthToken and the oAuthTokenSecret we saved before we navigated our users to the uservoice authentication site. Of course, we also need a handler for the response to this request:
private void HandleAccessTokenResponse(IRestResponse restResponse)
{
var response = restResponse;
AccessToken = response.Content.Substring(12, response.Content.IndexOf("&oauth_token_secret=") -12);
AccessTokenSecret = response.Content.Substring(response.Content.IndexOf("&oauth_token_secret=") + 20);
authBrowserGrid.Visibility = Visibility.Collapsed;
//continue with your code (new method call etc.)
}
The only thing we now need to do is to extract the AccessToken and the AccessTokenSecret and save them permanently in our app (as long as the user is authenticated). We need them for a lot of calls to the uservoice API.
Let’s call the uservoice API to get more information about the user that has now authorized our app:
public void GetUser()
{
var client = new RestClient(BaseUrl)
{
Authenticator = OAuth1Authenticator.ForProtectedResource(ConsumerKey, ConsumerSecret, AccessToken, AccessTokenSecret)
};
var request = new RestRequest(getUserPath, Method.GET);
var response = client.ExecuteAsync(request, HandleGetUserResponse);
}
As you can see, we are now only using the AccessToken and the AccessTokenSecret to call the uservoice API, no additional login is required. To complete this sample, here is again the handler for the response:
private void HandleGetUserResponse(IRestResponse restResponse)
{
var response = restResponse;
//tbd: do something with the result (e.g. checking response.StatusCode)
}
We have now received a JSON string that tells us a lot of information about our user and the date we have on uservoice:
As you can see, it is relatively easy to get our users authenticated and calling the uservoice API. In my next blog post, I will write about suggestions (that’s the idea forum). I will go into details on getting a list of all suggestions, how to let a user post a new idea and letting a user vote for ideas – all from within your app!
In the meantime, I hope this post is helpful for some of you.