App doesn't response after got content of URL - c#

I a absolute new beginner with Swift. So i wanted to get a string from URL (in C#:
wc = System.Net.WebClient();
string response = wcDownloadString("url");
)
In Swift i tried that:
func StrToUrl(newURL: String) -> NSURL
{
return NSURL(string: newURL)!;
}
func DataToStr(getData: NSData) -> String
{
var datastring = NSString(data: getData, encoding:NSUTF8StringEncoding) as! String;
return datastring;
}
func getStringFromURL(url: String) -> String
{
return DataToStr(NSData(contentsOfURL: StrToUrl(url))!);
}
func action()
{
let tmpNewsCount = getStringFromURL("http://example.com"); // STUCK HERE
L_lastSeen.setValue("Got String: " + tmpNewsCount);
}
But after i started the function action(), my app doesn't response.
Seems like Mac App functions are running asynchron. So i can start other functions in my App, too!?
Thank You!

Related

How to wait and get return value from ViewModel using Caliburn Micro ActivateItem

I'm developing a desktop application that can communicate with a browser. What I want is to send a parameter from the browser to the desktop app to do some process and then get the return value as value.
In the app, I use Nancy to get POST data from the browser. Then I pass the data to SignHashViewModel as parameter to do some process, but I can't get the value from SignHashViewModel.
I'm trying to learn async and await to see if that can solve the problem, but I don't know how to apply it to my code.
Javascript code below posts a string hash to the Nancy server and gets the result back:
Signhash.php
<?php
if (isset($_GET['hashStr']))
{
$hashStr = $_GET['hashStr']; // get param from URL
}
?>
<script type="text/javascript">
$(document).ready(function() {
var hash = JSON.stringify("<?php echo $hashStr ?>");
$.post("http://localhost:50011/MyProject/signHash", {hash}, function(data) //this line will post hash to nancy server and get the data as result
{
var result = JSON.parse(data);
console.log("ErrCode : " + result.ErrCode );
console.log("ErrMsg : " + result.ErrMsg );
console.log("CertData : " + result.CertData );
});
});
</script>
to get POST data from the javascript i used this class.
ServerModule.cs
Post ("/signHash", (args) =>
{
string result = null;
List<string> dataItem= new List<string>();
ActivateItems.OpenItem(new SignHashViewModel(dataItem)); //This line activate the screen with param
return result; // Here I dont know how to get return value from SignHashViewModel
});
This class will sign a hash
SignHashViewModel.cs
public SignHashViewModel(List<string> dataItem)
{
DataItem = dataItem; // Set as Property
}
public PDFInfo Sign() //Run this method when button is clicked
{
PDFInfo pi = new PDFInfo();
SignHashToken jsonData = new SignHashToken();
pi = jsonData.SignHash(DataItem , userPin); //
return result;
}
I expected that I could get the result of SignHashViewModel and pass to the browser. Hope someone could help me on this or providing any other solution would be great too, thank you.

C# How can I call an http post method and get back the results

I have a method that is a http Post I call that method and pass along 2 parameter then it returns 2 parameters back . I have it working the traditional way but now I would like to get it working using RestSharp .I would like to call that method now using RestSharp but I am having no luck . This below works
public static void Main() {
var getController = new AccessController();
var merchSales = getController.Merchandise("Bags",5);
var status = merchSales.Status;
var items = merchSales.ItemsCount;
if (status.sold == status)
{
console("It's Sold");
}
else if (status.available == status)
{
console("It's Available");
}
}
I am now trying to do that using RestSharp http://restsharp.org/ . However How can I get back the return value of the Enum to do an If statement check like I did above ? For instance in the code above the merchSales.Status is an enum that will return either Available or Sold . This is my code below it's meant to be a HTTP call
public static void Main() {
var client = new RestClient ("http://localhost:1275/api/");
var request = new RestRequest("Resource/{id}", Method.POST);
request.AddParameter("Item", "Bags");
request.AddParameter("Count", 5);
RestResponse response = client.Execute(request);
client.ExecuteAsync(request, data => {
Console.WriteLine(data.Content);
});
}

Pass class name to method

I am writing a Windows Phone 8.1 App (WINRT). I have to call HTTPHandlerMethod method accepting three parameters. I pass Server API address as string, JsonString to be send to server as string, and also I need to send class name to HTTPHandlerMethod also as third parameter. How to send class name? I actually need to use class name inside this method in JSON DeSerializing:
JsonConvert.DeserializeObject(JSonData_Recieved,CLASS NAME HERE);
public async void HTTPHandlerMethod(string AddressPath,
string JSonData_ToSend, **WHAT THIRD PARAMETER TO WRITE HERE??**)
{
Object resObject = null;
HttpBaseProtocolFilter HttpBaseProtocolFilterObject = new HttpBaseProtocolFilter();
HttpClient HttpClientObject = new HttpClient(HttpBaseProtocolFilterObject);
string CompleteAddress = singletonInstance.APIServer + AddressPath;
Uri UriObject = new Uri(CompleteAddress);
HttpRequestMessage HttpRequestMessageObject =
new HttpRequestMessage(HttpMethod.Post, UriObject);
HttpRequestMessageObject.Content = new HttpStringContent(JSonData_ToSend,
Windows.Storage.Streams.UnicodeEncoding.Utf8, "application/json");
try
{
HttpResponseMessage HttpResponseMessageObject =
await HttpClientObject.SendRequestAsync(HttpRequestMessageObject,
HttpCompletionOption.ResponseContentRead);
if (HttpResponseMessageObject.IsSuccessStatusCode) //If 2xx success is recieved
{
string JSonData_Recieved =
await HttpResponseMessageObject.Content.ReadAsStringAsync();
resObject = JsonConvert.DeserializeObject(JSonData_Recieved,resType);
}
}
catch { }
}
}
What modifications should I do to this HTTPHandlerMethod method? and how to call it then?
public async void HTTPHandlerMethod(string AddressPath,
string JSonData_ToSend, Type classname)
{
}

HTTPClient for calling REST service is not working

I am trying to consume REST service which returns me the data in JSON format. And I am using simple logic. But code get stuck on the line . I have check this code from emulator as well as from Device.
var response = await httpClient.SendAsync(request);
Here is my code
public async Task<string> GetMyData(string urlToCall)
{
using (HttpClient httpClient = new HttpClient())
{
HttpRequestMessage request = new HttpRequestMessage(System.Net.Http.HttpMethod.Get, urlToCall);
var response = await httpClient.SendAsync(request);
var responseString = await response.Content.ReadAsStringAsync();
return responseString;
}
}
and calling is like,
string result = GetMyData(url).Result;
Is I am missing something? I want to get the data synchronously, instead of WebClient I choose HTTPClient for synchronous data call.
Can anyone please suggest me any solution.
EDIT
Thanks #Mike Richards for pointing me in right direction
I want to achieve the flow like below,
Call from Main.xaml.cs for aunticateuser() -> calling aunticateuser() methode in Process Class-> once response get from service return control back to Main.xaml.cs -> naviagate to another page i.e. Dashboard.xaml
But in real case its working like, call going to aunticateuser() methode in Process Class and where its send request to service and coming back to Main.xaml.cs but not waiting there to listen the response so how I will decide is this user is valid or not until I get the response?
Code
private void ApplicationBarDone_Click(object sender, EventArgs e)
{
bool isValid = checkForValidation();
if (isValid)
{
string url = txtUrl.Text.ToString().TrimStart(' ').TrimEnd(' ');
string login = txtLogin.Text.ToString().TrimStart(' ').TrimEnd(' ');
string clientKey = txtSystemKey.Text.ToString().TrimStart(' ').TrimEnd(' ');
string psw = txtPassword.Text.ToString().TrimStart(' ').TrimEnd(' ');
RestfulWebServiceUserDAO userDAO = new RestfulWebServiceUserDAO();
userDAO.authenticateUser(login, psw, clientKey, url);
//navigate to another page from here ??
}
}
In RestfulWebServiceUserDAO class authenticateUser() methode present
public async override void authenticateUser(string login, string password, string clientkey, string systemurl)
{
string url = systemurl + "/rest/user?login=" + login + "&password=" + password + "&clientkey=" + clientkey + "&languageId=" + 1;
string result = await GetMyData(url);
//or shall I navigate from here?? this is not allowed :|
}
GetMyData() methode same in RestfulWebServiceUserDAO class that what I have mark above.
Once you go async, you need to go async all the way to the top. But you need to always return an awaitable (commonly a Task).
Exception made for event handlers and method overrides. But in this case those will be fire-and-forget.
What's hapening in your code is that, although inside your authenticateUser (which, by convention, should be called AuthenticateUserAsync) method you are awaiting for the result of GetMyData (again, GetMyDataAsync), you are not returning any awaitable results to the caller. Becaus aysnc methods return to the caller as soon as they hit the first await statement.
Because of that, when ApplicationBarDone_Click calls userDAO.authenticateUser it imediately returns because it's not awaitable.
If you can't change authenticateUser, you simply can't use async-await. But being Windows Phone, network calls need to be asynchronous and you need to change that. Being so, your AuthenticateUserAsync method (remember the convention?) should look something like this:
public async override Task<string> AuthenticateUserAsync(string login, string password, string clientkey, string systemurl)
{
string url = systemurl + "/rest/user?login=" + login + "&password=" + password + "&clientkey=" + clientkey + "&languageId=" + 1;
return await GetMyDataAsync(url);
}
And your ApplicationBarDone_Click should look something like this:
private async void ApplicationBarDone_Click(object sender, EventArgs e)
{
bool isValid = checkForValidation();
if (isValid)
{
string url = txtUrl.Text.ToString().TrimStart(' ').TrimEnd(' ');
string login = txtLogin.Text.ToString().TrimStart(' ').TrimEnd(' ');
string clientKey = txtSystemKey.Text.ToString().TrimStart(' ').TrimEnd(' ');
string psw = txtPassword.Text.ToString().TrimStart(' ').TrimEnd(' ');
RestfulWebServiceUserDAO userDAO = new RestfulWebServiceUserDAO();
string result = await userDAO.AuthenticateUserAsync(login, psw, clientKey, url);
// do whatever you need to do after login.
// just remember that, during the call to userDAO.AuthenticateUserAsync
// the UI is responsive and the user can click again
}
}
To learn more about asyn-await programming, read my curation.
Try awaiting GetMyData
string result = await GetMyData(url)

How to create simpliest PHP Get API with UTF-8 support?

How to create simpliest *(less lines of code, less strange words) PHP Get API *(so any programm made in .Net C# could call url like http://localhost/api.php?astring=your_utf-8_string&bstring=your_utf-8_string ) with UTF-8 support?
What I need Is PHP API with one function - concatinate 2 strings so that a simple .net client like this would be able to use it:
public string setStream(string astring, string bstring)
{
string newAstring =Uri.EscapeDataString(astring);
string newBstring = Uri.EscapeDataString(bstring);
WebClient client = new WebClient();
var result = client.DownloadString(("http://localhost/api.php?" + string.Format("astring={0}&bstring={1}", newAstring, newBstring)).ToString());
return result;
}
public string SetStream(string astring, string bstring)
{
using (var client = new WebClient())
{
var values = new NameValueCollection() {
"astring", astring,
"bstring", bstring
};
var result = client.UploadValues(
"http://localhost/api.php",
"GET",
values
);
return Encoding.Default.GetString(result);
}
}
Dunno if I'm missing something, but:
<?php
function concatinateStrigs($a, $b){
return $a . $b;
}
echo concatinateStrigs($_GET['astring'], $_GET['bstring']);
?>

Categories

Resources