ListTweetOnUserTimeline returns null - c#

I'm using TweetSharp for C#, and I'm successfully able to publish tweets to twitter via this.
However, I'm trying to read the most recent tweets from the account's timeline, but I keep getting null back every time I try to get the data. The following code returns null
string consumerKey = <consumerKey>;
string consumerSecret = <consumerSecret>;
TwitterService service = new TwitterService(consumerKey, consumerSecret);
service.AuthenticateWith(consumerKey, consumerSecret);
var options = new ListTweetsOnUserTimelineOptions()
{
ScreenName = screenName,
SinceId = 0,
Count = 5
};
var currentTweets = service.ListTweetsOnUserTimeline(options);
I've tried using UserId instead of ScreenName, but I still get null as a result fir currentTweets. All the examples I can find are pointing to this method, but it doesn't work.
Any Ideas?

If you're using an older version of .NET, then you may be using TLS 1.1 under the hood to communicate with Twitter. If you are doing this, then the AuthenticateWith will fail silently, and nothing will work.
You need to add the code
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
In order to make this work.
Also you should be passing the accessToken and accessTokenSecret to AuthenticateWith, not the consumer keys, as mentioned above.

I think your problem is the AuthenticateWith call. You appear to be passing the consumer token and secret again, but the AuthenticateWith overload that takes only two arguments expects a user token and secret. I suspect you are therefore getting an unauthorised response (not sure why you don't get an error).
I would suggest either removing the AuthenticateWith call (you've already provided the consumer token in the constructor), or changing it so you pass details for a valid user token instead of the consumer one.
You could also check the Response property on the twitter service after your call completes, and inspect the http status code/reason phrase/content etc. to see if that gives you more detail about what is going wrong.

Related

SnipCart API Authorization returns 401 Unauthorized

I want to use the V3 SnipCart API to get data about specific orders on my thank you page. I am using C# to do this. I keep getting this error when trying to use the API
System.Net.WebException:'The remote server returned an error: (401)
Unauthorized.'
I have tried to follow their documentation by using only the API key with no password as shown here. Below is my code that I wrote that is giving me the error. I wrote this inside my controller. I get the error as soon as the breakpoint hits this line responseObjGet = (HttpWebResponse)requestObjGet.GetResponse();
//Testing API get data begin
string strurltest = String.Format("https://app.snipcart.com/api/orders/c5541254-r8541-8501-0024-juy85vv002154");
WebRequest requestObjGet = WebRequest.Create(strurltest);
requestObjGet.Credentials = new NetworkCredential("HihiukoJOUBVCTYIiijiGiiYTd6tOiUyTYo", "");
requestObjGet.Method = "GET";
HttpWebResponse responseObjGet = null;
responseObjGet = (HttpWebResponse)requestObjGet.GetResponse(); //401 is triggered here
string strresulttest = null;
using (Stream stream = responseObjGet.GetResponseStream())
{
StreamReader sr = new StreamReader(stream);
strresulttest = sr.ReadToEnd();
sr.Close();
}
Concerns that I have as well are the following:
1.The API key that I entered here is my public api key since I am still in the development and testing phase. I am not sure if this api call will work with the test api key or if I have to use the real secret production key. Any thoughts?
2.I am debugging this off my local machine (localhost:) for now before I deploy these API calls to production to test these changes in prod still with the test api key, could that be a reason for the 401? Since the URL that is trying to get the info is my localhost: url and not my actual domain that I added to SnipCart Dashboard. I was thinking maybe I have to try and hit this from prod environment instead? Any thought?
These are the 2 possibilities that come to mind for me. I am not too savvy on APi's yet so I don't know if my call is missing something.
Summary: All I am trying to do is be able to use the API so that I can load the data I want for an order when users reach my custom thank you page with their token.
Our 401 "Unauthorized" status code is returned when the authentication failed to our API with your Authorization header's value.
Here's the documentation about the auth to our APIs. Make sure to return us a base64 value of your secret API key and the trailing single colon character at the end to respect the Basic Authentication Scheme.
And if you are trying to get data for an order that was placed in live mode then you would need to use the live secret API key.

Okta 'request body was not well-formed' during very simple property update

I am calling the okta API from my .Net back-end. It works fine when creating the user (the first part of the snippet below), so I know the token is correct etc. and I can confirm the new user exists.
I also, subsequently, update a property I've added to the user called 'Site'. When attempting to assign this property a value it throws an exception on the 'UpdateAsync' line that the request body was not well formed
var user = await _oktaClient.Users.CreateUserAsync(new CreateUserWithPasswordOptions
{
Profile = new UserProfile
{
FirstName = value.FirstName,
LastName = value.Surname,
Email = value.Email,
Login = value.Email,
},
Password = value.Password,
Activate = true,
});
var newUser = await _oktaClient.Users.GetUserAsync(user.Id);
newUser["site"] = Site;
await newUser.UpdateAsync(); // This line throws!
Note: I wasn't always doing it this way, I was previously assigning to the user object and then calling UpdateAsync() once I'd updated 'site' on the user object. This is an alternative approach as I'm trying different things (i.e. getting the user from the API again). Neither approach works.
What's very strange is that this has been working, I am 100% certain of that. I'm looking through my okta users directory 'as we speak', and there are a load of users, all with their site property populated. There has been no problem previously. I believe something must've been updated okta's end that now doesn't like my request for some reason but in either case I need a work-around ideally.
I can confirm Site is neither null or empty, it's simply a string.
UPDATE
I just discovered a SetProperty extension on okta's IResource, calling this before attempting to update the user causes the same issue.
Any help on this greatly appreciated.
Looks like custom attributes can't be assigned to the User object itself anymore, but need to be in the users profile: newUser.Profile["site"] = Site;

CustomVision API returns "Operation returned an invalid status code: 'NotFound'"

I am using the Nuget package Microsoft.Azure.CognitiveServices.Vision.CustomVision.Prediction
I have created a Custom Vision application in the Custom Vision portal and obtained API keys and a project ID.
Whenever I try to make a request to the API, I always get the following exception thrown:
HttpOperationException: Operation returned an invalid status code
'NotFound'
Here is my code:
HttpClient httpClient = new HttpClient();
CustomVisionPredictionClient customVisionPredictionClient = new CustomVisionPredictionClient(httpClient, false)
{
ApiKey = PredictionKey,
Endpoint = PredictionEndpoint,
};
var result = customVisionPredictionClient.PredictImageAsync(CUSTOM_VISION_PROJECT_GUID, imageData);
I have tried several different endpoints:
https://southcentralus.api.cognitive.microsoft.com/customvision/v2.0/Prediction
https://southcentralus.api.cognitive.microsoft.com/customvision/Prediction/v1.0
https://southcentralus.api.cognitive.microsoft.com/customvision/v1.1/Prediction
though on the portal the listed one is the first of the list. I have also succesfuly exported my app on Azure, which gives me the second endpoint in the list but with no more success.
I have also set a default iteration as suggested in a similar issue that I found ( CustomVision: Operation returned an invalid status code: 'NotFound' ).
I have tried this sample https://github.com/Microsoft/Cognitive-CustomVision-Windows/tree/master/Samples/CustomVision.Sample which uses a deprecated windows client, to at least ensure my project information are correct and I was able to access the API.
Any insight would be appreciated
For the .NET client SDK, you need to specify the base endpoint URL without the version or the rest of the path. The version is automatically added by the client SDK. In other words, you'll want (assuming SouthCentralUS is your region):
PreditionEndpoint = "https://southcentralus.api.cognitive.microsoft.com";
CustomVisionPredictionClient customVisionPredictionClient = new CustomVisionPredictionClient()
{
ApiKey = PredictionKey,
Endpoint = PredictionEndpoint,
};
var result = customVisionPredictionClient.PredictImageAsync(CUSTOM_VISION_PROJECT_GUID, imageData);
As an aside, note that unless you want to fine-tune the behavior, you don't need to pass in an HttpClient object to CustomVisionPredictionClient constructor.
If you need more sample code, please take a look at the QuickStart.
How to use the Prediction API
If you have an image URL:
your endpoint would be something like this
https://southcentralus.api.cognitive.microsoft.com/customvision/v2.0/Prediction/{Project-GUID}/url?iterationId={Iteration-ID}
Set Prediction-Key Header to : predictionId
Set Content-Type Header to : application/json
Set Body to : {"Url": "https://example.com/image.png"}
Or If you have an image file:
Endpoint would be like
https://southcentralus.api.cognitive.microsoft.com/customvision/v2.0/Prediction/{ProjectGuid}/image?iterationId={Iteration-Id}
Set Prediction-Key Header to : Predcition-key
Set Content-Type Header to : application/octet-stream
Set Body to : <image file>
Remember, you can mark an iteration as Default so you can send data to it without specifying an iteration id. You can then change which iteration your app is pointing to without having to update your app.
Check my other answer on the similar issue using python
Python custom vision predictor fails
Hope it helps.

C# AWS SQS request signature does not match the signature provided

I have a single project that contains classes to communicate with AWS. SQS is the only one that is not working. It is safe to assume that the access and secret keys are valid. I am also able to access this queue elsewhere so i am 100% it exists.
I have created a super basic method and this is failing.
var Config = new AmazonSQSConfig() { ServiceURL = "https://sqs.eu-west-1.amazonaws.com/.....etc"};
var Client = new AmazonSQSClient(Config);
SendMessageRequest request = new SendMessageRequest() { MessageBody = "Hello", };
SendMessageResponse sendMessageResponse = Client.SendMessage(request);
When the final line Client.SendMessage(request) runs it throws a 403 exception with the error
The request signature we calculated does not match the signature you
provided. Check your AWS Secret Access Key and signing method. Consult
the service documentation for details.
The code is so basic that i cant see where it could be wrong. The secret and access keys work for all other AWS communication so this cant be the cause and i am 100% sure the queue exists. What could be causing this?
This code works - see if you can use it instead:
using (var client = new AmazonSQSClient(Amazon.RegionEndpoint.USEast1))
{
client.SendMessage(new SendMessageRequest { QueueUrl = _queueName, MessageBody = JsonConvert.SerializeObject(request) });
}
Seems to be a really weird one, but i resolved the issue by using the fragmented AWSSDK instead of the complete one. I was using the main sdk from NuGet that contains everything for AWS. I removed this and install the core, s3 and sqs parts of the SDK. The code immediately worked once i did this. No idea why it did this and why it worked for S3 and not SQS, but at least this was a fairly simple fix.

Validating Google ID tokens in C#

I need to validate a Google ID token passed from a mobile device at my ASP.NET web api.
Google have some sample code here but it relies on a JWT NuGet package which is .Net 4.5 only (I am using C#/.Net 4.0). Is anyone aware of any samples which do this without these packages or has achieved this themselves? The use of the package makes it very difficult to work out what I need to do without it.
According to this github issue, you can now use GoogleJsonWebSignature.ValidateAsync method to validate a Google-signed JWT. Simply pass the idToken string to the method.
var validPayload = await GoogleJsonWebSignature.ValidateAsync(idToken);
Assert.NotNull(validPayload);
If it is not a valid one, it will return null.
Note that to use this method, you need to install Google.Apis.Auth nuget firsthand.
The challenge is validating the JWT certificate in the ID token. There is currently not a library I'm aware of that can do this that doesn't require .Net 4.5 and until there is a solution for JWT validation in .NET 4.0, there will not be an easy solution.
However, if you have an access token, you can look into performing validation using oauth2.tokeninfo. To perform basic validation using token info, you can do something like the following:
// Use Tokeninfo to validate the user and the client.
var tokeninfo_request = new Oauth2Service().Tokeninfo();
tokeninfo_request.Access_token = _authState.AccessToken;
var tokeninfo = tokeninfo_request.Fetch();
if (userid == tokeninfo.User_id
&& tokeninfo.Issued_to == CLIENT_ID)
{
// Basic validation succeeded
}
else
{
// The credentials did not match.
}
The information returned from the Google OAuth2 API tells you more information about a particular token such as the client id it was issued too as well as its expiration time.
Note You should not be passing around the access token but instead should be doing this check after exchanging a one-time code to retrieve an access token.
ClientId also needs to be passed, which should be set from Google API Console. If only pass TokenId, GoogleJsonWebSignature throws error. This answer is in addition to #edmundpie answer
var settings = new GoogleJsonWebSignature.ValidationSettings()
{
Audience = new List<string>() { "[Placeholder for Client Id].apps.googleusercontent.com" }
};
var validPayload = await GoogleJsonWebSignature.ValidateAsync(model.ExternalTokenId, settings);

Categories

Resources