Outlook Rest API returning no results - c#

I'm trying to display a list of events from an Outlook calendar using the example request microsoft have here
However, I've no proper experience with using any sort of REST APIs before. Using the URL they provide I should be getting something back but I'm not. Here is the code in my controller:
string uri = "https://outlook.office365.com/api/v1.0/me/events";
var webRequest = (HttpWebRequest)WebRequest.Create(uri);
webRequest.Method = "GET";
string result = "";
try
{
WebClient webClient = new WebClient();
webClient.Encoding = Encoding.UTF8;
result = webClient.DownloadString(uri);
try
{
string returnedString = result;
TempData.Add("myval", result);
ViewBag.result = "returned string " + result;
}
catch (Exception er2)
{
ViewBag.error = er2.Message;
}
ViewBag.secondresult = "first result " + result;
}
catch (Exception er)
{
}
ViewBag.firstResult = "Outside try catch " + result;
ViewBag.url = uri;
return View();
Then in my view I'm calling the ViewBags like this:
<p> here </p>
#ViewBag.url
#ViewBag.firstResult
#ViewBag.result
#ViewBag.error
#ViewBag.secondresult
<p> end </p>
But besides my here and end I get nothing. This is a project that was set up without any input from myself so I'm having to do everything across a network which is why I'm using so many try catches.
Can someone with more experience with using REST APIs tell me if I'm messing something up somewhere?

I don't see any authentication in your code, so it's likely returning a 401. You need to use OAuth2 to get an access token and use that to authenticate your calls. Since you're doing this in C#, you might want to look at the API wrappers on NuGet that implement a lot of this for you. There are some sample starter apps on http://dev.office.com/code-samples that might be helpful too (search for ASP.NET MVC).

Related

C# Webclient returning error 404

I'm using below script to retrieve HTML from an URL.
string webURL = #"https://nl.wiktionary.org/wiki/" + word.ToLower();
using (WebClient client = new WebClient())
{
string htmlCode = client.DownloadString(webURL);
}
The variable word can be any word. In case there is no WIKI page for the "word" be retrieved the code is ending in error with code 404, while retrievng the URL with a browser opens a WIKI page, saying there is no page for this item yet.
What I want is that the code always gets the HTML, also when the WIKI page says there is no info yet. I do not want to avoid the error 404 with a try and catch.
Does anyone has an idea why this is not working with a Webclient?
try this. You can catch the 404 error content in a try catch block.
var word = Console.ReadLine();
string webURL = #"https://nl.wiktionary.org/wiki/" + word.ToLower();
using (WebClient client = new WebClient() { })
{
try
{
string htmlCode = client.DownloadString(webURL);
}
catch (WebException exception)
{
string responseText=string.Empty;
var responseStream = exception.Response?.GetResponseStream();
if (responseStream != null)
{
using (var reader = new StreamReader(responseStream))
{
responseText = reader.ReadToEnd();
}
}
Console.WriteLine(responseText);
}
}
Console.ReadLine();
Since this WIKI-server use case-sensitive url mapping, just don't modify case of URL to harvest (remove ".ToLower()" from you code).
Ex.:
Lower case:
https://nl.wiktionary.org/wiki/categorie:onderwerpen_in_het_nynorsk
Result: HTTP 404(Not Found)
Normal (unmodified) case:
https://nl.wiktionary.org/wiki/Categorie:Onderwerpen_in_het_Nynorsk
Result: HTTP 200(OK)
Also, keep in mind what most (if not all) WiKi servers (including this one) generates custom 404 pages, so in browser they looks like "normal" pages, but, despite this, they are serving with 404 http code.

Unable to create a shared link using the Box API V2

UPDATE: I figured it out and posted the answer below.
All I'm trying to do is update any file attribute. Description, name, anything, but no matter how I format it I get a 403.
I need to be able to modify a file so it can be shared via the Box API from a cloud app. I'm updating someone else's code from V1, but they are no longer available... I've tried many things but mostly just get 403 Forbidden errors.
There are no issues with OAuth2, that works fine and I can list files and folders, but can not modify them. This question is about sharing, but I can't change a description either. The box account is mine and I authenticate with my admin credentials. Any suggestions would be appreciated.
Here is the method I am using. I pass in the fileId and token and I've left out try/catch etc. for brevity.
string uri = string.Format("https://api.box.com/2.0/files/{0}", fileId);
string body = "{\"shared_link\": {\"access\": \"open\"}}";
byte[] postArray = Encoding.ASCII.GetBytes(body);
using (var client = new WebClient())
{
client.Headers.Add("Content-Type", "application/x-www-form-urlencoded");
client.Headers.Add("Authorization: Bearer " + token);
var response = client.UploadData(uri, postArray);
var responseString = Encoding.Default.GetString(response);
}
Thanks.
Okay, My Homer Simpson moment...
UploadData is a POST, I needed to do a PUT. Here is the solution.
string uri = String.Format(UriFiles, fileId);
string response = string.Empty;
string body = "{\"shared_link\": {\"access\": \"open\"}}";
byte[] postArray = Encoding.ASCII.GetBytes(body);
try
{
using (var client = new WebClient())
{
client.Headers.Add("Authorization: Bearer " + token);
client.Headers.Add("Content-Type", "application/json");
response = client.UploadString(uri, "PUT", body);
}
}
catch (Exception ex)
{
return null;
}
return response;
try changing your content type to 'multipart/form-data'?
I just looked up the api at: https://developers.box.com/docs/#files-upload-a-file
and it looks like the server is expecting a multipart post
here is stack overflow post on posting multipart data:
ASP.NET WebApi: how to perform a multipart post with file upload using WebApi HttpClient

how to post in facebook from my asp.net mvc 3 website

I pretend to integrate my website with facebook, whant to make a automatic post (on a specific facebook account) while a user interacts with a web application.
is there any way to make this operation like a webservice way?, authenticating and calling a url that posts the information i send directly on the facebook wall?
i'm using asp.net mvc3 C# i've found a facebook developer toolkit library, is this the correct way to start or what should i do?
What is necessary is only write a post automatically on a facebook account, for example when i write a new article (news) on my website, it will be automatically posted on fb.
any idea to get me started?
I did something kind of similar, when a user clicks on a "share" button on my mvc app, it posts something on his wall. The problem using the oauth dialog, is that it will redirect the browser to a facebook site for the user to log in and accept the application permissions.
On the "share" button, I linked it to this url:
<a href=""https://www.facebook.com/dialog/oauth?client_id=[YOUR_APP_ID]&redirect_uri=[THE_REDIRECT_PAGE]/&scope=publish_stream"">
<img src='#Url.Content("~/Images/facebook_share.png")' alt="Share on Facebook!" style="height:28px" />
</a>
YOUR_APP_ID is your facebook application ID.
THE_REDIRECT_PAGE is a public page on your site that facebook will automatically redirect once the user has logged in and accepted the permissions. When facebook redirects, it appends a querystring parameter called "code" to it.
NOTE: The redirect page MUST END with a "/", it cannot end with a document, or else it doesn't work!
Once the user has accepted your request, you must ask facebook another code, called access code, used to post on the user's wall.
This code is on the redirect page:
public ActionResult Index(string code)
{
string fbAuthCode = Request["code"]; //The authorization code.
string fbAppId = "XXXXXXX"; //Your fb application id.
string fbSecretAppId = "XXXXXXXXXXXXXXXXXXXXX"; //Your fb secret app id, it is found on the fb application configuration page.
string redirectUrl = string.Format("[THE_REDIRECT_PAGE]", locationPointId, entryLocationId); //The redirect url. THIS MUST BE THE EXACT SAME REDIRECT URL USED ON THE JAVASCRIPT LINK!
string fbUrl = "https://graph.facebook.com/oauth/access_token?client_id=" + fbAppId + "&redirect_uri=" + redirectUrl + "&client_secret=" + fbSecretAppId + "&code=" + fbAuthCode; //Url used to post.
string accessToken = string.Empty;
try
{
WebClient client = new WebClient();
using (Stream stream = client.OpenRead(fbUrl))
using (StreamReader reader = new StreamReader(stream))
{
accessToken = reader.ReadToEnd().Split('&')[0].Replace("access_token=", string.Empty);
reader.Close();
}
}
catch (Exception ex)
{
throw new Exception("An error ocurred while trying to get the fb token in " + fbUrl, ex);
}
Once you have the access token, you can post to the user wall:
string postUrl = "https://graph.facebook.com/me/feed";
string postParameters;
postParameters = string.Format("message={0}&picture={1}&name={2}&caption={2}&description={3}&link={4}&access_token={5}",
"[Message]",
"[PictureUrl]",
"[Name]",
"[Caption]",
"[Link]",
accessToken);
try
{
System.Net.WebRequest req = System.Net.WebRequest.Create(postUrl);
req.ContentType = "application/x-www-form-urlencoded";
req.Method = "POST";
byte[] bytes = System.Text.Encoding.UTF8.GetBytes(postParameters);
req.ContentLength = bytes.Length;
using (System.IO.Stream os = req.GetRequestStream())
{
os.Write(bytes, 0, bytes.Length); //Push it out there
os.Close();
using (WebResponse resp = req.GetResponse())
using (StreamReader sr = new StreamReader(resp.GetResponseStream()))
{
ViewBag.PostResult = sr.ReadToEnd().Trim();
sr.Close();
}
os.Close();
}
}
catch (Exception ex)
{
throw new Exception("An error ocurred while posting data to the user's wall: " + postUrl + "?" + postParameters, ex);
}
return RedirectToAction(XXXXXXXXXXXxx....); //Then i redirect to another page.
You can see that on the exception I throw the posted url (for debugging purposes).
With that url you can usually go to the facebook Graph API Explorer or the Linter and check the real error.
I don't know if this is exactly what you want but hope it gives you a kickoff...
I've struggled a few days with this, because facebook documentation on open graph is not very good yet, at least for us that don't use curl :)
https://developers.facebook.com/docs/opengraph/tutorial/
https://developers.facebook.com/docs/opengraph/
Hope it helps.
MT.
It's easy:
Step 1:
Get a valid facebook token by requesting "*https://www.facebook.com/dialog/oauth?client_id=YOUR_APP_ID&redirect_uri=YOUR_URL&scope="publish_stream,email*" (full list of permissions there: https://developers.facebook.com/docs/reference/api/user/)
Step 2:
Post your message to the user wall:
curl -F 'access_token=...' \
-F 'message=your message' \
https://graph.facebook.com/ID_OR_USERNAME/feed

How to call an external URL from a ASP.NET MVC solution

First post inhere ever. So better make it a good one.
I have a ASP.NET MVC 2 web application in which I have an actionResult I need to do a call for me.
The thing is I need this A.R to handle some data operations and after that I need it to call an external URL which is actually a Company Module that handles sending messages to our company handset phones.
It just needs to call the URL that looks like this:
string url = "http://x.x.x.x/cgi-bin/npcgi?no=" + phoneNumber + "&msg=" + message;
I don't need any return message or anything. Just want to call that external URL which is of course outside the scope of my own web application. (I do not want to Redirect). That URL must be called behind the GUI without the user ever realising. And the page that they are viewing must not be affected.
I tried with:
Server.Execute(url);
However did not work. I've heard that some ppl go about this by having a hidden iFrame on the page. The setting the src to the url one may need and then somehow execute that, to get the call instantiated. It doesn't seem so elegant to me, but if that is the only solution, does anyone have an example as to how that is done. Or if you have a more sleek suggestion I am all ears.
I finally got it working with this piece of code:
string messageToCallInPatient = "The doctor is ready to see you in 5 minutes. Please wait outside room " + roomName;
string url = "http://x.x.x.x/cgi-bin/npcgi?no=" + phoneNumber + "&msg=" +
messageToCallInPatient;
HttpWebRequest webReq = (HttpWebRequest)WebRequest.Create(string.Format(url));
webReq.Method = "GET";
HttpWebResponse webResponse = (HttpWebResponse)webReq.GetResponse();
//I don't use the response for anything right now. But I might log the response answer later on.
Stream answer = webResponse.GetResponseStream();
StreamReader _recivedAnswer = new StreamReader(answer);
Since you don't expect a return value from the url, simplest way is
After the AR Execution, use Webclient to trigger the URL
Either by HTTP GET or POST (Synchronous or Asynchronous)
Sample code
WebClient wc = new WebClient();
wc.UploadProgressChanged += (sender, evtarg) =>
{
Console.WriteLine(evtarg.ProgressPercentage);
};
wc.UploadDataCompleted += (sender, evtarg) =>
{
String nResult;
if (evtarg.Result != null)
{
nResult = Encoding.ASCII.GetString(evtarg.Result);
Console.WriteLine("STATUS : " + nResult);
}
else
Console.WriteLine("Unexpected Error");
};
String sp= "npcgi??no=" + phoneNumber + "&msg=" + message;
System.Uri uri = new Uri("http://x.x.x.x/cgi-bin/");
wc.UploadDataAsync(uri, System.Text.Encoding.ASCII.GetBytes(sb);
The sample uses HTTP POST and Asynchronous call( So it will return immediately after triggering the URL - Non blocking)
You can use simply " return Redirect(url);"

Twitter: verifying username and password in C#

Bounty Question
I am using c# 3.5 Window Forms Application. I am using the code mentioned in the accepted answer. and I am getting below error
The remote server returned an error: (401) Unauthorized.
Sample code to verify the UserName and Password will be really appreciated
Bounty Question Ends
I have an application with the following use-case: when the user first starts using the application, he inputs his username and password. Then, at a much later stage, the application may update his status.
Currently I'm using Twitterizer, but I believe the question is beyond the scope of the specific library I'm using. Following are the two relevant lines of code:
Twitter twitter = new Twitter("username", "password", "source");
twitter.Status.Update("update");
The construction of the Twitter object does not throw an exception if the username/password are incorrect. This is probably because nothing is sent at this point. On the other hand, the status update does throw an exception if the username/password are invalid.
My problem is that I want to validate the username/password at the point of user input, not when trying to post the update.
How can I validate the username/password without posting anything (in Twitterizer or otherwise)?
Taking a quick look at the verify_credentials API as mentioned by peSHIr, I wrote a little routine which seems to do the trick. It's late, but I was able to test it a couple of times and seems to work.
In my function, I am just returning true if I I get an HttpResponseCode.OK, and false if I get anything else or an exception is thrown. If twitter does not like the uid/password an exception will be thrown with a 401 error (not authorized.)
public bool CheckTwitterCredentials(string UserName, string Password)
{
// Assume failure
bool Result = false;
// A try except block to handle any exceptions
try {
// Encode the user name with password
string UserPass = Convert.ToBase64String(
System.Text.Encoding.UTF8.GetBytes(UserName + ":" + Password));
// Create our HTTP web request object
HttpWebRequest Request =
(HttpWebRequest)WebRequest.Create("http://twitter.com/account/verify_credentials.xml");
// Set up our request flags and submit type
Request.Method = "GET";
Request.ContentType = "application/x-www-form-urlencoded";
// Add the authorization header with the encoded user name and password
Request.Headers.Add("Authorization", "Basic " + UserPass);
// Use an HttpWebResponse object to handle the response from Twitter
HttpWebResponse WebResponse = (HttpWebResponse)Request.GetResponse();
// Success if we get an OK response
Result = WebResponse.StatusCode == HttpStatusCode.OK;
} catch (Exception Ex) {
System.Diagnostics.Debug.WriteLine("Error: " + Ex.Message);
}
// Return success/failure
return Result;
}
You could try to use the API call account/verify_credentials. Hopefully the API library you use already supports this.. Twitter is notorious now for really hating third party programmers, so unless you have good reason to do something with Twitter, just stay away...
I have used other Twitter Libraries but none of them support checking the username and password for validitity. This might be because Twitter API does not have the facility to validate the username and password unless we try to do something which requires authentication.
One thing you can do is try to get friend list or any other methods that requires authentication.
Twitter API hasn't supported username/password in years. Instead, you have OAuth, which lets the user authorize your application to act on their behalf. Twitter has an account/verify_credentials endpoint you can use to verify whether the user who's tokens you have still authorizes your app. Here's an example of how you could call this endpoint with LINQ to Twitter:
var accounts =
from acct in twitterCtx.Account
where acct.Type == AccountType.VerifyCredentials
select acct;
You can visit Account/VerifyCredentials documentation for more details:
as #joe-mayo informed, you have to switch to OAuth. twitter expired v1 of their API and they documented that in following url https://dev.twitter.com/docs/faq#17750.
Here's a function i wrote that will verify twitter username and password in C# :
public bool isTwitterValid(string username, string password)
{
try
{
string user = Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(username + ":" + password));
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("https://twitter.com/statuses/verify.xml");
request.Method = "POST";
request.ServicePoint.Expect100Continue = false;
request.Headers.Add("Authorization", "Basic " + user);
request.ContentType = "application/x-www-form-urlencoded";
WebResponse response = request.GetResponse();
StreamReader reader = new StreamReader(response.GetResponseStream());
string responseString = reader.ReadToEnd();
reader.Close();
}
catch (Exception ex)
{
if (ex.Message.Contains("404")) { return true; }
}
return false;
}

Categories