authorization error using linqtotwitter for streaming api - c#

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

Related

creating a github issue in octokit.net

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.

Quickblox chat setting save_to_history to true in Xamarin C# SDK

I'm using Quickblox C# SDK. I want to send message to a specific dialog. It's not well documented in Xamarin specific documentation. I decided to visit REST API documentation. As I could learn from there
By using Chat 2.0, you are not automatically storing your messages. Also a dialog entity won't be created/updated without saving a message to history.
I can infer if I set save_to_history to 1, chat dialog will be automatically created and message will be stored in the backend. However I couldn't figure out how I should specify that in C# SDK, cause extraParam in this method signature
public void SendMessage(int userId, string body, string extraParams, string dialogId, string subject = null, Quickblox.Sdk.Modules.ChatXmppModule.Models.MessageType messageType = Quickblox.Sdk.Modules.ChatXmppModule.Models.MessageType.Chat)
is just a string. I've dug into disassembled code and after some investigation understood that internally this parameter is used as XML so I tried these two options
var extraParams = "<extraParams> " +
"<save_to_history>1</save_to_history> " +
"</extraParams>";
And Also
var extraParams = "<save_to_history>1</save_to_history> ";
But none of these worked.
Anybody has idea how I should specify the extraParam?
Regards
The issue was simply that I forgot to call connect before I was sending a message.
Here is the method to send a message
public async Task SendMessageAsync(IUser sender, IChatMessage message, string channelID, CancellationToken token)
{
await loginIfRequired(sender, token);
var jsonMessage = JsonConvert.SerializeObject(message);
var recipientID = await getQuickbloxUserId(message.RecipientID, token);
var extraParams = "<extraParams> " +
"<save_to_history>1</save_to_history> " +
"</extraParams>";
_quickblox.ChatXmppClient.SendMessage(recipientID, jsonMessage, extraParams, channelID);
}
Inside loginIfRequired I call
_quickblox.ChatXmppClient.Connect(_currentUserID.Value, password);
And everything worked fine and the dialog was created.
Hope this will help someone.

Tweetsharp - Oauthaccestoken overflowexception

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.

Ensure download was completed

I am using a for loop in which Webclient class Downloadstring() method is used to load a external url .
The Url has been provided by SMS service provider in which Mobile number and the message to be transmitted is added.
But message is not being submitted to SMS gateway for all mobile numbers specified in phNos[] array ie downloading Url is skipped for some numbers . This occurs mostly for mobile numbers at end of array.
How can I ensure that program waits until url is loaded for particular number and then the program progresses forward.
WebClient cli = new WebClient();
for (i=0;i<phNos.Length;i++)
{
string url = #"http://example.com?DestNo=" + phNos[i] + "&msg=" + message;
cli.DownloadString(url);
}
Alternately I have also used System.Net.HttpWebRequest but the problem persist.
for (i=0;i<phNos.Length;i++)
{
string url = #"http://example.com?DestNo=" + phNos[i] + "&msg=" + message;
Uri targetUri = new Uri(url);
HttpWebRequest hwb = (HttpWebRequest)HttpWebRequest.Create(targetUri);
System.Net.HttpWebResponse response = hwb1.GetResponse();
int status = (int)response.StatusCode;
if (status == 200)
{
Response.Write("Successfully transmitted" + status);
}
}
Is there any other alternative method to ensure message is submitted 100 %.
Your code looks fine. DownloadString is blocking and if an error occurs it should raise an exception. How does the SMS gateway respond to your request? You should have a look at their documentation, because probably you can write a function that tests whether everything worked fine or not.
const int MAX_RETRY = 10;
WebClient cli= new WebClient();
for(i=0;i<phNos.Length;i++)
{
url = #"http://aaa.bbb.ccc.ddd?DestNo=" + phNos[i] + "&msg=" + message;
int cntRetry = 0;
while (!TestResult(cli.DownloadString(url)) && cntRetry < MAX_RETRY)
++cntRetry;
}
The problem could be that you are submitting too many requests to the gateway in a very short time. You could try to put some Thread.Sleep(1000) calls somewhere and see if things get any better.
WebClient cli= new WebClient();
for(i=0;i<phNos.Length;i++)
{
Thread.Sleep(1000);
url = #"http://aaa.bbb.ccc.ddd?DestNo=" + phNos[i] + "&msg=" + message;
cli.DownloadString(url);
}
You could also combine the two above examples, using maybe lower values for MAX_RETRY and Thread.Sleep.
const int MAX_RETRY = 5;
WebClient cli= new WebClient();
for(i=0;i<phNos.Length;i++)
{
url = #"http://aaa.bbb.ccc.ddd?DestNo=" + phNos[i] + "&msg=" + message;
int cntRetry = 0;
while (!TestResult(cli.DownloadString(url)) && cntRetry < MAX_RETRY) {
Thread.Sleep(500);
++cntRetry;
}
}
I would instantiate a webclient for every call and dispose it after downloadstring is called, like so
foreach(var phone in phNos)
{
using(WebClient cli= new WebClient())
{
url = String.Format(#"http://aaa.bbb.ccc.ddd?DestNo={0}&msg={1}", phone, message);
string result = cli.DownloadString(url);
// check if result has somekind of errorreport maybe?
Trace.WriteLine(result); // optionally write it to a trace file
}
}
Getting it disposed explicitely might help in also closing underlying networkconnections more quickly because I suspect the sheer number of connections are causing the issue. Throttling might also be an option (send less calls to the gateway per minute)
If this are 10000 or 100000 calls the network components between you and the sms gateway can be the culprit. Think off adsl modems/vpn software/routing issues or even the sms-gateway itself.
If that still doesn't resolve the issue: try Fiddler and or Wireshark to deeply inspect http traffic or even tcp/ip traffic.

Google Analytics API in C# -Execution of request failed: https://www.google.com/analytics/feeds/accounts/default

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.

Categories