Fetch Twitter Timeline as XML/JSON, show in Windows 8 app - c#

I'm currently following a tutorial on how to show Twitter feeds with LINQ to XML in C#. However, seeing as Microsoft has replaced WebClient with HTTPClient, I'm unsure how to proceed on my quest of integrating this into my Windows 8 application.
The tutorial: http://www.codeproject.com/Articles/117614/How-to-query-twitter-public-status-using-LINQ-to-X
The thing is that I'm "halfway" used to DownloadStringCompleted, which I believe is not in the HTTPClient api. So after searching for a while on the async/await functionality, I mixed some of my knowledge together with some tutorials and snippets I found, but what I ended up with would not work:
public async Task<XElement> GetXmlAsync()
{
var client = new HttpClient();
var response = await client.GetAsync("http://api.twitter.com/1/statuses/user_timeline.xml?screen_name=VladimirPutin");
var text = response.Content.ReadAsStringAsync();
return XElement.Parse(text.Result);
XElement xmlTweets = XElement.Parse(text.Result);
listboxTweetsSecond.ItemsSource = from tweet in xmlTweets.Descendants("status")
select new UserTweet
{
UserImageSrc = tweet.Element("user").Element("profile_image_url").Value,
UserMessage = tweet.Element("text").Value,
UserName = tweet.Element("user").Element("screen_name").Value
};
}
(Yeah, the Twitter username is just a placeholder)
I do not need an entire code as an answer, but I'd love it if someone could point out where I should go from here, as well as what I should do in general, as this (of course) does not work (as in, it does not show anything when I run it/debug mode).

Comment out the line
return XElement.Parse(text.Result);
and it should probably work.
Having done that (i.e. you are no longer returning an XElement) you can probably change the method signature top return just a task.
public async Task GetXmlAsync()
{
// method body
}

Related

How to retrieve username, email and image with OneDrive/Graph APIs?

I'm working on a UWP app and I was thinking about moving from the old LiveSDK (which is discontinued and was last updated around 2015) to the new OneDriveSDK (the Graph APIs), specifically using the UWP Community Toolkit Services package and its APIs.
The library seems pretty easy to use as far as login and files/folders management go, but so far I haven't been able to find a way to retrieve the user full name, the user email and the profile picture.
Here's the code I'm currently using to do so, using LiveSDK (code simplified here):
public static async Task<(String username, String email)> GetUserProfileNameAndEmailAsync(LiveConnectSession session)
{
LiveConnectClient connect = new LiveConnectClient(session);
LiveOperationResult operationResult = await connect.GetAsync("me");
IDictionary<String, object> results = operationResult.Result;
String username = results["name"] as String;
if (!(results["emails"] is IDictionary<string, object> emails)) return default;
String email = emails["preferred"] as String ?? emails["account"] as String;
return (username, email);
}
public static async Task<ImageSource> GetUserProfileImageAsync([NotNull] LiveConnectSession session)
{
LiveConnectClient liveClient = new LiveConnectClient(session);
LiveOperationResult operationResult = await liveClient.GetAsync("me/picture");
String url = operationResult.Result?["location"] as String;
// The URL points to the raw image data for the user profile picture, just download it
return default;
}
I've looked at the guide here and I see there seems to be a replacement for all of the above, but I haven't been able to integrate that with the UWP Toolkit service. For example, to retrieve the user info, here's what I've tried:
HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, "https://graph.microsoft.com/v1.0/me/");
await OneDriveService.Instance.Provider.AuthenticationProvider.AuthenticateRequestAsync(request);
using (HttpResponseMessage response = await OneDriveService.Instance.Provider.HttpProvider.SendAsync(request))
{
String content = await response.Content.ReadAsStringAsync();
}
But this fails with an exception at the SendAsync call.
NOTE: I know there are the Graph APIs too in the UWP Toolkit, with ready-to-use methods to retrieve the user info and profile picture, but apparently you need an office 365 subscription to use those APIs (both as a dev, and probably as a user too), so I guess that's not what I'm looking for here, since I've always been able to retrieve these info using a normal OneDrive client.
Is there a way to do this on UWP, either through some method within the UWP Toolkit, or with some other solution?
Thanks!
EDIT: I've reused the code from the sample app, registered my app to get a clientID and made a quick test, but it's not working as expected and I'm getting this exception:
Fixed, see below
EDIT #2: According to this question, I had to switch to https://graph.microsoft.com/beta to get the profile picture, as the 1.0 version of the APIs doesn't support it for normal MS accounts right now. All things considered, it seems to be working just fine now 👍
I followed the MSDN document to register my app for Microsoft Graph. After that, I will get an application ID(in API, it's called as clientId).
Then, I used the Microsoft Graph Connect Sample for UWP to login in with my general MS account. It worked well. I could get the username, email etc.
Please note that if you want to run this sample successfully, you would need to use the application ID to initialize the PublicClientApplication object in AuthenticationHelper.cs.
public static PublicClientApplication IdentityClientApp = new PublicClientApplication("your client id");

PHP - Upload specified collection of values to a resource identified by specified URI

Just finished an automatic newsletter-subscriber module written in C#. Now I have to translate it in PHP so I can use it with my wordpress sites as well. I'm not that good in PHP as most of the time I'm writting .NET MVC applications. In C# I came up with the following solution:
// Code below runs each time a user submits the newsletter form
using (var client = new WebClient()) {
var MyValues = new NameValueCollection();
MyValues["list"] = "123456789";
MyValues["boolean"] = "true";
MyValues["name"] = model.NameSec;
MyValues["email"] = model.EmailSec;
var MyResponse = client.UploadValues("http://www.XXXXXX.com/subscribe", MyValues);
var MyValue = Encoding.Default.GetString(MyResponse);
if (MyValue.Equals("true")) {
// All correct
}
else {
// Oops, smth went wrong
}
}
Now I'm looking for a similar method as WebClient.UploadValues but for PHP. Could you please give me some guidance?
WebClient.UploadValues() is making a POST request to your URI. To achieve the same in PHP, you should look into Curl. There are plenty of examples available and a number of questions that already address the topic.
This is probably the best answer with source code/examples.

Instasharp in a Console Application

I have a .net console application that I want to use to pull Instagram posts via the Instasharp wrapper using a hashtag search.
I use C# .net web forms extensively and am not very familiar with MVC nor how to use the await keyword. The code sample below seems to run, but never provides any output.
This line:
var tagInfo = await tagApi.Get("soccer");
Returns me to the calling method with no indication of retrieved data.
Can anyone provide insights as to what I am doing wrong here?
public static async void GetInstagram(String tag, InstagramConfig config)
{
var instagramPosts = await LoadInstagramPosts(tag, config);
dynamic dyn = JsonConvert.DeserializeObject(instagramPosts.ToString());
foreach (var data in dyn.data)
{
Console.WriteLine("{0} - {1}", data.filter, data.images.standard_resolution.url);
}
}
public static async Task<TagResponse> LoadInstagramPosts(String hashTagTerm, InstagramConfig config)
{
var tagApi = new InstaSharp.Endpoints.Tags(config);
var tagInfo = await tagApi.Get("soccer");
}
EDITED code after first comment which solved my initial problem.
I feel like I'm close but something is still missing.
See specific questions below...
I've based the code on the documentation from InstaSharp GitHub (https://github.com/InstaSharp/InstaSharp). GitHubs example is based on an MVC application, mine is not an MVC project, but a console application.
I feel like I am very close and maybe others will benefit from helping me solve this.
My specific questions...
1) Not sure where the 'code' parameter in the OAuth method originate??
2) How to perform the needed call backs with Instagram??
var config = new InstaSharp.InstagramConfig(location.InstagramClientId, location.InstagramClientSecret, "http://localhost");
string instagramLoginLink = InstagramLogin(config);
GetInstagram("soccer", config, instagramLoginLink);
public static async void GetInstagram(String tag, InstagramConfig config, string code)
{
OAuthResponse oAuthResponse = await OAuth(code, config);
var instagramPosts = await LoadInstagramPosts(tag, config, oAuthResponse);
if(instagramPosts.Data != null)
{
dynamic dyn = JsonConvert.DeserializeObject(instagramPosts.Data.ToString());
foreach (var data in dyn.data)
{
Console.WriteLine("{0} - {1}", data.filter, data.images.standard_resolution.url);
}
}
}
public static string InstagramLogin(InstagramConfig config)
{
var scopes = new List<OAuth.Scope>();
scopes.Add(InstaSharp.OAuth.Scope.Likes);
scopes.Add(InstaSharp.OAuth.Scope.Comments);
string link = InstaSharp.OAuth.AuthLink(config.OAuthUri + "authorize", config.ClientId, config.RedirectUri, scopes, InstaSharp.OAuth.ResponseType.Code);
return link;
}
public static async Task<OAuthResponse> OAuth(string code, InstagramConfig config)
{
// add this code to the auth object
var auth = new OAuth(config);
// now we have to call back to instagram and include the code they gave us
// along with our client secret
return await auth.RequestToken(code);
}
public static async Task<TagResponse> LoadInstagramPosts(String hashTagTerm, InstagramConfig config, OAuthResponse OAuth)
{
var tagApi = new InstaSharp.Endpoints.Tags(config, OAuth);
return await tagApi.Get("soccer");
}
I'm a bit late to the show, yet probably my answer will help someone who find this question when googling, someone like me.
The main problem with your approach is that Instagram is using OAuth authentication. I suggest you to google on OAuth to understand the principles, but I will try to explain the practical points of it below.
OAuth approach means that the result of the InstagramLogin method in the snippet above is not the code. It's the link where you need to send you user (yes, using a browser or a web-view) so that they can sign into their Instagram account and then authorize your application to access their data (so-called user consent screen).
In the end, after user consent, Instagram will redirect browser to the URL of your choice (it should be previously added in the list of allowed redirect urls in Instagram API -> Manage Clients (top-right corner) -> Create/Select client to Manage -> Security tab)
You can try set a breakpoint and copy the value of instagramLoginLink into your browser's address box. You will be able to see the whole flow of authentication and consent - and finally the redirect url that will most probably produce 404 in your browser.
This final link will contain the code in a get parameter. It's the so-called grant code that allows you to get an access token. This code is to be extracted from url and then used in your call to OAuth.RequestToken).
PS: Yes, everything I say above means that you need either a web app running that will redirect user to Instagram or a client-side app that will show the user a web view and somehow handle the moment when Instagram sends the user back to your redirect url - to grab the code and proceed.

Simple image file POST to Web Api

I have been reading around building an action method in my Web Api to allow the posting of images, which would be saved on the server and related to a Contact object via a field imageURL.
I have found a few examples online of how to set this up, and am wanting to test them. I currently have:
public Task<HttpResponseMessage> PostFile()
{
HttpRequestMessage request = this.Request;
if (!request.Content.IsMimeMultipartContent())
{
throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
}
string root = System.Web.HttpContext.Current.Server.MapPath("~/Content/images");
var provider = new MultipartFormDataStreamProvider(root);
var task = request.Content.ReadAsMultipartAsync(provider).
ContinueWith<HttpResponseMessage>(o =>
{
string file1 = provider.BodyPartFileNames.First().Value;
//Use file name to update ImageURL of contact
return new HttpResponseMessage()
{
Content = new StringContent("File uploaded.")
};
}
);
return task;
}
from How To Accept a File POST, and whilst I understand the flow I want to test it properly.
What would an example of a client call be to this API method, where I can include the contactid as a header?
I need to understand this properly to test this code sample so I can start understanding this more, but I'm really new to this area. I have kind of a chicken and egg scenario where I understand little about posting and receiving images and need a start point.
Thanks.
You can use a small MVC or ASP application (you only need one page) where you can use some JS plugins to post files to your controller.
Plugins: jQueryFileUpload or DropzoneJS. The last one is more easy to integrate. Both plugins has support for sending additional data.

Facebook page /feed missing images

I was using the Facebook Public API Feed for the longest time and since they deprecated it I've been trying to find a replacement method in C#.
I am able to get my page posts but any post that contains images I only get the message and no images. After spending the past weekend trying to find a way I am desperate to know if anyone has had any success in getting full page post content from the Facebook C# SDK library.
Here is what I have and it works for getting the posts but they do not contain any images.
var fb = new FacebookClient
{
AppId = ConfigurationManager.AppSettings.Get("FacebookAppID"),
AppSecret = ConfigurationManager.AppSettings.Get("FacebookAppSecret"),
AccessToken = ConfigurationManager.AppSettings.Get("FacebookAccessToken")
};
var pageFeed = string.Format("/v2.4/{0}/feed", _facebookPageId);
dynamic response = fb.Get(pageFeed);
Since the upgrade in Graph API v2.4. Only a limited set of data is sent via FB unless specifically requested. You should pass the fields parameter with the keyword of data which you would like to retrieve.
A list of keyword is available here
In your case, the request statement would be:
var pageFeed = string.Format("/v2.4/{0}/feed?fields=id,message,picture", _facebookPageId);
To get all pictures from a post: replace picture with attachments, as picture will return the very first picture linked to the post.
var pageFeed = string.Format("/v2.4/{0}/feed?fields=id,message,attachments", _facebookPageId);

Categories

Resources