.NET - Access webservice (.asmx) method using WebRequest in c#? - c#

I got a .net project from client. Right now, I need to make a WebRequest to a WebService (.asmx). The problem is i dont know how call the method in that web service using web request from c#.
my code :
RunRoutines.aspx
string UseAddress = "http://localhost:31952/api/RunRoutines.asmx";
string address = string.Format(UseAddress);
HttpWebRequest httpRequest = (HttpWebRequest)WebRequest.Create(address);
RunRoutines.asmx
public class RunRoutines : System.Web.Services.WebService
{
[WebMethod]
public string RunRR1()
{
return "Hello World";
}
}
I need to access the RunRR1() method from the web request in RunRoutines.aspx. Please advise. Thanks!

Well you can access it using the name of the reference you have given while adding service reference.
For example if it is localHost then you can try below code:
var yourService = new localHost.WebService();
yourService.RunRR1();
For more details have a look here:
Image ref: http://www.c-sharpcorner.com/UploadFile/0c1bb2/consuming-web-service-in-Asp-Net-web-application/
Which is here for more details .

Related

Accessing list from Sharepoint Webservice with Sharepoint Online 2013

I am trying to access a list from sharepoint via the web services.
I have tried lots of different web reference URLS for my web service.
The list is found at :
example.com/sites/dms/_layouts/15/start.aspx#/Lists/Documents/AllItems.aspx
the Web service URL I am using now is
https://example.com/sites/dms/_vti_bin/lists.asmx
Obviously example.com is not the real URL.
when I run the code
service.GetList("Documents");
I get the error:
List does not exist.
The page you selected contains a list that does not exist. It may have been deleted by another user.
0x82000006
My full code (many things are just for testing purposes):
public void UpdateList()
{
MKLists.Lists service = GetService();
string targetSite = "https://mywebpage.com/sites/dms";
using (ClientContext ctx = ClaimClientContext.GetAuthenticatedContext(targetSite))
{
if (ctx != null)
{
ctx.Load(ctx.Web); // Query for Web
ctx.ExecuteQuery(); // Execute
string test = (ctx.Web.Title);
}
}
CookieCollection authCookie = ClaimClientContext.GetAuthenticatedCookies(targetSite, 925, 525);
service.CookieContainer = new CookieContainer();
service.CookieContainer.Add(authCookie);
XmlNode tester = service.GetList("Documents");
}
private MKLists.Lists GetService()
{
MKLists.Lists myService = new MKLists.Lists();
myService.Credentials = System.Net.CredentialCache.DefaultCredentials;
return myService;
}
change this line:
MKLists.Lists service = GetService();
with
MKLists.Lists service = new MKLists.Lists();
i hope this helps.
Edit
according to your comment in the answer here is the update #Michael
try changing your targetsite url to
string targetSite = "https://mywebpage.com/sites/dms/_vti_bin/Lists.asmx";
hope this time it helps
IT turns out it was to do with the subsites.. and this line solved it:
service.Url = "https://mywebpage.com/sites/dms/_vti_bin/lists.asmx";
I've found some users with the same issue.
They said that these links below solved that issue. Could you try it?
http://blogs.msdn.com/b/sharepointdev/archive/2011/05/12/connecting-to-sharepoint-online-web-services.aspx
http://www.wictorwilen.se/Post/How-to-do-active-authentication-to-Office-365-and-SharePoint-Online.aspx

Change the url of a web service by reading from the web.config [duplicate]

This question already has answers here:
What should be modified to change the URL of a web service in C#?
(3 answers)
Closed 8 years ago.
I have a WCF app that consumes an asmx web service. I use the web service in a million places in the app:
public string LogOnUser(string username, string password, string db)
{
var wsi = new ASMXServiceInterface();
return wsi.LogIn();
}
public string GetNotes(string username, string password, string db)
{
var wsi = new ASMXServiceInterface();
return wsi.GetNotes();
}
etc, etc etc...
Of course i want to set the url of the service in the contructor, but its auto generated in reference.cs and if i change it there, it works but if i update my reference ( and i will) its lost and i have to manually do it again:
/// <remarks/>
public ASMXServiceInterface()
{
this.Url =
System.Web.Configuration.WebConfigurationManager.AppSettings["RQTCSServiceURL"];
}
The web service url will need to be dynamic because different versions of it have been implemented. How can i set the url of my web service once in my WCF project so the url of the service can be changed in the web.config without having to do it in reference.cs?
You can do so by adding a key to your web.config like:
<add key="webserviceURL" value ="https://mywebservice.com/WebService.asmx" />
Then in your code, do something like:
private static WebService createWebService() {
WebService service= new WebService();
string url = ConfigurationManager.AppSettings["webserviceURL"];
if ( !string.IsNullOrEmpty(url) ) {
service.Url = url;
}
return service;
}
You can change the autogeneated url for webservice by converting the UrlBehaviour to dynamic
Please see example on how to do http://www.codeproject.com/Articles/12317/How-to-make-your-Web-Reference-proxy-URL-dynamic

Working with Web services response

My page must get a response from a web service with the following calls:
GetModBook.InvService.InventoryServiceClient isc = new GetModBook.InvService.InventoryServiceClient();
GetModBook.InvService.GetModBookingsOperationRequest gmoreq = new GetModBook.InvService.GetModBookingsOperationRequest();
GetModBook.InvService.GetModBookingsOperationResponse gmores = new GetModBook.InvService.GetModBookingsOperationResponse();
GetModBookingsOperationResponse has a field called Bookings with an array of Booking as such
public GetModBookingsOperationResponse
{
public Booking Bookings;
}
I have used the request portion of a web service
example:
gmoreq.RatePackages = new GetModBook.InvService.GetModBookingsOperationRequest[NoofRatePackages]
Editted:
Calling a web service
but I do not know how to call the response portion
Any advise would be greatly appreciated.
Editted:
GetModBookingsResponse GetModBookings(GetModBookingsRequest request)
Here is how you can get response
GetModBook.InvService.InventoryServiceClient isc = new GetModBook.InvService.InventoryServiceClient();
GetModBook.InvService.GetModBookingsOperationRequest gmoreq = new GetModBook.InvService.GetModBookingsOperationRequest();
//set the request parameters if there any
GetModBook.InvService.GetModBookingsOperationResponse gmores =isc.GetModBookings(gmoreq);
Without seeing your complete class implementation I can't say how to call it but here is an example on how to call web service method.
The following example will show how to get server using web service.
Web service cs file
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.ComponentModel.ToolboxItem(false)]
public class SampleWebService : System.Web.Services.WebService
{
[WebMethod]
public DateTime GetServerDate()
{
return DateTime.Now;
}
}
Webservice consumer page
SampleWebServiceWS.SampleWebServiceClient ws = new SampleWebServiceWS.SampleWebServiceClient();
DateTime dt= ws.GetServerDate();
Similar way you can call your method and assign it to a variable.
I didn't tested the code but hope this will give an idea on how to implement this.

SimpleGeo DotnetOpenAuth for C#

I have moved simpleGeo sample from VB(langsamu) to C#. This is an amazing feature for my needs but i not abled to fix the OAuth class that i can't initialize correctly to test-it. I haved posted my complete project in this bottom link including sample. The simpleGeo.dll implement base classes to connect and query simpleGeo. Client.cs is the main point to go & implementing ConsumerBase. need and Gmaps key and simpleGeo key easier to get. Can someone help me to fix.
Thanks for your help, Romi.
here VB : http github.com / simplegeo / simplegeo-dotnet
here C# : C# simpleGeo that need your help
namespace SimpleGeo
{
public class Client : DotNetOpenAuth.OAuth.ConsumerBase
{
private SimpleGeo.Description Services;
private SimpleGeo.TokenManager Tokens;
public Client(Version Version, string Key, string Secret): base(new Description(Version), new TokenManager(Key, Secret))
{
//added because not firing Public proprieties of base.
Services = new Description(Version);//remplace Services
Tokens = new TokenManager(Key, Secret);//remplace Token
}
...
public ServiceProviderDescription Service
{
get { return base.ServiceProvider; }
}
private IConsumerTokenManager Token
{
get { return base.TokenManager; }
}
....
Well, I love simplegeo but the guys dont see .NET as a viable API consumer :) - VB sample is pretty much useless and SimpleGeo.NET seems abandoned (?). I decided to roll out my own client for a project I have in mind and since there is an excellent REST library supporting OAuth (RestSharp) I gave it a try with simplegeo. A very rude example follows:
//create client and pass OAuth credentials
RestClient client = new RestClient("http://api.simplegeo.com");
client.Authenticator = OAuth1Authenticator.ForRequestToken(yourapikey, yoursecret);
//sample of creating a request for a specific simplegeo endpoint (places near an IP)
RestRequest request = new RestRequest(Method.GET) {Resource = "{version}/places/{ip}.json", RequestFormat.Json};
request.AddParameter("version", "1.0", ParameterType.UrlSegment);
request.AddParameter("ip", anyiphere, ParameterType.UrlSegment);
//call the api function
RestResponse response = client.Execute(request);
//get the simplegeo response in json
string json = response.Content;
Use Json.NET for deserializing into any custom classes of yours.
You may have a helper class constructing the request for you according to parameters passed - keep version somewhere not hardcoded just in case :)

Android -- How to access data in an ASP.NET database via app?

I have a Windows web server already set up with a website (unlimited application pools) and I want to be able to access a database on that server via the Android app I'm developing. How can I do this? Can someone point me to a tutorial or give code example of how this cross-platform (Android/Java to ASP.NET/C#) communication can be done?
(I'm trying to create a leader board or global scoreboard for my Android game on my server.)
Thanks.
Your app should expose a webservice.
There is no native support for .net soap based webservices. But you can use the ksoap android port:
http://code.google.com/p/ksoap2-android/
which allows an android app to consume a .net asmx webservice.
However the deserialisation of complex on the client side involves lot of code writing for every object you want so pass to the client.
I tried it for a project and there were some problems I ran into (either I could get result back to the client but the parameters i passed where always null or the other way - I could pass arguments but the result was null).
Here is an example I posted for getting an int: How to call a .NET Webservice from Android using KSOAP2?
However, from my current knowlege I would suggest using a .asmx webservice that returns a json string and use a java json serialiser to parse the output. The advantages:
Write less code
Faster, since mobile devices don't always have good internet connections and the xml overhead from soap is bigger than json.
Quickstart:
Create a new asmx Webservice in your .net webapp.
Include a reference to System.Web.
Decorate your webservice class with [ScriptService] and your method with [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
[ScriptService]
public class WebService1 : System.Web.Services.WebService
{
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public string HelloAndroid()
{
return "Hello Android";
}
}
(I think you have to add a reference to System.Web.Extension.dll which is available since .net 3.5).
Your webservice will still return XML (so you can use it with a soap client) unless you make a HTTPPost request with content-type "application/json".
use this code to contact the webservice from android:
private JSONObject sendJsonRequest(string host, int port,
String uri, JSONObject param)
throws ClientProtocolException, IOException, JSONException
{
HttpClient httpClient = new DefaultHttpClient();
HttpHost httpHost = new HttpHost(host, port);
HttpPost httpPost = new HttpPost(uri);
httpPost.addHeader("Content-Type", "application/json; charset=utf-8");
if (param != null)
{
HttpEntity bodyEntity = new StringEntity(param.toString(), "utf8");
httpPost.setEntity(bodyEntity);
}
HttpResponse response = httpClient.execute(httpHost, httpPost);
HttpEntity entity = response.getEntity();
String result = null;
if (entity != null) {
InputStream instream = entity.getContent();
BufferedReader reader = new BufferedReader(
new InputStreamReader(instream));
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null)
sb.append(line + "\n");
result = sb.toString();
instream.close();
}
httpPost.abort();
return result != null ? new JSONObject(result) : null;
}
if your webservice methods looks like this:
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public User GetUser(string name, int age)
{
return new User { Name = name, Age = age; }
}
You can call it this way from android:
public void getUser() {
// if you put a json object to the server
// the properties are automagically mapped to the methods' input parameters
JSONObject param = new JSONObject();
param.put("name", "John Doe");
param.put("age", 47);
JSONObject result = sendJsonRequest("server", 80,
"http://server:80/service1.asmx/GetUser", param);
if (result != null) {
JSONObject user = new JSONObject(result.getString("d"));
// .net webservices always return the result
// wrapped in a parameter named "d"
system.out.println(user.getString("name"));
system.out.println(user.getInt("age").toString());
}
}
Handling server exceptions on the client side:
Add this class to your project:
import org.json.JSONException;
import org.json.JSONObject;
public class JSONExceptionHelper {
private static final String KEY_MESSAGE = "Message";
private static final String KEY_EXCEPTIONTYPE = "ExceptionType";
private static final String KEY_STACKTRACE = "StackTrace";
public static boolean isException(JSONObject json) {
return json == null
? false
: json.has(KEY_MESSAGE) &&
json.has(KEY_EXCEPTIONTYPE) &&
json.has(KEY_STACKTRACE);
}
public static void ThrowJsonException(JSONObject json) throws JSONException {
String message = json.getString(KEY_MESSAGE);
String exceptiontype = json.getString(KEY_EXCEPTIONTYPE);
String stacktrace = json.getString(KEY_STACKTRACE);
StringBuilder sb = new StringBuilder();
sb.append(exceptiontype);
sb.append(": ");
sb.append(message);
sb.append(System.getProperty("line.separator"));
sb.append(stacktrace);
throw new JSONException(sb.toString());
}
}
Now replace the return statement from the sendJSONRequest with:
JSONObject json = result != null ? new JSONObject(result) : null
if (JSONExceptionHelper.isException(json))
JSONExceptionHelper.ThrowJsonException(json);
return json;
Please note: The exception is passed to the client only if connection comes from localhost.
Otherwise you get an http error 500 (or 501? I can't remember). You have to configure your IIS to send error 500 to the client.
Try it out and create a webservice that always throws an exception.
Sounds like a job for Web Services.
Start by creating a Web Service on the Windows web server, you can do this with ASP.NET (or maybe this might be more current).
On the Java side you can call the webservice and use the results that you get back. I think this question may help you get started on this side.
In case you have trouble writing web methods which return array of objects, you may want to refer here:
ksoap android web-service tutorial
Hope it helps.

Categories