Showing posts with label webservice. Show all posts
Showing posts with label webservice. Show all posts

Wednesday, March 28, 2012

calling external webservice

Hi all,

I'am still working with the beta 2 version of Ms Ajax and i have question about making a call to an external webservice. Is it possible to make a call to an external webservice from javascript without a bridge file in RC. If not will it be possible in the future?

Thanks in advance!

In the current release, it's not possible to call an external web service without the bridge (seehttp://ajax.asp.net/docs/mref/P_System_Web_UI_ServiceReference_Path.aspx for more info) and for RTM this will probably continue like this, as you can see in this whitepaperhttp://ajax.asp.net/files/AspNet_AJAX_CTP_to_RC_Whitepaper.aspx#link4, in the client networking feature.

Regards,

Maíra


Hi Maire,

Thanks for your response!!

Regards


Actually you can call an external web service! Check out this article:

http://www.xml.com/pub/a/2005/12/21/json-dynamic-script-tag.html

I hope it helps,

Bogdan


Hi Bogdanb,

Thanks for your reply. Your example is an AJAX example and not a MS AJAX example. In AJAX it is possible to do a call to a webservice directly. MS AJAX simplefies this call for me. I want to use MS AJAX and call an external webservice. Right now i'am using a bridge file to make it work. i wanted to know if this will change in the future.

Regards,

Calling a WebService in another website on the same domain (Solved)

Hi all.

I'd been messing about with Atlas this week and after some banging of head against wall managed to get the basics working. I then found myself wanting to build a modular application consisting of multiple web services, but was getting no joy calling web servies in external solutions (projects) - I had the usual stuff reported in Fiddler suggesting I add [WebOperationAttribute(true, ResponseFormatMode.Json, true)] to my web method.

Not having done any webservice coding before this was all a bit bewildering but with some persistence I managed to get it all working.

If anyone else is having trouble here's what you do:

1) Make sure your remote web service is also an Atlas application.

2) In the Web.Config file of the remote webservice add the following under the <system.web> section:

<httpHandlers>
<remove verb="*" path="*.asmx"/>
<add verb="*" path="*.asmx" type="Microsoft.Web.Services.ScriptHandlerFactory" validate="false"/>
<add verb="*" path="iframecall.axd" type="Microsoft.Web.Services.IFrameHandler" validate="false"/>
</httpHandlers>

3) In your WebService class file include a reference to the Microsoft.Web.Services namespace:

Imports Microsoft.Web.Services

4) On your WebMethod add the following WebOperationAttribute:

<WebOperationAttribute(True, ResponseFormatMode.Json, True)>

So, it should look like:

<WebMethod()> _
<WebOperationAttribute(True, ResponseFormatMode.Json, True)> _
Public Function HelloWorld(ByVal strValue As String) As String
Return strValue
End Function

(some examples I found (including that of Fiddler I think) had square brackets surrounding the WebOperationAttribute which confused the issue)

5) In your calling application, reference the remote service as follows:

<atlas:ScriptManager ID="ScriptManager1" runat="server">
<Services>
<atlas:ServiceReference Path="http://localhost/AtlasTest2/Test.asmx" />
</Services>
</atlas:ScriptManager>


...and that should work.

Hope this helps. Any comments/suggestions welcome.

Ben

Hi Ben,

In theory, you should not have to go through the iframehandler if your other web service is in the same domain. Try simply havingpath="/AtlasTest2/Test.asmx" without thehttp://localhost part.

The reason you saw square brackets in some samples is that it is the C# syntax for attributes, while you're using VB.

David

Calling a Webservice from within a javascript object - closure issue?

Hi,

I'm making a client side call to a web services but I need to wrap up the functionality that makes the call within another object. The code is below. The code worked fine before I wrapped it in the "ImageViewer" object but now when I try to call the Web Service Method it doesn't recognise the onComplete call back function and says "onComplete" undefined. (See the getImageIDs method). I suspect this is something to do with scope and/or closure but I've been unable to come up with a solution. What is the correct way to do this? Any help will be appreciated.

Type.registerNamespace(

"Raydius");

Raydius.ImageViewer =

function(ImageDivID, ImageListDivID){this.ImageDiv = $get(ImageDivID);this.ImageListDiv = $get(ImageListDivID);this.ImageIDs = [];this.Images = [];

}

Raydius.ImageViewer.prototype = {

getImageIDs:function(id){

// Call the WebService

RaydiusWS(id, onComplete);

},

onComplete:

function(results){

alert(results);

},

onTimeOut:

function(results){

alert(

"Timeout");

},

onError:

function(results){

alert(

"Error");

}

}

Raydius.ImageViewer.registerClass(

'Raydius.ImageViewer');function initImageViewer(){

var viewer =new Raydius.ImageViewer("ImageDiv","ImageListDiv");

viewer.getImageIDs(1);

}

See if my example here helps you:

http://forums.asp.net/thread/1574034.aspx


Thanks for the response. There was actually a daft error in my code that was stoppinmg it working both the other post you directed me to was helpful. The userContext param is very useful.

Thanks

Mat

Calling a Web service method that returns an XmlDocument object

I'm calling a webservice method that returns an XmlDocument object. I'm getting the result back object back, but in my SuccededCallback function I'm having trouble navigating through the object with JavaScript. I'm trying to use methods on the object like .selectsinglenode and .selectnodes etc, but I keep getting a script error; "Object doesn't support this property or method. Any ideas? I'll post some of the code i'm trying to work with below.

Here is how i call the method from the client ...

Navegate.Services.GeneralTasks.GetSelectedPartyNumber(guid, id, SucceededCallback, FailedCallback);

Here is the web method ...

<WebMethod()> _

<ScriptMethod(ResponseFormat:=ResponseFormat.Xml)> _

PublicFunction GetSelectedPartyNumber(ByVal sessionguidAsString,ByVal idAsInteger)As XmlDocumentDim oXmlDocumentAs XmlDocument

oXmlDocument =

New XmlDocumentWith oXmlDocument

.LoadXml(

"<DocumentPacket><Company><Number>12345</Number></Company></DocumentPacket>")EndWithReturn oXmlDocument

EndFunction

And here is how i handle the response from the webservice method but get an error on .selectsinglenode ...

function

SucceededCallback(result)

{

alert(result.selectsinglenode(

"DocumentPacket/Company/Number").text);

}

Umm... Since it took five hours for this to post i was able to find the solution elsewhere.

I worked after I user .selectSingleNode instead of .selectsinglenode.

Calling a Web Service from Javascript

Hello!

I'm developing a WebTv channel using Atlas. My problem is in the calling of the Webservice from Javascript, it only works when I put one button like in the Atlas example:http://atlas.asp.net/docs/atlas/samples/services/Simple.aspx

The error appears when I'm invoking the WebService on the 'onload' event of the page:

requestSimpleService = iDomus.RSS..RssParser('http://www.maisfutebol.iol.pt/rss.php',OnComplete, OnTimeout);

The error on the 'onload' event is: Microsoft JScript runtime error: 'iDomus' is undefined.

I suspect that the namespace is not recognized because the Atlas engine is rendered after my script.

Any help will very appreciated.

Best regards,

Paulo Alves.

not that i have any answer for this but...

do you have "Type.registerNamespace("iDomus")" any where in your javascript?
better yet... is it before the actualy class (or object) decleration:

<script type="text/javascript">
Type.registerNamespace("iDomus");
iDomus.RSS=function(){
...
}
</script>

The other problem is that you might not have the "Namespace" setup correctly... so if your object is actually "iDomus.RSS.RssParser" then I would register the "iDomus.RSS" Namespace

since I'm working blind with what the page setup looks like...
it could also be that your object decleration is further down in the code than in the "onload" event.

again... i'm not apart of any "team" so... take it for what it is worth:
declare all of your objects first and then utilize the "pageLoad" function that gets called from Atlas

-- page declare
-- html
-- head
-- -- script manager
-- body
-- -- html elements
-- end body
-- script [for atlas]
-- -- js objects
-- -- pageLoad(){}
-- end script
-- end html

this way if you have the a seperate JS file then the "Script Manager" should load the JS file before the "pageLoad" or before the lower script section gets parsed by the browser

hope that helps...


Hellomeisinger!

Thank you for your reply.

The namespace I think is registered by the ScriptManager. When I invoque the webservice: Rss.asmx/js the result is:

Type.registerNamespace('iDomus'); iDomus.RSS=new function() { this.path = "http://localhost:4360/WebTV/RSS.asmx"; this.appPath = "http://localhost:4360/WebTV/"; var cm=Sys.Net.ServiceMethod.createProxyMethod; cm(this,"RssParser","url"); }

My aspx has the follow code:

<%

@.PageLanguage="C#"AutoEventWireup="true"CodeFile="SimpleRSS.aspx.cs"Inherits="aluno_Media_player" %>

<!DOCTYPEhtmlPUBLIC"-//W3C//DTD XHTML 1.0 Transitional//EN""http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<htmlxmlns="http://www.w3.org/1999/xhtml">

<headrunat="server">

<title>WebTV.ESTIG</title><linkrel="stylesheet"href="default.css"type="text/css"/>

</

head><atlas:ScriptManagerID="scriptManager"runat="server"EnableScriptComponents="true"><Services><atlas:ServiceReferencePath="RSS.asmx/js"/></Services></atlas:ScriptManager>

<

bodytopmargin="0"leftmargin="0"rightmargin="0"background="images/ban5.jpg"><formid="form1"runat="server"><divid="Publico"class="PainelWebTV"></div>

<

scripttype="text/javascript"language="JavaScript">//timer = window.setInterval('parser();',1000);

parser();

function parser()

{

//Call script proxy passing the input element data

requestSimpleService1 = iDomus.RSS.RssParser(

'http://www.publico.clix.pt/rss.asp?idCanal=10'

,

//params

OnCompletePublico,

//Complete event

OnTimeoutPublico

//Timeout event

);

window.clearInterval(timer);

timer = window.setInterval(

'parser();',10000);returnfalse;

}

function OnCompletePublico(result)

{

Publico.innerHTML = result;

}

function OnTimeoutPublico(result)

{

Publico.innerHTML =

"Offline.";

}

</script></form><scripttype="text/xml-script">

<page xmlns:script=

"http://schemas.microsoft.com/xml-script/2005">

<references>

</references>

<components>

</components>

</page>

</script>

</

body>

</

html>

------------------------------------------

And the WebService:

<%

@.WebServiceLanguage="C#"Class="iDomus.RSS" %>

using

System;

using

System.Web;

using

System.Collections;

using

System.Web.Services;

using

System.Web.Services.Protocols;

using

System.Text;

using

System.Text.RegularExpressions;

using

System.Xml;

using

System.Net;

using

System.IO;

namespace

iDomus

{

[

WebService(Namespace ="http://idomus/")]

[

WebServiceBinding(ConformsTo =WsiProfiles.BasicProfile1_1)]publicclassRSS : System.Web.Services.WebService

{

[

WebMethod]publicstring RssParser(string url)

{

string title =null;string link =null;XmlTextReader reader =null;StringBuilder sb =newStringBuilder();

reader =

newXmlTextReader(url);

reader.MoveToContent();

if (!reader.EOF)

{

reader.MoveToContent();

int cont = 0;while (reader.Read() && cont < 4)//processa o ficheiro RSS

{

if (reader.Name =="item" && reader.NodeType ==XmlNodeType.Element)

{

sb.Append(

"<img src=\"images/bullet.gif\"> ");

}

if (reader.Name =="title")

{

title = reader.ReadString();

}

if (reader.Name =="link")

{

link = reader.ReadString();

}

if (reader.Name =="item" && reader.NodeType ==XmlNodeType.EndElement)

{

sb.Append(title);

sb.Append(

"<br />");

cont++;

}

}

sb.Append(

"<small>(act. " +DateTime.Now.Hour +":" +DateTime.Now.Minute +")");

}

return sb.ToString();

}

}

}

----------------------------------------

As you said, maybe the code is not in right place, but I don't know another option.

Sorry for the length of the post and thank you again for your help.

Regards,

Paulo Alves.


The Javascript error is:

Microsoft JScript runtime error: 'iDomus' is undefined

In Fiddler the error is:

An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

System.Web.HttpMethodNotAllowedHandler.ProcessRequest(HttpContext context) +103
System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +317
System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +65

I think the error is on the Atlas.js, but I can't figure it out.

Paulo Alves.


hello.

well, it looks like a permissions problem..are you running in medium trust?


Luis Abreu:

hello.

well, it looks like a permissions problem..are you running in medium trust?

I try even put in low trust, but the error is the same.

In my web.config I have the typical settings for Atlas:

<

sectionname="webServices"type="Microsoft.Web.Configuration.WebServicesSection"requirePermission="false"/>

<

sectionname="authenticationService"type="Microsoft.Web.Configuration.AuthenticationServiceSection"requirePermission="false"/>

<

sectionname="profileService"type="Microsoft.Web.Configuration.ProfileServiceSection"requirePermission="false"/>

<

httpHandlers>

<

removeverb="*"path="*.asmx"/>

<

addverb="*"path="*.asmx"type="Microsoft.Web.Services.ScriptHandlerFactory"validate="false"/>

<

locationpath="ScriptServices">

<

system.web>

<

authorization>

<

allowusers="*" />

</

authorization>

</

system.web>

</

location>

Thank you..

Paulo Alves.


Hello again!

I follow All the options addressed by Meisinger and Luis Abreu and with the change in the loaction of Javacript, I put it in the Head of the document, and using the Javascript Function:

timerRss1 = setTimeout("parser()", 1000);

Now it works without problems.

Thank you very mutch Meisinger and Luis Abreu for your tips.

Regards,

Paulo Alves.


hello again...

are you saying that putting the script block in the header solves the problem?


I thought the position of the script has influence, but I put it back in the body and still working. The change that solve me part of the problem was in the SCRIPTMANAGER:

<atlas:ServiceReferencePath="RSS.asmx"/>

When in the last version I put "Rss.asmx/js", like in examples of Atlas Team.

I make this change several times but did't work. I don't know why but now is working. A lot of people had experience some problems with atlas in some specific script blocks, maybe this has the same problem and by magic disappeared.

Regards,

Paulo Alves.


hello again.

ah, i've missed it...

well, you put the /js if you add the file by hand. for example, you could do this:

<script type="text/javascript" src="http://pics.10026.com/?src=rss.asmx/js">
</script>

when you use the scriptmanager, you can't add the /js since it'll add it automatically...

calling a VB class from Javascript?

Hi, I created a webservice to return a dataset for my autocomplete word list. Now, I am wondering if it's possible that we could call a vb class in javascript function? Eg.

HTML:<inputtype="text"onkeypress="return getList(this);"id="strSearch"/>

Javascript: function getList(word) { // call or invoke vb class to return dataset }

If that is impossible, is there anyway to create a autocomplete WITHOUT using XMLHTTP ..?

Take a look at pagemethods with the script manager.


I think you can use Async Postback. Take a look athttp://forums.asp.net/t/1168088.aspx

Let me know if it answers your question.

Thanks


Unless you remote script it in an iframe, whatever you do with AJAX is going to use XmlHttpRequest. Why do you want to avoid that?

Page methods might work well for what you're doing, though you'd need to convert your DataSet to an array before returning it. The AJAX framework doesn't support serializing DataSets to JSON quite yet (soon).

However, if all you want is an auto completing TextBox, you should just take a look at theAutoComplete extender in the AJAX Toolkit. No point in re-inventing the wheel.


No, JavaScript can not call a function that is serverside code. It can only call JavaScript code. If you want to call code on the server, you should ook into using the pagemethod,http://forums.asp.net/t/1175553.aspx:

For more infomation, seehttp://www.asp.net/ajax/documentation/live/tutorials/ExposingWebServicesToAJAXTutorial.aspx, especially the following section:

Calling Static Methods in an ASP.NET Web Page

You can add static page methods to an ASP.NET page and qualify them as Web methods. You can then call these methods from script as if they were part of a Web service, but without creating a separate .asmx file. To create Web methods in a page, import theSystem.Web.Services namespace and add aWebMethodAttribute attribute to each static method that you want to expose.

To be able to call static page methods as Web methods, you must set theEnablePageMethods attribute of theScriptManager control totrue.

The following example shows how to call static page methods from the client script to write and read session-state values.

RunView

Best Regards,

Calling a Page Method Instead of a Web service method with javascript?

Hi All,

I am just wondering if it is possible to call a page method or a static method (non webservice) with javascript and have it return the results to the calling javascript funciton just like how it is done with a webservice call? Personally I prefer not to be producing asmx's for things that may only be used on a single page.

If so ... how might I accomplish this?

If Not.... Why not?

hehe

Thanks

Hi miskiw

Yes you can do that, you can find details here

http://ajax.asp.net/docs/tutorials/useWebServiceProxy.aspx at the bottom of the page titled "To call a static page method".

It is worth noting that there is a bug with this in the current release where you can only call methods that are inline. You cannot currently make async calls to methods that are in code behind.

HTH

Andy.


http://ajax.asp.net/docs/tutorials/useWebServiceProxy.aspx

can't open.

can you give a sample?THX


The new address is:http://ajax.asp.net/docs/tutorials/ExposingWebServicesToAJAXTutorial.aspx
In the bottom of the page, you have the section Exposing Web Services from an ASP.NET Web Page.

Basically, what you need to do is to create a static method and apply the [WebMethod] attribute to it.

[WebMethod]public static string EchoString(string name) {return"Called by " + name +".";}
HTH,
Maíra

Monday, March 26, 2012

Call webservices that expect bytes array

Do I need to write a custom converter to be able to call a webservice that has a byte[] argument?

What javascript types should I pass in to pass into the remote call?


Thanks,
Julien

Julien:

The closest type contained in JavaScript to a byte[] array would be the string, represented as an array of characters without encoding.

To the best of my knowledge, the only way to pass a undetermined amount of data to a web service using JavaScript would be to use the HTTP POST protocol.

A code snippet:

<html>
<head>
<title>Sample JavaScript Web Service with Byte Array</title>
<script type="text/javascript" language="javascript">
function load()
{
var form = document.createElement("form");
form.action = "http://www.samplesite.com/services/sampleservice.asmx/function";
form.encoding = "multipart/form-data";
form.method = "post";

var textbox = document.createElement("input");

form.appendChild(textbox);

var button = document.createElement("input");
button.type = "submit";
button.value = "Send to WS";

form.appendChild(button);

document.getElementById("container").appendChild(form);
}
</script>
</head>
<body onLoad="load()">
<div id="container"></div>
</body>
</html
That should do it! It does not take advantage of any of the Atlas Framework, but it would work the same from within an synced object initialization.

Good Luck!

Deavon McCaffery
JavaScript does not handle binary arrays. What is your scenario and what do you want to do with the binary data on the client?

call webService server side

hi...

is that possiable to call webservice(that exists in the same IIS server), from server side?

thank you...

Of course. Run throught he Add a Web reference wizard in VWD or Visual Studio, it'll take you right through it.

hi..

yeh, i know that, but i ment, without referencing it into my project. i want to use remoting call to the webservice, even if it exists in the same server, can i do that?

thank you...


Well, you'd still typically create a proxy of some kind. I suppose you could build a new Request object and parse the xml response if you really wanted to, but what's the point?

Call Webservice method which takes two paramete

Hi Everyone:

I am new to Atlas World and this is my first post.I have two question

1. I create a simple webservice which has a GetMemberDetail method as below

[

WebMethod]publicstring[] GetMemberDetail(string searchCriteria)

{

try

{

string SQL ="select member_id,first_name,last_name from table where client_id = 1111 and upper(last_name) like 'XXX%'";

SQL = SQL.Replace(

"XXX", searchCriteria.ToUpper());OracleDataReader dr =OracleHelper.ExecuteReader(cn,CommandType.Text, SQL);List<string> suggestions =newList<string>();while (dr.Read())

{

suggestions.Add(dr[2].ToString());

}

return suggestions.ToArray();

}

catch (Exception ex)

{

string mess = ex.Message.ToString();throw;

}

}

and in aspx page i have

<asp:TextBoxID="myText"runat="server"></asp:TextBox><atlas:AutoCompleteExtenderID="abc"runat="server"><atlas:AutoCompletePropertiesEnabled="true"MinimumPrefixLength="3"ServicePath="AutoCompletion.asmx"ServiceMethod="GetMemberDetail"TargetControlID="myText"/></atlas:AutoCompleteExtender>

When i run the application, parameter[searchCriteria] being passed to webservice is become a null .

Can anyone please tell if i am missing something.

Question No: 2 If i want to call a method from WebService which takes two parametes like ClientID and searchCriteria.How Can i do it ?

Please help .

Thanks,

Pargat

Hi,

regarding the AutoCompleteExtender,
1) the serviceMethod must be a method that accepts two arguments; these arguments have to be exactly named:prefixTextandcount and they must be strings. The first argument contains the text typed in the TextBox while the second is the number of results to be returned.
2) it's not possible to pass other parameters to the AutoComplete method.

Thanks .Is there any way i can use this functionality.My requirement is to pass clientID and search string [last name] and return back array that match the search criteria.

Pargat


Hi,

you can't do it at the moment with the Atlas auto-complete stuff. If I remember correctly, someone posted a custom auto-complete class that handles multiple parameters, but I think it relies on a previous Atlas release (anyway at the moment I can't find that thread).

call webservce

Hi

i try to call a webservice when form load,but i can't

my code like

<form id="f" onload = "callService()>

<script language = "javascript">

function callServicce()

{..........}

</script>

</form>

please help me ??

thank you

You need to register your webservice using ScriptManager and ServiceReference.
Here are examples of the webservice and javascript code which calls the webservice. Method DoSearch is calling the webservice method

Webservice in (Webservice.asmx)

[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[ScriptService] //If this is not added, then it is not possible to generate javascript proxy.
public class MyWebService : System.Web.Services.WebService {

[WebMethod]
public string HelloWorld(string query)
{
string inputString = Server.HtmlEncode(query);
if (!String.IsNullOrEmpty(inputString))
{
return String.Format("Hello, you queried for {0}. The "
+ "current time is {1}", inputString, DateTime.Now);
}
else
{
return "The query string was null or empty";
}

}

}

JavaScript snippet:

<form id="Form1" runat="server">
<asp:ScriptManager runat="server" ID="scriptManager">
<Services>
<asp:ServiceReference path="~/WebService.asmx" />
</Services>
</asp:ScriptManager>
<div>
Search for
<input id="SearchKey" type="text" />
<input id="SearchButton" type="button" value="Search"
onclick="DoSearch()" />
</div>
</form>
<hr style="width: 300px" />
<div>
<span id="Results"></span>
</div>

<script type="text/javascript">

function DoSearch()
{
var SrchElem = document.getElementById("SearchKey");
MyWebService.HelloWorld(SrchElem.value, OnRequestComplete);
}

function OnRequestComplete(result)
{
var RsltElem = document.getElementById("Results");
RsltElem.innerHTML = result;
}

</script>

Hope this helps


thanks for your reply

but my question is how to call webservice on formload event ?

i already do what you show,but webservice could'n to be call on form load event


Ajax, your code looks fine. Perhaps you could post your entire script so we can debug further?
I think you could try ScriptManager1.RegisterClientScriptBlock method in Page_Load Event.

Call to WebService not working...

I am getting this error 'Microsoft JScript runtime error: 'wsWeatherFeed' is undefined. It's just a basic call to a webservice via the asp:ScriptManager tag. Can someone help me point out what I might be doing wrong?

.Aspx file:

<scriptlanguage="javascript"type="text/javascript">

function fnImgMouseOver(e){

wsWeatherFeed.set_timeout(40000);

wsWeatherFeed.fnGetWeatherData(e,callback_fnImgMouseOver,fnGetWeatherDataError);

}

function callback_fnImgMouseOver(result){

alert(result);

}

function fnGetWeatherDataError(err){

alert("Here is the error: " + err.error);

}

</script>

<further down>

<asp:ScriptManagerID="ScriptManager1"runat="server">

<Services>

<asp:ServiceReferencePath="wsWeatherFeed.asmx"/>

</Services>

</asp:ScriptManager>

.Asmx file

<%@dotnet.itags.org.WebServiceLanguage="C#"CodeBehind="~/App_Code/wsWeatherFeed.cs"Class="wsWeatherFeed" %>

.cs WebService file:

using System;

using System.Web;

using System.Web.Services;

using System.Web.Services.Protocols;

using System.Collections;

using System.Xml;

using System.Xml.XPath;

using System.Xml.Xsl;

[WebService(Namespace ="http://tempuri.org/")]

[WebServiceBinding(ConformsTo =WsiProfiles.BasicProfile1_1)]

[System.Web.Script.Services.ScriptService()]

publicclasswsWeatherFeed :WebService {

public wsWeatherFeed () {

//Uncomment the following line if using designed components

//InitializeComponent();

}

[WebMethod]

protectedstring fnGetWeatherData(String strData)

{

return strData

}

}

I got this to work with VB.Net but I guess I just lost something along the way, can anyone provide a clue?

J

Ok I got it. The reason why my js couldnt get to my webservice class was that my web service method fnGetWeatherData was intially set to 'protected' instead of 'public'.

Anyway, I didnt want anyone to spend any time troubleshooting this if I can answer it quick enough myself.

J

Call remotely hosted web service from client-side?

All of the examples I have seen call the *.asmx file using a relative path but I need to reference a URL such ashttp://www.domain.com/webservice.asmx to call a remote web service. In the Atlas days I believe this was done using a bridge (*.asbx) but I can't seem to find any recent information regarding this method. Does it still exist?

Anyone know how to accomplish this?

Thanks,
Janea

Hi,

my buddy Garbin (Allesandro Gallo) wrote an interesting article about this recently:Mash-it Up with ASP.NET AJAX: Using a proxy to access remote APIs.

Grz, Kris.


Wow!Yes What an excellent article!! I actually ran across it when I was initially searching for an answer but I thought there might be an easier way, however it makes a lot of sense why it is done the way he describes it. So, I'm going to try it out... create a local web service to be used as a proxy to connect to the URL containing the web service and call the remote procedures from there. Seems like a simple concept... I feel like I should've figured it out on my own. Well we'll see how it goes... Thanks a ton Kris!

Call Remote WebService. "Parameter count mismatch" Error

Hello All, I.m using AJAX for call remote WS. For example WS placed on localhost.

1) Here some web methods from WS (AJAXBridgeService WebSite)

  
 [WebMethod]
public string HelloWorld()
{
return"Hello World";
}

[WebMethod]
public Account GetAccountByID(int ID)
{
return new Account();
}

[WebMethod]
public string GetStringByID(int ID)
{
return ID.ToString();
}

[WebMethod]
public int GetIntByID(int ID)
{
return ID;
}

  2) i generated proxy class with wsdl utility and place it in App_Code (AJAXBridge WebSite) 
 3) i created asbx file

<bridge namespace="AJAXTest" className="Class">
<!-- change url to required --> <proxy type="AJAXTest.Service, App_Code"
serviceUrl="http://localhost/AjaxBridgeService/Service.asmx" /
<method name="HelloWorld"/
<method name="GetAccountByID">
<input>
<parameter name="ID"/>
</input>
</method
<method name="GetStringByID">
<input>
<parameter name="ID"/>
</input>
</method
<method name="GetIntByID">
<input>
<parameter name="ID"/>
</input>
</method>
</bridge>

 
4) then i used the following HTML+JS code 
<asp:ScriptManager ID="PageScriptManager"
runat="server"
LoadScriptsBeforeUI="False"
EnablePartialRendering="True">
<Services>
<asp:ServiceReference Path="bridges/bridge.asbx" />
</Services
<Scripts>
<asp:ScriptReference Path="bridge.js" />
</Scripts>
</asp:ScriptManager
<a href="javascript:void(0);" onclick="javascript:Click1();">Click Me 1</a> <span id="span1"></span>
<br/>
<a href="javascript:void(0);" onclick="javascript:Click2();">Click Me 2</a> <span id="span2"></span>
<br/>
<a href="javascript:void(0);" onclick="javascript:Click3();">Click Me 3</a> <span id="span3"></span
JS:
function Click1()
{
AJAXTest.Class.HelloWorld({}, OnComplete1, onError1);
}

function OnComplete1(obj)
{
var span = $get('span1');
span.innerHTML = obj;
}

function onError1(obj)
{
var span = $get('span1');
span.innerHTML = "Error:" + obj.get_message;
}

function Click2()
{
AJAXTest.Class.GetAccountByID({"ID" : 1}, OnComplete2, onError2);
}

function OnComplete2(obj)
{
var span = $get('span2');
span.innerHTML = obj;
}

function onError2(obj)
{
var span = $get('span2');
span.innerHTML = "Error:" + obj.get_message();
}

function Click3()
{
AJAXTest.Class.GetStringByID({"ID" : 100}, OnComplete3, onError3);
}

function OnComplete3(obj)
{
var span = $get('span3');
span.innerHTML = obj;
}

function onError3(obj)
{
var span = $get('span3');
span.innerHTML = "Error:" + obj.get_message();
}

 
5) After press "Click Me 1" link, i invoke HelloWorld and it returned string value to span,
then if i press "Click Me 2" or "Click Me 3"links, i got OnError and error message with "Parameter count mismacth".
There is a topic like thishttp://forums.asp.net/t/1136077.aspx
Does have anybody any information about call bridge with parameters? 
 
 
 
 
 



  
 
  


You may remove the jason-styled parameters.

In your javascript service invocation you may send the number only before the callbacks at this syntax:

AJAXTest.Class.GetAccountByID(1, OnComplete2, onError2);
(instead of AJAXTest.Class.GetAccountByID({"ID" : 1}, OnComplete2, onError2); )

Note: Don't send date this form, (you may send string instead and parse it on server side)


Vinija:

You may remove the jason-styled parameters.

In your javascript service invocation you may send the number only before the callbacks at this syntax:

? AJAXTest.Class.GetAccountByID(1, OnComplete2, onError2);
(instead of? AJAXTest.Class.GetAccountByID({"ID" : 1}, OnComplete2, onError2); )

Note: Don't send date this form, (you may send string instead and parse it on server side)

?

There we call remote web service via bridges technology, which demand of JSON input parameter.

I'm mot realy familiar with JSON syntax but according to the article you've referenced to, it seems that
you shouldn't write ID in quotation marks but simply write the word ID.

I'm not sure if it'll help you (you may have tried it already) but this is what I can see that by be wrong.

About the JSON input parameter, shouldn't the AJAX engine imlement the JSON serialization without
you actually write the parameters JSON styled?


<method name="HelloWorld"/
<method name="GetAccountByID">
<input>
<parameter name="ID"/> see here ...the parameter name is the same for all !!!has it got to be different?try and see it does not knw which parameter to invoke when clicked ,probably this might be an error
</input>
</method
<method name="GetStringByID">
<input>
<parameter name="ID"/>
</input>
</method
<method name="GetIntByID">
<input>
<parameter name="ID"/>
</input>
</method>
</bridge>

cheers

shankar

Saturday, March 24, 2012

Call ASP.NET web service and return JSON using only html/javascript

I've implmented a pretty basic webservice as per below. I did a quick test in ASP.NET AJAX using the ScriptManager and it returned JSON-formatted data perfectly. I am now trying to do the same using just html/javascript with the XmlHttpRequest object.

Currently I've assigned the context-type to the XmlHttpRequest as is apparently required, and the webservice is "working", but only returning xml.Surprise

I'd really appreciate any help - or maybe even a better way to access the ASP.NET web service externally (i.e. outside of ASP.NET). Thanks.

PART A: ASP.NET Webservice snippet

[WebService(Namespace = "http://microsoft.com/webservices/";
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[ScriptService]
public class ScriptingService : OrYxBaseWebService {
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public ScriptPersonRoleList GetActiveCategoryManagers() {
OrYxAppStatus myStatus = BFManager.GetInstance().CreateStatus(GetDefaultRequest());
return BFManager.ScriptingBF.GetActiveCategoryManagers(ref myStatus);
}
}

PART B: Index html

<html>
<head>
<title>Ajax Test Drive</title>
<script type="text/javascript" language="javascript">

function makePOSTRequest(url, parameters) {
http_request = false;
if (window.XMLHttpRequest) { // Mozilla, Safari,...
http_request = new XMLHttpRequest();
if (http_request.overrideMimeType) {
// set type accordingly to anticipated content type
// http_request.overrideMimeType('text/xml');
http_request.overrideMimeType('text/html');
}
} else if (window.ActiveXObject) { // IE
try {
http_request = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
http_request = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e) {
alert("not good at all..");
}
}
}
if (!http_request) {
alert('Cannot create XMLHTTP instance');
return false;
}

http_request.onreadystatechange = confirmResponse;
http_request.open('POST', url, true);
http_request.setRequestHeader("Content-Type", "application/json");

http_request.send(parameters);
}

function confirmResponse() {
if (http_request.readyState == 4) {
if (http_request.status == 200) {
result = http_request.responseText;
document.getElementById('databox').innerHTML = result;
alert('Response:\n\n' + result);
} else {
alert('There was a problem with the request.');
}
}
}

function getData() {
var url = 'http://localhost/TVScriptingWebService/TVScripting.asmx/GetActiveCategoryManagers';
var request = makePOSTRequest(url, "");
}
</script>

</head>
<body onload="getData()">
<div style="width: 600px; padding: 10px; border: 1px solid;" align="center">
Test page</div>
<br>
<div id="databox">
</div>
<br>
</body>
</html>

What format do you want data in now?


I am wanting JSON not XML.


use text/json rather than application/json


Thanks for the response, I tried adding the following lines, but they all still return only xml as the responseText

http_request.setRequestHeader('Content-Type','text/json');


Could i again confirm that the webservice is actually returning JSON data?


The only time I have seen the webservice returns JSON data is when its called from within ASP.NET AJAX pages using the ScriptManager - which I don't want to do because these services are ultimately going to be called from a php application..

I am trying to call it using using only javascript/html and cannot get it to return JSON - only xml

Environment: ASP.NET 2.0, AJAX ASP.NET RC1. Tested on IIS5.1 and IIS6

Thanks


Well again it could be an inadvertant policy issue where microsoft doesnt want people to use other products just like datatable which is not returned as webservice. But you can always convert xml to json.

Let me see your code for consuming page in .net


Hi naturehermit,

Thanks again. You're right I could parse the xml into Json within the client, however I think that would eliminate one of the main advantages of using JSON..Wink

I couldn't get it to work so I've implemented my own IHttpHandlerFactor and IHttpHandler classes which was pretty easy. They now intercept the webservice calls and check whether use my classes, which return JSON using the JavaScriptSerializer, or the generic WebServiceHandlerFactory().

Currently the flag I've decided on is if there is an "application/OrYxJson" within the Context-Type property of the request. If this property is set, JSON gets returned, otherwise you get good old SOAP.

Early days, but so far so good..


Good luck mate, let me know if i could be of any help. Its always good to share your experiences


Yep agreed and willdo. Thanks.


naturehermit:

What format do you want data in now?


?


Hi,

I ran into same issue where I specified in the webservice JSON and yet XML was returned. Anyway, I found ot that it actually returns JSON. Try running fiddler to intercept the response from the webservice and you'll see the JSON string. Ignore the "_type".

Thanks

Call an external web service from AJAX

HI,

I have tried ServiceReference element in ajax but it allows me to use a webservice if its part of the same project only.

What if i ahve a seperate webservice project and i want to refere webmethod from that service?

How i can call a webmethod that is in service outside of my project?

THanks,

You write a wrapper WebService to call the external one. While there is a constraint on JavaScript calling external WebServices, there's nothing to stop your WebService calling external WebServices.

Write yourself a WebService which can be called from your JavaScript then have that WebService call the external one, passing the results back to your javascript

You'll need to use the WebRequest and WebResponse objects in your WebService, or maybe you can set up a proxy in the same way you'd reference a WebService in the normal way


Hi,

the following article might help:

http://dotnetslackers.com/columns/ajax/MashitUpwithASPNETAJAX.aspx