Using RetrieveFeedAsync to get Twitter Search Results in a Metro App - c#

Getting familiar with Metro apps so I thought I would try my hand at some twitter stuff. The following code doesn't work.
public static async Task<IEnumerable<TwitterItem>> Search(string term)
{
var search = new SyndicationClient();
var searchUri = new Uri("http://search.twitter.com/search.atom?q=" + term);
//var searchUri = new Uri("http://windowsteamblog.com/windows/b/developers/atom.aspx");
var results = await search.RetrieveFeedAsync(searchUri);
return from item in results.Items
select new TwitterItem
{
Text = item.Title.Text,
CreatedAt = item.PublishedDate.DateTime,
FromUser = item.Authors[0].Name
};
}
It works if I use the windows team blog url but not the twitter url. No exceptions, it just never comes back. Tried to use fiddler but it does not intercept Metro traffic for some reason. Any thoughts?

I agree with #Jon.
Please debug this code with Fiddler to ensure that you're not producing a malformed url.
Please see this answer for more information about using Fiddler with a Metro app.

Related

GMB API - Unable to Get/Updated Google Business Account Pub/Sub Notification Settings

I am trying to use Google My Business API C# Client Library: https://developers.google.com/my-business/samples/ in order to get real-time notifications for Location and Reviews. I have followed the steps provided at: https://developers.google.com/my-business/content/notification-setup#get_started . But I am stuck at point 5) Account.updateNotifications.
I am receiving this error: "{Parameter validation failed for \"name\"}"
I am able to use the same "name" parameter to fetch the Account, Locations, Review etc. successfully, but it's not working with Notifications. I am attaching the code below.
GMBServiceInit();
string name = "accounts/1234567890132456"
var notification = new Notifications
{
TopicName = "projects/gmbproject/topics/notification_topic",
NotificationTypes = new List<string>
{
"NEW_REVIEW",
}
};
//Get Notifications Settings
var response = await GMBService.Accounts.GetNotifications(name).ExecuteAsync();
//Update Notifications Settings
var updateNotificationRequest = GMBService.Accounts.UpdateNotifications(notification, name);
var updateNotificationReponse = await updateNotificationRequest.ExecuteAsync();
If someone had this issue, please help me to figure out this issue. Thanks!
Found the solution.
I am using the name as:
string name = "accounts/1234567890132456"
I should be using:
string name = "accounts/1234567890132456/notifications"

Paypal Rest API not triggering webhooks

I've seen a lot of people with this same question and none of the answers solve my issue. I'm making a sale using the Paypal .Net SDK. In my sale I use this code and it works and the process is successfully completed. Then I my success page I execute the payment like this:
public ActionResult Success(string paymentId, string token, string PayerID)
{
var config = ConfigManager.Instance.GetProperties();
var accessToken = new OAuthTokenCredential(config).GetAccessToken();
var apiContext = new APIContext(accessToken);
apiContext.Config = config;
var paymentExecution = new PaymentExecution() { payer_id = PayerID };
var payment = new Payment() { id = paymentId };
// Execute the payment.
var executedPayment = payment.Execute(apiContext, paymentExecution);
return View();
}
This code is executed without any problem.
My only problem is that my webhook is never triggered. I created the webhook, in the paypal developer dashboard, with all events. When I test with the webhook simulator it gets triggered but when I do the normal process it never does.
What am I doing wrong?
Thanks for any help.
I'm facing the same issue, however I haven't gone live.
By this answer, it is an issue on Paypal's sandbox side: https://stackoverflow.com/a/44984794/1393652
Hope it will be solved soon.

Post message with Facebook SDK .NET

I have created a facebook page and a facebook application for my website and now I need to post messages onto the facebook page with help of facebook SDK .NET.
This is what I got so far :
public static bool UploadPost(string message)
{
dynamic result;
//https://developers.facebook.com/tools/explorer/
//https://developers.facebook.com/tools/access_token/
FacebookClient client = new FacebookClient("secret access token");
result = client.Get("oauth/access_token", new
{
client_id = "[Client ID number]",
client_secret = "[Client sercret",
grant_type = "client_credentials",
});
result = client.Post("[facebook app Id]/feed", new { message = "Test Message from app" });
//result.id;
result = client.Get("[facebook app Id]");
return false;
}
When running this I get : Additional information: (OAuthException - #200) (#200) The user hasn't authorized the application to perform this action on client.Post. If I remove the client.Post row every thing works good, the correct data is fetched.
I have tried follow some helps on facebook SDK .NET website but it is still not working.
The main problem now is that I get permission exception. I was hoping that my facebook app hade enouth permissions to publish post from my website to the facebook page.
Here is a step wise tutorial to register your application with facebook and get an app Id for your application.
Then for permissions ::
private const string ExtendedPermissions = "user_about_me,read_stream,publish_stream";
This is a string of permissions. Pass it on further for getting correct permissions to post messages on page. Post using your standard code for posting no FB pages.
Cheers. Hope it helps.
Are you trying to post to [facebook app id]?
I would recomend to post to "me/feed" and test if that works.
Also, to post to Facebook you have to have the publish_stream permission
private async Task Authenticate()
{
string message = String.Empty;
try
{
session = await App.FacebookSessionClient.LoginAsync("user_about_me,read_stream,publish_actions");
App.AccessToken = session.AccessToken;
App.FacebookId = session.FacebookId;
Dispatcher.BeginInvoke(() => NavigationService.Navigate(new Uri("/Pages/LandingPage.xaml", UriKind.Relative)));
}
catch (InvalidOperationException e)
{
message = "Login failed! Exception details: " + e.Message;
MessageBox.Show(message);
}
}
Should work :)
The following should work.
var fb = new FacebookClient("access_token");
fb.PostCompleted += (o, e) => {
if(e.Error == null) {
var result = (IDictionary<string, object>)e.GetResultData();
var newPostId = (string)result.id;
}
};
var parameters = new Dictionary<string, object>();
parameters["message"] = "My first wall post using Facebook SDK for .NET";
fb.PostAsync("me/feed", parameters);
This was taken directly from the documentation.
By creating a extended page token and use it to make the post everything works just fine. See this : How to get Page Access Token by code?
Im surprised that this simple task was so hard to get running and that there was vary little help to get.

Accessing GData Calender from Google Apps account?

I'm building a simple app too that needs to access a calendar that's in my Google Apps account. But I'm having problems with authentication. I've tried the following code but it doesn't work:
Service service = new Service("<appname>");
service.setUserCredentials("<email>", "<password>");
CalendarEntry entry = (CalendarEntry)service.Get("<eventUrl>");
How do you get this to work with Google Apps? Is there any other type of authentication that I have to use for Google apps?
Update:
Unlocking the captcha solved my problem with getting the feed. Now I've hit the next wall: updating an event.
entry.Title.Text = "Foo";
entry.Update();
Gives me the GDataRequestException exception: "Can not update a read-only entry".
Im using the private calendar xml address that I got under kalendarsettings:
https://www.google.com/calendar/feeds/_%40group.calendar.google.com/private-/basic
I would recommend using Fiddler to see what http response you are getting back from Google. When I ran your code against my google apps account, I was getting back an "Error=CaptchaRequired" response. This required that I go to https://www.google.com/a/yourgoogleappdomain.com/UnlockCaptcha (replacing with your domain obviously). After I did that I was able to properly connect. You may be getting a different error code too so check for that and post it here. You could have an invalid password or invalid url or this functionality is disabled by your google apps administrator. Here is my sample code:
var calendarService = new CalendarService("company-app-version");
calendarService.setUserCredentials("<email>", "<password>");
var eventQuery = new EventQuery("http://www.google.com/calendar/feeds/user%40domain.com/private/full");
var eventFeed = calendarService.Query(eventQuery);
foreach (var atomEntry in eventFeed.Entries)
{
Console.WriteLine(atomEntry.Title.Text);
}
Make sure to replace the email, password, and email inside of the URL (url encode the # sign too).
using Google.GData.Client;
public bool ValidateGoogleAccount(string login, string password)
{
try
{
Service bloggerService = new Service("blogger", "App-Name");
bloggerService.Credentials = new GDataCredentials(login, password);
string token = bloggerService.QueryAuthenticationToken();
if (token != null)
return true;
else
return false;
}
catch (Google.GData.Client.InvalidCredentialsException)
{
return false;
}
}
Yet another solution Austin from google provides (it worked for me):
http://groups.google.com/group/google-calendar-help-dataapi/browse_thread/thread/400104713435a4b4?pli=1

Update Twitter Status in C#

I'm trying to update a user's Twitter status from my C# application.
I searched the web and found several possibilities, but I'm a bit confused by the recent (?) change in Twitter's authentication process. I also found what seems to be a relevant StackOverflow post, but it simply does not answer my question because it's ultra-specific regading a code snippet that does not work.
I'm attempting to reach the REST API and not the Search API, which means I should live up to the stricter OAuth authentication.
I looked at two solutions. The Twitterizer Framework worked fine, but it's an external DLL and I would rather use source code. Just as an example, the code using it is very clear and looks like so:
Twitter twitter = new Twitter("username", "password");
twitter.Status.Update("Hello World!");
I also examined Yedda's Twitter library, but this one failed on what I believe to be the authentication process, when trying basically the same code as above (Yedda expects the username and password in the status update itself but everything else is supposed to be the same).
Since I could not find a clear cut answer on the web, I'm bringing it to StackOverflow.
What's the simplest way to get a Twitter status update working in a C# application, without external DLL dependency?
Thanks
If you like the Twitterizer Framework but just don't like not having the source, why not download the source? (Or browse it if you just want to see what it's doing...)
I'm not a fan of re-inventing the wheel, especially when it comes to products that already exist that provide 100% of the sought functionality. I actually have the source code for Twitterizer running side by side my ASP.NET MVC application just so that I could make any necessary changes...
If you really don't want the DLL reference to exist, here is an example on how to code the updates in C#. Check this out from dreamincode.
/*
* A function to post an update to Twitter programmatically
* Author: Danny Battison
* Contact: gabehabe#hotmail.com
*/
/// <summary>
/// Post an update to a Twitter acount
/// </summary>
/// <param name="username">The username of the account</param>
/// <param name="password">The password of the account</param>
/// <param name="tweet">The status to post</param>
public static void PostTweet(string username, string password, string tweet)
{
try {
// encode the username/password
string user = Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(username + ":" + password));
// determine what we want to upload as a status
byte[] bytes = System.Text.Encoding.ASCII.GetBytes("status=" + tweet);
// connect with the update page
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://twitter.com/statuses/update.xml");
// set the method to POST
request.Method="POST";
request.ServicePoint.Expect100Continue = false; // thanks to argodev for this recent change!
// set the authorisation levels
request.Headers.Add("Authorization", "Basic " + user);
request.ContentType="application/x-www-form-urlencoded";
// set the length of the content
request.ContentLength = bytes.Length;
// set up the stream
Stream reqStream = request.GetRequestStream();
// write to the stream
reqStream.Write(bytes, 0, bytes.Length);
// close the stream
reqStream.Close();
} catch (Exception ex) {/* DO NOTHING */}
}
Another Twitter library I have used sucessfully is TweetSharp, which provides a fluent API.
The source code is available at Google code. Why don't you want to use a dll? That is by far the easiest way to include a library in a project.
The simplest way to post stuff to twitter is to use basic authentication , which isn't very strong.
static void PostTweet(string username, string password, string tweet)
{
// Create a webclient with the twitter account credentials, which will be used to set the HTTP header for basic authentication
WebClient client = new WebClient { Credentials = new NetworkCredential { UserName = username, Password = password } };
// Don't wait to receive a 100 Continue HTTP response from the server before sending out the message body
ServicePointManager.Expect100Continue = false;
// Construct the message body
byte[] messageBody = Encoding.ASCII.GetBytes("status=" + tweet);
// Send the HTTP headers and message body (a.k.a. Post the data)
client.UploadData("http://twitter.com/statuses/update.xml", messageBody);
}
Try LINQ To Twitter. Find LINQ To Twitter update status with media complete code example that works with Twitter REST API V1.1. Solution is also available for download.
LINQ To Twitter Code Sample
var twitterCtx = new TwitterContext(auth);
string status = "Testing TweetWithMedia #Linq2Twitter " +
DateTime.Now.ToString(CultureInfo.InvariantCulture);
const bool PossiblySensitive = false;
const decimal Latitude = StatusExtensions.NoCoordinate;
const decimal Longitude = StatusExtensions.NoCoordinate;
const bool DisplayCoordinates = false;
string ReplaceThisWithYourImageLocation = Server.MapPath("~/test.jpg");
var mediaItems =
new List<media>
{
new Media
{
Data = Utilities.GetFileBytes(ReplaceThisWithYourImageLocation),
FileName = "test.jpg",
ContentType = MediaContentType.Jpeg
}
};
Status tweet = twitterCtx.TweetWithMedia(
status, PossiblySensitive, Latitude, Longitude,
null, DisplayCoordinates, mediaItems, null);
Try TweetSharp . Find TweetSharp update status with media complete code example works with Twitter REST API V1.1. Solution is also available for download.
TweetSharp Code Sample
//if you want status update only uncomment the below line of code instead
//var result = tService.SendTweet(new SendTweetOptions { Status = Guid.NewGuid().ToString() });
Bitmap img = new Bitmap(Server.MapPath("~/test.jpg"));
if (img != null)
{
MemoryStream ms = new MemoryStream();
img.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
ms.Seek(0, SeekOrigin.Begin);
Dictionary<string, Stream> images = new Dictionary<string, Stream>{{"mypicture", ms}};
//Twitter compares status contents and rejects dublicated status messages.
//Therefore in order to create a unique message dynamically, a generic guid has been used
var result = tService.SendTweetWithMedia(new SendTweetWithMediaOptions { Status = Guid.NewGuid().ToString(), Images = images });
if (result != null && result.Id > 0)
{
Response.Redirect("https://twitter.com");
}
else
{
Response.Write("fails to update status");
}
}
Here's another solution with minimal code using the excellent AsyncOAuth Nuget package and Microsoft's HttpClient. This solution also assumes you're posting on your own behalf so you have your access token key/secret already, however even if you don't the flow is pretty easy (see AsyncOauth docs).
using System.Threading.Tasks;
using AsyncOAuth;
using System.Net.Http;
using System.Security.Cryptography;
public class TwitterClient
{
private readonly HttpClient _httpClient;
public TwitterClient()
{
// See AsyncOAuth docs (differs for WinRT)
OAuthUtility.ComputeHash = (key, buffer) =>
{
using (var hmac = new HMACSHA1(key))
{
return hmac.ComputeHash(buffer);
}
};
// Best to store secrets outside app (Azure Portal/etc.)
_httpClient = OAuthUtility.CreateOAuthClient(
AppSettings.TwitterAppId, AppSettings.TwitterAppSecret,
new AccessToken(AppSettings.TwitterAccessTokenKey, AppSettings.TwitterAccessTokenSecret));
}
public async Task UpdateStatus(string status)
{
try
{
var content = new FormUrlEncodedContent(new Dictionary<string, string>()
{
{"status", status}
});
var response = await _httpClient.PostAsync("https://api.twitter.com/1.1/statuses/update.json", content);
if (response.IsSuccessStatusCode)
{
// OK
}
else
{
// Not OK
}
}
catch (Exception ex)
{
// Log ex
}
}
}
This works on all platforms due to HttpClient's nature. I use this method myself on Windows Phone 7/8 for a completely different service.

Categories