How to connect EWS (Problematically) through windows phone 8.1? - c#

I have been trying since last 3 days to connect EWS from windows phone 8.1. But I'm unable to connect with EWS.
I'm following this blog..
https://social.msdn.microsoft.com/Forums/en-US/78396950-7549-4f4f-92a6-bdf48c35300d/error-integrating-ews-22-with-windows-phone-81-app?forum=exchangesvrdevelopment
As per above site, the code which they did if we will implement that code in windows phone 8.1, the code give us exception "Method is not supported".
If we try to connect edmx url of EWS by using HttpClient from windows phone 8.1.. It will give us unauthorized ERROR.
I have checked iphone and android code for connect EWS. Its working fine.
Can any one help me for this?
Hi Jason,
I tried using HTTPWebRequest, in a sample command line project and it works fine. Below is the code -
public bool Request(string URL, string RequestXML, NetworkCredential UserCredentials)
{
HttpWebRequest SoapRequest = (HttpWebRequest)WebRequest.Create(URL);
StreamWriter RequestWriter=null;
Stream ResponseStream=null;
HttpWebResponse SoapResponse=null;
try
{
SoapRequest.AllowAutoRedirect = false;
SoapRequest.Credentials = UserCredentials;
SoapRequest.Method = "POST";
SoapRequest.ContentType = "text/xml";
RequestWriter = new StreamWriter(SoapRequest.GetRequestStream());
RequestWriter.Write(RequestXML);
RequestWriter.Close();
SoapResponse = (HttpWebResponse)SoapRequest.GetResponse();
if (SoapResponse.StatusCode == HttpStatusCode.OK)
{
ResponseStream = SoapResponse.GetResponseStream();
ResponseEnvelop = XElement.Load(ResponseStream);
return true;
}
else
{
return false;
}
}
catch(Exception ex)
{
ResponseEnvelop = null;
return false;
throw ex;
}
finally
{
SoapRequest = null;
RequestWriter.Dispose();
RequestWriter = null;
ResponseStream.Dispose();
ResponseStream = null;
SoapResponse.Dispose();
SoapResponse = null;
}
}
-------------
However some methods are not available in Windows App, so tried below code. There are no compile errors but I receive error "Method not supported". I am trying from weeks but no luck, wondering is some help is available
public async Task<bool> Request(string URL, string RequestXML, NetworkCredential UserCredentials)
{
HttpWebRequest SoapRequest = (HttpWebRequest)WebRequest.Create(URL);
StreamWriter RequestWriter = null;
Stream ResponseStream = null;
WebResponse SoapResponse = null;
try
{
SoapRequest.Credentials = UserCredentials;
SoapRequest.Method = "POST";
SoapRequest.ContentType = "text/xml";
RequestWriter = new StreamWriter(await System.Threading.Tasks.Task<Stream>.Run(() => SoapRequest.GetRequestStreamAsync()));
RequestWriter.AutoFlush = true;
RequestWriter.Write(RequestXML);
SoapResponse = await System.Threading.Tasks.Task<Stream>.Run(() => SoapRequest.GetResponseAsync());
ResponseStream = SoapResponse.GetResponseStream();
ResponseEnvelop = XElement.Load(ResponseStream);
return true;
}
Appreciate some quick help
Thanks,
Nasir

Related

Get GitHub Rest API User info C# code

https://api.github.com/users/[UserName] can be accessed via browser. I get a Json result. But I want to retrieve the same information programmatically.
I'm using the below code, which is not working as expected. Please advice.
var credentials =
string.Format(System.Globalization.CultureInfo.InvariantCulture, "{0}:",
githubToken);
credentials = Convert.ToBase64String(Encoding.ASCII.GetBytes(credentials));
client.DefaultRequestHeaders.Authorization = new
AuthenticationHeaderValue("Basic", credentials);
var contents =
client.GetStreamAsync("https://api.github.com/users/[userName]").Result;
As a result of the above code, I'm getting "Aggregate Exception".
How to achieve the requirement using c# code??? Please help
Note: Not expecting a solution with Octokit. Need proper c# code.
I found the solution. Here is the code.
HttpWebRequest webRequest = System.Net.WebRequest.Create(url) as HttpWebRequest;
if (webRequest != null)
{
webRequest.Method = "GET";
webRequest.UserAgent = "Anything";
webRequest.ServicePoint.Expect100Continue = false;
try
{
using (StreamReader responseReader = new StreamReader(webRequest.GetResponse().GetResponseStream()))
{
string reader = responseReader.ReadToEnd();
var jsonobj = JsonConvert.DeserializeObject(reader)
}
}
catch
{
return;
}
}

Unauthorized error when trying to get Nest Access Token

Everything was working fine until a couple days ago, I started getting an Unauthorized error when trying to get a Nest Access Token. I've double checked and the client ID and client secret code are all correct. Any ideas on what could be causing it?
HttpWebRequest request = WebRequest.CreateHttp("https://api.home.nest.com/oauth2/access_token?");
var token = await request.GetValueFromRequest<NestToken>(string.Format(
"client_id={0}&code={1}&client_secret={2}&grant_type=authorization_code",
CLIENTID,
code.Value,
CLIENTSECRET));
public async static Task<T> GetValueFromRequest<T>(this HttpWebRequest request, string postData = null)
{
T returnValue = default(T);
if (!string.IsNullOrEmpty(postData))
{
byte[] requestBytes = Encoding.UTF8.GetBytes(postData);
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
using (var postStream = await request.GetRequestStreamAsync())
{
await postStream.WriteAsync(requestBytes, 0, requestBytes.Length);
}
}
else
{
request.Method = "GET";
}
var response = await request.GetResponseAsync();
if (response != null)
{
using (var receiveStream = response.GetResponseStream())
{
using (var reader = new StreamReader(receiveStream))
{
var json = await reader.ReadToEndAsync();
var serializer = new DataContractJsonSerializer(typeof(T));
using (var tempStream = new MemoryStream(Encoding.UTF8.GetBytes(json)))
{
return (T)serializer.ReadObject(tempStream);
}
}
}
}
return returnValue;
}
While I can't provide an answer I can confirm the same thing is happening to my iOS app in the same timeframe.
Taking my url and post values works fine using postman in chrome. Alamofire is throwing up error 401, as is native swift test code like yours.
Have Nest perhaps changed their https negotiation?
This turned out to be because of a fault on Nest's end which was later fixed.

I get error remote server not found with a request to https url

I am developing a windows phone 8 application that gets video feeds from youtube data api. I make a httpWebRequest to https://gdata.youtube.com/feeds/api/videos?max-results=10&v=2&alt=jsonc&q=fondoflamenco but I get Error remote Server: Not Found. I have the windows phone 8 devices connected to the same network.
this is the source code:
Uri targetUri = new Uri("https://gdata.youtube.com/feeds/api/videos?max-results=10&v=2&alt=jsonc&q=fondoflamenco");
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(targetUri);
request.Method = "GET";
request.BeginGetResponse(new AsyncCallback(ReadWebRequestCallback), request);
the code for ReadWebRequestCallback is:
private void ReadWebRequestCallback(IAsyncResult callBackResult)
{
HttpWebRequest myRequest = (HttpWebRequest)callBackResult.AsyncState;
try
{
HttpWebResponse myResponse = (HttpWebResponse)myRequest.EndGetResponse(callBackResult);
using (StreamReader httpwebStreamReader = new StreamReader(myResponse.GetResponseStream()))
{
var results = httpwebStreamReader.ReadToEnd();
JObject jsonObject = JObject.Parse(results);
JArray items = JArray.FromObject(jsonObject["items"]);
List<Video> videos = new List<Video>();
foreach (var item in items)
{
Video video = new Video();
video.descripcion = item["description"].ToString();
if (item["player"]["mobile"] != null)
{
video.url = item["player"]["mobile"].ToString();
}
video.imagen = new System.Windows.Media.Imaging.BitmapImage(new Uri(item["thumbnail"]["sqDefault"].ToString()));
videos.Add(video);
}
Dispatcher.BeginInvoke(delegate()
{
MediaList.ItemsSource = videos;
});
}
}
catch (WebException ex)
{
//Dispatcher.BeginInvoke(delegate() { DescriptionBox.Text = ex.Message; });
throw;
}
}
What is wrong I am doing to get Remote Server error: Not Found
I just resolved it adding empty credentials to https requests, like this
myRequest.Credentials = new NetworkCredential("", "");
here he explains it better
http://blog.toetapz.com/2010/11/15/windows-phone-7-and-making-https-rest-api-calls-with-basic-authentication/

Posting score to Facebook app

I've been trawling the answers in SO concerning posting a score to a Facebook app, and I still can't get it to work. The code I'm using is here -
private const string FACEBOOK_POST_SCORE_URL = "https://graph.facebook.com/me/scores?access_token={0}";
public void PostScoreAsync(Action<FacebookResponse> response, FacebookScore score)
{
try
{
// Append the user's access token to the URL
Uri fullUri = new Uri(string.Format(FACEBOOK_POST_SCORE_URL, AccessToken));
string json = JsonConvert.SerializeObject(score);
var request = (HttpWebRequest)WebRequest.Create(fullUri);
request.Method = "POST";
request.ContentType = "application/json; charset=utf-8";
using (StreamWriter writer = new StreamWriter(request.GetRequestStream()))
{
writer.Write(json);
}
request.BeginGetResponse(WebRequestCallback, new FacebookResult
{
Request = request,
Response = response
});
}
catch (ThreadAbortException)
{
throw;
}
catch (WebException ex)
{
if (response != null)
response(FacebookResponse.NetworkError);
}
catch (Exception ex)
{
if (response != null)
response(FacebookResponse.OtherError);
}
}
We're using webViews rather than iOS / Android Facebook SDKs, as we're building a cross-platform app in Mono.
Obviously I have the access token & the app appears to have full permissions to do what I want to do, which I allowed after login. Any thoughts appreciated!
I eventually found out (from a colleague) that the Facebook graph api won't take json encoded parameters, so we sorted it like so -
string parameters = "score=" + score.Score;
var request = (HttpWebRequest)WebRequest.Create(fullUri);
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
using (StreamWriter writer = new StreamWriter(request.GetRequestStream()))
{
writer.Write(parameters);
}
Now it works fine - hopefully this'll help someone else not have the same problem.

System.Net.WebException: The underlying connection was closed: An unexpected error occurred on a receive

I'm trying to create a method in C# to return a string of a web pages html content from the url. I have tried several different ways, but I am getting the error System.Net.WebException: The underlying connection was closed: An unexpected error occurred on a receive.
The following works fine locally, but gets the above error when running on a remote server:
public static string WebPageRead(string url)
{
string result = String.Empty;
WebResponse response = null;
StreamReader reader = null;
try
{
if (!String.IsNullOrEmpty(url))
{
HttpWebRequest request = HttpWebRequest.Create(url) as HttpWebRequest;
request.Method = "GET";
request.KeepAlive = false;
request.ProtocolVersion = HttpVersion.Version10;
response = request.GetResponse();
reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8);
result = reader.ReadToEnd();
}
}
catch (Exception exc)
{
throw exc;
}
finally
{
if (reader != null)
{
reader.Close();
}
if (response != null)
{
response.Close();
}
}
return result;
}
This is probably not the problem, but try the following:
public static string WebPageRead(string url)
{
if (String.IsNullOrEmpty(url))
{
return null;
}
HttpWebRequest request = HttpWebRequest.Create(url) as HttpWebRequest;
if (request == null)
{
return null;
}
request.Method = "GET";
request.KeepAlive = false;
request.ProtocolVersion = HttpVersion.Version10;
using (WebResponse response = request.GetResponse())
{
using (Stream stream = response.GetResponseStream())
{
using (StreamReader reader =
new StreamReader(stream, Encoding.UTF8))
{
return reader.ReadToEnd();
}
}
}
}
I echo the earlier answer that suggests you try this with a known good URL. I'll add that you should try this with a known good HTTP 1.1 URL, commenting out the line that sets the version to 1.0. If that works, then it narrows things down considerably.
Thanks for the responses, the problem was due to a DNS issue on the remote server! Just to confirm, I went with the following code in the end:
public static string WebPageRead(string url)
{
string content = String.Empty;
if (!String.IsNullOrEmpty(url))
{
HttpWebRequest request = HttpWebRequest.Create(url) as HttpWebRequest;
if (request != null)
{
request.Method = "GET";
request.KeepAlive = false;
request.ProtocolVersion = HttpVersion.Version10;
try
{
using (WebResponse response = request.GetResponse())
{
using (Stream stream = response.GetResponseStream())
{
using (StreamReader reader = new StreamReader(stream, Encoding.UTF8))
{
content = reader.ReadToEnd();
}
}
}
}
catch (Exception exc)
{
throw exc;
}
}
}
return content;
}
Had a problem like this before that was solved by opening the url in IE on the machine with the problem. IE then asks you whether you want to add the url to the list of secure sites. Add it and it works for that url.
This is just one of the possible causes. Seriously a lot of other problems could cause this. Besides the problem described above, the best way I've found to solve this is the just catch the exception and retry the request.

Categories

Resources