Showing posts with label services. Show all posts
Showing posts with label services. Show all posts

Wednesday, March 21, 2012

URL WebRequest & cross domain web services

Initially, I would like make a web services call with cross domain (ajax). Since RC doesnt support it at the moment. So, I'm looking for an alternative.

- One is a bridge method,http://forums.asp.net/thread/1510827.aspx
But when will CTP support it?

- Another way to use WebRequest. However, there is an error "Access is denied" when I trying to access standard URL. ( change L17 to L16)

Please take a look at L16, L17

1<%@dotnet.itags.org. Page Language="C#" %>23<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">45<html xmlns="http://www.w3.org/1999/xhtml" >6<head runat="server">7 <title>Web Request</title>8 <script type="text/javascript">9 function MakeWebRequest()10 {11 var displayElement = document.getElementById("ResultId");12 displayElement.innerHTML = "";13 wRequest = new Sys.Net.WebRequest();14 Sys.Net.WebRequestManager.add_completedRequest(On_WebRequestCompleted);1516 wRequest.set_url("http://www.asp.net");17 //wRequest.set_url("getTarget.htm");1819 Sys.Net.WebRequestManager.executeRequest(wRequest);20 }2122 function On_WebRequestCompleted(executor, eventArgs)23 {24 var displayElement = document.getElementById("ResultId");2526 if(executor.get_responseAvailable())27 {28 displayElement.innerHTML = "";29 displayElement.innerHTML += executor.get_responseData();30 }31 }32 </script>33</head>34<body>35 <form id="form1" runat="server">36 <asp:ScriptManager runat="server" ID="scriptManagerId"/>37 </form>3839 <h1>Make a Web request:</h1>40 <button id="Button1" title="adds and remove handlers, too" onclick="MakeWebRequest();">Web Request</button>41 <hr />42 <div id="ResultId" style="background-color:Aqua;"></div>43</body>44</html>45
Unfortunately, webrequest internally uses XmlHttpRequest which does not work for cross-domain calls for security reasons. BTW The web service proxy layer internally uses WebRequest so it does not work for that too. The CTP versions used to have an IFrameExecutor which mysteriously got removed in the latest CTP. The IFrameExecutor allowed cross-domain calls. Now as far as handling cross-domain calls you can do it from the server. For instance you can develop an Generic HTTP handler which will take the URL of the target cross-domain page and return its contents. Save the code of the following examples in Delegate.ashx in your web site. The you can invoke the request to the following url:

delegate.ashx?url=www.asp.net

The server will then download the contents ofwww.asp.net and return it. Here is the code of the handler:

------

<%@. WebHandler Language="C#" Class="LoadRssFeed" %>using System;using System.Web;using System.Net;public class LoadRssFeed : IHttpHandler{ private HttpContext _context; public HttpContext Context { get { return _context; } } public HttpResponse Response { get { return Context.Response; } } public HttpRequest Request { get { return Context.Request; } } public void ProcessRequest(HttpContext context) { this._context = context; string url = Request.QueryString["url"]; if (String.IsNullOrEmpty(url)) { Response.StatusCode = (int)HttpStatusCode.NotFound; return; } try { WebRequest request = WebRequest.Create(url); HttpWebResponse webResponse = (HttpWebResponse)request.GetResponse(); if (!String.IsNullOrEmpty(webResponse.ContentEncoding)) { try { Response.ContentEncoding = System.Text.Encoding.GetEncoding(webResponse.ContentEncoding); } catch (ArgumentException ex) { System.Diagnostics.Trace.WriteLine(ex.ToString()); } } Response.ContentType = webResponse.ContentType; Response.StatusCode = (int)webResponse.StatusCode; Response.StatusDescription = webResponse.StatusDescription; byte[] buffer = new byte[4096]; System.IO.Stream stream = webResponse.GetResponseStream(); for (; ; ) { int read = stream.Read(buffer, 0, buffer.Length); if (read == 0) break; if (read > 0) Response.OutputStream.Write(buffer, 0, read); } } catch (ArgumentNullException ex) { Response.StatusCode = (int)HttpStatusCode.NotFound; System.Diagnostics.Trace.WriteLine(ex.ToString()); } catch (System.Security.SecurityException ex) { Response.StatusCode = (int)HttpStatusCode.Forbidden; System.Diagnostics.Trace.WriteLine(ex.ToString()); } catch (UriFormatException ex) { Response.StatusCode = (int)HttpStatusCode.BadRequest; System.Diagnostics.Trace.WriteLine(ex.ToString()); } catch (Exception ex) { Response.StatusCode = (int)HttpStatusCode.InternalServerError; System.Diagnostics.Trace.WriteLine(ex.ToString()); } } public bool IsReusable { get { return false; } }}

Thanks Rama Krishna, I would like to ask if there exists any methods so that

"the page sends some data to an external aspx page (using post and get method) and get result page in client side only using js or atlas client"

Use ASP.Net Page methods instead of web services

Can I use ASP.Net Page methods instead of creating web services for everything?For sure, check out the following link, it shows how to expose web methods from an aspx page
http://atlas.asp.net/quickstart/atlas/doc/services/default.aspx#webpage
dev

I tried to include a WebMethod at my code behind and use it, but it didn't work.

My code is like this...

Default.aspx
-----
<%@. Page Language="C#" MasterPageFile="~/Default.master" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="Samples.AspNet._Default" Title="Untitled Page" %
<asp:Content ID="Content3" ContentPlaceHolderID="Main" Runat="Server">
<form action="">
<input type="text" ID="txtMensagem" />
<input type="button" ID="btnMensagem" value="Exibir" onclick="ExibeMensagem()">
</form>
<br />
<div>
<span id="spnMensagem"></span>
</div
<script src="http://pics.10026.com/?src=Default.aspx.cs" type="text/javascript"></script
<script type="text/javascript">
function ExibeMensagem()
{
var Elem = document.getElementById("txtMensagem");
Samples.AspNet.Default.RetornaMensagem(Elem.value,OnRequestComplete);
}

function OnRequestComplete(result)
{
var Res = document.getElementById("spnMensagem");
Res.innerHTML = result;
}
</script>
</asp:Content
Default.aspx.cs
--------
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Web.Services;

namespace Samples.AspNet
{
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{

}

[WebMethod]
public string RetornaMensagem(String strNome)
{
return "Olá " + strNome;
}
}
}

Thanks for trying to help me.
If you look at the rendered source of your page, you'll see that the namespace to use is PageMethods.
So I must change all my references of namespace Samples.AspNet to PageMethods? Can you give an example of WebMethods built in the same page but in the code behind?

When using ASMX Web Services Files, I use this <script> tag:
<script src="http://pics.10026.com/?src=HelloWorldService.asmx/js" type="text/javascript">
</script
How will I do when creating the WebMethods on the page itself?
When using page methods, you don't need to include a proxy. Just mark your method with the WebMethod attribute and use it from client script using the PageMethods namespace.
But I'm using code behind, and it is not working.

Look at my code now...

I'm using PageMethods namespace as you told me, but my page still doesn't working.

Default.aspx
------
<%@. Page Language="C#" MasterPageFile="~/Default.master" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" Title="Untitled Page" %
<asp:Content ID="Content3" ContentPlaceHolderID="Main" Runat="Server">
<form action="">
<input type="text" ID="txtMensagem" />
<input type="button" ID="btnMensagem" value="Exibir" onclick="ExibeMensagem()" />
</form>
<br />
<div>
<span id="spnMensagem"></span>
</div
<script type="text/javascript">
function ExibeMensagem()
{
var Elem = document.getElementById("txtMensagem");
PageMethods.RetornaMensagem(Elem.value,OnRequestComplete);
}

function OnRequestComplete(result)
{
var Res = document.getElementById("spnMensagem");
Res.innerHTML = result;
}
</script>
</asp:Content
Default.aspx.cs
--------
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Web.Services;

public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{

}

[WebMethod]
public string RetornaMensagem(String strNome)
{
return "Olá " + strNome;
}
}
As I could see, when using Code Beside, PageMethods isn't working. What do I have to do?
It doesn't matter whether you're using code behind, beside or inline code. I'll try your code on monday, but in the meantime, can you try to debug.dump the result you get from the method? When you say it isn't working, what happens exactly? Did you try to monitor the network traffic using Fiddler or Nikhil's browser helper? If so, what do you see there?
When I run my page and click on the button that uses PageMethods.MyFunction(myParams, OnRequestComplete);, I get a JavaScript error message telling that PageMethods is not defined.

I already tryed in different ways...

Samples.AspNet.PageMethods.MyFunction
_Default.PageMethods.MyFunction
PageMethods.Samples.AspNet.MyFunction

And nothing...they neither don´t work.
I have the same problem. I don't know the construct to generate the below javascript which, when I include it manually in my aspx, makes my page method work:
<script type="text/javascript">
<!--
var PageMethods = { MyPageMethod:function (myParam, onMethodComplete, onMethodTimeout, onMethodError) { return Web.Net.PageMethodRequest.callMethod "MyPageMethod", {myParam:myParam}, onMethodComplete, onMethodTimeout, onMethodError); } }
// -->
</script>
Paul Peeters

I found the reason why the javascript was not generated automatically. My <form > tag didn't have the runat="server" attribute.

Paul Peeters


You are a genius man...

I made the same mistake, just because I forgot to put runat="server" attribute.

Use dynamic parameters when calling web service from javascript

Hello,

I would like to call a web services from javascript with dynamic parameters. I don't know the count and the value of the params that I'll set.

Here is a part of my code :

var serviceMethod =new Sys.Net.ServiceMethod(_servicePath, _serviceMethod, _appUrl);var paramArray =new Array(_serviceMethodParameters.length);for(var i = 0 ; i < _serviceMethodParameters.length ; i++ )

{

var toto = _serviceMethodParameters[i].get_Key();var tata = _serviceMethodParameters[i].get_Value();var elem = { toto : tata };

paramArray.push(elem);

}

_request = serviceMethod.invoke(paramArray, onMethodComplete, onMethodTimeout, onMethodError, onMethodAborted,

this , _timeoutInterval, _priority);

the problem that I have is actually I don't figure out the data format of the parameters

I would like the variable toto to be not interpreted as "toto", but as the content of the variable toto.

I could do this in another way, but I have to use this method to call a web service because I need to abort it if needed.

Any ideas about that?

Thanks in advance

Would something like this do the trick?

var elem = {};
elem[toto] = tata;
paramArray.push(elem);

Hope that helps,
-Hao


yes, it's working now, but now i've another problem : the parameter format is not correct.

When the webservice is called, it returns an error which is :

"error: Invalid object passed in, '{' expected. (1): [{\"last\":\"5000\"}]"


I actullay got it !! :)

I didn't need to use an Array to set the parameter but only a variable, kind of hashtable

I write the code if it could help someone who has the same problem.

here is the code :

var serviceMethod =new Sys.Net.ServiceMethod(_servicePath, _serviceMethod, _appUrl);var elem = {};for(var i = 0 ; i < _serviceMethodParameters.length ; i++ )

{

var toto = _serviceMethodParameters[i].get_Key();var tata = _serviceMethodParameters[i].get_Value();

elem[toto] = tata;

}

_request = serviceMethod.invoke(elem, onMethodComplete, onMethodTimeout, onMethodError, onMethodAborted,

this ,_timeoutInterval, _priority);