Xamarin Forms SOAP WebService, how to get data? - c#

I have searched for a few days now and cannot figure this out. I would like to get my results from a WebService. I am using PCL and as far as I can tell we cannot use string as a variable when returning, only void.
WebServiceSoapClient client = new WebServiceSoapClient();
string result = client.SetDriverAvailAsync(varUserid, varPassword, varLocation, varDateTime);
Above is what I'm using to call the method. And the web service was written as such.
[WebMethod]
public string SetDriverAvail(string drivername, string password, string location, string datetime)
{
if (location == "" || datetime == "")
{
return "failed";
}
It does a bunch of other stuff. Then returns "success" or "failed". Bottom line is. When i make my Service Reference for a Portable Form in Xamarin the only methods it makes in the Connection Service are public voids.
If I make a Service Reference in all other projects like ASP Web Page, ect. It builds these methods differently. And does let you return a string.
CONFUSED ... THANKS

This may be a simplistic answer, but I suggest you read Xamarin introduction to web services

Related

How can I connect my front end to my individually created backend

I am a beginner in creating a code and I am trying to code using vue js for my front end and aspnet core for my backend (web api). There arent many references in creating a to do list with this two connected.
I have already individually set up my front end in vs code while my back end in c#. I am having a hard time in connecting this two as there is not much update reference. How can I call my backend and connect it to my vue js.
thank you!
The first thing you need to do is open the back end CORS settings.
It connects to an endpoint on the Vue side, you can use axios framework to pull data
Here is an example
https://www.freecodecamp.org/news/how-to-build-an-spa-with-vuejs-and-c-using-net-core/
All you need to do is call the backend via API. Get the data via GET method, send the data via POST method. Let's say you want to get person list from the backend. You can do this -
const response = await fetch('https://yourawesomebackend.com/api/person/getpeople');
const content = await response.json();
// Now manipulate the DOM with the response.
In your backend, you might want to do this -
[Route("api/[controller]/[action]")]
[ApiController]
public class PersonController : ControllerBase
{
public IActionResult GetPeople()
{
// read people from database
var people = getFromDatabase();
return Ok(people);
}
}
Hope this helps.

PATCH to a Firestore cloud Database + Refit, Update single field (c#, wpf)

I am trying to update a single attribute of a Firebase document.
I am using Refit (c#, wpf)
[Patch("/projects/super-project-name/databases/(default)/documents/users/{userId}?updateMask.fieldPaths=licence")]
public Task UpdateUserLicence3(string userId, [Body] Fields licence);
I have a 400 bad request and I wonder if the Refit Query doesn't contain a mistake somewhere.
What I know :
Publishing the same request without the [Body] Fields licence=> remove my "licence" field" from my document and doesn't crash.
GET methods on single user works too.
Thanks by advance :)
Ok, I found out what was going wrong :
The actual 'licence' attribute wasn't correct (the body).
To fix it:
I switch the 'type' from "Fields" to a string
I put into my string, my following body :
{
"fields": {
"Licence": {
"stringValue": "hello world!"
}
}
}
using a website link this : https://jsontostring.com/

Get IP Address with Web API

I'm currently using MVC4 web API and for one of the calls I need to get the client's IP address. Here is my setup...
Client computers have no internet access, only access to our intranet
since I am making cross domain calls, I have to iframe a web server page into the client HTML page and post a message.
Once the web server receives the message, it makes an ajax call to the RESTful service and C# takes it from there...
So my current goal is the get the IP address of the client machine. After some research, I found this...
private string GetClientIp(HttpRequestMessage request)
{
if (request.Properties.ContainsKey("MS_HttpContext"))
{
return ((HttpContextWrapper)request.Properties["MS_HttpContext"]).Request.UserHostAddress;
}
else if (request.Properties.ContainsKey(RemoteEndpointMessageProperty.Name))
{
RemoteEndpointMessageProperty prop;
prop = (RemoteEndpointMessageProperty)this.Request.Properties[RemoteEndpointMessageProperty.Name];
return prop.Address;
}
else
{
return null;
}
Now I realize I'm not the smartest person, but what would I pass for the parameter of HTTPRequestMessage request?
private string GetClientIp(HttpRequestMessage request)
Is there an example of this? Is this possible? Or is there another approach I should take for this
Excuse the VB.NET but you could do this also:
Add to your Global.asax (this will include the current session in your Web Api Controller):
Private Shared Function IsWebApiRequest() As Boolean
Return HttpContext.Current.Request.AppRelativeCurrentExecutionFilePath.StartsWith("~/api")
End Function
Protected Sub Application_PostAuthorizeRequest()
If IsWebApiRequest() Then
HttpContext.Current.SetSessionStateBehavior(SessionStateBehavior.Required)
End If
End Sub
Then in your Web API Controller:
Public Shared Function GetIPAddress() As String
Dim context As System.Web.HttpContext =
System.Web.HttpContext.Current
Dim sIPAddress As String =
context.Request.ServerVariables("HTTP_X_FORWARDED_FOR")
If String.IsNullOrEmpty(sIPAddress) Then
Return context.Request.ServerVariables("REMOTE_ADDR")
Else
Dim ipArray As String() = sIPAddress.Split(
New [Char]() {","c})
Return ipArray(0)
End If
End Function
You will be breaking RESTful design with this but it is all about what works, people are too dogmatic about REST in regards to certain types of projects in my opinion anyways.

C# MVC4 windows username and cookie issues

First, I'm sad to say I'm not sure whether this code should be in the _Layout.cshtml or somewhere in the controller. It needs to run on all pages, so I've put it in the _Layout.cshtml page.
This is for an intranet web app. What I'm attempting to do is this: if a cookie (holding the user's userid) is not found, get the windows username, run it through a class that will go into the database and get the corresponding user's username, and - if we get a user id back - make a cookie containing it. Doesn't sound too hard, but one line in particular, and various incarnations of it, is refusing to be supportive. Here's the code as a whole.
if(!Context.Response.Cookies.AllKeys.Contains("userid")){
var winuser = System.Web.HttpContext.Current.User.Identity.Name;
var winuserid = myprojectname.Models.MyIntranetDataContext.getUserId(winuser).UserID();
if (winuserid == null) {
Response.Redirect("/someotherpage");
} else {
HttpCookie cookieuser = new HttpCookie("userid");
DateTime now = DateTime.Now;
cookieuser.Value = winuserid;
cookieuser.Expires = now.AddMonths(1);
Response.Cookies.Add(cookieuser);
}
}
Line 2 - var winuser... - appears to be the problem. In this current incarnation, I'm getting a build error: An object reference is required for the non-static field, method, or property 'myprojectname.Models.MyIntranetDataContext.getUserId(string)'
It doesn't like it when I add a .ToString to it either.
I've tried making winuser this as well:
Page.User.Identity.Name;
That gave no build errors. When I attempt to Start Debugging, she blows up with this beauty of an error: 'Cannot perform runtime binding on a null reference'
Once I get the windows username, all will be well.
Really, this isn't about cookies, or even mvc to much of an extent (except maybe guidance on where to put this code - the _Layout.cshtml?). Really it's about getting the windows username, which I seem unable to do. Thanks in advance for any assistance you are able to provide.
Note, the above names aren't actual - just for example only.
If they are on the domain, couldn't you use something like the following to retrieve that information?
AppDomain.CurrentDomain.SetPrincipalPolicy(PrincipalPolicy.WindowsPrincipal);
WindowsPrincipal principal = (WindowsPrincipal)Thread.CurrentPrincipal;
WindowsIdentity identity = (WindowsIdentity)principal.Identity;
String userName= principal.Identity.Name;

Integer value is lost in web service call

I have an application that makes a web service call to get the URL of an MSI depending on whether the user's computer is 32bit or 64bit.
The call GetURLByOS takes 2 methods (1. string AuthenticationInfo , 2. int osBit). As I'm debugging, I can see the authentication info. The osBit's value is 8 (for 64bit) when calling into the web service. But its value is lost (0) when actually in the web service.
Can someone help me figure out why the integer value is lost?
Update:
I'm attaching to the process. In the client, I see value 8 being passed in. In the web service call, I see 0.
This is a SOAP web service call.
Here's the WSDL code on the client:
[System.Web.Services.Protocols.SoapDocumentMethodAttribute("http://mydomain.com/product/1.0/GetURLByOs", RequestNamespace = "http://mydomain.com/product/1.0", ResponseNamespace = "http://mydomain/product/1.0", Use = System.Web.Services.Description.SoapBindingUse.Literal, ParameterStyle = System.Web.Services.Protocols.SoapParameterStyle.Wrapped)]
public string GetURLByOs(string eTicket, int OsBitType)
{
object[] results = this.Invoke("GetURLByOs", new object[] {
eTicket, OsBitType});
return ((string)(results[0]));
}
Here's the actual web service:
[WebMethod]
public string GetURLByOs(string eTicket, int osBitType)
{
return MyFacade.GetUrl(eTicket, osBitType);
}
BTW, when I change the parameter to type string, it gets passed properly (value "8"). It's only when I pass it as an integer that the value is zeroed out.
I found out what was the problem. On the (client) WSDL code, the parameter is OsBitType. But on the actual web service, the parameter is osBitType. After changing the web service parameter to OsBitType, it's working fine.
Strange thing is, this doesn't occur if the parameter is a string.
For my situation, after update reference of web service, it's working fine.

Categories