Showing posts with label object. Show all posts
Showing posts with label object. Show all posts

Wednesday, March 28, 2012

Accessing server-side Datatable object from client-side javascript?

I am working on a control that generates 2D charts (line,bar,pie,etc) using VML (for now) to draw the charts client-side. I am new to Javascript and still cant figure out how to access the data I need to graph from the javascript side. I am currently using a Sys.Data.Datable on the client side as test data (building the table manually in javascript) and it works fine but I cannot figure how to pass a datatable from the server to the control extension behavior?

I have read/seen code on the forums on how to do this using a web-service but I am really looking at a more generic approach where people could just bind a datatable to the control via the properties or in code so they can use their business logic layer functionality without having to write web-services.

Let's say I have the name of the page object/variable holding the datatable (from properties of control) how would I access this object as a Sys.Data.Datatable in Javascript? Would I need to use some kind of converter?

(hope I explained myself correctly and this makes sense to someone hehe)

Thanks in Advance

Pascal

Hello Pascal:

> I am new to Javascript and still cant figure out how to access the data I need to graph from the javascript side.

Strictly speaking, you can't! It is the server-side code that renders client-side code, so what you can do is actually the reverse: write the datatable to javascript.

Here is a topic that can give some hints:http://forums.asp.net/thread/1285185.aspx

This said, please feel free to go deeper with your question if needed.

-LV


Thanks for the quick reply btw :)

Here is some example of what I am trying to do (not actual code):

Lets say I have some ASPX page code like...

<script language="VB"> Private sub Page_Load() dim myTable as System.Data.Datatable ... populate table ... End sub</script><html> <body> <atlas:ScriptManager runat="server" ID="PageScriptManager" EnablePartialRendering="True"> </atlas:ScriptManager> <asp:Panel ID="ChartPanel" runat="server" Height="300" Width="400" /> <cc1:ChartPanelExtender ID="ChartPanelExtender1" runat="server" > <cc1:ChartPanelProperties ChartTitle="This is my Graph!" TargetControlID="ChartPanel" ChartType="0" ChartHeight="100" ChartWidth="300" ChartBackColor="#FF3A00" ChartTitleFontFamily="Arial Black" ChartTitleFontSize="20" ChartTitleFontWeight="Normal" ChartTitleTextAlign="Right" /> </cc1:ChartPanelExtender> </body></html>

The ChartPanelExtender is an atlas control extender that has its functionality (chart graphing) in its ChartPanelBehavior.js javascript file. What I would like to do is access that myTable from inside the javascript behavior file? Is that possible?

Thanks in advance,

Pascal

Accessing Request headers from asp.net web service, invoked using Ajax

I need a small help.

I have a web service, in which I have a web method, which detects the browser locale using asp.net request object.

If I invoke the web service directly from the browser, I am able to get the browser language from Request object'sHTTP_ACCEPT_LANGUAGEheader.

But If I invoke the same web method from some aspx using javascript XMLHttpRequest, I always get the request headerHTTP_ACCEPT_LANGUAGE null.

Is this the behavior of the web services.

Then how can I access the browser language setting for the current request in the web service.

Is there a way to invoke the web service with the same request settings as that of aspx page while using xmlhttp.

Thanks in Advance

Hi,

I saw that you got this issue answered byJohn Saunders athttp://forums.microsoft.com/MSDN/ShowPost.aspx?PostID=2341086&SiteID=1, Here is quotation:

You are unlikely to receive a browser language setting if the web service is not called from a browser.

Accessing DropDownList in UpdatePanel programmatically

I have an updatepanel within and updatepanel and am trying to access a drop down list as shown below. I am receiving an error saying the object is not set.

Dim LOAN_TYPEAs DropDownList =New DropDownList

LOAN_TYPE = UpdatePanel1.FindControl("UpdatePanel2").FindControl("ddlSIM_TYPE")

If LOAN_TYPE.SelectedValue ="Std"Then 'THIS IS WHERE I RECEIVE MY ERROR

Any ideas?

Try:

Dim LOAN_TYPEAs DropDownList = CType(UpdatePanel1.FindControl("UpdatePanel2").FindControl("ddlSIM_TYPE") , DropDownList)

-Damien


I tried that as well and same message. This is driving me nuts...

Any other ideas? Thanks for your help!


Use UpdatePanel.ContentTemplateContainer.FindControl(), instead.


You are going to hate me but that resulted in the same error message.

UpdatePanel1.ContentTemplateContainer.FindControl("UpdatePanel2").FindControl("ddlSIM_TYPE")


You need to use it on both UpdatePanels. In C#, it would work like this:

UpdatePanel up2 = (UpdatePanel)UpdatePanel1.ContentTemplateContainer.FindControl("UpdatePanel2");
DropDownList ddl = (DropDownList)up2.ContentTemplateContainer.FindControl("ddlSIM_TYPE");

I'm not sure of the exact VB syntax, but hopefully that makes sense.

Though, unless UpdatePanel2 is dynamically generated, you ought to be able to just find the dropdown like this:

DropDownList ddl = (DropDownList)UpdatePanel2.ContentTemplate.FindControl("ddlSIM_TYPE");

Ok, tried that and no luck. Here is the code section:

Dim p2As UpdatePanel = UpdatePanel1.ContentTemplateContainer.FindControl("UpdatePanel2")

Dim PVAs TextBox = p2.ContentTemplateContainer.FindControl("txtSIM_PV")

Dim IAs TextBox = p2.ContentTemplateContainer.FindControl("txtSIM_I")

Dim NAs TextBox = p2.ContentTemplateContainer.FindControl("txtSIM_N")

Dim LOAN_TYPEAs DropDownList = p2.ContentTemplateContainer.FindControl("ddlSIM_TYPE")

If LOAN_TYPE.SelectedValue ="Std"Then

When accessing this if statement i get an object not set error when accessing any of the objects shown above. I have checked and double checked everything and no luck. its inside the Form tag, it has runat=server, etc. Any other ideas - I am at my wits end...

Thanks


Well on the bright side, if you're not getting the error until the conditional, that means the UpdatePanel2 find is working.

Inside UpdatePanel2, are your TextBox and DropDownList controls contained within another control, like a panel or a wizard or a repeater?


Hi,

I agree withgt1329a.

But seeSolution to the FindControl problem for more information about FindControl problem.

Best Regards,

Monday, March 26, 2012

Accessing complex data properties on the client side.

I'm trying to access the properties of an object passed back from a web service but am having trouble. I thought the syntax was...

results.getItem(i).getProperty(

'propertyname') but I'm getting an error 'results.getItem(i).getProperty' is not a function.

I'm able to bind 'results' to a listview fine on the client side and debug.dump shows the data being returned is correct.

i don't know what type 'results' is.
you can try to use code below to list methods and propertis of getItem(i)
function(obj)
{
for(var name in obj)
names+=name+"\n";
alert(names);
}

tonyqus:

i don't know what type 'results' is.
you can try to use code below to list methods and propertis of getItem(i)
function(obj)
{
for(var name in obj)
names+=name+"\n";
alert(names);
}

Sorry tonyqus, 'results' is a generic collection and the javascript function on the client returns '_serverType' and the property names of the objects (similar to debug.dump). If I return a datatable the following works fine.

for (var i = 0; i < results.get_length(); i++) { alert(results.getItem(i).getProperty("PropertyName"));}
Is there a way to do something similar with object collections? The object collection binds fine to a listview or select element using set_data(results) so there must be some way of referencing the properties in javascript.

Never mind:!

Came back to it today and looked a little closer at the response from fiddler for a datatable vs an object collection. Also looked a little closer at JSON (http://www.json.org/). The line results.getItem(i).getProperty("PropertyName") works with datatables where results[i].PropertyName works with collections.

Accessing ASP.NET Session object during calls to Web Service Bridge?

Hi there,

Just getting started with the Web Service Bridge, looking at the MSN search example.

I've built my own Atlas enabled ASP.NET web application and created a .asbx file that points to an external Web Service and I can call methods on the Web Service through the class I derived from BridgeHandler, so all looking good.

Now I want to be able to make my BridgeHandler derived class interact with the ASP.NET Session object to set and retrieve session data from within my ASP.NET web application.

I can't see a way I can get at the Session object once I'm in my BridgeHandler derived class? Is this possible, or is there a way the Session or Context object can be passed as a parameter to my BridgeHandler derived class through the .asbx file?

I notice the MSN example uses the following syntax to pass a value stored in the Web.config as a parameter:

<parameter name="appId" value="% appsettings : MSNWalkthroughAppId %" serverOnly="true" /
Is there simlar syntax for passing the Session object? Are the options for what you can do in between the %% tags documented anywhere?

Thanks,

Mark

Hi Mark,

Right now we don't support an expression for session within %%, but we will consider adding it in the future. You can get access to Session thru HttpContext, which you can access thru HttpContext.Current...

In terms of expressions currently supported:

args: request args
appsettings: config
resultschain: see quickstart on chaining bridges declaratively
querystring: useful if you use HTTP get to make your bridge requests

Hope that helps,
-Hao


Doh, actually it turns out you can't access Session thru HttpContext.Current because we aren't emitting the proper interface on the generated class, so we'll definitely need to enable this in a future release, but at this time you unfortunately don't have any way to get to the session data...


Thanks for the response. I've just install the April release of Atlas and it doesn't appear to be in there yet either. Looks like I'll have to wait and in the meantime keep experimenting with other parts of Atlas.

Don't suppose you can give me any idea roughly when this feature will be included? (a bit hopeful I know :-)

BTW - does the current 'Context' object on the BridgeHandler class do anything useful at this stage? I get an exception 'Accessing context too early, it is null' exception when attempting to use that object.

Cheers,

Mark

Unfortunately this came up too late to get into the April CTP, but most likely we will get it in the next CTP...

You should be able to access the BridgeHandler.Context from within any of the bridge pipeline methods, basically the first thing that BridgeHandler.Invoke does is build the Context, so within the other virtual methods that you override, you should be able to access the BridgeContext, where are you trying to use the Context object?

Hope that helps,
-Hao

accessing arg.IsValid from callback function.

I have a custom validator on an aspx page which calls the function below: the args object passes in the value from a dropdownlistbox and has a property IsValid. The problem I'm facing is I don't have access to the results ofOnDoesExchangeRageExistComplete in the main fuction, because I want to set args.IsValid to the result. Any ideas on how I can do this?

This is the manin function called from the aspx page

functionDoesExchangeRateExist(sender, args)
{
//pass in the period date in args.value to the webservice.
UtilityService.DoesExchangeRateExist(args.Value, OnDoesExchangeRageExistComplete); //What I would like to do is set args.IsValid to the result of the webservice call. Because this determines if the page is submitted.
}

//----------------------------------

function

OnDoesExchangeRageExistComplete(result)
{
var errMsg = document.getElementById( "lblErrorMsg");
if(result ==true)
{
errMsg.innerHTML =""
returntrue;
}
else
{

errMsg.innerHTML =

"Exchange rates are not available for selected period date. Please select a different period date."\n

returnfalse;\n

}

\n

}

\n

\n

thanks,

\n

Garfield.

\n\n",0]);D(["ce"]);//-->returnfalse;

}

}

thanks,

Garfield.

I think you can returnargs.IsValidas a return value of the WebMethod?UtilityService.DoesExchangeRateExist?and access it in the callback of the client side through javascript.
Try to take a look at the following for details about calling web service in javascript from the client side.
If the web service class on the server includes a web method that does not return data, you can call the web service without having to handle a response. This is the simplest web method call that can be made from the client. For example, your application has the following web method:
?
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[Microsoft.Web.Script.Services.ScriptService]
public class Parts : System.Web.Services.WebService
{
[WebMethod]
public void NoReturn()
{
//do work here
System.Threading.Thread.Sleep(2000);
}
}
?
The following JavaScript can be used to invoke that web method
?
function RunWebService()
{
Parts.NoReturn();
}
?
If the webservice is in a custom namespace, you would need to fully
qualify the call to the webservice. For example, if the WebService
has a namespace of MyCustomNameSpace.WebServices, the above JavaScript
becomes:
?
function RunWebService()
{
MyCustomNameSpace.WebServices.Parts.NoReturn();
}
?
Getting a return value?
In a scenario where the web method has a return value, then the asynchronous invocation model requires providing a callback function that will be called when the web service call returns. The callback function has an input parameter that contains the results of the web service call.
?
The server-side AJAX stack will appropriately serialize the return value from the web method, and the client-side AJAX stack will deserialize the data to an appropriate JavaScript type to be passed to the callback function.
?
On the Server-side, there is a WebMethod that returns a string:
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[Microsoft.Web.Script.Services.ScriptService]
public class Parts : System.Web.Services.WebService
{
[WebMethod]
public string DynamicDropdown()
{
string tmpDropDown;
tmpDropDown = "<select id=test name=test><option value=Part1>Part1</option><option value=Part2>Part2</option></select>";
return tmpDropDown;
}
}
?
When you call the web service in client script, the call will need to have a callback function specified to handle the return value. The following script demonstrates calling the DynamicDropdown WebMethod of the Parts Web Service and specifies OnComplete as the callback function. The OnComplete function has an input paramter which is the return object from the web service call, in this case, this will be the string value. The OnComplete function then takes the return value and inserts it as the innerHTML property of a span with ID DynamicArea. The result is that a dropdown appears on the page.
function InsertDropdown()
{
Parts.DynamicDropdown(OnComplete);
return false;
}
function OnComplete(result)
{
DynamicArea.innerHTML += result;
}
Passing primitive type parameters to web method
If the web method takes input parameters, then the JavaScript invocation of the method will take corresponding JavaScript parameters. The parameter values will be serialized by the AJAX stack into JSON and packaged in the body of the request and then de-serialized as .Net types corresponding to the signature of the web method.
?
For example, given the following server method that accepts a string parameter and returns a string:
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[Microsoft.Web.Script.Services.ScriptService]
public class Parts : System.Web.Services.WebService
{
[WebMethod]
public string EchoString(String s)
{
return s;
}
}
?
You would use the following JavaScript to call the web service, pass the string parameter and include the callback function:
?
function CallEchoString()
{
Parts.EchoString(form1.GetString.value, OnCallBack);
}
function OnCallBack(results)
{
alert(results);
}
?
The call to the EchoString web method on the Parts.asmx web service is taking the value from a textbox named GetString in a form with ID of "form1" to pass as the input parameter and specifying OnCallBack as the callback function. The OnCallBack function has an input parameter of "results" which is the return type from the EchoString web method. The JavaScript then displays that in a popup box.
Specifying a callback for failure cases?
If the request to the web method is unsuccessful, whether because of error, timeout, or if server code aborts the request, then the callback specified for successful completion will not be called. A second callback function can be specified in the call to the web service for failure cases, receiving an error object as parameter, as in the following javascript:
?
function CallService()
{
PeopleServices.ThrowError(OnCallBackThrowError, OnError);
}
function OnCallBackThrowError(result)
{
alert("OnCallbackThrowError: " + result);
}
function OnError(result)
{
alert("OnError: " + result.get_message());
alert(result.get_stackTrace());
}
?
In the code sample, the ThrowError method of the PeopleServices web service does not take any input parameters. The method call passes the callback function "OnCallBackThrowError" and a method for handling any error condition called "OnError". The OnError method takes an input parameter which is a error object that contains the error message and stack information passed from the server if a .NET Exception was thrown. In this case, the information is displayed in popup windows, but once you have the errors in the browser, you can notify the user in any manner you feel is appropriate.
Using the same callback from multiple callers?
You can leverage the same callback function on the client for multiple web service calls. This allows you to avoid having to write a client function for each callback. In order to differentiate the calls, you pass a user context object that contains information that can be used to tell the requests apart. The user context object can be any JavaScript primitive type, array, or object.
?
For example, let's say you have a web service that contains a web method that you need to call multiple times from the client. You need to know which response corresponds to each call. For example, the first call's return value is placed in Span1 and the second call is in Span2. In order to do this, you can associate context information with the request and you can use the context information to distinguish which request is providing the response. This information is not passed to the server by default. If you want to pass this information to the web service, you would need to pass it as an input parameter to the remote method.
?
On the server, you have the following web service method that is taking in the a string which should be a stock symbol and returning a string:
?
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[Microsoft.Web.Script.Services.ScriptService]
public class Parts : System.Web.Services.WebService
{
[WebMethod]
public string UserContextSample(string stockSymbol)
{
string returnValue = String.Empty;
//do work here to look up stock symbol info
return returnValue;
}
}
?
On the client, you create a JavaScript object to store context specific information and pass that as the last parameter to the web service call. In the sample below, we're creating a dictionary object on the client with a key of contextKey and a value of a stock quote. The syntax for the web service call is:
?
WebService.Method(InputParams, CallBackMethod, ErrorMethod, contextInfo);
?
function CallServicesTest()
{
var userContext1 = {contextKey:"MSFT"};
Parts.UserContextSample("MSFT", OnCallBack, OnError, userContext1);
var userContext2 = {contextKey:"AAPL"};
Parts.UserContextSample("AAPL", OnCallBack, OnError, userContext2);
}
In the callback function, you add a second input parameter that contains the context passed in the web service call. This way you get the results of the web service call in the first input parameter and the context information in the second parameter. In this case, we're checking the context information and inserting text into specific spans on the page along with the response from the web service.
?
function OnCallBack(results, userContext)
{
switch(userContext.contextKey)
{
case "MSFT":
SPAN1.innerHTML = "Microsoft " + results;
break;
case "AAPL":
SPAN2.innerHTML = "Apple " + results;
break;
}
}
Using the same callback for different web methods?
This scenario is similar to using the same callback for multiple calls with the exception that you have two separate web service methods on the client that are using the same callback method. In this scenario, you include a third input parameter on the callback function to receive the web service call that the response is associated to.
?
For example, you have two Web Methods that your function needs to call, but you want to have a single callback method. You can tell which web method is returning by accessing the optional third input parameter to the callback function.
?
On the server you have:
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[Microsoft.Web.Script.Services.ScriptService]
public class Parts : System.Web.Services.WebService
{
[WebMethod]
public string EchoString(String s)
{
return s;
}
[WebMethod]
public string AnotherEchoString(String s)
{
return s;
}
}
?
On the client you have a button that has an onclick method calling GetEcho() function in JavaScript:
?
function GetEcho()
{
Parts.EchoString("This is echo number 1", OnCallBack);
Parts.AnotherEchoString("Another echo string!", OnCallBack);
}
function OnCallBack(results, userContext, sender)
{
alert(results + "\n" + sender);
}
?
When OnCallBack runs, you will get an alert dialog with the string you passed to the web service along with Parts.EchoString or Parts.AnotherEchoString.
Passing and receiving a server type?
As mentioned previously, the AJAX networking stack will generate proxy scripts for any server type that is referenced as an input or output parameter by the web methods contained in linked web services. This allows a developer to access these types on the client in a similar fashion as they would on the server. The types are serialized using JSON serialization which is covered in the next lesson.
?
For example, let's say you have the following web service called PeopleServices. This web service has a method called NewPerson that takes in 3 parameters; 2 Person objects and 1 object of type bool. The return value is also of type Person.
?
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[Microsoft.Web.Script.Services.ScriptService]
public class PeopleServices : System.Web.Services.WebService
{
?
[WebMethod]
public Person NewPerson(Person parent1, Person parent2, bool female)
{
Person _newPerson = new Person();
//Do other work
return _newPerson;
}
}
When you add this web service to the ScriptManager, the client will make a request for the proxy script as discussed in the Proxy Generation section. The result is that the Proxy script will have the web service method as well as the properties for the Person class. The person class is defined as the following on the server:
?
public class Person
{
public string Name
{
get { return _name; }
set { _name = value; }
}
public int Age
{
get { return _age; }
set { _age = value; }
}
public int Height
{
get { return _height; }
set { _height = value; }
}
}
?
On the client, you would need to generate two objects of type Person and pass them as parameters to the web service. In the callback script, the result parameter will be of type Person. Here's a sample JavaScript function that takes the values of textboxes on the page and creates two Person objects, then calls the NewPerson object on the above web service.
?
function GetNewPerson()
{
var person1 = new Person();
var _name = document.getElementById('p1FirstName');
var _age = document.getElementById('p1Age');
var _height = document.getElementById('p1Height');
person1.Name = _name.value;
person1.Age = _age.value;
person1.Height = _height.value;
?
var person2 = new Person();
_name = document.getElementById('p2FirstName');
_age = document.getElementById('p2Age');
_height = document.getElementById('p2Height');
?
person2.Name = _name.value;
person2.Age = _age.value;
person2.Height = _height.value;
PeopleServices.NewPerson(person1, person2, true, OnCallbackGetNewPerson, OnError);
}
?
Here is a sample callback function that handles the return type from the NewPerson method. The result parameter is a Person object and you can directly access the properties. In this case NewPerson is the ID on a Div in the page.
?
function OnCallbackGetNewPerson(result)
{
var newPerson = result;
NewPerson.innerHTML = "New Person <br/>";
NewPerson.innerHTML += "Name: " + newPerson.Name + "<br />";
NewPerson.innerHTML += "Age: " + newPerson.Age + "<br />";
NewPerson.innerHTML += "Height: " + newPerson.Height + "<br />";
}
When you run pages that make these calls and check out the network traffic, you'll see the following:
Web service call is a POST to …/PeopleService.asmx/js/NewPerson. Since the request ends in /js/NewPerson, the AJAX HttpHandler will handle the request to the web service. The Content-Type of the request is application/json.
Request Body contains all the data to create the Person object on the server. The main piece is the __type parameter which tells the server what type to create:
?
{"parent1":{"__type":"Person","Name":"Name1","Age":"12","Height":"60"},"parent2":{"__type":"Person","Name":"Name2","Age":"24","Height":"72"},"female":true}
The response also has a Content-Type of application/json and has a similar body containing the __type parameter and values necessary to create the Person object on the client:
?
{"__type":"Person","Name":"Name1name2ella","Age":23,"Height":71}
?Demo is FireForgetDemo.aspx
?Wish the above can help you.

Accessing a property from a custom object

Hi all,
I am trying to mimic what I can do imperitively, in a declarative way for the purposes of a demo. I have no issue an accessing a web service that returns a custom object imperitively. For example:
function MakeTheCall()
{
DataTier.DoTheAsyncMethod(OnMethodComplete);
}
function OnMethodComplete(customer)
{
alert(customer.FirstName + " " + customer.LastName);
}

where the 'customer' is what the web service returns and is defined as something like:
public class MyCustomer
{
public string FirstName;
public string LastName;
//...and a couple of others
}

Again, imperitively, this is easy and requires little code, however declaratively is causing me issues. I can make the call but am unsure of how to extract say the 'FirstName' from the response object and place it into a textbox. Currently I having something like:
<textBox id="txtFirstName">
<bindings>
<binding id="custServiceBindingFirstName" property="text"
dataContext="custService"
dataPath="response.object"
automatic="false" />
</bindings>
</textBox>
which as you would expect, simply puts the text '[object Object]' into the text field, but I have tried a number of permutations and am unsure of how to extract the 'FirstName' property from the response.object so that the binding can put this value into the text field. I know the calls are being made fine in my delcarative code as I can see the call being made via Fiddler tool and can see the serialise properties. I am sure I am missing something simple.
Thanks in advance.You're so close :). Try changing the dataPath to "response.object.FirstName".
Atlas will basically split the data path (based on the dot), and treateach part as a property. In this case, "response" is a property ofcustService, "object" is a property of the return value ofcustService.get_response() and "FirstName" is a property of the returnvalue of custService.get_response().get_object().

That was one of the 1st things I tried but I get a javascript error saying that the 'Object doesn't support this property or method'.


Oh, I see. Interesting. When an object is serialized to JSON,properties like FirstName are really just fields. If the serializerwould actually generate "real properties" (ie. functions likeget_FirstName), and a getDescriptor implementation (to register theseproperties), then it should've worked.
I think this means you currently can't do this declaratively.

Okay, fair enough. Does that mean it probably will work in future builds? I would assume so.
Just as a FYI, the object gets serialised like so (taken from fiddler):
{"FirstName":"Joe","LastName":"Bloggs","AddressLine1":"Level 1","AddressLine2":"18 Tarmac rd","Suburb":"Scumsville","PostCode":1234,"DateOfBirth":new Date(2003,0,17,17,37,46)}
I'm pretty sure they will come up with a way that will make it possible.
If you want, you could probably hack the atlas scripts a bit to addsupport for it yourself (obviously this is not recommended). All you'dhave to do is extend this object, after it was 'deserialized', byadding a getDescriptor implementation and add the 'properties'. I couldhelp you with this, but the question is: how badly do you want to getthis working? :)

Well its not that important really, but your offer is tempting to simply learn the inner workings of Atlas better. I'll get back to you on that one Wilco. I might hack and slash at it first, then give you a shout if (when :-) ) I get stuck.

Thanks heaps for the offer.


Ralph Sommerer's post about the beautified sources may help you to read the source code.

Okay, I have given this a shot and have gone part way there. I have defined a type descriptor function, and have added a property 'FirstName' of type string to the type descriptor for my object. Next, I do a:
Web.Component.registerBaseMethod(this,'getDescriptor');

I am not sure if this is correct, in fact, I am just guessing at which 'registerBaseMethod' implementation I should be using (ie. the Web.Component one listed above or a different one).
I then register a 'getter' for the object:
o.get_FirstName = function() { return 'My Firstname Text'; };

And all this works, generates no errors, and in the declarative section of the Atlas markup, the "response.object.FirstName" now works and returns the hardcoded text I have used in the line above. My questions are:
Is my usage ofWeb.Component.registerBaseMethodcorrect? Should I be using the registerBaseMethod of a different class?
I am now not sure how to generically examine the returned serialised object for its list of properties, and determine their types, then add them into the type descriptor. I imagine there are some support routines around this but I haven't found them yet. I could write up a lengthy string parsing routine but that doesn't sound like much fun. Any direction here would be helpfull.
Thanks.
P.S. As you are probably aware, this is all in the AtlasCore.js file. Also note, this excercise is not that important, but it is heling me to familiarise myself with the Atlas libraries.

Hi,
I think your problem should be related to mine:http://forums.asp.net/1080824/ShowPost.aspx so I tried setting datapath to dot convention, as Wilco suggests, but it still doesnt work. What is interesting is that when i use dataPath like "anything.something" my controls show empty space (even in this case) instead of "undefined" word. I tried all combinations of my custom class names like _actualTO.Brn, Xdmpactualto.Brn etc etc..but no result :(
Adam


The method registerBaseMethod is part of the Function prototype (ie.all functions have this function :)). You should generally call thisfunction like:
MyComponent.registerBaseMethod(this, 'getDescriptor');
You should also do this _inside_ 'MyComponent'.
It would probably be easier to modify the JSON.deserialize implementation, to something like:
this.deserialize = function(data) {
var x = eval('(' + data +')');
return new ObjectWrapper(x);
}
[...]
Web.ObjectWrapper = function(obj) {
var _obj = obj;
for (var member in _obj) {
// Create properties for each non-function in the wrapped object.
if (typeof(_obj[member]) != "function") {
this['get_' + member] = function() {
return _obj[member];
}
this['set_' + member] = function(value) {
_obj[member] = value;
}
}
}
this.getDescriptor = function() {
var td = new Web.TypeDescriptor();
for (var member in _obj) {
if (typeof(_obj[member]) != "function") {
td.addProperty(member, Object.getType(_obj[member]));
}
}
return td;
}
}
Type.registerClass('Web.ObjectWrapper', null, Web.ITypeDescriptorProvider);
I haven't tested this, so I don't know if this would actually work. But I think something like this would work.

Okay, I have modifications as per your post above. My current code looks like this:

this.deserialize =function(data)
{
var o = eval('('+data +')');

// Previous code
// return o;

// New code.
return new Web.DeserialisedPropertyWrapper(o);
}
}


// The object that 'wraps' the returned/serialised object. This object provides a type descriptor
// that defines each property within the deserialised object. Without this, the properties are
// not available within the declarative markup sections.
Web.DeserialisedPropertyWrapper = function(obj) {
var _obj = obj;

for (var member in _obj) {
// Create properties for each non-function in the wrapped object.
if (typeof(_obj[member]) != "function") {
this['get_' + member] = function() { // getter
return _obj[member];
}
this['set_' + member] = function(value) { // setter
_obj[member] = value;
}
}
}

// Set up property descriptions in our type descriptor for the object wrapper.
this.getDescriptor = function() {

var td = new Web.TypeDescriptor();
for (var member in _obj) {
if (typeof(_obj[member]) != "function") {
td.addProperty(member, Object.getType(_obj[member]));
}
}
return td;
}
}

// Make sure our new property wrapper object is registered and available.
Type.registerClass('Web.DeserialisedPropertyWrapper', null, Web.ITypeDescriptorProvider);

It 'mostly works' however the issue is that the 'getter' always returns the value of 'DateOfBirth'. Reason is because the'DateOfBirth' is what is the last field is when setting up the functions for each getter. Subsequently, the variable'member' is set at'DateOfBirth' when the function exists. The code for each getter in each function reads'return _obj[member]' which obviously equates to'return _obj['DateOfBirth'];' (because DateOfBirth is what member last equalled).
My javascript is pretty poor and this is probably the real issue, however I need to ensure that the function that each getter uses equates to 'return _obj['FirstName']; ' or something similar, not an actual variable that is defined when the 'getter' is setup. Hope I am making sense here, but I am unsure how to achieve this in javascript.

Saturday, March 24, 2012

A simple question: Do webservices work with the beta?

I can't seem to get of my webservice to work. All I get is object undefined. I have javascript that gets triggered on an onblur() event which calls a webservice where the code is in another file. Nothing I do will get it to work. I've tried all the solutions I've found and still errors.

Same goes for cascadingdropdowns. It's like my webservice is invisible. I read the sticky about putting the webservice call in the aspx file and I did that but it still can't be found.

I find that the documentation is limited and what I do find, it seems to be written for experts. So, I guess for now, I have no option but to dump the path I'm on since it appears to me the code isn't ready for beta. Too many issues. Not enough documentation and examples.

Very frustrated!

Hi jax67, can we see the webservice class and the javascript function that calls it? Also the error message that you are getting. Maybe I can help. I used cascadingdropdowns a lot too, it was very frustated at first, but then I figured it out. So, everything is all good now.

Thanks AW - I am so frustrated :( The first file is in a folder called Maint (off of the root) and the webservice asmx file is in the root. The code for the webservice is in app_code.

Here is the code that has the javascript call. The onblur is what calls the javascript and that part works. It's the actual call to the service that fails. I put an alert before the call and the alert is displayed. A javascript error occurs after I dismiss the alert. I do not have the alert code in the following code files.

Thank you for any help you can provide. I really do appreciate it...

Dave

<%@. Page Language="C#" MasterPageFile="~/MasterPage.master" AutoEventWireup="true"
CodeFile="Amendment.aspx.cs" Inherits="Maint_Amendment" Title="Add A New Contract Amendment"
EnableEventValidation="false" %>
<%@. Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="ajaxToolkit" %
<asp:Content ID="Content1" ContentPlaceHolderID="ContentPlaceHolder1" runat="Server">
<ajax:ScriptManager ID="sm" runat="server" EnablePartialRendering="True">
<Services>
<ajax:ServiceReference Path="../ContractService.asmx"/>
</Services>
</ajax:ScriptManager>
<script type="text/javascript" language="javascript">
function AddDates_click()
{
// Get the values necessary to pass to the webservice
var startDate = $get('<%= txtStartDate.ClientID %>').value;

var periodInYears = $get('<%= txtPeriodYears.ClientID %>').value;
if (periodInYears == "") periodInYears = "0";

var periodInMonths = $get('<%= txtPeriodMonths.ClientID %>').value;
if (periodInMonths == "") periodInMonths = "0";

if (startDate != "")
{
// Show the progress and resize the textbox
document.getElementById('calculating').style.display = '';
$get('<%= txtExpirationDate.ClientID %>').style.width = '90%';
// Make the call to the webservice
alert("Before Call...");
var x = ContractService.CalculateExpirationDate(startDate, periodInYears, periodInMonths, OnComplete, OnTimeout);
}

return false;
}
function OnComplete(result)
{
$get('<%= txtExpirationDate.ClientID %>').value = result;
document.getElementById('calculating').style.display = 'none';
$get('<%= txtExpirationDate.ClientID %>').style.width = '98%';
}
function OnTimeout(result)
{
document.getElementById('calculating').style.display = 'none';
$get('<%= txtExpirationDate.ClientID %>').style.width = '98%';
}
</script>
<ajax:UpdateProgress ID="UpdateProgress1" runat="server">
<ProgressTemplate>
<img src="http://pics.10026.com/?src=../images/spinner.gif" />
</ProgressTemplate>
</ajax:UpdateProgress>
<ajax:UpdatePanel ID="upAmendment" runat="server">
<ContentTemplate>
<table align="center" border="1" bordercolor="#000000" cellpadding="4" style='width: 50%;
border-collapse: collapse">
<tr>
<td class="label" style='width: 30%'>
<asp:Label ID="Label2" runat="server" SkinID="bold" Text="Amendment Num"></asp:Label></td>
<td class="alt">
<asp:TextBox ID="txtAmendmentNumber" runat="server" MaxLength="10" ReadOnly="True"></asp:TextBox><br />
<asp:TextBox ID="txtContract" runat="server" ReadOnly="True" Visible="False"></asp:TextBox></td>
</tr>
<tr>
<td class="label" style='width: 30%'>
<asp:Label ID="lblStartDate" runat="server" SkinID="bold" Text="Start Date"></asp:Label></td>
<td class="alt">
<asp:TextBox ID="txtStartDate" runat="server" MaxLength="15" onblur="return AddDates_click()"
AutoCompleteType="Disabled"></asp:TextBox>
<asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" ControlToValidate="txtStartDate"
Display="Dynamic" ErrorMessage="This field is required"></asp:RequiredFieldValidator>
<asp:RegularExpressionValidator ID="regStartDate" runat="server" ControlToValidate="txtStartDate"
Display="Dynamic" ErrorMessage="Invalid Date Format"></asp:RegularExpressionValidator></td>
</tr>
<tr>
<td class="label" style='width: 30%'>
<asp:Label ID="Label3" runat="server" SkinID="bold" Text="Period (Years)"></asp:Label></td>
<td class="alt">
<asp:TextBox ID="txtPeriodYears" runat="server" MaxLength="3" onblur="return AddDates_click()"
AutoCompleteType="Disabled"></asp:TextBox>
<asp:RangeValidator ID="rngYears" runat="server" ControlToValidate="txtPeriodYears"
Display="Dynamic" ErrorMessage="Invalid Value" MaximumValue="100" MinimumValue="1"
Type="Integer" SetFocusOnError="True"></asp:RangeValidator>
</td>
</tr>
<tr>
<td class="label" style='width: 30%'>
<asp:Label ID="Label4" runat="server" SkinID="bold" Text="Period (Months)"></asp:Label></td>
<td class="alt">
<asp:TextBox ID="txtPeriodMonths" runat="server" MaxLength="2" onblur="return AddDates_click()"
AutoCompleteType="Disabled"></asp:TextBox>
<asp:RangeValidator ID="RangeValidator1" runat="server" ControlToValidate="txtPeriodMonths"
Display="Dynamic" ErrorMessage="Invalid Value" MaximumValue="11" MinimumValue="0"
SetFocusOnError="True" Type="Integer"></asp:RangeValidator></td>
</tr>
<tr>
<td class="label" style='width: 30%'>
<asp:Label ID="Label5" runat="server" SkinID="bold" Text="Expiration Date"></asp:Label></td>
<td class="alt">
<asp:TextBox ID="txtExpirationDate" TabIndex="-1" runat="server" MaxLength="15"></asp:TextBox>
<span id="calculating" style='display: none;'>
<img src="http://pics.10026.com/?src=../images/spinner.gif" /></span>
</td>
</tr>
<tr>
<td class="label" style='width: 30%'>
<asp:Label ID="Label11" runat="server" SkinID="bold" Text="Class"></asp:Label></td>
<td class="alt">
<asp:DropDownList ID="ddlClass" runat="server">
</asp:DropDownList>
<asp:RequiredFieldValidator ID="reqClass" runat="server" ControlToValidate="ddlClass"
Display="Dynamic" ErrorMessage="This field is required"></asp:RequiredFieldValidator></td>
</tr>
<tr>
<td class="label" style='width: 30%'>
<asp:Label ID="Label12" runat="server" SkinID="bold" Text="Type Of"></asp:Label></td>
<td class="alt">
<asp:DropDownList ID="ddlType" runat="server">
</asp:DropDownList>
<asp:RequiredFieldValidator ID="reqType" runat="server" ControlToValidate="ddlType"
Display="Dynamic" ErrorMessage="This field is required"></asp:RequiredFieldValidator></td>
</tr>
<tr>
<td class="label" style='width: 30%'>
<asp:Label ID="Label6" runat="server" SkinID="bold" Text="Consideration"></asp:Label></td>
<td class="alt">
<asp:TextBox ID="txtConsideration" runat="server" MaxLength="10" AutoCompleteType="Disabled"></asp:TextBox>
<asp:RangeValidator ID="rngConsideration" runat="server" ControlToValidate="txtConsideration"
Display="Dynamic" ErrorMessage="Invalid Value" MaximumValue="999999999" MinimumValue="0"
SetFocusOnError="True" Type="Double"></asp:RangeValidator>
</td>
</tr>
<tr>
<td class="label" style='width: 30%'>
<asp:Label ID="Label7" runat="server" SkinID="bold" Text="Percent of Credit"></asp:Label></td>
<td class="alt">
<asp:TextBox ID="txtPercentCredit" runat="server" MaxLength="30" AutoCompleteType="Disabled"></asp:TextBox>
<asp:RangeValidator ID="rngPercentCredit" runat="server" ControlToValidate="txtPercentCredit"
Display="Dynamic" ErrorMessage="Invalid Value" MaximumValue="100" MinimumValue="0"
SetFocusOnError="True" Type="Double"></asp:RangeValidator></td>
</tr>
<tr>
<td class="label" style='width: 30%'>
<asp:Label ID="Label8" runat="server" SkinID="bold" Text="Credit Type"></asp:Label></td>
<td class="alt">
<asp:DropDownList ID="ddlCreditType" runat="server" DataTextField="LOV_ITEM" DataValueField="LOV_VALUE">
</asp:DropDownList></td>
</tr>
<tr>
<td class="label" style='width: 30%'>
<asp:Label ID="Label9" runat="server" SkinID="bold" Text="Carry Forward (Years)"></asp:Label></td>
<td class="alt">
<asp:TextBox ID="txtCarryForward" runat="server" MaxLength="2" AutoCompleteType="Disabled"></asp:TextBox>
<asp:RangeValidator ID="rngCarryForward" runat="server" ControlToValidate="txtCarryForward"
Display="Dynamic" ErrorMessage="Invalid Value" MaximumValue="100" MinimumValue="0"
SetFocusOnError="True" Type="Integer"></asp:RangeValidator></td>
</tr>
<tr>
<td class="label" style='width: 30%'>
<asp:Label ID="Label10" runat="server" SkinID="bold" Text="Assignable ?"></asp:Label></td>
<td class="alt">
<asp:RadioButtonList ID="optAssignable" runat="server" RepeatDirection="Horizontal">
<asp:ListItem Value="Y">Yes</asp:ListItem>
<asp:ListItem Value="N">No</asp:ListItem>
</asp:RadioButtonList></td>
</tr>
<tr>
<td class="label" style='width: 30%'>
<asp:Label ID="lblEffectivityDate" runat="server" SkinID="bold" Text="Effectivity Date"></asp:Label></td>
<td class="alt">
<asp:TextBox ID="txtEffectivityDate" runat="server" AutoCompleteType="Disabled" MaxLength="15"
onblur="return AddDates_click()"></asp:TextBox>
<asp:RegularExpressionValidator ID="regEffectivityDate" runat="server" ControlToValidate="txtEffectivityDate"
Display="Dynamic" ErrorMessage="Invalid Date Format"></asp:RegularExpressionValidator>
<asp:RequiredFieldValidator ID="reqEffectivityDate" runat="server" ControlToValidate="txtEffectivityDate"
Display="Dynamic" ErrorMessage="This field is required"></asp:RequiredFieldValidator></td>
</tr>
</table>
<ajaxToolkit:CascadingDropDown ID="cddClass" runat="server" Category="Class" PromptText="Select a Class"
ServicePath="../ContractService.asmx" ServiceMethod="GetClasses" TargetControlID="ddlClass" Enabled="true" />
<ajaxToolkit:CascadingDropDown ID="cddType" runat="server" Category="Type" PromptText="Select a Type"
ServicePath="../ContractService.asmx" ServiceMethod="GetTypes" TargetControlID="ddlType" ParentControlID="ddlClass" Enabled="true" />
<ajaxToolkit:TextBoxWatermarkExtender ID="wmPeriodYears" runat="server" TargetControlID="txtPeriodYears" WatermarkCssClass="WaterMark" WatermarkText="Terms in years" />
<ajaxToolkit:TextBoxWatermarkExtender ID="wmPeriodMonths" runat="server" TargetControlID="txtPeriodMonths" WatermarkCssClass="WaterMark" WatermarkText="Terms in months" />
<ajaxToolkit:TextBoxWatermarkExtender ID="wmStartDate" runat="server" TargetControlID="txtStartDate" WatermarkCssClass="WaterMark" WatermarkText="Contract Start Date" />
<ajaxToolkit:TextBoxWatermarkExtender ID="wmConsideration" runat="server" TargetControlID="txtConsideration" WatermarkCssClass="WaterMark" WatermarkText="Amount paid or units mined in consideration" />
<ajaxToolkit:TextBoxWatermarkExtender ID="wmPercentCredit" runat="server" TargetControlID="txtPercentCredit" WatermarkCssClass="WaterMark" WatermarkText="% of credit received from payment" />
<ajaxToolkit:TextBoxWatermarkExtender ID="wmCarryForward" runat="server" TargetControlID="txtCarryForward" WatermarkText="Period in years credits may be carried forward" WatermarkCssClass="WaterMark" />
<ajaxToolkit:TextBoxWatermarkExtender ID="wmEffectivityDate" runat="server" TargetControlID="txtEffectivityDate" WatermarkCssClass="WaterMark" WatermarkText="When does this amendment take affect" />
</ContentTemplate>
</ajax:UpdatePanel>
<asp:Panel runat="server" ID="pnlReasonForEdit" SkinID="reasonforedit">
<br />
<table align="center" border="1" bordercolor="#000000" cellpadding="4" style='width: 50%;
border-collapse: collapse">
<tr>
<td class="label" style='width: 30%'>
<asp:Label ID="Label1" runat="server" SkinID="bold" Text="Reason for Edit"></asp:Label></td>
<td class="alt">
<asp:TextBox ID="txtReasonForEdit2" runat="server" MaxLength="2000" TextMode="MultiLine"
Rows="2"></asp:TextBox>
<asp:RequiredFieldValidator ID="reqReasonForEdit" runat="server" ControlToValidate="txtReasonForEdit2"
Display="Dynamic" ErrorMessage="A reason must be entered" SetFocusOnError="True"></asp:RequiredFieldValidator></td>
</tr>
</table>
</asp:Panel>
<p align="center">
<asp:Button ID="cmdSave" runat="server" OnClick="cmdSave_Click" Text="Save" />
<asp:Button ID="cmdCancel" runat="server" CausesValidation="False" OnClick="cmdCancel_Click"
Text="Cancel" />
</p
<script type="text/javascript">
var styleToSelect;
function onOk() {
//$get('Paragraph1').className = styleToSelect;
}
</script
<asp:Panel ID="Panel1" runat="server" Style='display: none' Width='65%' SkinID='ReasonHeader'>
Please provide a reason for the edit
<asp:Panel ID="pnlBody" runat="server" SkinID="ReasonBody" Style='margin: 5px;'>
<br />
Enter the reason for editing this Amendment:
<asp:TextBox EnableTheming="false" runat="server" ID="txtReasonForEdit" TextMode="multiLine"
Width="96%" Rows="5"></asp:TextBox>
<br />
<br />
<center>
<asp:Button ID="OkButton" runat="server" Text="OK"></asp:Button>
<asp:Button ID="CancelButton" runat="server" Text="Cancel"></asp:Button>
</center>
<br />
</asp:Panel>
</asp:Panel>
</asp:Content>

Here is the Webservice file:

using System;
using System.Data;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Web;
using System.Web.Services;
using System.Web.Services.Protocols;
using AjaxControlToolkit;
using Microsoft.Practices.EnterpriseLibrary.Data;
using Microsoft.Web.Script.Services;

/// <summary>
/// Summary description for ContractService
/// </summary>
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[Microsoft.Web.Script.Services.ScriptService()]
public class ContractService : System.Web.Services.WebService {

public ContractService () {

//Uncomment the following line if using designed components
//InitializeComponent();
}

[WebMethod]
public string GetNextContractSequence(string contract)
{
// ---------------------------
// Author: dzangger
// Company: Huber
// Date: 8/4/2006
// Time: 12:06
// Procedure Name: GetNextContractSequence
// Purpose: Get the next available sequence number for contract
// Parameters:
// - contract (string)() :
// ---------------------------
return contract.ToUpper() + CMSDB.GetNextContractSequence(contract.ToUpper());
}

[WebMethod]
public string DoesContractExist(string contract)
{
bool b = CMSDB.DoesContractExist(contract);

if (b)
return "~" + contract.ToUpper();
else
return contract.ToUpper();
}

[WebMethod]
public string GetIndexValue(string index, string beginDate, string endDate)
{
try
{
DateTime d = Convert.ToDateTime(beginDate);
d = Convert.ToDateTime(endDate);
}
catch (Exception)
{
return "";
}

return CMSDB.GetIndexValueFromDateRange(index, beginDate, endDate);
}

[WebMethod]
public string CalculateExpirationDate(string startDate, string years, string months)
{
// ---------------------------
// Author: dzangger
// Company: Huber
// Date: 8/3/2006
// Time: 13:21
// Procedure Name: CalculateExpirationDate
// Purpose: Adds a number of years and months to a given date
// Parameters:
// - startDate (string)() :
// - years (string)() :
// - months (string)() :
// ---------------------------
try
{
int iYears = 0, iMonths = 0;

try
{
iYears = Convert.ToInt16(years);
}
catch (Exception)
{
iYears = 0;
}

try
{
iMonths = Convert.ToInt16(months);
}
catch (Exception)
{
iMonths = 0;
}

DateTime date = Convert.ToDateTime(startDate);

if (iYears > 0)
date = date.AddYears(iYears);

if (iMonths > 0)
date = date.AddMonths(iMonths);

return date.ToShortDateString();
}
catch (Exception)
{
return "";
}
}

[WebMethod]
[Microsoft.Web.Script.Services.ScriptMethod()]
public AjaxControlToolkit.CascadingDropDownNameValue[] GetIndexTypes(string knownCategoryValues, string category)
{
// ---------------------------
// Author: david.zangger
// Company: Huber
// Date: 10/13/2006
// Time: 07:27
// Procedure Name: GetIndexTypes
// Purpose: Gets the indexes and their types
// Parameters:
// - knownCategoryValues (string)() :
// - category (string)() :
// ---------------------------
List<CascadingDropDownNameValue> values = new List<CascadingDropDownNameValue>();

IDataReader reader = CMSDB.GetIndexesAndIndexTypes();

while (reader.Read())
{
string classId = reader[0].ToString();
string index = reader[1].ToString();
values.Add(new CascadingDropDownNameValue(classId, index));
}

reader.Close();

return values.ToArray();
}

[WebMethod]
[Microsoft.Web.Script.Services.ScriptMethod()]
public AjaxControlToolkit.CascadingDropDownNameValue[] GetIndexSeries(string knownCategoryValues, string category)
{
List<CascadingDropDownNameValue> values = new List<CascadingDropDownNameValue>();

StringDictionary sd = CascadingDropDown.ParseKnownCategoryValuesString(knownCategoryValues);

if (sd.ContainsKey("Index"))
{
IDataReader reader = CMSDB.GetSeriesIds(sd["Index"].ToString());

while (reader.Read())
{
string series = reader[0].ToString();
values.Add(new CascadingDropDownNameValue(series, series));
}

reader.Close();

return values.ToArray();
}
else
return null;
}

[WebMethod]
[Microsoft.Web.Script.Services.ScriptMethod()]
public AjaxControlToolkit.CascadingDropDownNameValue[] GetClasses(string knownCategoryValues, string category)
{
List<CascadingDropDownNameValue> values = new List<CascadingDropDownNameValue>();

IDataReader reader = CMSDB.GetContractClasses();

while (reader.Read())
{
string classId = reader[0].ToString();
values.Add(new CascadingDropDownNameValue(classId, classId));
}

reader.Close();

return values.ToArray();
}

[WebMethod]
[Microsoft.Web.Script.Services.ScriptMethod()]
public AjaxControlToolkit.CascadingDropDownNameValue[] GetTypes(string knownCategoryValues, string category)
{
List<CascadingDropDownNameValue> values = new List<CascadingDropDownNameValue>();

StringDictionary sd = CascadingDropDown.ParseKnownCategoryValuesString(knownCategoryValues);

if (sd.ContainsKey("Class"))
{
IDataReader reader = CMSDB.GetContractTypes(sd["Class"].ToString());

while (reader.Read())
{
string classId = reader[1].ToString();
string desc = reader[0].ToString();
values.Add(new CascadingDropDownNameValue(desc, classId));
}

reader.Close();

return values.ToArray();
}
else
return null;
}
}

I seem to have it working. I created a new website (using the CTP version) and then used the web.config from that project. I migrated my appsettings and an Oracle assembly and then moved my webservice in the folder where the files calling it resides. For now, I'm going to leave it as it is.

Thanks AW for your assistance!

dave

Wednesday, March 21, 2012

A circular reference was detected while serializing an object of type "System.goblaization

Hi all,

I am trying to call a webservice through javascript to return a dataset to bind it to a datagrid on the client side.

I am using a scriptmanager and registered the service by setting the service path.

I am calling a method on a Textbox onKeydown event to call the webservice method. The web service is returning the a data set. But the problem is am geting an exception stating the following

The server method 'GetDataSet' failed with the following error: System.InvalidOperationException-- A Circular reference was detected while serializing an object of type "System.Globalization.CultureInfo"

Please help me out.

See the following code to get an idea about the problem i have

<WebMethod(EnableSession:=True)> _

PublicFunction GetDataSet(ByVal prefixTextAsString)As DataSet

Dim dtAs DataTable

dt =New DataTable

Dim drAs DataRow

dt =Me.GetSelectedTestSchema()

dr =Me.PopulateSelectedTestsRow("1020","dafda", dt)

Try

dt.Rows.Add(dr)

Catch exAs Exception

EndTry

Dim dsAs DataSet =New DataSet()

ds.Tables.Add(dt)

Return ds

EndFunction

Javascript code

function GenerateGrid()

{

var myGrid = igtbl_getGridById("grdSelectedTests");

TestListService.GetDataSet("x",OnWebRequestComplete);

// myGrid.Control.Set_DataDataSource(TestListService.GetDataSet("x").Table[0]);

//

}

function OnWebRequestComplete(results)

{

'I am using the Infragistics ultraWebgrid

var grdControl = igtbl_getGridById("grdSelectedTests");

grdControl.control.set_data(results);

}

Scriptmanager code

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

<Services>

<asp:ServiceReferencePath="../AutoCompleteServices/TestListService.asmx"/>

</Services>

</asp:ScriptManager>

Hi,

According to my understanding to your problem, I don't think it's a AJAX specific issue. The exception is related to your server side code.

Can you debug your server side code to try to solve it?

Or you may post the code for methods:GetSelectedTestSchema() andPopulateSelectedTestsRow here.


We are marking this issue as "Answered". If you have any new findings or concerns, please feel free to unmark the issue.


I too am having the same problems.

I'm using C# to write my webservice, I have almost an identical setup for the client-side scripts.


I get this error even when returning an empty DataSet.


 [WebMethod]public DataSet GetData() {return new DataSet(); }

Does anyone know what this error message is telling me? I tried debugging it, and no exception is thrown from the webservice and it works fine when I send a soap request to it.

Thanks,

Lee


You may try to overcome it by setting response format to XML. For instance:

[System.Web.Script.Services.ScriptMethod(ResponseFormat=System.Web.Script.Services.ResponseFormat.Xml)]
public DataSet GetData()
{