How to connect ASMX Webservice in xamarin forms app - asmx

I am developing an app using ASMX webservice. I don't know how to connect it. I have referred here, https://developer.xamarin.com/guides/xamarin-forms/web-services/consuming/asmx.
But I am not clear about how to do this.. please can anyone provide simple app using ASMX webservice...

I will share my code as I also needed to connect to my asmx .NET web service and finally managed to do it after a lot of researching and some days trying things with no luck. I saw many posts explaying other ways to do it, but this is the easiest that I've found and the first one that has worked for me.
(I am connecting to a web service that run's in another Visual Studio in debugging mode)
var httpClient = new HttpClient();
httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("text/xml"));
httpClient.DefaultRequestHeaders.Add("SOAPAction", "http://tempuri.org/WSLogin");
string wUser = "user";
string wPassword = "password";
string soapstr = string.Format(#"<?xml version=""1.0"" encoding=""utf-8""?>
<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/"">
<soap:Body>
<WSLogin xmlns=""http://tempuri.org/"">
<wUser>{0}</wUser>
<wPassword>{1}</wPassword>
</WSLogin>
</soap:Body>
</soap:Envelope>", wUser, wPassword);
var response = httpClient.PostAsync("http://localhost:49411/Default.asmx", new StringContent(soapstr, Encoding.UTF8, "text/xml")).Result;
var content = response.Content.ReadAsStringAsync().Result;
You just have to copy this code and modify it to point to your webservice URL, and change the function's name (in my case its WSLogin) and parameters. Or you can just simply copy the entire soap xml that the web service will show if you go to it's asmx file in any browser and then select the function you want to point to.
I read somewhere that iOs needs https to work, but I haven't tried it yet. It works fine on UWP and Android for me.
Hope this helps, this was driving me crazy :)
Edit: you may need this using statements
using System;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using Xamarin.Forms;

Related

How to post form data with ASP.NET MVC 6 from backend to another url?

I have some data in my app's backend that I need to post from my application to another application.
I was thinking about creating form, filling it with the data and auto-posting with javascript within onLoad. But this seems somehow outdated practice for me. What would be the correct way to post from backend to some other application's url using ASP.NET 5 & MVC6 features?
Note: preferably, it should be JSON & RESTful design (controller will be accepting the data on another end), though I don't think this should change anything.
You should be able to use e.g. ordinary HttpClient. This is an example from the MS blog.
using System.Net.Http;
using (var client = new HttpClient())
{
var baseUri = "http://playapi.azurewebsites.net/api/products";
client.BaseAddress = new Uri(baseUri);
client.DefaultRequestHeaders.Accept.Clear();
var response = await client.GetAsync(baseUri);
if (response.IsSuccessStatusCode)
{
var responseJson = await response.Content.ReadAsStringAsync();
//do something with the response here. Typically use JSON.net to deserialise it and work with it
}
}
This is a GET example, but POST should be pretty similar. If you control both servers, then you can use a fancy thing called Swagger (and Swashbuckle nuget package for .NET). It is kind of WSDL for the REST API, it can generate full proxy to access your API, similar to what WCF does + a nice page with documentation and testing forms.
P.S. Not sure of the state of Swashbuckle for ASP.NET Core, but the pre-release version is available on Nuget as well.

Get AngularJS to talk to .NET Web API secured with Azure AD

I have two different web projects on Microsoft Azure. One project is a .NET MVC web application and the other project is a .NET Web API.
Both projects are configured to use Azure AD. The MVC web application is able to get a token and use it to make requests against the Web API. Here's sample code from the MVC web app.
string userObjectID = ClaimsPrincipal.Current.FindFirst("http://schemas.microsoft.com/identity/claims/objectidentifier").Value;
AuthenticationContext authContext = new AuthenticationContext(Startup.Authority, new NaiveSessionCache(userObjectID));
ClientCredential credential = new ClientCredential(clientId, appKey);
result = authContext.AcquireTokenSilent(todoListResourceId, credential, new UserIdentifier(userObjectID, UserIdentifierType.UniqueId));
// Make a call against the Web Api
HttpClient client = new HttpClient();
HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, webApiBaseAddress + "/api/list");
request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", result.AccessToken);
HttpResponseMessage response = await client.SendAsync(request);
So this code works just fine. However, what I need to do now is call the Web API directly from an AngularJS application. When I try to do that, I get a 401 unauthorized error.
The way I am doing this is by adding a header to the HTTP GET request sent by AngularJS. I'm setting "Bearer" to the result.AccessToken value that I am passing to the page from my MVC application (code above).
Obviously this doesn't work. I suppose now my question is what are my options? Is there an official or better way to do this? Let's say I wanted to make calls to the Web API from standard JavaScript (lets forget the complexities of AngularJS). Is there a way to authenticate with Azure AD?
the canonical way of obtaining a token for an in-browser JS application would be to use the OAuth2 implicit flow. Azure AD does not currently expose that flow, but stay tuned: we are working on enabling the scenario. No dates to share yet.
HTH!
V.
The work I mentioned in the older answer finally hit the preview stage. Please take a look at http://www.cloudidentity.com/blog/2014/10/28/adal-javascript-and-angularjs-deep-dive/ - that should solve precisely the scenario you described. If you have feedback on the library please do let us know!
Thanks
V.

Client side trouble when calling

Please use my previous question as reference. I have marked an answer already.
Question
I'm a .NET developer doing some work for a company that uses Classic ASP. My experience with server side development is VB.NET or C# with some sort of MVC pattern. Consider the following code snippet, I wrote it in an ASP page the company would like to keep and "include" in other pages where this web call would be needed. Kind of like a reusable piece of code. I've left some out for sanity reasons.
//Create ActiveXObject, subscribe to event, and send request
var xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
xmlHttp.onreadystatechange = function() {
if (xmlHttp.readyState == 4) {
xmlDoc.loadXML(xmlHttp.responseText);
debugger;
var JSON = $.xml2json(xmlDoc);
parseResponse(JSON);
}
}
urlToSend = encodeURI(REQUEST);
urlRest += urlToSend
xmlHttp.open("GET", urlRest, false);
xmlHttp.send(null);
After struggling with a variety of security problems, I was glad when this finally worked. I changed a setting in Internet Options to allow scripts to access data from other domains. I presented my solution, but the Company would have to change this setting on every machine for my script to work. Not an ideal solution. What can I do to make this run on the server instead of the client's browsers?
I have a little bit of knowledge of the <% %> syntax, but not much.
This SO Question should help you call the service server side:
Calling REST web services from a classic asp page
To Summarise, use MSXML2.ServerXMLHTTP
Set HttpReq = Server.CreateObject("MSXML2.ServerXMLHTTP")
HttpReq.open "GET", "Rest_URI", False
HttpReq.send
And check out these articles:
Integrating ASP.NET XML Web Services with 'Classic' ASP Applications
Consuming XML Web Services in Classic ASP
Consuming a WSDL Webservice from ASP
You will also need a way to parse JSON

Invoking HTTPS webservice from flex

I have an https .net webservice. Invoking web methods using tools like soap UI works fine. I am unable to invoke the webmethod from flex. My WSDL loads up fine in flex.
On deployment my flex application and the webservice are on the same server. When use the machine url and access from within the server it works fine, but not when I use the https url for the flex application.
Eg - http://machinename/flex/flexApp.html works fine with https://publicname/wservice/ws.asmx but https://publicname/flex/flexapp.html fails to work.
I have the crossdomain policy in place with full access and also I have a valid SSL certificate on the server.
When I make the call from my local machine in debug mode I see the following in Fiddler-
The WSDL call goes fine and returns back correctly and the Protocol is shown as HTTPS where as the webmethod call following it shows the protocol as HTTP and returns back with the error -
I have been stuck on this for quite some time. Any help is greatly appreciated.
Thanks,
Nikhil.
Here is my Flex code that calls it:
//business delegate
public function BusinessDelegate(responder : IResponder):void
{
_responder = responder;
_service = ServiceLocator.getInstance().getService("sqlWebService");
_service.loadWSDL();
}
//Login User
public function Login(userId:String,password:String):void
{
var asyncToken:AsyncToken = _service.LoginUser(userId,password);
asyncToken.addResponder(_responder);
}
and the service locator has the following tag where I set the URL from outside as https://....
<mx:WebService
id="sqlWebService"
useProxy="false"
concurrency="multiple"
showBusyCursor="true"
wsdl="{Url}"/>
I finally was able to resolve this problem by replacing the code where I call the Flex WebService object with the specific generated classes for the webservice.
I generated classes for the webservice using Import WebService(WSDL) and was setting the url on the main class on run time as https://.....
and it works like a charm...and I see that in fiddler it shows me correctly going out as HTTPS instead of the HTTP.
Here is what helped me -
http://livedocs.adobe.com/flex/3/html/help.html?content=security2_15.html
Comment by nated.
Thanks Flextras.com for pointing me to right direction.
Resolved.
If using WCF service and WebService in Flex, use
service.svc?wsdl for HTTP and
service.svc/wsdl?wsdl for HTTPS,

(400) Bad Request When Calling the Facebook C# SDK

I'm attempting to make use of the Facebook C# SDK in my existing ASP.NET webforms application. My intent is to allow users to bypass the forms authentication by clicking the Facebook link. The URL on that link is as follows..
facebook
Facebook handles the request and then redirects back to fboauth.aspx which has the following code behind...
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Facebook;
using System.Net;
using System.IO;
namespace StorageByMail20
{
public partial class fboauth : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
string code;
code = Request.QueryString["code"];
Label1.Text = code;
string token;
string url = "https://graph.facebook.com/oauth/access_token?client_id=000000000000000&redirect_uri=http://localhost:2708/fboauth.aspx&client_secret=000000000000000000000000&code=" + code;
WebRequest request = WebRequest.Create(url);
WebResponse response = request.GetResponse();
StreamReader reader = new StreamReader(response.GetResponseStream());
token = reader.ReadToEnd();
string decodedtoken = HttpUtility.UrlDecode(token);
Facebook.FacebookAPI api = new Facebook.FacebookAPI(decodedtoken);
JSONObject result = api.Get("/first_name");
string name = result.Dictionary["first_name"].String;
Label2.Text = token;
Label3.Text = name;
}
}
}
What I'm attempting to do on this page is the following:
Parse the authorization code from
the Facebook response
Use the authorization code to obtain the
authentication token from Facebook
Make a JSON call using the
authentication code to retreive
information about the user (name,
email, etc...)
Print that information to the page (eventually
I'll do something more interesting
with the data. For now I'm just
trying to get the API interactions
working correctly).
Everything works as intended up to the JSON call. If I comment out that line I'm OK. Otherwise Facebook returns the (400) Bad Request error. Can someone spot where I have gone wrong?
Note: there's a known bug reported here https://github.com/facebook/csharp-sdk/issues that relates to encoding issues with the access token. I think I've addressed that with the my use of UrlDecode. Also, please note that the SDK I'm attemtpting to use is the offical one (currently in Alpha) from Facebook. There are a few other C# SDKs that were created by the community.
Here are some particularly helpful articles I discovered while researching my issue.
onishimura.com/2010/08/11/facebook-c-and-asp-net-mvc-code-samples-for-friends-list-activities-list-and-wall-posts/
multitiered.wordpress.com/2010/08/05/getting-started-with-the-facebook-c-sharp-sdk/
*I removed "http://" from the links above. Evidently I need more reputation points before SO will allow me to include more than two links. Sorry folks!
The SDK you link to on Github is not the Facebook C# SDK, it is a very old and very buggy commit that Facebook submitted and then left alone. There is a much more up to date and widely used project called the Facebook C# SDK here.
It seems that you are doing a lot of leg-work that could easily be handled by either the registration plugin or the javascript sdk (which is the convention when developing Facebook Connect sites.
If you are doing any more Facebook calls server-side I strongly recommend you use the linked C# SDK. Have a look at the sample to see how little coding you have to do.

Resources