Referencing a WCF Service in the web.config file via javascript - javascript

I have an asp.net webforms website and a wcf service. I use jQuery to perform my AJAX operations to/from the WCF service like so:
$.ajax({
type: "POST",
url: "192.168.1.24/ServiceMain.svc/" + serviceName,
dataType: "json",
contentType: "application/json; charset=utf-8",
data: "{}",
cache: true,
success: function (json)
{
//Success operation here
},
error: function ()
{
//Error operation here
}
});
All is fine right now. However, I want to be able to do a testing and production environment, both of which will be hosted on a different server with different IP Addresses.
Clearly, hard-coding the URL to point to the correct WCF service will become a tedious problem if left unchecked. Therefore, I was wondering what was the best approach in retrieving the WCF Service's URL. I thought about using the web.config file with something like the following:
<%=ConfigurationManager.AppSettings("SomeWCFKey")%>
However, I am not sure how to correctly reference the address in my web.config file:
<endpoint address="http://192.168.1.24/ServiceMain.svc"
binding="basicHttpBinding"
bindingConfiguration="BasicHttpBinding_IServiceMain"
contract="ServiceMain.IServiceMain"
name="BasicHttpBinding_IServiceMain" />
Any help would be appreciated, thanks.

Hi i think you are actully want to read endpoint address that you can get by this code
private List<string> GetEndpoints()
{
var endpointList = new List<string>();
var config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
var serviceModel = ServiceModelSectionGroup.GetSectionGroup(config);
foreach (ChannelEndpointElement endpoint in serviceModel.Client.Endpoints)
{
endpointList.Add(endpoint.Address.ToString());
}
return endpointList;
}
Here is pont that descirpt mroe in detail : Getting WCF Bindings and Behaviors from any config source
this might also help you : Programmatically enumerate WCF endpoints defined in app.config

Related

Application for phonegap with remote database

I made an application based on phone gap 2.9.1 android application with local database
with transaction and create query. but now i want to make remote database for this application so that i can use it from anywhere with same database. Can anyone help me? please..
Thanks..
Make a webservice. connect through it using ajax and parse json
Edited
I tried something like this (this is not web service though)
below is made from ASP.Net
[AllowCrossSiteJson]
public JsonResult AddPerson(Person person)
{
//Get Data here
return Json(*put something here*);
}
and called it in my javascript
function saveData(person) {
var json = $.toJSON(person); //converts person object to json
$.ajax({
url: "http://somedomain.com/Ajax/AddPerson",
type: 'POST',
dataType: 'json',
data: json,
contentType: 'application/json; charset=utf-8',
success: function (data) {
alert("ok");
}
});
}
Edited Part 2
You can do the same in PHP

Unable to perform a Cross domain ajax call. - JQuery

I have checked many post and tried every logic that were mentioned in various blogs and posts. But I am unable to perform a cross domain ajax call to an IIS server. Please anybody advice what else I should look into or configure it to get working. All your help is greatly appreciated.
Here is my ajax call:
var url = "http://mydomain .com/myauthorizeservice";
var jsonParam = JSON.stringify({ username: 'user007', password: 'pass007' });
$.ajax({
type: "POST",
url: url,
crossDomain: true,
data: jsonParam,
success: fnSuccess,
error: fnError,
dataType: "json",
contentType: "application/json"
});
function fnSuccess() {
alert("Success");
}
function fnError() {
alert("Error");
}
My config in the root web.config:-
Error:-
Access Denied.
I really struggled a lot to make this thing work. Here some points that also matters and restrict the cross domain calls-
Note: I am using WCF REST service. and configurations are for IIS 7.5.
1: Make sure your OPTIONSVerbHandler looks like-
2: Make sure you have the correct ordering in HandlerMappings-
Rest settings and the way to perform ajax call is mentioned in the question.
Happy coding!

WCF Service call from ajax(cross domain)

I am trying to call WCF Service from other project using the local address. I have two projects in same solution explorer. One project has the services and the other is a web application where I am using Ajax in javascript to call the WCF Service.
Following is my javascript code,
function sclick() {
alert("m here");
$.ajax({
type: "POST",
url: "http://localhost:4780/Service1.svc/myfunction",
contentType: "application/json; charset=utf-8 ",
dataType: "json",
success: success,
error: fail
})
}
function success(result) {
alert(result);
//alert("Success" + result.myfunctionResult);
}
function fail(result) {
alert("Fail..... " + result.statusText + ": " + result.status);
}
flow goes to success function but I get null in result object. URL in ajax part is the URL I got by viewing the service1.svc file in browser.
Can anyone please tell me where I am going wrong!
It works fine in same project. But cross domain is not working. When I call the service from other project it returns me null. I gave break point in service. Break point shows proper value but it does not come in my javascript code.
You shouldn't talk to a WCF service out of the box with a regaular Web service call, it is possible but more complicated. see: http://social.msdn.microsoft.com/Forums/vstudio/en-US/c896b564-7a9b-423d-a42d-d36c33c46e7d/consume-a-wcf-service-as-a-url
That is because WCF has an "overhead" of data used by the framework. Plus , WCF configuration may differ: It could be REST, SOAP or even Tcp or named pipe.
A more easy approach would be to generate the WCF client:
http://msdn.microsoft.com/en-us/library/ms733133.aspx
and than
call the client proxy from the ajax, instead of trying to call the server directly.
That is assuming you are running on a .Net web application.
otherwise, see how to talk to the service directly. This here an example on how to do this with Java:
http://hoonzis.blogspot.co.il/2011/07/consuming-wcf-services-with-java-client.html
And finally, another good answer which was suggested here and was later deleted, is to cofigure the WCF service to support REST API, like so:
http://www.codeproject.com/Articles/128478/Consuming-WCF-REST-Services-Using-jQuery-AJAX-Call
I think your issue may be that WCF doesn't support cross domain out of the box unless you enable CORS.
There's a good read with explanation and work around here: http://blogs.msdn.com/b/carlosfigueira/archive/2012/05/15/implementing-cors-support-in-wcf.aspx
Another alternative which may be easier for you would be to just drop the WebAPI into whichever project you're using, can do this in WebForms or MVC pretty easily.
Don't know about WCF web service but May be these lines of code which is for regular service , solve your problem
var jsonData = [YOUR JSON PARAMETER];
$.ajax({
async: false,
type: "POST",
url: [YOUR WEB SERVICE URL],
contentType: "application/json; charset=utf-8",
data: JSON.stringify({ json: jsonData }),
dataType: "json",
success: OnSuccess,
failure: function(err) {
alert("Error : " + err.d);
}
});
function OnSuccess(data) {
alert("Success:" + data.d);
}
You can do one thing for that just need to set Access-Control-Allow-Origin & Access-Control-Allow-Headers in CustomeHeaders your web service web.config file.
<add name="Access-Control-Allow-Origin" value="*" />
<add name="Access-Control-Allow-Headers" value="Content-Type" />
If you want to allow only for specific domain , you can do that with specific value of domain instead of * value

ASP.net web service using javascript to send commands

I am looking to send commands to a web service page on my local network via javascript that's being used on a WebOS tablet. Problem being is that I've never done this before and was wondering if it was even possible to do in the first place? Is it possible for me to create a VB.net to listen to a web service call/webpage?
I would be creating the "app" from phonegap using Dreamweaver. I am looking for examples of using javascript to send over a string to a web service that i can read constantly on the PC in order to preform tasks as needed depending on the button i push on the app.
So as an example:
WebOS app >
button pushed in app to call up Internet Explorer >
sends "IE" string to WS >
WS triggers the correct exec to start depending on the string sent to it (IE) >
WS sends back "OK" to WebOS app when program is launched
Does anyone have an example of something like this?
update
So i would do something like so in my javascript?:
<!DOCTYPE html>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js">
function buttonClicked(str what2Pass)
{
$.ajax({
async : false, /* set as true if you want asynchronous behavior */
type: "POST",
contentType: "application/json; charset=utf-8",
url: "http://localhost:7777/WebService.asmx/PerformAction",
data: { "webOSCommand" : what2Pass},
dataType: "json",
success: function(data){
alert(true);
}
});
}
<html>
<body>
<input type="button" id="button1" value="run IE on PC" onClick="buttonClicked('IE');" />
</body>
</html>
and for my WS it would be:
Imports System.Web
Imports System.Web.Services
Imports System.Web.Services.Protocols
Imports System.Diagnostics
Imports System.Web.Script.Services
' To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.
' <System.Web.Script.Services.ScriptService()> _
<WebService(Namespace:="http://tempuri.org/")> _
<WebServiceBinding(ConformsTo:=WsiProfiles.BasicProfile1_1)> _
<Global.Microsoft.VisualBasic.CompilerServices.DesignerGenerated()> _
<ScriptService()> _
Public Class Service
Inherits System.Web.Services.WebService
<WebMethod()> _
Public Function PerformAction(byRef webOSCommand as String) As String
Dim oPro As New Process
With oPro
.StartInfo.UseShellExecute = True
.StartInfo.Arguments = "http://www.google.com"
.StartInfo.FileName = "internet explorer.exe"
.Start()
End With
Return "Started"
End Function
End Class
Yes, you can call a Web Service from Javascript via ajax. One example is this:
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "WebService.asmx/PerformAction",
data: { "somestring" : "IE"},
dataType: "json"
});
Your web service:
[WebMethod]
//parameter name must match the parameter name passed in from the Ajax call (sometring)
public static string PerformAction(string somestring)
{
return "something";
}
Detailed example here.
What you are doing is correct, but you need to decorate your webservice class with the [ScriptService] attribute.
[ScriptService]
public class MyWebService : WebService {
[WebMethod]
public void MyMethod() {
}
}
Once this is done you can access the web service via $.ajax like you have done.
Update
Making a slight change to your javascript function. Instead of using the 'done' method, I am setting the 'success' property of the settings object passed to the $.ajax method. If you want the webservice call to be asynchronous, you can set the async property as shown in the code below.
function buttonClicked(str what2Pass)
{
$.ajax({
async : false, /* set as true if you want asynchronous behavior */
type: "POST",
contentType: "application/json; charset=utf-8",
url: "http://localhost:7777/WebService.asmx/PerformAction",
data: { "webOSCommand" : what2Pass},
dataType: "json",
success: function(data){
alert(data);
}
});
}

IIS6 javascript routing issues

I currently have the following within my view
function loadData() {
var url = "/Testx.mvc/GetData";
var id = "111111";
var format = "html";
$.ajax({
url: url,
type: "POST",
dataType: format,
data: "id=" + id,
success: populateResults
});
}
function populateResults(result) {
$('#results').html(result);
}
I also have a controller called TestxController with an action method called GetData(int? id).
Now the ajax call above works on Visual Studios 2008's built-in development server, but when i switch it to use IIS webserver it doesn't. It seems like the route isn't being found because I tried putting a break point on GetData but it doesn't even reach there.
Does anyone know what i would need to do to fix this?
Edit: I've also tried the wildcard mapping method discussed at http://haacked.com/archive/2008/11/26/asp.net-mvc-on-iis-6-walkthrough.aspx and it worked perfectly. (Of course I had to remov the .mvc from the url)
Is there any way to get this to work with the .mvc extension?
Thanks
Is Testx.mvc at the root of your webserver? If your application is running in a virtual directory on IIS then the correct path would be something like /YourApp/Testx.mvc/GetData.
The Visual Studio built-in webserver might be placing Testx.mvc at root, which is why it works within VS.
If that is the case, then try using the relative path Testx.mvc/GetData rather than /Testx.mvc/GetData.
Is there an actual function called 'callback'? Just asking because it seems like you might mean to be calling 'populateResults' with a successful response.
Try this perhaps:
$.ajax({
url: url,
type: "POST",
dataType: format,
data: "id=" + id,
success: function(results){$('#results').html(result)}
});
Did you check your ISS setup to see if it supports the POST action? It might only be specifying the GET action... see http://haacked.com/images/haacked_com/WindowsLiveWriter/07de283cb368_B754/application-mappings_3.png

Categories