ConnectFailure with HttpRequest in Xamarin - web-services

I'm using the free version of Xamarin Studio to do some test. In aprticular I'm trying to connect to web Service but I receive the ConnectFailure (Network unreachable) when I debug the application.
This is my code
public class MainActivity : Activity
{
protected override void OnCreate (Bundle bundle)
{
base.OnCreate (bundle);
// Set our view from the "main" layout resource
SetContentView (Resource.Layout.Main);
// Our code will go here
// Get our UI controls from the loaded layout
EditText phoneNumberText = FindViewById<EditText>(Resource.Id.editText1);
Button translateButton = FindViewById<Button>(Resource.Id.button1);
Button callButton = FindViewById<Button>(Resource.Id.button2);
// Disable the "Call" button
callButton.Enabled = false;
// Add code to translate number
string translatedNumber = string.Empty;
var rxcui = "198440";
var request = HttpWebRequest.Create(string.Format(#"http://rxnav.nlm.nih.gov/REST/RxTerms/rxcui/{0}/allinfo", rxcui));
request.ContentType = "application/json";
request.Method = "GET";
using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
{
if (response.StatusCode != HttpStatusCode.OK)
Console.Out.WriteLine("Error fetching data. Server returned status code: {0}", response.StatusCode);
using (StreamReader reader = new StreamReader(response.GetResponseStream()))
{
var content = reader.ReadToEnd();
if(string.IsNullOrWhiteSpace(content)) {
Console.Out.WriteLine("Response contained empty body...");
}
else {
Console.Out.WriteLine("Response Body: \r\n {0}", content);
}
//Assert.NotNull(content);
}
}
}
}
}
I don't understand if this is an error caused by the free version or it's me.
Please help me.
Thanks

Related

nswag generated service has no return logic

I have a asp.net WebAPI service for user login that takes an email and password. The api method has the following signature. LoginDto has two fileds, Email and password.
public async Task<IActionResult> Login(LoginDto dto)
Once the user is authenticated, WebAPI returns an object that has token and Id:
return Ok(new { Token = GenerateJwtTokenFromClaims(claims), Id=user.Id });
On the client side (Blazor app), I used nswag command line tool by running nswag run and it "successfully" generated the Service and Contract files. Everything complies. nswag generated code is pasted below.
When I want to use the login nswag Service, I have the following method (I also have an overloaded method with CancellationToken but I only use this method):
public System.Threading.Tasks.Task Login2Async(LoginDto body)
{
return Login2Async(body, System.Threading.CancellationToken.None);
}
The question that I have is that how do I get the response out of the nswag-generated-code that the WebAPI login sent back to the client? When I try to assign a var to the method, I get Cannot assign void to an implicitly-typed variable which makes sense since I don't see a return type. I also don't see any logic in the nswag generated service file to return the response to the caller. How do I get the response back from the nswag generated API call? Is there an option I have to set in nswag run to get a response object back? Thanks in advance.
public async System.Threading.Tasks.Task Login2Async(LoginDto body, System.Threading.CancellationToken cancellationToken)
{
var urlBuilder_ = new System.Text.StringBuilder();
urlBuilder_.Append(BaseUrl != null ? BaseUrl.TrimEnd('/') : "").Append("/api/Account/Login");
var client_ = _httpClient;
var disposeClient_ = false;
try
{
using (var request_ = new System.Net.Http.HttpRequestMessage())
{
var content_ = new System.Net.Http.StringContent(Newtonsoft.Json.JsonConvert.SerializeObject(body, _settings.Value));
content_.Headers.ContentType = System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json");
request_.Content = content_;
request_.Method = new System.Net.Http.HttpMethod("POST");
PrepareRequest(client_, request_, urlBuilder_);
var url_ = urlBuilder_.ToString();
request_.RequestUri = new System.Uri(url_, System.UriKind.RelativeOrAbsolute);
PrepareRequest(client_, request_, url_);
var response_ = await client_.SendAsync(request_, System.Net.Http.HttpCompletionOption.ResponseHeadersRead, cancellationToken).ConfigureAwait(false);
var disposeResponse_ = true;
try
{
var headers_ = System.Linq.Enumerable.ToDictionary(response_.Headers, h_ => h_.Key, h_ => h_.Value);
if (response_.Content != null && response_.Content.Headers != null)
{
foreach (var item_ in response_.Content.Headers)
headers_[item_.Key] = item_.Value;
}
ProcessResponse(client_, response_);
var status_ = (int)response_.StatusCode;
if (status_ == 200)
{
return;
}
else
if (status_ == 400)
{
var objectResponse_ = await ReadObjectResponseAsync<ProblemDetails>(response_, headers_).ConfigureAwait(false);
throw new ApiException<ProblemDetails>("Bad Request", status_, objectResponse_.Text, headers_, objectResponse_.Object, null);
}
else
{
var responseData_ = response_.Content == null ? null : await response_.Content.ReadAsStringAsync().ConfigureAwait(false);
throw new ApiException("The HTTP status code of the response was not expected (" + status_ + ").", status_, responseData_, headers_, null);
}
}
finally
{
if (disposeResponse_)
response_.Dispose();
}
}
}
finally
{
if (disposeClient_)
client_.Dispose();
}
}
Big thanks to the NSwag team, the issue is resolved. I was returning anonymous object from the WebAPI method. The correct way to do is the following. Notice that IActionResult was changed to ActionResult passing a concrete object to return to the caller.
public async Task<ActionResult<LoginDtoResponse>> Login(LoginDto dto)
then returning
return Ok(new LoginDtoResponse { Token = GenerateJwtTokenFromClaims(claims), Id=user.Id });
After that I did that, the following code was generated:
if (status_ == 200)
{
var objectResponse_ = await ReadObjectResponseAsync<LoginDtoResponse>(response_, headers_).ConfigureAwait(false);
return objectResponse_.Object;
}

How to running method webservice in background from android xamarin form

I want running this method UpdateStatus when he close app
It is my coding method UpdateStatus in android:
String id = "";
var id = Application.Current.Properties["Id"].ToString();
User user = new User(id);
user.Id = id;
user.Datetime = time;
var responseStatus = await api.UpdateStatus(new UpdateStatusQuery(user));
Could you help me ?
In the Android, When you close your applcation, based on my research, above code can not be run, because all of threads or services will be killed when applcation is killed.
If you want to run above code when application in the background, you can can use background service to achieve that, due to background execution limits in Android 8.0 or later, if you code need some time to execute, and you want code running stably, Foreground Services is a good choice.
In xamarin forms, you can use dependenceService in the OnSleep method of App.xaml.cs
OnSleep - called each time the application goes to the background.
You can create a interface.
IService.cs
public interface IService
{
void Start();
}
Then achieved DependentService to start a Foreground Service.
[assembly: Xamarin.Forms.Dependency(typeof(DependentService))]
namespace TabGuesture.Droid
{
[Service]
public class DependentService : Service, IService
{
public void Start()
{
var intent = new Intent(Android.App.Application.Context,
typeof(DependentService));
if (Android.OS.Build.VERSION.SdkInt >= Android.OS.BuildVersionCodes.O)
{
Android.App.Application.Context.StartForegroundService(intent);
}
else
{
Android.App.Application.Context.StartService(intent);
}
}
public override IBinder OnBind(Intent intent)
{
return null;
}
public const int SERVICE_RUNNING_NOTIFICATION_ID = 10000;
public override StartCommandResult OnStartCommand(Intent intent,
StartCommandFlags flags, int startId)
{
// From shared code or in your PCL
CreateNotificationChannel();
string messageBody = "service starting";
var notification = new Notification.Builder(this, "10111")
.SetContentTitle(Resources.GetString(Resource.String.app_name))
.SetContentText(messageBody)
.SetSmallIcon(Resource.Drawable.main)
.SetOngoing(true)
.Build();
StartForeground(SERVICE_RUNNING_NOTIFICATION_ID, notification);
//==============================do you work=====================
String id = "";
var id = Application.Current.Properties["Id"].ToString();
User user = new User(id);
user.Id = id;
user.Datetime = time;
var responseStatus = await api.UpdateStatus(new UpdateStatusQuery(user));
return StartCommandResult.Sticky;
}
void CreateNotificationChannel()
{
if (Build.VERSION.SdkInt < BuildVersionCodes.O)
{
// Notification channels are new in API 26 (and not a part of the
// support library). There is no need to create a notification
// channel on older versions of Android.
return;
}
var channelName = Resources.GetString(Resource.String.channel_name);
var channelDescription = GetString(Resource.String.channel_description);
var channel = new NotificationChannel("10111", channelName, NotificationImportance.Default)
{
Description = channelDescription
};
var notificationManager = (NotificationManager)GetSystemService(NotificationService);
notificationManager.CreateNotificationChannel(channel);
}
}
}
Here is similar thread:
How to create service doing work at period time in Xamarin.Forms?

Error during web service call in Xamarin Forms

I've added connected service via Microsoft WCF Web Service Reference Provider (see picture) proxy class has been successfuly created.
Then, when I try execute sample method from this web service (client.TestLanguageAsync() - which returns string) I get null reference exception - but I dont know what is null, because details of exception are very poor (look on picture). Below is code.
private async void BtnTest_Clicked(object sender, EventArgs e) {
try {
var endpoint = new EndpointAddress("https://f9512056.f95.ficosa.com/WMS/WMSWebService.asmx");
BasicHttpBinding binding = new BasicHttpBinding(BasicHttpSecurityMode.Transport) {
Name = "basicHttpBinding",
MaxBufferSize = 2147483647,
MaxReceivedMessageSize = 2147483647
};
TimeSpan timeout = new TimeSpan(0, 0, 30);
binding.SendTimeout = timeout;
binding.OpenTimeout = timeout;
binding.ReceiveTimeout = timeout;
WMSWebServiceSoapClient client = new WMSWebServiceSoapClient(binding, endpoint);
string text = await client.TestLanguageAsync(); //This causes exception
label.Text = text;
} catch (Exception E) {
label.Text = E.ToString();
}
}
Look also on screen
Adding service reference and exception screen
Any ideas? Thanks in advance:)

Want to get the details of the user(member) after login successfully in xamarin forms

my question is how to pass username and password from the C# client(xamarin forms) to server's API? if details are correct then the client will get whole product list from webapi(URL).and bind all the details to a listview.I want to get the member details after the success of response code.
the client will send username password from login page to server's API. if server's webapi check whether the details matched with the database, if not, don't let it get product list.
here is the code in loginservices for login(xamarin forms)
public async Task GetData(string username,string password)
{
//string detail = new UserDetails();
UserDetails userDetails = new UserDetails();
// List<UserDetails> detail = new List<UserDetails>();
try
{
var values = new List<KeyValuePair<string, string>>();
values.Add(new KeyValuePair<string, string>("Username", username));
values.Add(new KeyValuePair<string, string>("Password", password));
var content = new FormUrlEncodedContent(values);
using (var client = new HttpClient())
{
client.DefaultRequestHeaders.Clear();
client.DefaultRequestHeaders.AcceptLanguage.Add(new StringWithQualityHeaderValue("nl-NL"));
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
var response = await client.PostAsync("http://192.168.1.50/Accounts/Authenticate", content);
return response.IsSuccessStatusCode;
};
}
catch (Exception ex)
{
throw ex;
}
}
here is the code for web api---
public async Task ValidateUser([FromBody] Credentials credentials)
{
using (DemoAPPEntities entities = new DemoAPPEntities())
{
var result = await entities.MemberDetails.Where(x => x.UserName == credentials.UserName && x.Password == credentials.Password).SingleOrDefaultAsync();
if (result == null)
{
return NotFound();
}
return Ok(entities.MemberDetails);
}
}

Apple Dashcode and Webservices

I am developing my first Dashboard Widget and trying to call a webservice. But I keep on getting XMLHTTPRequest status 0.
Following is the code
var soapHeader = '<?xml version=\"1.0\" encoding=\"utf-8\"?>\n'
+'<soap:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">\n'
+'<soap:Body>\n'
+'<UsersOnline xmlns=\"http://wsSync\" />\n'
+'</soap:Body>\n'
+'</soap:Envelope>';
var destinationURI = 'http://ws.storan.com/webservicesformraiphone/wssync.asmx';
var actionURI = 'http://wsSync/UsersOnline';
function callWebService() {
try{
SOAPObject = new XMLHttpRequest();
SOAPObject.onreadystatechange = function() {fetchEnd(SOAPObject);}
SOAPObject.open('POST', destinationURI, true);
SOAPObject.setRequestHeader('SOAPAction', actionURI);
SOAPObject.setRequestHeader('Content-Length', soapHeader.length);
SOAPObject.setRequestHeader('Content-Type', 'text/xml; charset=utf-8');
var requestBody = soapHeader;
SOAPObject.send(requestBody);
} catch (E)
{
alert('callWebService exception: ' + E);
}
}
function fetchEnd(obj)
{
if(obj.readyState == 4){
if(obj.status==200)
{
alert("Yahooooooo");
}
}
}
Any ideas?
have you added
<key>AllowNetworkAccess</key>
<true/>
to the plist? if not the outside world will not be available.
You may also encounter problems if trying to cross domains.