GetRequestToken is not working in TweetSharp on Windows Phone - windows-phone-8

I can't use GetRequestToken in TwitterService anymore
and also GetAccessToken!
TwitterService service = new TwitterService("ConsumerKey", "ConsumerKeySecret");
service.GetRequestToken(Constants.CallbackUri, (request, response) =>
{
if (response.StatusCode == HttpStatusCode.OK)
{
Request = request;
var uri = service.GetAuthorizationUri(request);
Dispatcher.BeginInvoke(() => AuthBrowser.Navigate(uri));
}
});
it gives me:
'TweetSharp.TwitterService' does not contain a definition for 'GetRequestToken' and no extension method 'GetRequestToken' accepting a first argument of type 'TweetSharp.TwitterService' could be found (are you missing a using directive or an assembly reference?)

I solved it by getting Request Token via Hammock(https://github.com/danielcrenna/hammock)
and here is the code
/// <summary>
/// Gets Twitter Request Token
/// </summary>
private void GetTwitterToken()
{
var credentials = new OAuthCredentials
{
Type = OAuthType.RequestToken,
SignatureMethod = OAuthSignatureMethod.HmacSha1,
ParameterHandling = OAuthParameterHandling.HttpAuthorizationHeader,
ConsumerKey = "Your Consumer Key",
ConsumerSecret = "Your Consumer Secret",
Version = TwitterSettings.OAuthVersion,
CallbackUrl = TwitterSettings.CallbackUri
};
var client = new RestClient
{
Authority = "https://api.twitter.com/oauth",
Credentials = credentials,
HasElevatedPermissions = true,
};
var request = new RestRequest
{
Path = "/request_token"
};
client.BeginRequest(request, new RestCallback(TwitterRequestTokenCompleted));
}
and
private void TwitterRequestTokenCompleted(RestRequest request, RestResponse response, object userstate)
{
_oAuthToken = GetQueryParameter(response.Content, "oauth_token");
_oAuthTokenSecret = GetQueryParameter(response.Content, "oauth_token_secret");
var authorizeUrl = TwitterSettings.AuthorizeUri + "?oauth_token=" + _oAuthToken;
if (String.IsNullOrEmpty(_oAuthToken) || String.IsNullOrEmpty(_oAuthTokenSecret))
{
Dispatcher.BeginInvoke(() => MessageBox.Show("error calling twitter"));
return;
}
Dispatcher.BeginInvoke(() => AuthBrowser.Navigate(new Uri(authorizeUrl)));
}
and You can do the same with access token.

Have you checked to see if the TweetSharp Library supports Windows Phone 8?

Related

dot net Core 3.1 API HttpRequest returns usually bad request without even sending the request

I have a strange issue with my HttpRequest, i have 2 application one is clientside and the other one is RESTAPI, the issue is i am trying to update my entity by sending a request which the content is Json
public async Task<bool> Update(string url, T obj, string id)
{
var request = new HttpRequestMessage(HttpMethod.Put, url+id);
if (obj == null || String.IsNullOrEmpty(id))
{
return false;
}
request.Content = new StringContent(JsonConvert.SerializeObject(obj),
Encoding.UTF8, "application/json");
var client = _client.CreateClient();
client.DefaultRequestHeaders.Authorization =
new AuthenticationHeaderValue("bearer", GetBearerToken());
HttpResponseMessage response = await client.SendAsync(request);
if (response.StatusCode == System.Net.HttpStatusCode.NoContent)
{
return true;
}
return false;
}
And here is my clientapp controller below;
[HttpPost]
public async Task<IActionResult> EditUser([FromForm] UserDTO userDTO ,string id)
{
if (!ModelState.IsValid)
{
return RedirectToAction("ErrorPage", "Error");
}
userDTO.Id = id;
await _userRepository.Update(EndPoints.UserEndPoint,userDTO,id);
return RedirectToAction("GetUsers");
}
and i dont know if it is necessary because it doesnt hit even the breakpoint but i am also showing my RESTAPI code below;
/// <summary>
/// Update user
/// </summary>
/// <param name="id"></param>
/// <param name="userDTO"></param>
/// <returns></returns>
[HttpPut("{id}")]
[Authorize(Roles = "Administrator")]
[ProducesResponseType(StatusCodes.Status200OK)]
[ProducesResponseType(StatusCodes.Status400BadRequest)]
[ProducesResponseType(StatusCodes.Status404NotFound)]
[ProducesResponseType(StatusCodes.Status500InternalServerError)]
public async Task<IActionResult> UpdateUser(string id, [FromBody] UserDTO userDTO)
{
var location = GetControllerActionNames();
try
{
_logger.LogInfo($"{location}: Requested an Update for id: {id} ");
if (string.IsNullOrEmpty(id) || userDTO == null || id != userDTO.Id)
{
_logger.LogError($"{location}: Request for Id: {id} is not sucessful");
return BadRequest();
}
if (!ModelState.IsValid)
{
_logger.LogWarn($"{location}: Data was incomplete!");
return BadRequest(ModelState);
}
var isExist = await _userRepo.IsExist(id);
if (!isExist)
{
_logger.LogWarn($"{location}: with Id: {id} is not exisist");
return NotFound();
}
var usermap = _mapper.Map<CompanyUser>(userDTO);
if (usermap == null)
{
_logger.LogWarn($"{location}: Data is empty");
return BadRequest();
}
var response = await _userRepo.Update(usermap);
if (!response)
{
_logger.LogError($"{location}: Update is failed ");
return NotFound();
}
_logger.LogInfo($"User is Updated");
return NoContent();
}
catch (Exception e)
{
return InternalError($"{location} - {e.Message} - {e.InnerException}");
}
}
RESTAPI code is working when i try with PostMan.
But from the client side where i send the request it sometimes works but usually gives bad request as response instanly i mean not even go to my RESTAPI. Can you help to resolve this strange problem.
I fixed the issue, on my API Login
Because i was using Microsoft Identity and when i use await PasswordEmailSignInAsync(userName, password, false, false); it automatically genereates application cookie on my API side and i used fiddler to capture requests and i saw there when i get an error or on my API side when the thread exits the application cookie also expires after that when i made a new request from my Client to My API it was giving the bad request on my client side instantly.
So i changed my signin method to var user = await _userManager.FindByEmailAsync(userDTO.Email); var result = await _userManager.CheckPasswordAsync(user, userDTO.Password);
in order to avoid from the application cookie creation. I had already JWT token structure in my application but was useless because default authorized attribute was not using bearer schema and i modified my startup.cs a little help from [Authorize Attribute not working with JWT Access Token in ASP.Net Core1
and now everything works without any problem!.
[Route("login")]
[HttpPost]
[AllowAnonymous]
[ProducesResponseType(StatusCodes.Status200OK)]
[ProducesResponseType(StatusCodes.Status401Unauthorized)]
public async Task<IActionResult> Login([FromBody] UserLoginDTO userDTO)
{
var location = GetControllerActionNames();
try
{
var userName = userDTO.Email;
var password = userDTO.Password;
_logger.LogInfo($"{location}: User:{userName} - Attempted to Login");
//var result = await PasswordEmailSignInAsync(userName, password, false, false);
var user = await _userManager.FindByEmailAsync(userDTO.Email);
var result = await _userManager.CheckPasswordAsync(user, userDTO.Password);
if (result)
{
_logger.LogInfo($"{location}: User:{userName} Logged in Succesfully");
var tokenstring = await GenerateJSONWebToken(user);
return Ok(new { token = tokenstring });
}
_logger.LogWarn($"{location}: User:{userName} couldnt logged in ");
return Unauthorized(userDTO);
}
catch (Exception e)
{
return InternalError($"{location} - {e.Message} - {e.InnerException}");
}
}

httpclient 502 error xamarin app trasnfering photo via json

We are getting 502 error when we try to send photo in Json.
App developed with .NET and Xamarin.Form
var jsonObjGuid = JsonConvert.SerializeObject(ObjGuid);
var jsonObjFiles = JsonConvert.SerializeObject(ObjFiles, Formatting.Indented);
var url = $"{ Session.EndpointURL}{MethodNames.UploadDossierFiles.Value}";
try
{
using (HttpClient httpClient = new HttpClient())
{
httpClient.DefaultRequestHeaders.TransferEncodingChunked = true;
httpClient.Timeout = TimeSpan.FromMilliseconds(600000);
using (HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, url))
{
//request.Headers.Add(HeaderKeys.UserAgent.Value, Resources.DefaultUserAgent);
request.Headers.Add(HeaderKeys.UserAgent.Value, "MobileApp");
request.Headers.Add(HeaderKeys.Token.Value, token);
HttpContent ObjGuidContent = new StringContent(jsonObjGuid);
HttpContent ObjFilesContent = new StringContent(jsonObjFiles);
MultipartFormDataContent content = new MultipartFormDataContent
{
{ObjGuidContent, "ObjGuid"},
{ObjFilesContent, "ObjFiles"}
};
request.Content = content;
var response = await Policy.HandleResult<HttpResponseMessage>(message => !message.IsSuccessStatusCode)
.WaitAndRetryAsync(3, i => TimeSpan.FromSeconds(2), (result, timeSpan, retryCount, context) => { })
.ExecuteAsync(() => httpClient.SendAsync(request));
}
}
}
Sometimes it works but often I get this error.
Any help, suggestions? What do I need to check?

How to upload image to server (using POST) which return json in Windows Phone 8.1 RT?

I am making an app which can upload image to a server (the server works well), and I use this method to upload my image to it, but when I get the respond from the result, it return a null string, can you explain for me what did I do wrong.
I followed this method: How to upload file to server with HTTP POST multipart/form-data
HttpClient httpClient = new HttpClient();
MultipartFormDataContent form = new MultipartFormDataContent();
form.Headers.ContentType = new MediaTypeHeaderValue("multipart/form-data");
byte[] bytes = await Converter.GetBytesAsync(storageFile);
form.Add(new ByteArrayContent(bytes, 0, bytes.Count()), "\"upload-file\"", "\"test.jpg\"");
HttpResponseMessage response = await httpClient.PostAsync("my-url", form);
response.EnsureSuccessStatusCode();
httpClient.Dispose();
string sd = response.Content.ReadAsStringAsync().Result;
Debug.WriteLine("res: " + sd); // this return a null string
The request return like this:
--a81d2efe-5f2e-4f84-83b9-261329bee20b
Content-Disposition: form-data; name="upload-file"; filename="test.jpg"; filename*=utf-8''%22test.jpg%22
����Ivg?�aEQ�.�����(��9%�=��>�C�~/�QG$�֨������(�`������QE��Z��
Can you help me please!
P/s: Here is my convert method
public static async Task<byte[]> GetBytesAsync(StorageFile file)
{
byte[] fileBytes = null;
if (file == null) return null;
using (var stream = await file.OpenReadAsync())
{
fileBytes = new byte[stream.Size];
using (var reader = new DataReader(stream))
{
await reader.LoadAsync((uint)stream.Size);
reader.ReadBytes(fileBytes);
}
}
return fileBytes;
}
This might help
private async Task<string> UploadImage(StorageFile file)
{
HttpClient client = new HttpClient();
MultipartFormDataContent form = new MultipartFormDataContent();
HttpContent content = new StringContent("fileToUpload");
form.Add(content, "fileToUpload");
var stream = await file.OpenStreamForReadAsync();
content = new StreamContent(stream);
content.Headers.ContentDisposition = new ContentDispositionHeaderValue("form-data")
{
Name = "fileToUpload",
FileName = file.Name
};
form.Add(content);
var response = await client.PostAsync("my-url", form);
return response.Content.ReadAsStringAsync().Result;
}
Use ByteArrayContent instead of StringContent. That Should work.
And if you are expecting a stream-response you should use ReadAsStreamAsync instaed of ReadAsStringAsync.

Send Cookies with HTTPWebRequestion through WP8 App

I have to send the cookies to server for every subsequent HTTPWebRequest. My code goes below.
class APIManager
{
CookieContainer cookieJar = new CookieContainer();
CookieCollection responseCookies = new CookieCollection();
private async Task<string> httpRequest(HttpWebRequest request)
{
string received;
using (var response = (HttpWebResponse)(await Task<WebResponse>.Factory
.FromAsync(request.BeginGetResponse, request.EndGetResponse, null)))
{
using (var responseStream = response.GetResponseStream())
{
using (var sr = new StreamReader(responseStream))
{
cookieJar = request.CookieContainer;
responseCookies = response.Cookies;
received = await sr.ReadToEndAsync();
}
}
}
return received;
}
public async Task<string> Get(string path)
{
var request = WebRequest.Create(new Uri(path)) as HttpWebRequest;
request.CookieContainer = cookieJar;
return await httpRequest(request);
}
public async Task<string> Post(string path, string postdata)
{
var request = WebRequest.Create(new Uri(path)) as HttpWebRequest;
request.Method = "POST";
request.CookieContainer = cookieJar;
byte[] data = Encoding.UTF8.GetBytes(postdata);
using (var requestStream = await Task<Stream>.Factory.FromAsync(request.BeginGetRequestStream, request.EndGetRequestStream, null))
{
await requestStream.WriteAsync(data, 0, data.Length);
}
return await httpRequest(request);
}
}
Every time i ask for the question people say that i have to set the cookie container with request by following code line.
request.CookieContainer = cookieJar;
and i used it but still server returns the 'token does not match' error. Do i need to talk to the vendor for it?
Following image shows my problem and requirement.
I haven't seen you do something with the cookieJar !
//Create the cookie container and add a cookie.
request.CookieContainer = new CookieContainer();
// This example shows manually adding a cookie, but you would most
// likely read the cookies from isolated storage.
request.CookieContainer.Add(new Uri("http://api.search.live.net"),
new Cookie("id", "1234"));
cookieJar in your APIManager is a member, everytime your instance APIManager, the cookieJar is a new instance. you need to make sure cookieJar contains what the website needs.
you can have a look at this How to: Get and Set Cookies

How to send/post the JSON request in windowsphone

Anyone knows how to send the request using JSON content in windowsphone. I had the JSON parameters how to post it.
Simply serialize the data in JSON, and write it as a POST request to the server. Here's how I do it in one of my apps:
private static IObservable<T> GetDataAsync<T, TRequest>(TRequest input, string address)
{
var request = HttpWebRequest.Create(address);
request.Method = "POST";
var getRequestStream = Observable.FromAsyncPattern<Stream>(
request.BeginGetRequestStream,
request.EndGetRequestStream);
var getResponse = Observable.FromAsyncPattern<WebResponse>(
request.BeginGetResponse,
request.EndGetResponse);
return getRequestStream()
.SelectMany(stream =>
{
try
{
using (var writer = new StreamWriter(stream))
writer.WriteLine(JsonConvert.SerializeObject(input));
}
catch
{
// Intentionally ignored.
}
return getResponse();
})
.Select(webResponse =>
{
using (var reader = new StreamReader(webResponse.GetResponseStream()))
return JsonConvert.DeserializeObject<T>(reader.ReadToEnd());
});
}