xamarin.forms httpclient change BaseAddress multiple times runtime - xamarin.forms

I have updated my Xamarin.Forms to latest Version (4.5.0.530).
After that I cannot change the BaseAddress of my httpclient.
I have the following Code:
private static HttpClient client = new HttpClient(new NativeMessageHandler());
client = new HttpClient(new NativeMessageHandler());
client.BaseAddress = new Uri(App.hostserveradress);
client.Timeout = TimeSpan.FromMinutes(5);
Later, after I called the Webservice with:
responseReset = await client.PostAsync("GetResetFotos", contentReset);
I want to change the BaseAddress to another:
client.BaseAddress = new Uri(App.serveradress);
But when I set thew new BaseAddress I get following error:
This instance has already started one or more requests. Properties can only be modified before sending the first request.
Before the updating Xamarin.Forms everything works perfect, now I get the named error.
What can I do?
Thanks.

You don't NEED to set a base address. If you simply use full URLs, you
can make requests to as many sites as you want.
This solved my problem thanks #PaulVrugt

Related

Simple Odata Client to consume Odata with Authentication not working

I m new to Simple.Odata.client. I had a problem to access the Odata Service with below code. The below code return null. but Postman return with result.
suspected Problem : How to pass a url string with '1000' &format=json
Is the below Simple odata client setup correctly?
There is no UrlBase in Simple Odata client, but there is BAseUri
Is this ODataClientSettings working??
var settings = new Simple.OData.Client.ODataClientSettings();
settings.BaseUri = new Uri("https://..../UoM?$filter=wer eg '1000' &format=json");
settings.Credentials = new NetworkCredential("user1", "usrpwd");
var client = new ODataClient(settings);
please help
Thanks
This worked for me
var credentials = new NetworkCredential(userName, password); //you can use the override with the domain too.
var settings = new ODataClientSettings(baseUrl, credentials) //baseUrl is a string.
{
IgnoreResourceNotFoundException = true,
OnTrace = (x, y) => Debug.WriteLine(x, y),
PayloadFormat = ODataPayloadFormat.Json, //here is where you specify the format
IgnoreUnmappedProperties = true,
RenewHttpConnection = true,
TraceFilter = ODataTrace.All,
PreferredUpdateMethod = ODataUpdateMethod.Merge
};
var client = new ODataClient(settings);
Your baseUrl should not contain all those OData tags but the endpoint of your service like https://myservice.mysite.com/api.svc. Then as you use the Simple.OData.Client the resource url will be automatically completed.
Please, take a look at the OData standard to figure out how it works and see the Simple.OData.Client repo's examples to better understand how to use it.
To better understand how to use the Windows Authentication you can check Authentication and Authorization with Windows Accounts and how to access website with Windows credential
Hope this help.

Updating Calendar Event Giving Error "The specified value is not a valid quoted string"

As of today we are getting an error when we try to update an event using Google Calendar V3 API.
Here is our code:
string certificateFile = getCertificateFile();
string certificatePassword = getCertificatePassword();
string serviceAccountEmail = getServiceAccountEmail();
X509Certificate2 certificate = new X509Certificate2(AppDomain.CurrentDomain.BaseDirectory + "certs//" + certificateFile, certificatePassword, X509KeyStorageFlags.Exportable);
ServiceAccountCredential credential = new ServiceAccountCredential(
new ServiceAccountCredential.Initializer(serviceAccountEmail)
{
Scopes = new[] { Google.Apis.Calendar.v3.CalendarService.Scope.Calendar },
User = user
}.FromCertificate(certificate));
Google.Apis.Calendar.v3.CalendarService service = new Google.Apis.Calendar.v3.CalendarService(new BaseClientService.Initializer()
{
HttpClientInitializer = credential,
ApplicationName = "Test",
});
try
{
Event evv = service.Events.Get(user, "6ebr4dp452m453n468movuntag").Execute();
EventsResource.UpdateRequest ur = new EventsResource.UpdateRequest(service, evv, user, evv.Id);
ur.Execute();
}
catch (Exception ex)
{
Response.Write(ex.Message);
}
The Error message is " The specified value is not a valid quoted string. "
This is basic code that always works. We can still query and insert Events. For some reason updates have just stopped working?
Anybody else getting this?
I found what is the problem: Google API's ETag functionality seems to be broken.
To get around the issue I had to download the source code of the .NET Google API client libraries from google-api-dotnet-client Downloads and commented the call to the method AddETag() on line 189 of ClientServiceRequest.cs; that method adds the If-Match ETag header that's currently causing the issues. This file is in the GoogleApis project.
public HttpRequestMessage CreateRequest(Nullable<bool> overrideGZipEnabled = null)
{
var builder = CreateBuilder();
var request = builder.CreateRequest();
object body = GetBody();
request.SetRequestSerailizedContent(service, body, overrideGZipEnabled.HasValue
? overrideGZipEnabled.Value : service.GZipEnabled);
//AddETag(request);
return request;
}
See Protocol Reference: Updating Entries for more information on how Google API's use ETags and the If-Match header.
The problem in the Calendar API was fixed so no need to use this workaround!
Please don't use the above suggestion. Although it works, it will actually eliminate an important feature of etag in the library. A better solution is available at: https://codereview.appspot.com/96320045/
Thanks diegog for your work-around, I'm pretty sure it helped several users who were stuck today.

How to create persistent header in MVC web API

I am working on angularJS project right now, and on login of a user want to set my custom header value with UserID and name to be presistent. IS it possible to presist header enven after browser restart?
one of my last tries was this code:
var tokenIdentity = new AuthCacheManager().Authenticate(loginName, password);
// HttpContext.Current.Response.AppendHeader("Last-Update", "AuthToken");
response = Request.CreateResponse(HttpStatusCode.OK, tokenIdentity);
response.Content = new StringContent("asdasd", Encoding.GetEncoding("ISO-8859-1"), "text/xml");
response.Headers.Add("AuthToken", tokenIdentity.ToString());
response.Content.Headers.Expires = DateTimeOffset.Now.AddMinutes(10.0);
response.Content.Headers.Add("Content-Length", "{ab:a}");
response.Headers.Add("Connection", "Keep-Alive");
response.Headers.Add("Keep-Alive", "timeout = 20000 max = 100");
return response;
But it didn't work at all.
Does anyone know how to make a header persistent since what i am doing now is only alive for one request?

asynchronous web response windows phone 8

This is the code I use to download an URL as html. The thing is, is there any way I can do
this asynchronous? the problem I want to know whether the response is successful and what is in the response before the program continues. It would be perfect if you could await client.DownloadStringAsync and a task.delay won't always work besides I don't like that idea of setting an standard time to wait. Thank you!
Uri uri = new Uri(url);
WebClient client = new WebClient();
client.DownloadStringCompleted += new DownloadStringCompletedEventHandler(client_DownloadStringCompleted);
client.AllowReadStreamBuffering = true;
client.DownloadStringAsync(uri);
There are two solutions.
The first one (which I recommend) is to use the Microsoft.Net.Http NuGet package and change your code to use the new HttpClient instead of the old WebClient:
Uri uri = new Uri(url);
HttpClient client = new HttpClient();
await client.GetStringAsync(uri);
The second solution will allow you to continue using WebClient, so it may work as a temporary fix if you have a lot of other code depending on WebClient. To use async with WebClient, install the Microsoft.Bcl.Async NuGet package, and then you can use DownloadStringTaskAsync:
Uri uri = new Uri(url);
WebClient client = new WebClient();
await client.DownloadStringTaskAsync(uri);

Problem with posting to web services within asp.net

I have a web service sitting on a dev machine written in python. I am trying to access said webservice using asp.net via the server side. the webservice has been tested and works in every other instance. but when I hit it via asp.net using a post method asp.net doesn't seem to be sending the post values to the webservice at all, everything else is sent fine. If I run the exact same code in a console application everything works 100%.
using System;
using System.IO;
using System.Net;
using System.Web;
using System.Text;
class WebService {
static public String GetContent(String user_id, String content_id) {
Uri address = new Uri("http://url.to.api/");
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(address);
String response_text = String.Empty;
// Set type to POST
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.Credentials = new NetworkCredential("username", "password");
string data = string.Format("userid={0}&contentid={1}", user_id, content_id);
byte[] byteData = UTF8Encoding.UTF8.GetBytes(data.ToString());
request.ContentLength = byteData.Length;
using (Stream postStream = request.GetRequestStream()) {
postStream.Write(byteData, 0, byteData.Length);
}
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse()) {
StreamReader reader = new StreamReader(response.GetResponseStream());
response_text = reader.ReadToEnd();
}
return response_text;
}
}
updated * with the class more or less thats being used. "url, user/pass".
Also we have checked the information going back and fourth and the webservice never sees the post data... this code as is ran on both a console app and in a asp.net project both hit the webservice, both get a response. the console gets a response with valid information showing that its working, the asp.net project runs and receives and error stating that userid isn't being passed. We have dozens of other sites hitting this webservice with no issues, except non are written in asp.net.
Use a proxy such as Fiddler to view the HTTP transaction between your app and the web service. That should give you a better idea of which end the error is on, and its nature.
You may consider running this against a test "Hello World" service just to test communcations.
Also, post your real code. Change the uri if you want, but what you've quoted above won't compile. The problem may be outside of this snippet.
update
How long is it taking for you to receive a reply? Timeout? Running out of connections?

Resources