How to access a WCF Service within my webpage in vs2010? - c#

I have created a simple Web Service application and used SvcUtil.exe to generate the two needed files named MyService.cs and app.config.
What I want to do now is be able to use this webservice from a web-app or webpage.
What I was doing until now was creating my website and creating an angular factory that would use ajax to call the various functions on a class that I used to create for the purpose of dealing with those requests only. For example I would have the following function inside a file name fhandler.aspx.cs:
namespace MyApp
{
[ScriptService]
public partial class fHandler: System.Web.UI.Page
{
// Save Interests Stress Test in List.
[WebMethod]
public static string saveDataJS(string data)
{
...
This would get called by an ajax request that would return a promise like this:
saveData: function(data) {
var senddata = {
'data': data
};
return $http({
method: 'POST',
url: 'http://' + location.host + '/fHandler.aspx/saveDataJS',
data: senddata,
headers: {
"Content-Type": "application/download; charset=utf-8"
}
});
},
Now that I am using web-services though I am not sure how to approach this.
What would be the best set-up for consuming a WCF service from a webpage?
Assuming we skip the create another project inside your solution, add MyService.cs and app.config to it and add a Reference to your service, part.

This tutorial once helped me a great deal with creating and consuming a WCF service.
To consume a WCF service, you simply have to add a service reference to your project. Have a look at the tutorial, it is all described with pictures.
Solution Explorer > {your project} > Add Service Reference.
After that, you can enter the URL of your service. Afterwards, you should be able to see all public methods your service offers:

Related

How to reference to a controller in another project with AngularJS $http url?

This is how I do it if the C# controller is in the same project:
$http({
method: 'GET',
url: '/api/SomeController/SomeMethod',
headers: { 'Content-Type': 'application/json' }
I'm building a SPA, so I want my AngularJS stuff and the WebApi stuff to be in their own projects.
How it's done if the controller is in another project inside the solution?
Your url has to match your url of the Web API. Your problem will be that the port of your localhost will change everytime you start your webserver.
What you can do is setting this port.
For this you just go to the properties of your Web API project, choose the tab "Web" and then mark "Use Visual Studio Deployment Server" and enter a port.
If you take something like "1337" you can make your calls in Angular like that:
$http({
method: 'GET',
url: 'localhost:1337/api/SomeController/SomeMethod',
headers: { 'Content-Type': 'application/json' }
if would really suggest you to store a base url somewhere in your javascript code, so when you deploy your page some time soon, you'll just need to change one variable.
I hope this helps you
You need to inform a full url, like:
http://localhost:5376/api/SomeController/SomeMethod
and in production, change to the IP or domain.
I like to create two constants files in my project:
URL
angular.module('app')
.constant('URL', {
local : 'http://localhost:54341/api',
dev : 'http://...',
hom : 'http://...',
prod : 'http://...'
});
Config:
angular.module('app')
.constant('CONFIG', {
env: 'local'
});
And use like this:
var url = URL[CONFIG.env] + '/anotherPath';
You will likely have problems with POST, PUT (...) request. If so, search for CORS and pre-flight problems.

unexpected token < when calling asp.net remote webservice .asmx using ajax() and jsonp

I have a very basic - for testing - ASP.net Web service (2.0 and IIS 6.0) written in VB running on a remote server
WEB SERVICE
<WebService(Namespace:="CMS_ChecklistSystemWebService")> _
<WebServiceBinding(ConformsTo:=WsiProfiles.BasicProfile1_1)> _
<Global.Microsoft.VisualBasic.CompilerServices.DesignerGenerated()> _
<System.Web.Script.Services.ScriptService()> _
Public Class CMS_ChecklistSystemWebService
Inherits System.Web.Services.WebService
<WebMethod()> _
Public Function HelloWorld() As String
Return "Hello World"
End Function
CONFIG.
i had to add these following lines to my webservice config in order to be able to run the webservice in a Browser
<system.web>
<webServices>
<protocols>
<add name="HttpGet"/>
<add name="HttpPost"/>
</protocols>
</webServices>
</system.web>
**WEB SERVICE OUTCOME **
I was trying to call this web service from PHP page using AJAX JQUERY running XAMPP v3.1
JQUERY
$.ajax({
type: "GET",
url: "http://192.168.25.11/link to web service",
data: "",
dataType: "jsonp",
contentType: "application/jsonp; charset=utf-8",
success: function(data) {
console.log(data);
}
});
ERROR
Following is how my console looks like after calling the ajax() function
FYI if i click on the link in the second line it will link you to the webservice and run it as in the first image
NOTICE
if i use the same webservice from the same project - domain - i can easily do ajax() call and type='json' and it works perfectly with no errors
Question
What i'm doing wrong ?
Do i need to make the Webservice return a JSON object instead of XML if yes then how
I think the problem is, you are specifying content type as json in ajax call. But, your web service is returning xml.
So, either you can specify content type as xml in ajax call and process the xml (I am not sure whether it is possible or not), or you can configure web service to return json.
Refer this SO question (How to return JSON from a 2.0 asmx web service) to configure web service to return json.
Rumit has, I think, only given part of the answer here. You certainly need to set your web service to return JSON instead of XML.
However, you've stated that you're setting dataType: "jsonp" This requires that you return your JSON inside a method call with the name of the method being the value of the callback key in your second image above.
for example, it would look something* like this :
jQuery1910366312976758182({data: "Hello World"})
*not exactly, but step through and you'll get the idea...

Use jquery/ajax to call a c# (or any other .net) function in another project within the same solution

Does anyone know if it's possible to use jquery/ajax to call a c# (or any other .net) function in another project within the same solution?
Let's say that the solution's name is ExampleSolution , the name of the project from which I call the target function is Project.Source and the name of the target project is Project.Target,
and the name of the target function is TargetFunction().
I've tried following in an .js file in the Project.Source:
$.ajax({
url: '/ExampleSolution/Project.Target/TargetFunction',
type: 'get',
success: function (data) {
$(document.body).append(data);
}
});
Then I've modified the url-line in several ways but never succeed.
Do you have any advice?
Thank you all for your fast answers.
I found a solution for the problem and I'd like to share it just in case anybody faces the same problem in the future.
In the .js file before I call the $.ajax function I create a variable with help of window.location which points to the url to the targetfunction of the running target-project and use the variable in the ajax-function. So you don't point to another project. You point to url of running project.
Just as easy as it sounds.
Below follows the solution:
var url = window.location = 'http://localhost:13105/TargetFunction';
$.ajax({
url: url,
type: 'get',
success: function (data) {
$(document.body).append(data);
}
});
});
You can only call functions in the Code Behind because they're being registered by the web server.
If you want to have a function accessible outside the Code Behind it needs to be registered as a ASMX or WCF service.
See Creating and Consuming Your First WCF Service for setting up a WCF Service.
Once it is setup and running you can use Ajax to call the methods just like you would in the Code Behind.
$.ajax({
//Path to WCF Server and Target Method
url: "http://localhost:PORT/wcfsvc/FooService.svc/Foo",
type: 'get',
contentType: 'application/json; charset=utf-8',
success: function (data) {
$(document.body).append(data);
}
});
See also: Consuming WCF from jQuery as JSON
The short answer is "No, it isn't possible." Front-end code (like jQuery and AJAX) run on the client's machine, but C# functions are back-end and run on the server. There's no direct connection between them.
The longer answer is "Not directly, but there are ways to do something similar." Your easiest option is to use AJAX to POST to another controller/action on your server and then process the response. This is close to what you were doing, but you were slightly off. Rather than the url being a function, the url has to be an actual url on your website. Using /Functions/CallTargetFunction as an example, you would then create a controller like this:
public class FunctionsController : Controller
{
public ActionResult CallTargetFunction()
{
return Content(TargetFunction());
}
}
Note that doing this means anyone who visits http://yoursite.com/Functions/CallTargetFunction will get the result of that function.

I can't seem to call my web service from C# Forms app

I have a web site which has a simple web service. I can call the web service successfully from javascript on the page. I need to be able to call the same web service from a C# forms application.
The web service code is very simple:
[WebService(Namespace = "http://myurl.com/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.Web.Script.Services.ScriptService]
public class IDCService : System.Web.Services.WebService {
public IDCService () {
}
[WebMethod]
public string HelloWorld() {
return "Hello World";
}
My javascript works:
function HelloWorld() {
var yourName = $get('txtYourName').value;
alert(yourName);
IDCService.HelloWorld(HelloWorldCalback, failureCB);
}
function HelloWorldCalback(result) {
alert(result);
}
function failureCB(result) {
alert("Failed");
}
However, when I try to set a reference to the WS in my C# code what I expect to see is an object with a method "HelloWorld", what I in fact see is an object with properties like "HelloWorldRequest", "HelloWorldResponse", "HelloWorldRequestBody" and so forth.
I am new to web services, and am very confused. Any help would be appreciated.
Depends on how you added your reference :-)
If you added it by clicking "Add Web Reference", you specified the location of the service, and you gave it a namespace - let's assume it would be called "MySVC".
In that case, you should be able to do this in your Winforms program:
MySVC.MyTestService svc = new MySVC.MyTestService();
string message = svc.HelloWorld();
and thus retrieve the output of the HelloWorld method.
On the other hand, if you clicked on "Add Service Reference" (which is not the same - this will add a WCF client side proxy to your web service), then you'd get those request and response object classes. You should also get a xxxxClient class, and that's what you'll use:
MyWCFService.MyTestServiceSoapClient client =
new MyWCFService.MyTestServiceSoapClient();
string message = client.HelloWorld()
That way, you should be able to access all your methods on your web service, too.
Marc

Ajax post web service url error

I am trying posting a data to a web service. And this service in a different project in same solution.
This project name is WebServices and web service's name is HastaTahlilUyariService.asmx.
My code is here:
$.ajax(
{
type: "POST",
url: "WebServices/HastaTahlilUyariService.asmx/f_HastaninAktarilacakAlislabTestleri",
data: "{_sTcKimlikNo:" + Cell.innerHTML + ",_iKlinikKodu:18001,_bAy:12,_iYil:2009}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msg) {
alert(msg);
},
error: function(msg) {
alert( 'hata'+ msg);
}
}
);
I think my url is wrong. How can i give correct url.
Thanks in advance...
You might want to change your url to something that isn't relative to where you are right now, such as url: '/WebServices/... (initial slash...)
Using the firebug addon for firefox, you can inspect the AJAX callback and see what exact URL is being requested. You can copy that URL, and you should be able to point your browser to the URL of the asmx (i.e. without the last parameter, which is the method name).
Other than that, you need to make sure you've uncommented the ScriptService attribute in the top few lines of the asmx code file. It is commented out by default, but it needs to be there to allow jQuery to access the webservice.
First of all: build your webservice, and configure it to run under something like http://localhost/services/myservice.asmx in IIS Configuration Manager. Open IIS Manager, rightclick on website -> New Virtual Directory; and navigate to the folder where your webservice is located. Name the virtual directory then services.
Then call the service with it's fully qualified url like http://localhost/myservice.asmx/function.
The most easy way to do what you are trying to do (well, I guess)
Create the method you want to call in your codebehind like
[WebMethod]
public static object MethodToCallFromAjax(string argument)
{
//do something
return result;
}
Then add a ScriptManager to your aspx page; and set enablePageMethods=true. Then call your method from JavaScript like:
PageMethods.MethodToCallFromAjax("argument value", function(msg) { alert(msg); });
edit: removed some stuff about json and asmx that wasn't true :-)
Another option to look into is the standard XMLHttpRequest object that is built into the browser (for IE 6 you have to use the ActiveX object with the same name). It makes calling XML services pretty easy, although you end up having to some of the SOAP formatting yourself.
Wikipedia entry for XMLHttpRequest

Categories

Resources