Welcome to AspAdvice Sign in | Join | Help

Alessandro Gallo

.NET & Beyond
Hello World! in Atlas

Let's begin with the classic Hello World! example.

TheHelloWorld.aspx page contains two buttons. When a button is clicked,data is retrieved from the server and displayed in an alert box.

Inthis example we'll see how to make asynchronous calls to the server,i.e. how to retrieve data from the server without doing a postback. Todo this, we have to invoke a server method from client code.

Using Atlas, we can

  • Invoke a method defined in an .aspx page (i.e. a method of the Page class)
  • Invoke a method defined in a Web Service

Inour .aspx page, we declare two buttons. When the first button isclicked, a method HelloWorld() defined in the Page is called. Thismethod returns a string that is displayed in an alert box. When thesecond button is clicked, another HelloWorld() method, exposed in a Web Service, is called.

The code for the two buttons is

HelloWorld.aspx

<div>
    <input type="button"
           value="Hello from Page"
           onclick="sayHelloFromPage()" />

    <input type="button"
           value="Hello from WebService"
           onclick="sayHelloFromWS()" />
</div>

Asyou can see, the event handlers for the click event of the two buttonsare two client functions, sayHelloFromPage() and sayHelloFromWS(). Boththese functions are responsible to call the HelloWorld() server methodswe talked above.

So, we have to code something like

function sayHelloFromPage() {
   // Call HelloWorld() from Page.
}
function sayHelloFromWS() {
   // Call HelloWorld() from MyWebService.
}

Before filling the bodies of the client functions, let's declare the HelloWorld() server methods.

HelloWorld.aspx

<script runat="server">
   [WebMethod]
   public string HelloWorld()
   {
      return "Hello World from Page!";
   }
</script>

MyWebService.asmx

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

Now,we have to replace the comments in the client functions bodies with acall to the HelloWorld() server methods. Atlas helps us in doing thisby defining proxy classes. Aproxy class exposes a server method through a client function with thesame name of the server method. In other words, proxy classes allow tocall server methods "as if they were client methods".

If ourPage class contains web methods (i.e. method marked as [WebMethod]), aproxy class named PageMethods is generated at runtime. For a webservice, a proxy class is generated with the name of the web service.The proxy class for a web service resides in a file with the extension .asmx/js, that must be imported in the page as a script to be available. We can do this by dropping the declaration

<atlas:ScriptManager ID="scriptManager" runat="server">
    <Services>
        <atlas:ServiceReference Path="MyWebService.asmx" />
    </Services>
</atlas:ScriptManager>

in the <head>section of our HelloWorld.aspx page. The ScriptManager is a server control that is responsible to add the needed Atlas libraries and to import WebService proxies and Javascript external files.

The above declaration adds a reference to MyWebService.asmx, which is assumed to reside in the root directory of the application(note the Path attribute). References to Web Services are enclosed in the <Services> section, while references to external Javascript files are declared in the <Scripts> section. Finally, references to the main Atlas libraries (the core library and the compatibility layers) are added automatically at runtime so there is no need to explicitly declare them, while an explicit declaration is needed for certain Atlas control libraries (DragDrop controls or UI visual effects).

We were talking about proxy classes. Functionsdefined in a proxy class accept the same arguments as the correspondingserver methods, plus additional references to functions that areresponsible to process the result of the asynchronous call to theserver method.Thus, if we want to call the HelloWorld() method from the PageMethods proxy, we'll write a statement like

PageMethods.HelloWorld(onComplete);

TheHelloWorld() method accepts no arguments, but when invoking it throughthe proxy class we specify a function onComplete() to be called whenthe server method returns. With this function, we can access the datareturned by the server method through its first argument:

 

function onComplete(result) {
   alert(result);
}

Theabove function displays in an alert box the data returned from theHelloWorld() method. In a similar way, when calling methods from aproxy class, we can specify other functions to be invoked when theasynchronous call completes (tipically a function to be called if anerror occurred, another to be called if a timeout occurred).The above considerations lead to the following code for the Javascript functions,

<script type="text/javascript">
   function sayHelloFromPage() {
      PageMethods.HelloWorld(onComplete);
   }
   function sayHelloFromWS() {
      MyWebService.HelloWorld(onComplete);
   }
   function onComplete(result) {
      alert(result);
   }
</script>

Finally, here's the code for the file MyWebService.asmx:

<%@ WebService Language="C#" Class="MyWebService" %>

using System;
using System.Collections.Generic;
using System.Web;
using System.Web.Services;
using System.Web.Services.Protocols;

[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
public class MyWebService  : System.Web.Services.WebService
{
    [WebMethod]
    public string HelloWorld() {
        return "Hello World from MyWebService!";
    }
}

and the code for the HelloWorld.aspx page:

<%@ Page Language="C#" %>
<%@ Import Namespace="System.Web.Services" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<script runat="server">
    [WebMethod]
    public string HelloWorld()
    {
        return "Hello World! from Page";
    }
</script>

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title>Untitled Page</title>
    <atlas:ScriptManager ID="scriptManager" runat="server">
        <Services>
            <atlas:ServiceReference Path="MyWebService.asmx" />
        </Services>
    </atlas:ScriptManager>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <input type="button"
               value="Hello from Page"
               onclick="sayHelloFromPage();" />
        <input type="button"
               value="Hello from WebService"
               onclick="sayHelloFromWS();" />
    </div>
    </form>
    <script type="text/javascript">
        function sayHelloFromPage() {
            PageMethods.HelloWorld(onComplete);
        }
        function sayHelloFromWS() {
            MyWebService.HelloWorld(onComplete);
        }
        function onComplete(result) {
            alert(result);
        }
    </script>
</body>
</html>

UPDATE: the code has been updated to work with the January release of the Atlas CTP.
Posted: Thursday, December 22, 2005 4:25 PM by Garbin

Comments

Travis said:

Any chance of getting this same code to work with Master Pages? I can get it to work in a stand alone .aspx page like above, but when I move it to a Master Page"ed" aspx page, it fails.
# December 28, 2005 1:38 AM

Garbin said:

Travis,
the call to the web service method should work correctly with master pages. Regarding the Page method call, try to put the script section

<script runat="server">
[WebMethod]
public string HelloWorld()
{
return "Hello World from Page!";
}
</script>

inside the <asp:Content> tag of your page.

However, be sure to use the December release of the Atlas CTP (I have to update the code in this post to the December release, too).
# January 2, 2006 2:04 PM

Benjamin said:


  I think that all that you posted is really good but I've been improving on comparison between AjaxPro.NET vs Atlas technologies, and I have a question. Are you sure what are you sending when you causes a POST to a server?
  Using Sys.Net.ServiceMethod.invoke sentence you only sends a JSON data, but when you use a PageMathods sentence, you are sending ALL THE PAGE to the server.
  To make sure of that you can use IE HTTP Analyzer or Fiddler application
 
  This is a very important issue because in AjaxPro.NET all post that you cause to the server you are sending only JSON data and no more.

  I don't know why Microsoft ONLY USE web services to comunicate to server as a efficiently way. Why I can't communicate whit any WebMethod on any class like AjaxPro.NET??

  I like A lot Atlas because is a big Framework integrated on VS2005, and makes more easy development, but I think that there are very important issues that have not been resolved yet.

  Thanks!!!

   See you soon!!!
# May 4, 2006 4:44 AM

Pankaj said:

I want to call a web service that is not residing in the same project.(external web service). Can you help me out for this.
# May 15, 2006 3:30 AM

Garbin said:

Benjamin, this is very debated and here are a couple of links to interesting blog entries:

http://weblogs.asp.net/despos/archive/2006/05/09/445766.aspx

http://weblogs.asp.net/bleroy/archive/2005/06/27/415936.aspx

Garbin
# May 15, 2006 3:25 PM

Ken said:

I too cannot find an example that uses an external web service......
# May 22, 2006 12:56 PM

icy said:

hi there,

i am new to atlas, i tried to have this example worked, but the page keeps having "MyWebService" is not defined javascript error. it seems like the web service class didn't generate needed javascript. i have atlas.dll in my bin, i have added <controls> for atlas and <httpHandlers> for webservice in web.config.. have i missed anything? can anyone help me pls?
# May 31, 2006 4:16 PM

Garbin said:

icy, try to use the Atlas website template included in the Atlas installer, or copy the settings from its web.config. This is the quickest way to setup things correctly.
Garbin
# June 5, 2006 9:04 AM

pratibk said:

Garbin,
I tried running this same by placing the server method in a separate code behind and it doesnt work, it cannot understand pageMethods??

Any idea why would this be the case?

# June 7, 2006 12:54 AM

MS said:

I have a similar problem. I keep getting the 'MyWebService' is not defined error when I try to access the Web Service through JavaScript. I have made all necessary changes -added handlers to the web.config file, included the DLL in the bin directory, included referernce through the <ScriptManager> tag. What could I be missing? Any suggestions appreciated.

Thanks!
# June 7, 2006 4:34 PM

Sarah said:

Heey

I have the same problem as Icy and MS and i used the Atlas template. The JavaScript does not recognise eighter PageMethods or the WebService.

Thanks

# June 21, 2006 4:36 AM

Garbin said:

Sarah, are you adding a reference to the Web Service in the ScriptManager tag? Also, are you marking your page methods with the [WebMethod] attribute?
Garbin
# June 21, 2006 5:53 AM

rupesh tiwari said:

Hi
i am getting an error "PageMethods" undefined.

Please reply
Rupesh kumar tiwari
# June 23, 2006 7:22 AM

Mav said:

I see a couple of other people have asked and there's been no reply... have you any examples of accessing an external web service through Atlas? Examples of this are thin on te ground, surprising given that we can apparently use existing web services with Atlas.  From an architectural point of view I don't want my web services to reside in the same project as my atlas app, I want a separate dev team to work on the web service logic while my web team works on te main app.  The web team then needs to access a published web service.
# June 27, 2006 4:17 AM

examples of accessing an external web service through Atlas said:

Guys,
I too was struggling to get a good example of  accessing an external web service through Atlas. and fortunately i got a good one from the atlas samples which you can download http://atlas.asp.net..so good coding and NJoy...
::::-----)))))
Anil Nair
# July 21, 2006 11:17 AM

Greendot said:

In order to get the PageMethods to be generated, you need to make sure your defined WebMethod is public.  It works when the method is defined on your aspx or in the code-behind.

I fought this thing for a while until I figured out that it doesn't work for crap on protected methods.
# July 25, 2006 12:43 PM

johnlao said:

hi all,

i tried to run the example, but the result parameter on the javascript callback method returns a null value. why is it? i am using the latest june ctp of atlas. please see my code.

/* ------------------------------------------
Code Behind
---------------------------------------------*/
using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.Services;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

namespace Samples.AtlasPageMethods
{
   public partial class _Default : System.Web.UI.Page
   {
       [WebMethod()]
       public string DisplayWelcomeMessage(string pstrMsg)
       {
           return "Welcome " + pstrMsg + "!!!";
       }
       protected void Page_Load(object sender, EventArgs e)
       {

       }
   }
}

/*------------------------------------------
Page code
--------------------------------------------*/

<%@ Page Language="C#" AutoEventWireup="true"  CodeFile="Default.aspx.cs" Inherits="Samples.AtlasPageMethods._Default" %>

<%@ Register Assembly="Microsoft.Web.Atlas" Namespace="Microsoft.Web.UI" TagPrefix="cc1" %>

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

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
   <title>Atlas Page Methods</title>
   <cc1:ScriptManager ID="smManager" runat="server" >
       <Services></Services>
   </cc1:ScriptManager>
</head>
<body>
   <form id="frmDefault" runat="server">
   <div>
       <input id="btnDisplayMessage" type="button" value="Display Message" onclick="btnDisplayMessage_onClick()" />
   </div>
   </form>
   <script language="javascript" type="text/javascript">
       function btnDisplayMessage_onClick()
       {
           PageMethods.DisplayWelcomeMessage('John', Callback);
       }
       function Callback(resp)
       {
           alert(resp);
       }
   </script>
</body>
</html>

# July 28, 2006 1:27 AM

Garbin said:

johnlao: I suggest to download Fiddler at http://www.fiddlertool.com to monitor the asynchronous HTTP requests and responses.
# July 29, 2006 4:37 AM

Mike said:

A simple question but I am getting a compilation error when I try to use the [WebMethod] attribute.  I started a new atlas website and tried to copy in your example but to no avail.  I've updated to the latest CTP of Atlas.  Please help!

"CS0246: The type or namespace name 'WebMethod' could not be found (are you missing a using directive or an assembly reference?)"
# August 1, 2006 10:18 AM

Garbin said:

Mike: be sure you are importing the System.Web.Services namespace (with a using directive in C# or an Imports in VB.NET)
# August 3, 2006 6:55 PM

Martin Koster said:

I also got javascript errors on the page.
Found that in the web config file one line is missing in the example (if you add Atlas to your web config manually)

<webServices enableBrowserAccess="true"/>

it comes in the <microsoft.web> section AFTER the <converters>

Found out by comparing it with a web config that was created by the template ...
# August 5, 2006 4:26 PM

Tony said:

Bless you Martin Koster!!! I went through 3 examples including MS documentation and none of them mentioned this!

# August 22, 2006 4:09 PM

dandan80 said:

Sorry,

but even if I have

<webServices enableBrowserAccess="true"/>

in the web.config file of my application,  I still have the javascript problem when I include the problem. BTW, I am using the MS example and using the Visual Studio webserver everything works OK

Any other ideas?

Cheers,

dandan

# September 29, 2006 4:00 AM

Caladin said:

I'm sure I'm making a boneheaded mistake but

I'm not able to get this going in my "real" project.

I'm getting the error <serviceName> is not defined in my attempt to use this example.

I have the webservice defined in the script manager section, but its in a subdirectory

<atlas:ScriptManager ID="ScriptManager1" runat="server" EnablePartialRendering="true">

           <Services>

               <atlas:ServiceReference Path="~/WebServices/SecWizardData.asmx"  />

           </Services>

       </atlas:ScriptManager>

so it's saying SecWizardData is undefined when i try use it thusly.

SecWizardData.WebMethod(p1,p2,callback)

The script manager is on a masterpage in the Projroot/master directory and the content page is in the Projroot/content directory.

Am i specifying the relative paths incorrectly?

is there somethign I'm supposed to add to get it set up correctly.

the Project is the project for the web service and i added the webpages directly into it.

# November 20, 2006 10:58 AM

Caladin said:

Figured one part out.

If you're getting [Web Method[ is undefined and the method is in the code behind of the webpage, try adding this.

   [System.Web.Services.WebMethod]

instead of this

   [WebMethod]

(or add the appropriate using .. statement)

If you are getting it with the method on the webpage, add this to the 2nd line of the webpage (right after the PAGE tag)

<%@ Import Namespace="System.Web.Services" %>

I still get "PageMethods as undefined, when i click the buttons on my recreation of the above "hello world" project... still working on that one.

Thanks,

Cal-

# November 20, 2006 2:18 PM

Garbin said:

Caladin: the code in the blog post is outdated since it was written for an early CTP. Are you declaring your web method as a static method? Recall that page methods must be static starting from beta1.

# November 20, 2006 2:35 PM

Caladin said:

Nice!

That fixed the Page Methods both in the apsx page and on the code behind. I tried making the one in the webservice static also, but I'm still getting <webServiceName> is undefined when i click on it.

Any ideas?

# November 20, 2006 3:07 PM

Caladin said:

Here is what i think is the minmum relavent code

//aspx page, script block

function sayHelloFromPage3()

{

   //var service

   //service = new TestWebService();

   //service.HelloWorld(onComplete);

   TestWebService.HelloWorld(onComplete);// webService in same project

}

// html

   <asp:ScriptManager ID="ScriptManager1" runat="server" >

           <Services>

               <asp:ServiceReference Path="TestWebService.asmx" />

           </Services>

   </asp:ScriptManager>

...

<input id="Button3" type="button" value="Hello from Page3 web service" onclick="sayHelloFromPage3()" />

//webservice

[WebMethod]

   public static string HelloWorld() {

       return "Hello World";

   }

# November 20, 2006 3:11 PM

Garbin said:

Caladin: making the web service method static is not mandatory (it's mandatory only for page methods). Regarding the web service, be sure to decorate the web service class with the [ScriptService] attribute.

# November 20, 2006 3:12 PM

Caladin said:

I'm not sure I'm following what it is you want me to do there....

Reading that I guessed this, on the code behind for the webservice:

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

[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]

[ScriptService]

public class TestWebService : System.Web.Services.WebService {

   public TestWebService () {

       //Uncomment the following line if using designed components

       //InitializeComponent();

   }

   [WebMethod]

   public static string HelloWorld() {

       return "Hello World";

   }

}

Which does not compile... So I must have not gotten your suggestion.

Thanks again!

Cal-

# November 20, 2006 3:55 PM

Caladin said:

Nevermind, I'm an idiot... i needed to add this

using Microsoft.Web.Script.Services;

Then I was able to put it in...

Still getting the same error though...

# November 20, 2006 4:04 PM

Caladin said:

I figured it out, the web method on the webservice CANNOT be static.

Once i removed that and had the [ScriptService]

attribute it worked in my simple tester.

It worked both on a simple page and on a MasterPage/ContentPage.

I figured it out by looking at the webService directly in the browser.. the HelloWorld() method didn't show up when it was static.

Thanks,

Cal-

# November 20, 2006 4:51 PM

Michael said:

Hello,

I am having the same problem.  My code seems to be the same as yours is now.  Here's a snipit:

.cs file:

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

[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]

[ScriptService]

public class ws_DeleteMedia : System.Web.Services.WebService

{

   public ws_DeleteMedia()

   {

       //InitializeComponent();

   }

   [WebMethod]

   public string deleteMedia(int iMediaID)

   {

       try

       {

           return "success";

       }

       catch (Exception ex)

       {

           return ex.Message;

       }

   }

.aspx page:

<asp:scriptmanager id="ScriptManager1" runat="server">

 <Services>

    <asp:ServiceReference Path="~/Members/ws_DeleteMedia.asmx" />

 </Services>

</asp:scriptmanager>  

function deleteMedia(sMediaName,iMediaID)

{

deleteMediaResults = ws_DeleteMedia.deleteMedia(iMediaID,OnDeleteComplete);

}

It was working until I upgraded to the latest version of the CTP.  Any help out there?  Caladin, could you possibly email me your simple tester for me to test?  My email is michael_at_thebigonion_dot_com

Thx, Michael

# November 30, 2006 5:04 PM

lloyd m said:

when i tried to add the reference to Microsoft.Web.Script.Services, there is no services option after Microsoft.Web.Script, what could be wrong, also i am trying to access server code in a aspx file and not a webservice from the client. It also complains about not finding PageMethods.

Please help

# December 5, 2006 5:21 PM

robe said:

all works fine, but when my webservise and app, that execute that service are in the local network, if I'm trying execute service from out of local network, doesn't work

# March 15, 2007 10:00 AM

Amit said:

I was having same problem of PageUndefined script error.

to remove pageundefined error we need to add

EnablePageMethods="true" in script manager..

# March 24, 2007 8:25 AM

Amit said:

Sorry just hit submit too fast...

I noticed one more thing that we can use server side button instead of HTML button but we have to add one return false statement to it (Old javascript trick), I used add attribute at page load to bind server side button to call client side function.

    function sayHelloFromPage() {

           PageMethods.Hi("S",onComplete);

           return false

       }

       function onComplete(args)

       {

           alert (args)

       }

# March 24, 2007 8:28 AM

Damian said:

Hiya - i hit this problem yesterday and managed to work out what the problem was.

please see my blog:

http://omensblog.blogspot.com/2007/07/aspnet-ajax-web-service-calls-from.html

# July 17, 2007 8:27 AM

Frenky said:

Thank you so much for this tutorial. I got my webservice up and running in just a minute or two :))))

# April 2, 2008 7:57 AM

Garbin said:

Thank you :)

# April 5, 2008 12:46 PM

Mike said:

Thanks so much Martin Koster - you rock!

Your suggestion of adding :

<webServices enableBrowserAccess="true"/>

to the web.config file made all the difference for me. Previously I was getting the "is not defined" error, presumably because the JSON proxy was not being created. Your suggestion solved a 5 hour problem for me! Thanks again.

# April 17, 2008 5:58 AM
New Comments to this post are disabled