Sample code to consume resume rest API from Xamarin Storyboard ViewController - xamarin

Does anyone have sample code to consume RFest API from Xamarin Storyboard Viewcontroller. I have to use a POST method with authentication. I always get timeout error.

here is my sample code
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = data.Length;
request.Credentials = new NetworkCredential("Test1", "Pw1232");
using (var response = (HttpWebResponse)request.GetResponse())
{
var stream = response.GetResponseStream();
var reader = new StreamReader(stream);
string apiResponse = reader.ReadToEnd();
new UIAlertView("Test API", apiResponse, null, "cancel", null);
}

Related

How to find out ContentType of HtmlAgilityPack.HtmlDocument

Im trying to determine the content type of HtmlAgility.HtmlDocument. Any idea??
HtmlWeb web = new HtmlWeb();
var hDocument = web.Load(/*string*/ url);
I want to know how to find out the contentType of hDocument if possible, or if there is any work round it. Thanks
Basically what you want is the httpwebresponse object, to get this with hap you can use the taskcompletionsource class like this.
var web = new HtmlAgilityPack.HtmlWeb();
var tcs = new TaskCompletionSource<HttpWebResponse>();
web.PostResponse = delegate(HttpWebRequest request, HttpWebResponse response)
{
tcs.SetResult(response);
};
var document = web.Load("http://stackoverflow.com/");
var httpWebResponse = await tcs.Task;
var contentType = httpWebResponse.ContentType
I have not done this in a while and didn't get a chance to test this code but it should work for what you want.
Get HttpWebResponse from Html Agility Pack HtmlWeb
https://learn.microsoft.com/en-us/dotnet/api/system.net.httpwebresponse.contenttype?view=netframework-4.7.2

Asp.net Web API returning null response

am faced with a challenge for some time now. I have a web service (asp.net web api), that consumes a certain api, after the consumption, my api will then send the consumed data to another external api. I use REST Sharp for my data serialization and request.
But anytime i send this request. I get a null result.
Anybody to help?
Sequel to my question above #igor, below is my code snippet
public object AccountOpening(JObject exRequest)
{
var Account = new AccountViewModel(exRequest.ToString());
Account.cifID = "null";
Account.AddrCategory = "Mailing";
Account.Country = "NG";
Account.HoldMailFlag = "N";
Account.PrefAddr = "Y";
Account.Language = "UK (English)";
Account.IsMinor = "N";
Account.IsCustNRE = "N";
Account.DefaultAddrType = "Mailing";
Account.Occupation = "OTH";
Account.PhoneEmailType = "CELLPH";
var serviceAPI = ConfigurationManager.AppSettings["RemoteAPI"];
var request = new RestSharp.Serializers.Newtonsoft.Json.RestRequest();
request.AddParameter("application/json", Account, ParameterType.RequestBody);
request.RequestFormat = DataFormat.Json;
request.Method = Method.POST;
request.JsonSerializer = new RestSharp.Serializers.JsonSerializer();
var client = new RestClient(serviceAPI);
IRestResponse resp = client.Post(request);
if (resp.IsSuccessful==true)
{
return Json(new {resp.Content });
}
}

ASP MVC - Upload Rar Files with FTP

I have this code to upload a rar file to server and this works. But when i download the file from server, contents of file are spoiled. Please tell me how can I fix that. Thanks.
public ActionResult UpFile(HttpPostedFileBase upFile)
{
string fileName = System.IO.Path.GetFileName(upFile.FileName);
FtpWebRequest request = (FtpWebRequest)WebRequest.Create("ftp://myhostaddress.com/" + fileName);
request.Method = WebRequestMethods.Ftp.UploadFile;
request.Credentials = new NetworkCredential("myUserName", "MyPassword");
StreamReader streamReader = new StreamReader(upFile.InputStream);
byte[] fileContents = Encoding.Default.GetBytes(streamReader.ReadToEnd());
streamReader.Close();
request.ContentLength = fileContents.Length;
Stream requestStream = request.GetRequestStream();
requestStream.Write(fileContents, 0, fileContents.Length);
requestStream.Close();
FtpWebResponse response = (FtpWebResponse)request.GetResponse();
return RedirectToAction("/");
}
This code is working for me, try it:
var request = (FtpWebRequest)WebRequest.Create(ftp + fileName);
request.Method = WebRequestMethods.Ftp.UploadFile;
request.Credentials = new NetworkCredential(user, pass);
using (var input = File.OpenRead(filePth))
{
using (var output = request.GetRequestStream())
{
input.CopyTo(output);
}
}
var response = (FtpWebResponse)request.GetResponse();
response.Close();

Not able to construct httpmessage for push notification in windows phone 7

I am trying to construct the httpmessage for sending push notification(toast type), but it doesn't recognize methods in the below code. I have this code in Class Library.
Add method in sendNotificationRequest.Headers.Add("X-NotificationClass", "2");
Content Length in sendNotificationRequest.ContentLength = notificationMessage.Length;
GetRequestStream in Stream requestStream = sendNotificationRequest.GetRequestStream()
GetResponse in HttpWebResponse response = (HttpWebResponse)sendNotificationRequest.GetResponse();
HttpWebRequest sendNotificationRequest = (HttpWebRequest)WebRequest.Create(channel.ChannelUri.ToString());
sendNotificationRequest.Method = "POST";
//Indicate that you'll send toast notifications!
sendNotificationRequest.ContentType = "text/xml";
sendNotificationRequest.Headers = new WebHeaderCollection();
sendNotificationRequest.Headers.Add("X-NotificationClass", "2");
if (string.IsNullOrEmpty(txtMessage.Text)) return;
//Create xml envelope
string data = "X-WindowsPhone-Target: toast\r\n\r\n" +
"<?xml version='1.0' encoding='utf-8'?>" +
"<wp:Notification xmlns:wp='WPNotification'>" +
"<wp:Toast>" +
"<wp:Text1>{0}</wp:Text1>" +
"</wp:Toast>" +
"</wp:Notification>";
//Wrap custom data into envelope
string message = string.Format(data, txtMessage.Text);
byte[] notificationMessage = Encoding.Default.GetBytes(message);
// Set Content Length
sendNotificationRequest.ContentLength = notificationMessage.Length;
//Push data to stream
using (Stream requestStream = sendNotificationRequest.GetRequestStream())
{
requestStream.Write(notificationMessage, 0, notificationMessage.Length);
}
//Get reponse for message sending
HttpWebResponse response = (HttpWebResponse)sendNotificationRequest.GetResponse();
string notificationStatus = response.Headers["X-NotificationStatus"];
string notificationChannelStatus = response.Headers["X-SubscriptionStatus"];
string deviceConnectionStatus = response.Headers["X-DeviceConnectionStatus"];
Got it worked after moving the code to WCF project.

WP7 - Lost object's reference when making an asynchronous request/response

I am making a request to a service and getting a response. Service works fine and I am deserializing an object without a problem.
Below is an example of my code. The problem is the result object is null at the end. I do not know why am I losing a reference. What is the proper solution?
HttpWebRequest hwrq = (HttpWebRequest)WebRequest.Create("http://service.svc/Login");
hwrq.ContentType = "application/x-www-form-urlencoded; encoding='utf-8'";
hwrq.Accept = "text/xml";
hwrq.Method = "POST";
Users result = null; // object initializaiton
hwrq.BeginGetRequestStream(ar =>
{
var requestStream = hwrq.EndGetRequestStream(ar);
using (var sw = new StreamWriter(requestStream, System.Text.Encoding.UTF8))
{
sw.Write("Username Password");
sw.Close();
}
hwrq.BeginGetResponse(a =>
{
var response = hwrq.EndGetResponse(a);
var responseStream = response.GetResponseStream();
using (var sr = new StreamReader(responseStream))
{
returnedXML = sr.ReadToEnd();
XmlSerializer xds = new XmlSerializer(typeof(Users));
byte[] byteArray = Encoding.UTF8.GetBytes(returnedXML);
MemoryStream stream = new MemoryStream(byteArray);
result = (Users)xds.Deserialize(stream); // object is correct
}
responseStream.Close();
response.Close();
}, null);
}, null);
return result; // object is null!
Just like MarcinJuraszek suggested, the proper way is to make a callback and handle the results there.

Resources