I've been stuck for a while on the following problem when I debug the following code:
TwitterService service = new TwitterService("_consumerkey", "_consumersecret");
OAuthRequestToken requestToken = service.GetRequestToken();
Uri uri = service.GetAuthorizationUri(requestToken);
Process.Start(uri.ToString());
Console.Write("Verificatiecode? ");
string verifier = Console.ReadLine();
OAuthAccessToken access = service.GetAccessToken(requestToken, verifier);
service.AuthenticateWith(access.Token, access.TokenSecret);
TwitterUser twitterUser = service.GetUserProfile(new GetUserProfileOptions());
ListFriendsOptions friends_options = new ListFriendsOptions();
friends_options.UserId = twitterUser.Id;
friends_options.Cursor = -1;
var friends = service.ListFriends(friends_options);
do
{
if (friends_options.Cursor != null)
{
foreach (var friend in friends) {Console.WriteLine(friend.ScreenName);}
friends_options.Cursor = friends.NextCursor;
}
} while (friends_options.Cursor != null);
Console.ReadKey(true);
I always get an overflow exception after filling in the verification code here:
OAuthAccessToken access = service.GetAccessToken(requestToken, verifier);
Anyone who can help me?
Thanks in advance
Looking at the source, it seems like the problem is when it tries to return the results inside GetAccessToken:
return new OAuthAccessToken()
{
Token = nameValueCollection["oauth_token"] ?? "?",
TokenSecret = nameValueCollection["oauth_token_secret"] ?? "?",
//this is the only place a conversion to int is occurring that I've found
UserId = Convert.ToInt32(nameValueCollection["user_id"] ?? "0"),
ScreenName = nameValueCollection["screen_name"] ?? "?"
};
Looking on Github, it seems this update might solve the problem.
Download the last version of TweetSharp, old version has user_id as Int32, but new version as Int64 https://github.com/danielcrenna/tweetsharp
This happens because Twitter introduced 64bit user ids a while back.
Older Twitter accounts still have the 32-bit Ids and TweetSharp works just fine with them. But if you opened an account recently you already might have a 64 bit ID and Tweet Sharp fails.
I fixed the problem by getting the tweetsharp-unofficial package from NuGet.
Related
I am trying to write a script that will open an issue typed in the console.
For some reason the issue variable comes back empty in the debugger.
class Program
{
public async static Task Main()
{
var client = new GitHubClient(new ProductHeaderValue("test-app"));
var user = await client.User.Get("medic17");
var tokenAuth = new Credentials(APIKeys.GithubPersinalAccessToken);
client.Credentials = tokenAuth;
var exampleIssue = new NewIssue("test body");
var issue = await client.Issue.Create("owner","name", exampleIssue);
}
}
APIKeys holds my token.
Thanks
I found a solution hope this helps someone else as well.
class Program
{
public async static Task Main()
{
// client initialization and authentication
var client = new GitHubClient(new ProductHeaderValue("<anything>"));
var user = await client.User.Get("<user>");
var tokenAuth = new Credentials(APIKeys.GithubPersinalAccessToken);
client.Credentials = tokenAuth;
// user input
Console.WriteLine("Give a title for your issue: ");
string userIssueTitle = Console.ReadLine().Trim();
Console.WriteLine("Describe your issue:", Environment.NewLine);
string userIssue = Console.ReadLine().Trim();
// input validation
while (string.IsNullOrEmpty(userIssue) || string.IsNullOrEmpty(userIssueTitle))
{
Console.WriteLine("ERROR: Both fields must contain text");
Console.ReadLine();
break;
}
var newIssue = new NewIssue(userIssueTitle) { Body = userIssue };
var issue = await client.Issue.Create(<owner>, <repo> newIssue);
var issueId = issue.Id;
Console.WriteLine($"SUCCESS: your issue id is {issueId} ");
Console.ReadLine();
}
}
Note
You need to store your keys in a separate file and write a class for it so your authentication flow might be different.
Note 2
You must replace all text with real values.
Still a little confused the app is OpenSource for transport since it deals with HIPPA data, users who want to use it need GitHub account if they want to do any error reporting. I assume I don’t share the authToken in the source of the project but the desktop Binary needs it plus the users GitHub login and password. Any pointers? I have tried just using username password that gets entered when creating issue but that fails with “not found”. It seems like any secret that gets deployed with binary app is potentially an issue.
I made a very simple console application which will hit MWS service and return XML document containing list of financial events. As it starts, an exception hits at line 14 'client.ListFinancialEvents(request)' and it just show null and no other information as to why its not working.
string accessKey = "AccessKey";
string secretKey = "SecretKey";
string appName = "AppName";
string appVersion = "1.0";
string serviceURL = "http://mws.amazonservices.com/Finances/2015-05-01/";
try
{
MWSFinancesServiceConfig config = new MWSFinancesServiceConfig();
config.ServiceURL = serviceURL;
MWSFinancesServiceClient client = new MWSFinancesServiceClient(accessKey, secretKey, appName, appVersion, config);
ListFinancialEventsRequest request = new ListFinancialEventsRequest();
request.SellerId = "SellerID";
request.AmazonOrderId = "111-111111111-111111111";
ListFinancialEventsResponse response = client.ListFinancialEvents(request);
Console.WriteLine("Response:");
ResponseHeaderMetadata rhmd = response.ResponseHeaderMetadata;
Console.WriteLine("RequestId: " + rhmd.RequestId);
Console.WriteLine("Timestamp: " + rhmd.Timestamp);
string responseXml = response.ToXML();
Console.WriteLine(response.ResponseHeaderMetadata);
}
catch (Exception e)
{
Console.WriteLine("Error: " + e.Message);
}
Console.ReadLine();
The DLLs used as reference were downloaded from here. I have already tried MWS Scratchpad and values are working fine. What could be the possible issues due to which this exception occurred and how to solve this issue?
I am posting an answer to my own question in case someone faces similar issue in the future.
I was making a very stupid mistake and it took me a week to figure it out. In service URL, instead of "http://..." it should be "https://..." and it starts working perfectly. It return complete XML as response in 'responseXml' variable.
i'm trying to get a stream of tweets using LinqToTwitter library and the below c# code, but i get this error:
Error 401 Unauthorized
public static SingleUserAuthorizer auth;
static void Main(string[] args)
{
Task task = new Task(getStreamOfTweets);
task.Start();
task.Wait();
Console.ReadLine();
}
static async void getStreamOfTweets()
{
auth = new SingleUserAuthorizer
{
CredentialStore = new SingleUserInMemoryCredentialStore
{
ConsumerKey = CUSTOMER_KEY,
ConsumerSecret = CUSTOMER_SECRET,
AccessToken = ACCESS_TOKEN,
AccessTokenSecret = ACCESS_TOKEN_SECRET
}
};
var context = new TwitterContext(auth);
int count = 0;
await (from strm in context.Streaming
where strm.Type == StreamingType.Filter
&& strm.Track == "federer"
select strm)
.StartAsync(async strm =>
{
string message =
string.IsNullOrEmpty(strm.Content) ?
"Keep-Alive" : strm.Content;
Console.WriteLine(
(count + 1).ToString() +
". " + DateTime.Now +
": " + message + "\n");
if (count++ == 5)
strm.CloseStream();
});
}
notes:
the permission in twitter app is "Read, Write and Access direct messages"
i can get tweet by REST API correctly
Please review the LINQ to Twitter FAQ, which has an extensive section on resolving 401 errors. That said, if it's working for the REST API, but not Streaming, that might narrow the options to try. Here are a couple things to try first:
Double check the keys to make sure you didn't accidentally add a space or lose a character on the ends.
Give a little time before trying again because sometimes too many accesses or failed attempts might cause them to deny your connection for a certain period of time.
Re: #2, try another stream, like Sample.
There are a lot of moving parts in play for using OAuth, so work through that list in case you might have missed something.
this issue happens because the time of windows was wrong.
If you copied & pasted from the Linq"Twitter sample code, make sure you have set properly all the keys:
ConsumerKey
ConsumerSecret
AccessToken
AccessTokenSecret
Then dont use "Application only" auth, use "user auth" instead for streaming which uses all of the above keys.
the issue was because the timing in PC was wrong
I'm trying to filter EC2 instances using the AWS SDK in .NET and, although I have seen inumerous threads on SO and on other websites of people resolving this issue, nothing I've tried on my end worked.
So, as a last resource, I'm coming to you guys for help. Can anyone shed some light on what I'm missing ? I know it's very likely that I'm doing something stupid, but I can't afford to waste too much time solving this issue.
This is the chunk of code I'm using to filter an EC2 instance (get it's metadata) by it's tag name:
DescribeInstanceStatusRequest req = new DescribeInstanceStatusRequest ();
req.Filters.Add (new Filter() { Name = "tag:Name", Values = new List <string> () { "some_random_name" } });
// Executing request & fetching response
DescribeInstanceStatusResponse resp = m_ec2Client.DescribeInstanceStatus (req);
But I keep on running into this exception:
The filter 'tag:Name' is invalid
I have replaced the filter name ("tag:Name" in the example) by several filters listed in the documentation (e.g. "tag-key", "tag-value", "tag:key=value"), but nothing works.
Thank you all in advance :)
After a more thorough research, I found out that the "DescribeInstanceStatus" routine doesn't support searching by tag, but I found a somewhat "simple" way of doing so. I'll post it in here in case anyone goes through the same situation.
Here's how:
DescribeInstancesRequest req = new DescribeInstancesRequest ();
req.Filters.Add (new Filter () { Name = "tag-value", Values = new List <string> () { "something" }});
// Executing request & fetching response
DescribeInstancesResponse resp = m_ec2Client.DescribeInstances (req);
return resp.Reservations.SelectMany (x => x.Instances).Where (y => y.State.Name == InstanceStateName.Pending || y.State.Name == InstanceStateName.Running).ToList (); {code}
In theory, with this routine you can use any of the filters listed under the "Supported Filters" table in the documentation.
Getting Number of running instance from AWS EC2
DescribeInstancesRequest req = new DescribeInstancesRequest();
req.Filters.Add(new Filter {
Name = "instance-state-name",
Values = new List<string>() { "running" }
});
DescribeInstancesResponse resp = _amazonEC2Client.DescribeInstances(req);
It's may be...
// Executing request & fetching response
DescribeInstancesResponse resp = m_ec2Client.DescribeInstances (
new DescribeInstancesRequest()
{
Filters = new List<Filter>()
{
new Filter("tag:Name", new List<string>(){"some_random_name"})
}
});
i want to access Google analytic data and i got samples from Google data API SDK. but these coding does not working and throws exception
Execution of request failed: https://www.google.com/analytics/feeds/accounts/default
so i found the reason for this is Google updated it's to v3.0. i searched updated coding for the C#, but i couldn't find solution for this.
i have same problem as this, but with C#.
Exception thrown when using GData .NET Analytics API
i tried coding with doing changes as follows as it says in Google developer - https://developers.google.com/analytics/resources/articles/gdata-migration-guide#appendix_a
string userName = this.Username.Text;
string passWord = this.Password.Text;
AnalyticsService service = new AnalyticsService("AnalyticsSampleApp");
service.setUserCredentials(userName, passWord);
string googleAccountWebId = "AIXXXXXXXXXXXXXXXXXXXXXXXXXXX";
string profileFeedUrl = "https://www.googleapis.com/analytics/v2.4/data?key=" + googleAccountWebId;
DataQuery query2 = new DataQuery(profileFeedUrl);
query2.Ids = "12345678";
query2.Metrics = "ga:visits";
query2.Sort = "ga:visits";
query2.GAStartDate = DateTime.Now.AddMonths(-1).AddDays(-2).ToString("2011-08-01");
query2.GAEndDate = DateTime.Now.ToString("2013-09-01");
query2.StartIndex = 1;
DataFeed data = service.Query(query2);
foreach (DataEntry entry in data.Entries)
{
string st=entry.Metrics[0].Value;
}
but even i change this it throws exception in
DataFeed data = service.Query(query2);
this line. exception is as follows:
Execution of request failed: https://www.googleapis.com/analytics/v2.4/data?key=AIXXXXXXXXXXXXXXXXXXXXXX-8&start-index=1&end-date=2013-09-01&ids=12345678&metrics=ga:visits&sort=ga:visits&start-date=2011-08-01
i'm using following DLL
Google.GData.Analytics.dll
Google.GData.Client.dll
Google.GData.Extensions.dll
My Questions :
how can i correct this error?
how can i access Google analytic data? is this correct? or else what is the way to doing it??
for a example i want to get available ProfileId and their values. (Title and Page views)
Analytics Account:
I am assuming you have an analytics account already if you don't then create one, and sign up your domain here:
http://www.google.com/intl/en/analytics/
To get your API Key do this:
Follow the instructions on https://developers.google.com/analytics/resources/articles/gdata-migration-guide (Create a Project in the Google APIs Console) to generate your key Once you have it set it as part of the querystring to request to Google Analytics service, in this case:
YourAPIkEStringabcdefghijklmno
To get the profileId (Ids on the code) you should do this:
Log into your analytics account, select the desired domain on your list (blue link) click on the administrator button and on the profiles tab find the profile
configuration subtab, right there you will find the profile id in this case the eight characters long id:
12345678
Here you have some C# code to help you getting the number of visits for that Id:
public string VisitsNumber()
{
string visits = string.Empty;
string username = "youremailuser#domain.com";
string pass = "yourpassword";
string gkey = "?key=YourAPIkEYYourAPIkEYYourAPIkEYYourAPIkE";
string dataFeedUrl = "https://www.google.com/analytics/feeds/data" + gkey;
string accountFeedUrl = "https://www.googleapis.com/analytics/v2.4/management/accounts" + gkey;
AnalyticsService service = new AnalyticsService("WebApp");
service.setUserCredentials(username, pass);
DataQuery query1 = new DataQuery(dataFeedUrl);
query1.Ids = "ga:12345678";
query1.Metrics = "ga:visits";
query1.Sort = "ga:visits";
//You were setting 2013-09-01 and thats an invalid date because it hasn't been reached yet, be sure you set valid dates
//For start date is better to place an aprox date when you registered the domain on Google Analytics for example January 2nd 2012, for an end date the actual date is enough, no need to go further
query1.GAStartDate = new DateTime(2012, 1, 2).ToString("yyyy-MM-dd");
query1.GAEndDate = DateTime.Now.ToString("yyyy-MM-dd");
query1.StartIndex = 1;
DataFeed dataFeedVisits = service.Query(query1);
foreach (DataEntry entry in dataFeedVisits.Entries)
{
string st = entry.Title.Text;
string ss = entry.Metrics[0].Value;
visits = ss;
}
return visits;
}
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
Response.Write("Visits:" + this.VisitsNumber());
}
}
Since the 2.4 API is not so flexible anymore, I have another post here hacking it to get the profile Id:
Getting an specific ProfileId from registered Accounts using GData .NET Analytics API 2.4 if you need to convert the code to C# you can use the Telerik converter: http://converter.telerik.com/
I think this suffice to use the 2.4 API. If you need extra help let me know.