Search Results

Search found 42 results on 2 pages for 'scriptservice'.

Page 1/2 | 1 2  | Next Page >

  • Webservice complex types and class inheritance

    - by pygorex1
    Using the following Webservice definition using aClientArgs as a complex type: [System.Web.Script.Services.ScriptService] public class Controller : System.Web.Services.WebService { [WebMethod] public void save_client(aClientArgs client) { // Save client data } } Then defining aClientArgs as a sub-class: public class aArgs { public string id = null; public string name = null; } public class aClientArgs : aArgs { public string address = null; public string website = null; } Returns the following WSDL fragment for the save_client args: <save_client xmlns="http://tempuri.org/"> <client> <address>string</address> <website>string</website> </client> </save_client> When I'm expecting the following: <save_client xmlns="http://tempuri.org/"> <client> <id>string</id> <name>string</name> <address>string</address> <website>string</website> </client> </save_client> So it appears that the .NET WebService is not treating inherited properties as arguments/variables for purposes of a web service. How do I get .NET to also use the properties of the base class?

    Read the article

  • Usehttpget for script methods in config of asp.net web services

    - by Ajay
    Is there a way to put the usehttpget true/false option for scriptmethods in web.config? I see that even the scriptmethod annotations are placed inline with the code. Is there a way to move this to config as well? Ive seen usehttpget/post option in web.config for webservices but I need the same thing applicable for scriptservices.

    Read the article

  • How to solve Only Web services with a [ScriptService] attribute on the class definition can be called from script

    - by NevenHuynh
    I attempt to use webservice return POCO class generated from entity data model as JSON when using Jquery AJAX call method in webservice. but I have problem with error "Only Web services with a [ScriptService] attribute on the class definition can be called from script", and getting stuck in it, Here is my code : namespace CarCareCenter.Web.Admin.Services { /// <summary> /// Summary description for About /// </summary> [WebService(Namespace = "http://tempuri.org/")] [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)] [System.ComponentModel.ToolboxItem(false)] // To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line. // [System.Web.Script.Services.ScriptService] public class About : System.Web.Services.WebService { [ScriptMethod(ResponseFormat = ResponseFormat.Json)] [WebMethod] public static Entities.Category getAbout() { Entities.Category about = new Entities.Category(); using (var context = new CarCareCenterDataEntities()) { about = (from c in context.Categories where c.Type == "About" select c).SingleOrDefault(); } return about; } } } aspx page : <script type="text/javascript"> $(document).ready(function () { $.ajax({ type: 'POST', dataType: 'json', contentType: 'application/json; charset=utf-8', url: '/Services/About.asmx/getAbout', data: '{}', success: function (response) { var aboutContent = response.d; alert(aboutContent); $('#title-en').val(aboutContent.Name); $('#title-vn').val(aboutContent.NameVn); $('#content-en').val(aboutContent.Description); $('#content-vn').val(aboutContent.DescriptionVn); $('#id').val(aboutContent.CategoryId); }, failure: function (message) { alert(message); }, error: function (result) { alert(result); } }); $('#SaveChange').bind('click', function () { updateAbout(); return false; }); $('#Reset').bind('click', function () { getAbout(); return false; }) }); function updateAbout() { var abt = { "CategoryId": $('#id').val(), "Name": $('#title-en').val(), "NameVn": $('#title-vn').val(), "Description": $('#content-en').val(), "DescriptionVn": $('#content-vn').val() }; $.ajax({ type: "POST", url: "AboutManagement.aspx/updateAbout", data: JSON.stringify(abt), contentType: "application/json; charset=utf-8", dataType: "json", success: function (response) { var aboutContent = response.d; $('#title-en').val(aboutContent.Name); $('#title-vn').val(aboutContent.NameVn); $('#content-en').val(aboutContent.Description); $('#content-vn').val(aboutContent.DescriptionVn); }, failure: function (message) { alert(message); }, error: function (result) { alert(result); } }); } </script> Do any approaches to solve it ? Please help me . Thanks

    Read the article

  • Calling a webservice via Javascript

    - by jeroenb
    If you want to consume a webservice, it's not allways necessary to do a postback. It's even not that hard! 1. Webservice You have to add the scriptservice attribute to the webservice. [System.Web.Script.Services.ScriptService]public class PersonsInCompany : System.Web.Services.WebService { Create a WebMethod [WebMethod] public Person GetPersonByFirstName(string name) { List<Person> personSelect = persons.Where(p => p.FirstName.ToLower().StartsWith(name.ToLower())).ToList(); if (personSelect.Count > 0) return personSelect.First(); else return null; } 2. webpage Add reference to your service to your scriptmanager <script type="text/javascript"> function GetPersonInCompany() { var val = document.getElementById("MainContent_TextBoxPersonName"); PersonsInCompany.GetPersonByFirstName(val.value, FinishCallback); } function FinishCallback(result) { document.getElementById("MainContent_LabelFirstName").innerHTML = result.FirstName; document.getElementById("MainContent_LabelName").innerHTML = result.Name; document.getElementById("MainContent_LabelAge").innerHTML = result.Age; document.getElementById("MainContent_LabelCompany").innerHTML = result.Company; } </script> Add some javascript, where you first call your webservice. Classname.Webmethod = PersonsInCompany.GetPersonByFirstName Add a callback to catch the result from the webservice. And use the result to update your page. <script type="text/javascript"> function GetPersonInCompany() { var val = document.getElementById("MainContent_TextBoxPersonName"); PersonsInCompany.GetPersonByFirstName(val.value, FinishCallback); } function FinishCallback(result) { document.getElementById("MainContent_LabelFirstName").innerHTML = result.FirstName; document.getElementById("MainContent_LabelName").innerHTML = result.Name; document.getElementById("MainContent_LabelAge").innerHTML = result.Age; document.getElementById("MainContent_LabelCompany").innerHTML = result.Company; } </script>   If you have any question, feel free to contact me! You can download the code here.

    Read the article

  • Preventing duplicate Data with ASP.NET AJAX

    - by Yousef_Jadallah
      Some times you need to prevent  User names ,E-mail ID's or other values from being duplicated by a new user during Registration or any other cases,So I will add a simple approach to make the page more user-friendly. Instead the user filled all the Registration fields then press submit after that received a message as a result of PostBack that "THIS USERNAME IS EXIST", Ajax tidies this up by allowing asynchronous querying while the user is still completing the registration form.   ASP.NET enables you to create Web services can be accessed from client script in Web pages by using AJAX technology to make Web service calls. Data is exchanged asynchronously between client and server, typically in JSON format. I’ve added an article to show you step by step  how to use ASP.NET AJAX with Web Services , you can find it here .   Lets go a head with the steps :   1-Create a new project , if you are using VS 2005 you have to create ASP.NET Ajax Enabled Web site.   2-Create your own Database which contain user table that have User_Name field. for Testing I’ve added SQL Server Database that come with Dot Net 2008: Then I’ve created tblUsers:   This table and this structure just for our example, you can use your own table to implement this approach.   3-Add new Item to your project or website, Choose Web Service file, lets say  WebService.cs  .In this Web Service file import System.Data.SqlClient Namespace, Then Add your web method that contain string parameter which received the Username parameter from the Script , Finally don’t forget to qualified the Web Service Class with the ScriptServiceAttribute attribute ([System.Web.Script.Services.ScriptService])     using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Services; using System.Data.SqlClient;     [WebService(Namespace = "http://tempuri.org/")] [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)] [System.Web.Script.Services.ScriptService] public class WebService : System.Web.Services.WebService {     [WebMethod] public int CheckDuplicate(string User_Name) { string strConn = @"Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\TestDB.mdf;Integrated Security=True;User Instance=True"; string strQuery = "SELECT COUNT(*) FROM tblUsers WHERE User_Name = @User_Name"; SqlConnection con = new SqlConnection(strConn); SqlCommand cmd = new SqlCommand(strQuery, con); cmd.Parameters.Add("User_Name", User_Name); con.Open(); int RetVal= (int)cmd.ExecuteScalar(); con.Close(); return RetVal; } } .csharpcode, .csharpcode pre { font-size: small; color: black; font-family: consolas, "Courier New", courier, monospace; background-color: #ffffff; /*white-space: pre;*/ } .csharpcode pre { margin: 0em; } .csharpcode .rem { color: #008000; } .csharpcode .kwrd { color: #0000ff; } .csharpcode .str { color: #006080; } .csharpcode .op { color: #0000c0; } .csharpcode .preproc { color: #cc6633; } .csharpcode .asp { background-color: #ffff00; } .csharpcode .html { color: #800000; } .csharpcode .attr { color: #ff0000; } .csharpcode .alt { background-color: #f4f4f4; width: 100%; margin: 0em; } .csharpcode .lnum { color: #606060; }   Our Web Method here is CheckDuplicate Which accept User_Name String as a parameter and return number of the rows , if the name will found in the database this method will return 1 else it will return 0. I’ve applied  [WebMethod] Attribute to our method CheckDuplicate, And applied the ScriptService attribute to a Web Service class named WebService.   4-Add this simple Registration form : <fieldset> <table id="TblRegistratoin" cellpadding="0" cellspacing="0"> <tr> <td> User Name </td> <td> <asp:TextBox ID="txtUserName" onblur="CallWebMethod();" runat="server"></asp:TextBox> </td> <td> <asp:Label ID="lblDuplicate" runat="server" ForeColor="Red" Text=""></asp:Label> </td> </tr> <tr> <td colspan="3"> <asp:Button ID="btnRegistration" runat="server" Text="Registration" /> </td> </tr> </table> </fieldset> .csharpcode, .csharpcode pre { font-size: small; color: black; font-family: consolas, "Courier New", courier, monospace; background-color: #ffffff; /*white-space: pre;*/ } .csharpcode pre { margin: 0em; } .csharpcode .rem { color: #008000; } .csharpcode .kwrd { color: #0000ff; } .csharpcode .str { color: #006080; } .csharpcode .op { color: #0000c0; } .csharpcode .preproc { color: #cc6633; } .csharpcode .asp { background-color: #ffff00; } .csharpcode .html { color: #800000; } .csharpcode .attr { color: #ff0000; } .csharpcode .alt { background-color: #f4f4f4; width: 100%; margin: 0em; } .csharpcode .lnum { color: #606060; }   onblur event is added to the Textbox txtUserName, This event Fires when the Textbox loses the input focus, That mean after the user get focus out from the Textbox CallWebMethod function will be fired. CallWebMethod will be implemented in step 6.   5-Add ScriptManager Control to your aspx file then reference the Web service by adding an asp:ServiceReference child element to the ScriptManager control and setting its path attribute to point to the Web service, That generate a JavaScript proxy class for calling the specified Web service from client script.   <asp:ScriptManager runat="server" ID="scriptManager"> <Services> <asp:ServiceReference Path="WebService.asmx" /> </Services> </asp:ScriptManager> .csharpcode, .csharpcode pre { font-size: small; color: black; font-family: consolas, "Courier New", courier, monospace; background-color: #ffffff; /*white-space: pre;*/ } .csharpcode pre { margin: 0em; } .csharpcode .rem { color: #008000; } .csharpcode .kwrd { color: #0000ff; } .csharpcode .str { color: #006080; } .csharpcode .op { color: #0000c0; } .csharpcode .preproc { color: #cc6633; } .csharpcode .asp { background-color: #ffff00; } .csharpcode .html { color: #800000; } .csharpcode .attr { color: #ff0000; } .csharpcode .alt { background-color: #f4f4f4; width: 100%; margin: 0em; } .csharpcode .lnum { color: #606060; }     6-Define the JavaScript code to call the Web Service :   <script language="javascript" type="text/javascript">   // This function calls the Web service method // passing simple type parameters and the // callback function function CallWebMethod() { var User_Name = document.getElementById('<%=txtUserName.ClientID %>').value; WebService.CheckDuplicate(User_Name, OnSucceeded, OnError); }   // This is the callback function invoked if the Web service // succeeded function OnSucceeded(result) { var rsltElement = document.getElementById("lblDuplicate"); if (result == 1) rsltElement.innerHTML = "This User Name is exist"; else rsltElement.innerHTML = "";   }   function OnError(error) { // Display the error. alert("Service Error: " + error.get_message()); } </script> .csharpcode, .csharpcode pre { font-size: small; color: black; font-family: consolas, "Courier New", courier, monospace; background-color: #ffffff; /*white-space: pre;*/ } .csharpcode pre { margin: 0em; } .csharpcode .rem { color: #008000; } .csharpcode .kwrd { color: #0000ff; } .csharpcode .str { color: #006080; } .csharpcode .op { color: #0000c0; } .csharpcode .preproc { color: #cc6633; } .csharpcode .asp { background-color: #ffff00; } .csharpcode .html { color: #800000; } .csharpcode .attr { color: #ff0000; } .csharpcode .alt { background-color: #f4f4f4; width: 100%; margin: 0em; } .csharpcode .lnum { color: #606060; }   This call references the WebService Class and CheckDuplicate Web Method defined in the service. It passes a User_Name value obtained from a textbox as well as a callback function named OnSucceeded that should be invoked when the asynchronous Web Service call returns. If the Web Service in different Namespace you can refer it before the class name this Main formula may help you :  NameSpaceName.ClassName.WebMethdName(Parameters , Success callback function, Error callback function); Parameters: you can pass one or many parameters. Success callback function :handles returned data from the service . Error callback function :Any errors that occur when the Web Service is called will trigger in this function. Using Error Callback function is optional.   Hope these steps help you to understand this approach.

    Read the article

  • Preventing duplicate Data with ASP.NET AJAX

    - by Yousef_Jadallah
      Some times you need to prevent  User names ,E-mail ID's or other values from being duplicated by a new user during Registration or any other cases,So I will add a simple approach to make the page more user-friendly. Instead the user filled all the Registration fields then press submit after that received a message as a result of PostBack that "THIS USERNAME IS EXIST", Ajax tidies this up by allowing asynchronous querying while the user is still completing the registration form.   ASP.NET enables you to create Web services can be accessed from client script in Web pages by using AJAX technology to make Web service calls. Data is exchanged asynchronously between client and server, typically in JSON format. I’ve added an article to show you step by step  how to use ASP.NET AJAX with Web Services , you can find it here .   Lets go a head with the steps :   1-Create a new project , if you are using VS 2005 you have to create ASP.NET Ajax Enabled Web site.   2-Create your own Database which contain user table that have User_Name field. for Testing I’ve added SQL Server Database that come with Dot Net 2008: Then I’ve created tblUsers:   This table and this structure just for our example, you can use your own table to implement this approach.   3-Add new Item to your project or website, Choose Web Service file, lets say  WebService.cs  .In this Web Service file import System.Data.SqlClient Namespace, Then Add your web method that contain string parameter which received the Username parameter from the Script , Finally don’t forget to qualified the Web Service Class with the ScriptServiceAttribute attribute ([System.Web.Script.Services.ScriptService])     using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Services; using System.Data.SqlClient;     [WebService(Namespace = "http://tempuri.org/")] [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)] [System.Web.Script.Services.ScriptService] public class WebService : System.Web.Services.WebService {     [WebMethod] public int CheckDuplicate(string User_Name) { string strConn = @"Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\TestDB.mdf;Integrated Security=True;User Instance=True"; string strQuery = "SELECT COUNT(*) FROM tblUsers WHERE User_Name = @User_Name"; SqlConnection con = new SqlConnection(strConn); SqlCommand cmd = new SqlCommand(strQuery, con); cmd.Parameters.Add("User_Name", User_Name); con.Open(); int RetVal= (int)cmd.ExecuteScalar(); con.Close(); return RetVal; } } .csharpcode, .csharpcode pre { font-size: small; color: black; font-family: consolas, "Courier New", courier, monospace; background-color: #ffffff; /*white-space: pre;*/ } .csharpcode pre { margin: 0em; } .csharpcode .rem { color: #008000; } .csharpcode .kwrd { color: #0000ff; } .csharpcode .str { color: #006080; } .csharpcode .op { color: #0000c0; } .csharpcode .preproc { color: #cc6633; } .csharpcode .asp { background-color: #ffff00; } .csharpcode .html { color: #800000; } .csharpcode .attr { color: #ff0000; } .csharpcode .alt { background-color: #f4f4f4; width: 100%; margin: 0em; } .csharpcode .lnum { color: #606060; }   Our Web Method here is CheckDuplicate Which accept User_Name String as a parameter and return number of the rows , if the name will found in the database this method will return 1 else it will return 0. I’ve applied  [WebMethod] Attribute to our method CheckDuplicate, And applied the ScriptService attribute to a Web Service class named WebService.   4-Add this simple Registration form : <fieldset> <table id="TblRegistratoin" cellpadding="0" cellspacing="0"> <tr> <td> User Name </td> <td> <asp:TextBox ID="txtUserName" onblur="CallWebMethod();" runat="server"></asp:TextBox> </td> <td> <asp:Label ID="lblDuplicate" runat="server" ForeColor="Red" Text=""></asp:Label> </td> </tr> <tr> <td colspan="3"> <asp:Button ID="btnRegistration" runat="server" Text="Registration" /> </td> </tr> </table> </fieldset> .csharpcode, .csharpcode pre { font-size: small; color: black; font-family: consolas, "Courier New", courier, monospace; background-color: #ffffff; /*white-space: pre;*/ } .csharpcode pre { margin: 0em; } .csharpcode .rem { color: #008000; } .csharpcode .kwrd { color: #0000ff; } .csharpcode .str { color: #006080; } .csharpcode .op { color: #0000c0; } .csharpcode .preproc { color: #cc6633; } .csharpcode .asp { background-color: #ffff00; } .csharpcode .html { color: #800000; } .csharpcode .attr { color: #ff0000; } .csharpcode .alt { background-color: #f4f4f4; width: 100%; margin: 0em; } .csharpcode .lnum { color: #606060; }   onblur event is added to the Textbox txtUserName, This event Fires when the Textbox loses the input focus, That mean after the user get focus out from the Textbox CallWebMethod function will be fired. CallWebMethod will be implemented in step 6.   5-Add ScriptManager Control to your aspx file then reference the Web service by adding an asp:ServiceReference child element to the ScriptManager control and setting its path attribute to point to the Web service, That generate a JavaScript proxy class for calling the specified Web service from client script.   <asp:ScriptManager runat="server" ID="scriptManager"> <Services> <asp:ServiceReference Path="WebService.asmx" /> </Services> </asp:ScriptManager> .csharpcode, .csharpcode pre { font-size: small; color: black; font-family: consolas, "Courier New", courier, monospace; background-color: #ffffff; /*white-space: pre;*/ } .csharpcode pre { margin: 0em; } .csharpcode .rem { color: #008000; } .csharpcode .kwrd { color: #0000ff; } .csharpcode .str { color: #006080; } .csharpcode .op { color: #0000c0; } .csharpcode .preproc { color: #cc6633; } .csharpcode .asp { background-color: #ffff00; } .csharpcode .html { color: #800000; } .csharpcode .attr { color: #ff0000; } .csharpcode .alt { background-color: #f4f4f4; width: 100%; margin: 0em; } .csharpcode .lnum { color: #606060; }     6-Define the JavaScript code to call the Web Service :   <script language="javascript" type="text/javascript">   // This function calls the Web service method // passing simple type parameters and the // callback function function CallWebMethod() { var User_Name = document.getElementById('<%=txtUserName.ClientID %>').value; WebService.CheckDuplicate(User_Name, OnSucceeded, OnError); }   // This is the callback function invoked if the Web service // succeeded function OnSucceeded(result) { var rsltElement = document.getElementById("lblDuplicate"); if (result == 1) rsltElement.innerHTML = "This User Name is exist"; else rsltElement.innerHTML = "";   }   function OnError(error) { // Display the error. alert("Service Error: " + error.get_message()); } </script> .csharpcode, .csharpcode pre { font-size: small; color: black; font-family: consolas, "Courier New", courier, monospace; background-color: #ffffff; /*white-space: pre;*/ } .csharpcode pre { margin: 0em; } .csharpcode .rem { color: #008000; } .csharpcode .kwrd { color: #0000ff; } .csharpcode .str { color: #006080; } .csharpcode .op { color: #0000c0; } .csharpcode .preproc { color: #cc6633; } .csharpcode .asp { background-color: #ffff00; } .csharpcode .html { color: #800000; } .csharpcode .attr { color: #ff0000; } .csharpcode .alt { background-color: #f4f4f4; width: 100%; margin: 0em; } .csharpcode .lnum { color: #606060; }   This call references the WebService Class and CheckDuplicate Web Method defined in the service. It passes a User_Name value obtained from a textbox as well as a callback function named OnSucceeded that should be invoked when the asynchronous Web Service call returns. If the Web Service in different Namespace you can refer it before the class name this Main formula may help you :  NameSpaceName.ClassName.WebMethdName(Parameters , Success callback function, Error callback function); Parameters: you can pass one or many parameters. Success callback function :handles returned data from the service . Error callback function :Any errors that occur when the Web Service is called will trigger in this function. Using Error Callback function is optional.   Hope these steps help you to understand this approach.

    Read the article

  • Ajax Autocompleteextender not showing the autocompletelist to choose

    - by subash
    i was working ajax auto completeextender witha text box in asp.net and c#.net. i am not able to get list to choose ,i have the appropriate web service method called..can anyone guide me to get the automo complete done. <form id="form1" runat="server"> <asp:ToolkitScriptManager ID="ToolkitScriptManager1" runat="server"> </asp:ToolkitScriptManager> <div> <asp:AutoCompleteExtender runat="server" ID="autoComplete1" TargetControlID="TextBox1" ServiceMethod="GetCompletionList" ServicePath="AutoComplete.asmx" MinimumPrefixLength="0" CompletionInterval="50" EnableCaching="true" CompletionSetCount="1" DelimiterCharacters=";, :" ShowOnlyCurrentWordInCompletionListItem="true"> </asp:AutoCompleteExtender> <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox> </div> </form> and the web service method contains the following code [WebService(Namespace = "http://tempuri.org/")] [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)] [System.ComponentModel.ToolboxItem(false)] [ScriptService] // To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line. // [System.Web.Script.Services.ScriptService] public class AutoComplete : System.Web.Services.WebService { [WebMethod] public string HelloWorld() { return "Hello World"; } [WebMethod] public string[] GetCompletionList(string prefixText, int count) { List<string> responses = new List<string>(); for (int i = 0; i < count; i++) responses.Add(prefixText + (char)(i + 65)); return responses.ToArray(); } }

    Read the article

  • How to change the default "double click" action of a web service in a class library (VS2010)?

    - by JL
    I have a web service defined as follows, residing in a class library: [WebService(Namespace = "http://comp.com/")] [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)] // To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line. // [System.Web.Script.Services.ScriptService] public class SendingItems_new : System.Web.Services.WebService When I double click it, instead of going to code view, it shows the design view. I NEVER use design view, so how can I get it to open up code view instead, its very annoying having to flick from design view each time. Thank you

    Read the article

  • Converting a generic list into JSON string and then handling it in java script

    - by Jalpesh P. Vadgama
    We all know that JSON (JavaScript Object Notification) is very useful in case of manipulating string on client side with java script and its performance is very good over browsers so let’s create a simple example where convert a Generic List then we will convert this list into JSON string and then we will call this web service from java script and will handle in java script. To do this we need a info class(Type) and for that class we are going to create generic list. Here is code for that I have created simple class with two properties UserId and UserName public class UserInfo { public int UserId { get; set; } public string UserName { get; set; } } Now Let’s create a web service and web method will create a class and then we will convert this with in JSON string with JavaScriptSerializer class. Here is web service class. using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Services; namespace Experiment.WebService { /// <summary> /// Summary description for WsApplicationUser /// </summary> [WebService(Namespace = "http://tempuri.org/")] [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)] [System.ComponentModel.ToolboxItem(false)] // To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line. [System.Web.Script.Services.ScriptService] public class WsApplicationUser : System.Web.Services.WebService { [WebMethod] public string GetUserList() { List<UserInfo> userList = new List<UserInfo>(); for (int i = 1; i <= 5; i++) { UserInfo userInfo = new UserInfo(); userInfo.UserId = i; userInfo.UserName = string.Format("{0}{1}", "J", i.ToString()); userList.Add(userInfo); } System.Web.Script.Serialization.JavaScriptSerializer jSearializer = new System.Web.Script.Serialization.JavaScriptSerializer(); return jSearializer.Serialize(userList); } } } Note: Here you must have this attribute here in web service class ‘[System.Web.Script.Services.ScriptService]’ as this attribute will enable web service to call from client side. Now we have created a web service class let’s create a java script function ‘GetUserList’ which will call web service from JavaScript like following function GetUserList() { Experiment.WebService.WsApplicationUser.GetUserList(ReuqestCompleteCallback, RequestFailedCallback); } After as you can see we have inserted two call back function ReuqestCompleteCallback and RequestFailedCallback which handle errors and result from web service. ReuqestCompleteCallback will handle result of web service and if and error comes then RequestFailedCallback will print the error. Following is code for both function. function ReuqestCompleteCallback(result) { result = eval(result); var divResult = document.getElementById("divUserList"); CreateUserListTable(result); } function RequestFailedCallback(error) { var stackTrace = error.get_stackTrace(); var message = error.get_message(); var statusCode = error.get_statusCode(); var exceptionType = error.get_exceptionType(); var timedout = error.get_timedOut(); // Display the error. var divResult = document.getElementById("divUserList"); divResult.innerHTML = "Stack Trace: " + stackTrace + "<br/>" + "Service Error: " + message + "<br/>" + "Status Code: " + statusCode + "<br/>" + "Exception Type: " + exceptionType + "<br/>" + "Timedout: " + timedout; } Here in above there is a function called you can see that we have use ‘eval’ function which parse string in enumerable form. Then we are calling a function call ‘CreateUserListTable’ which will create a table string and paste string in the a div. Here is code for that function. function CreateUserListTable(userList) { var tablestring = '<table ><tr><td>UsreID</td><td>UserName</td></tr>'; for (var i = 0, len = userList.length; i < len; ++i) { tablestring=tablestring + "<tr>"; tablestring=tablestring + "<td>" + userList[i].UserId + "</td>"; tablestring=tablestring + "<td>" + userList[i].UserName + "</td>"; tablestring=tablestring + "</tr>"; } tablestring = tablestring + "</table>"; var divResult = document.getElementById("divUserList"); divResult.innerHTML = tablestring; } Now let’s create div which will have all html that is generated from this function. Here is code of my web page. We also need to add a script reference to enable web service from client side. Here is all HTML code we have. <form id="form1" runat="server"> <asp:ScriptManager ID="myScirptManger" runat="Server"> <Services> <asp:ServiceReference Path="~/WebService/WsApplicationUser.asmx" /> </Services> </asp:ScriptManager> <div id="divUserList"> </div> </form> Now as we have not defined where we are going to call ‘GetUserList’ function so let’s call this function on windows onload event of javascript like following. window.onload=GetUserList(); That’s it. Now let’s run it on browser to see whether it’s work or not and here is the output in browser as expected. That’s it. This was very basic example but you can crate your own JavaScript enabled grid from this and you can see possibilities are unlimited here. Stay tuned for more.. Happy programming.. Technorati Tags: JSON,Javascript,ASP.NET,WebService

    Read the article

  • Queued Loadtest to remove Concurrency issues using Shared Data Service in OpenScript

    - by stefan.thieme(at)oracle.com
    Queued Processing to remove Concurrency issues in Loadtest ScriptsSome scripts act on information returned by the server, e.g. act on first item in the returned list of pending tasks/actions. This may lead to concurrency issues if the virtual users simulated in a load test scenario are not synchronized in some way.As the load test cases should be carried out in a comparable and straight forward manner simply cancel a transaction in case a collision occurs is clearly not an option. In case you increase the number of virtual users this approach would lead to a high number of requests for the early steps in your transaction (e.g. login, retrieve list of action points, assign an action point to the virtual user) but later steps would be rarely visited successfully or at all, depending on the application logic.A way to tackle this problem is to enqueue the virtual users in a Shared Data Service queue. Only the first virtual user in this queue will be allowed to carry out the critical steps (retrieve list of action points, assign an action point to the virtual user) in your transaction at any one time.Once a virtual user has passed the critical path it will dequeue himself from the head of the queue and continue with his actions. This does theoretically allow virtual users to run in parallel all steps of the transaction which are not part of the critical path.In practice it has been seen this is rarely the case, though it does not allow adding more than N users to perform a transaction without causing delays due to virtual users waiting in the queue. N being the time of the total transaction divided by the sum of the time of all critical steps in this transaction.While this problem can be circumvented by allowing multiple queues to act on individual segments of the list of actions, e.g. per country filter, ends with 0..9 filter, etc.This would require additional handling of these additional queues of slots for the virtual users at the head of the queue in order to maintain the mutually exclusive access to the first element in the list returned by the server at any one time of the load test. Such an improved handling of multiple queues and/or multiple slots is above the subject of this paper.Shared Data Services Pre-RequisitesStart WebLogic Server to host Shared Data ServicesYou will have to make sure that your WebLogic server is installed and started. Shared Data Services may not work if you installed only the minimal installation package for OpenScript. If however you installed the default package including OLT and OTM, you may follow the instructions below to start and verify WebLogic installation.To start the WebLogic Server deployed underneath of Oracle Load Testing and/or Oracle Test Manager you can go to your Start menu, Oracle Application Testing Suite and select the Restart Oracle Application Testing Suite Application Service entry from the Tools submenu.To verify the service has been started you can run the Microsoft Management Console for Services by Selecting Run from the Start Menu and entering services.msc. Look for the entry that reads Oracle Application Testing Suite Application Service, once it has changed it status from Starting to Started you can proceed to verify the login. Please note that this may take several minutes, I would say up to 10 minutes depending on the strength of your CPU horse-power.Verify WebLogic Server user credentialsYou will have to make sure that your WebLogic Server is installed and started. Next open the Oracle WebLogic Server Adminstration Console on http://localhost:8088/console.It may take a while until the application is deployed and started. It may display the following until the Administration Console has been deployed on the fly.Afterwards you can login using the username oats and the password that you selected during install time for your Application Testing Suite administrative purposes.This will bring up the Home page of you WebLogic Server. You have actually verified that you are able to login with these credentials already. However if you want to check the details, navigate to Security Realms, myrealm, Users and Groups tab.Here you could add users to your WebLogic Server which could be used in the later steps. Details on the Groups required for such a custom user to work are exceeding this quick overview and have to be selected with the WebLogic Server Adminstration Guide in mind.Shared Data Services pre-requisites for Load testingOpenScript Preferences have to be set to enable Encryption and provide a default Shared Data Service Connection for Playback.These are pre-requisites you want to use for load testing with Shared Data Services.Please note that the usage of the Connection Parameters (individual directive in the script) for Shared Data Services did not playback reliably in the current version 9.20.0370 of Oracle Load Testing (OLT) and encryption of credentials still seemed to be mandatory as well.General Encryption settingsSelect OpenScript Preferences from the View menu and navigate to the General, Encryption entry in the tree on the left. Select the Encrypt script data option from the list and enter the same password that you used for securing your WebLogic Server Administration Console.Enable global shared data access credentialsSelect OpenScript Preferences from the View menu and navigate to the Playback, Shared Data entry in the tree on the left. Enable the global shared data access credentials and enter the Address, User name and Password determined for your WebLogic Server to host Shared Data Services.Please note, that you may want to replace the localhost in Address with the hosts realname in case you plan to run load tests with Loadtest Agents running on remote systems.Queued Processing of TransactionsEnable Shared Data Services Module in Script PropertiesThe Shared Data Services Module has to be enabled for each Script that wants to employ the Shared Data Service Queue functionality in OpenScript. It can be enabled under the Script menu selecting Script Properties. On the Script Properties Dialog select the Modules section and check Shared Data to enable Shared Data Service Module for your script. Checking the Shared Data Services option will effectively add a line to your script code that adds the sharedData ScriptService to your script class of IteratingVUserScript.@ScriptService oracle.oats.scripting.modules.sharedData.api.SharedDataService sharedData;Record your scriptRecord your script as usual and then add the following things for Queue handling in the Initialize code block, before the first step and after the last step of your critical path and in the Finalize code block.The java code to be added at individual locations is explained in the following sections in full detail.Create a Shared Data Queue in InitializeTo create a Shared Data Queue go to the Java view of your script and enter the following statements to the initialize() code block.info("Create queueA with life time of 120 minutes");sharedData.createQueue("queueA", 120);This will create an instantiation of the Shared Data Queue object named queueA which is maintained for upto 120 minutes.If you want to use the code for multiple scripts, make sure to use a different queue name for each one here and in the subsequent steps. You may even consider to use a dynamic queueName based on filters of your result list being concurrently accessed.Prepare a unique id for each IterationIn order to keep track of individual virtual users in our queue we need to create a unique identifier from the virtual user id and the used username right after retrieving the next record from our databank file.getDatabank("Usernames").getNextDatabankRecord();getVariables().set("usernameValue1","VU_{{@vuid}}_{{@iterationnum}}_{{db.Usernames.Username}}_{{@timestamp}}_{{@random(10000)}}");String usernameValue = getVariables().get("usernameValue1");info("Now running virtual user " + usernameValue);As you can see from the above code block, we have set the OpenScript variable usernameValue1 to VU_{{@vuid}}_{{@iterationnum}}_{{db.Usernames.Username}}_{{@timestamp}}_{{@random(10000)}} which is a concatenation of the virtual user id and the iterationnumber for general uniqueness; as well as the username from our databank, the timestamp and a random number for making it further unique and ease spotting of errors.Not all of these fields are actually required to make it really unique, but adding the queue name may also be considered to help troubleshoot multiple queues.The value is then retrieved with the getVariables.get() method call and assigned to the usernameValue String used throughout the script.Please note that moving the getDatabank("Usernames").getNextDatabankRecord(); call to the initialize block was later considered to remove concurrency of multiple virtual users running with the same userid and therefor accessing the same "My Inbox" in step 6. This will effectively give each virtual user a userid from the databank file. Make sure you have enough userids to remove this second hurdle.Enqueue and attend Queue before Critical PathTo maintain the right order of virtual users being allowed into the critical path of the transaction the following pseudo step has to be added in front of the first critical step. In the case of this example this is right in front of the step where we retrieve the list of actions from which we select the first to be assigned to us.beginStep("[0] Waiting in the Queue", 0);{info("Enqueued virtual user " + usernameValue + " at the end of queueA");sharedData.offerLast("queueA", usernameValue);info("Wait until the user is the first in queueA");String queueValue1 = null;do {// we wait for at least 0.7 seconds before we check the head of the// queue. This is the time it takes one user to move through the// critical path, i.e. pass steps [5] Enter country and [6] Assign// to meThread.sleep(700);queueValue1 = (String) sharedData.peekFirst("queueA");info("The first user in queueA is currently: '" + queueValue1 + "' " + queueValue1.getClass() + " length " + queueValue1.length() );info("The current user is '"+ usernameValue + "' " + usernameValue.getClass() + " length " + usernameValue.length() + ": indexOf " + usernameValue.indexOf(queueValue1) + " equals " + usernameValue.equals(queueValue1) );} while ( queueValue1.indexOf(usernameValue) < 0 );info("Now the user is the first in queueA");}endStep();This will enqueue the username to the tail of our Queue. It will will wait for at least 700 milliseconds, the time it takes for one user to exit the critical path and then compare the head of our queue with it's username. This last step will be repeated while the two are not equal (indexOf less than zero). If they are equal the indexOf will yield a value of zero or larger and we will perform the critical steps.Dequeue after Critical PathAfter the virtual user has left the critical path and complete its last step the following code block needs to dequeue the virtual user. In the case of our example this is right after the action has been actually assigned to the virtual user. This will allow the next virtual user to retrieve the list of actions still available and in turn let him make his selection/assignment.info("Get and remove the current user from the head of queueA");String pollValue1 = (String) sharedData.pollFirst("queueA");The current user is removed from the head of the queue. The next one will now be able to match his username against the head of the queue.Clear and Destroy Queue for FinishWhen the script has completed, it should clear and destroy the queue. This code block can be put in the finish block of your script and/or in a separate script in order to clear and remove the queue in case you have spotted an error or want to reset the queue for some reason.info("Clear queueA");sharedData.clearQueue("queueA");info("Destroy queueA");sharedData.destroyQueue("queueA");The users waiting in queueA are cleared and the queue is destroyed. If you have scripts still executing they will be caught in a loop.I found it better to maintain a separate Reset Queue script which contained only the following code in the initialize() block. I use to call this script to make sure the queue is cleared in between multiple Loadtest runs. This script could also even be added as the first in a larger scenario, which would execute it only once at very start of the Loadtest and make sure the queues do not contain any stale entries.info("Create queueA with life time of 120 minutes");sharedData.createQueue("queueA", 120);info("Clear queueA");sharedData.clearQueue("queueA");This will create a Shared Data Queue instance of queueA and clear all entries from this queue.Monitoring QueueWhile creating the scripts it was useful to monitor the contents, i.e. the current first user in the Queue. The following code block will make sure the Shared Data Queue is accessible in the initialize() block.info("Create queueA with life time of 120 minutes");sharedData.createQueue("queueA", 120);In the run() block the following code will continuously monitor the first element of the Queue and write an informational message with the current username Value to the Result window.info("Monitor the first users in queueA");String queueValue1 = null;do {queueValue1 = (String) sharedData.peekFirst("queueA");if (queueValue1 != null)info("The first user in queueA is currently: '" + queueValue1 + "' " + queueValue1.getClass() + " length " + queueValue1.length() );} while ( true );This script can be run from OpenScript parallel to a loadtest performed by the Oracle Load Test.However it is not recommend to run this in a production loadtest as the performance impact is unknown. Accessing the Queue's head with the peekFirst() method has been reported with about 2 seconds response time by both OpenScript and OTL. It is advised to log a Service Request to see if this could be lowered in future releases of Application Testing Suite, as the pollFirst() and even offerLast() writing to the tail of the Queue usually returned after an average 0.1 seconds.Debugging QueueWhile debugging the scripts the following was useful to remove single entries from its head, i.e. the current first user in the Queue. The following code block will make sure the Shared Data Queue is accessible in the initialize() block.info("Create queueA with life time of 120 minutes");sharedData.createQueue("queueA", 120);In the run() block the following code will remove the first element of the Queue and write an informational message with the current username Value to the Result window.info("Get and remove the current user from the head of queueA");String pollValue1 = (String) sharedData.pollFirst("queueA");info("The first user in queueA was currently: '" + pollValue1 + "' " + pollValue1.getClass() + " length " + pollValue1.length() );ReferencesOracle Functional Testing OpenScript User's Guide Version 9.20 [E15488-05]Chapter 17 Using the Shared Data Modulehttp://download.oracle.com/otn/nt/apptesting/oats-docs-9.21.0030.zipOracle Fusion Middleware Oracle WebLogic Server Administration Console Online Help 11g Release 1 (10.3.4) [E13952-04]Administration Console Online Help - Manage users and groupshttp://download.oracle.com/docs/cd/E17904_01/apirefs.1111/e13952/taskhelp/security/ManageUsersAndGroups.htm

    Read the article

  • Cannot find System.Web.Script.Service namespace error after upgrading to Visual studio 2010

    - by Gavin
    I've just upgraded a VS 2008 project to VS 2010, converting the project but keeping the target as .NET 3.5 (SP1 is installed). My project worked without issue under VS 2008 on another machine. I've added references to System.Web.Extensions.dll but I'm still getting the following errors from code in the App_Code folder: 1) Cannot find System.Web.Script.Service namespace 2) Type 'System.Web.Script.Services.ScriptService' is not defined. 3) Type 'System.Runtime.Serialization.Json.DataContractJsonSerializer' is not defined. Anyone have any ideas what the problem might be as I'm pretty stumped? :(

    Read the article

  • Error calling webservice from JQuery

    - by Robban
    I have a strange problem when I'm trying to call a simple webservice method from Jquery. Locally it works fine, but on my test-server it does not. The jquery request looks like this (only showing the actual request and not the rest of the method): $.ajax({ type: "POST", url: "/Service/Service.asmx/AddTab", data: "tab=" + element.innerHTML, success: function(msg) { alert('success'); } }); When I run this locally from the test-server it works fine, which has me wondering if it could be some setting that I've missed in the IIS. If I navigate to the .asmx file and click the AddTab method I get a list of SOAP 1.1 and SOAP 1.2 XML, but not the HTTP POST request. If I navigate to it locally I get all three (SOAP 1.1, SOAP 1.2 and HTTP Post) The service is set up as follows: [WebService(Namespace = "mynamespace")] [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)] [System.ComponentModel.ToolboxItem(false)] [ScriptService()] public class Service : System.Web.Services.WebService { [WebMethod(EnableSession=true)] [ScriptMethod()] public void AddTab(string tab) { //Some code to add a tab which evidently works locally... } } Anyone have a clue what I'm missing here?

    Read the article

  • webservice - unknown web method parameter name methodname

    - by ch3r1f
    I called a webservice for fetching items in fullcalendar. The method is never called and firebug gives this error: *"POST [http]://localhost:50536/FullCalendar/ServicioFullCalendar.asmx/GetEventosCalendario POST [http]://localhost:50536/FullCalendar/ServicioFullCalendar.asmx/GetEventosCalendario 500 Internal Server Error 1.01s" "unknown web method parameter name methodname"* Here is the asmx.vb code: <System.Web.Script.Services.ScriptService()> _ <System.Web.Services.WebService(Namespace:="http://localhost/uva/")> _ <System.Web.Services.WebServiceBinding(ConformsTo:=WsiProfiles.BasicProfile1_1)> _ <ToolboxItem(False)> _ Public Class ServicioFullCalendar Inherits System.Web.Services.WebService <ScriptMethod(ResponseFormat:=ResponseFormat.Json)> _ <WebMethod(MessageName:="ObtieneEventos")> _ Public Shared Function GetEventosCalendario(ByVal startDate As String, ByVal endDate As String) As String Try Return CalendarioMensualDAO.Instance.getEventos(startDate, endDate) Catch ex As Exception Throw New Exception("FullCalendar:GetEventos: " & ex.Message) Finally End Try End Function The webservice is "loaded" from the fullcalendar as follows: events: "ServicioFullCalendar.asmx/GetEventosCalendario",

    Read the article

  • jsonp cross domain only working in IE

    - by iboeno
    EDIT: At first I thought it wasn't working cross domain at all, now I realize it only works in IE I'm using jQuery to call a web service (ASP.NET .axmx), and trying to us jsonp so that I can call it across different sites. Right now it is working ONLY in IE, but not in Firefox, Chrome, Safari. Also, in IE, a dialog pops up warning "This page is accessing information that is not under its control..." Any ideas? Here is the code: $.ajax({ type: "POST", url: "http://test/TestService.asmx/HelloWorld?jsonp=?", dataType: "jsonp", success: function(data) { alert(data.prop1); }, error: function(XMLHttpRequest, textStatus, errorThrown) { alert(XMLHttpRequest.status + " " + textStatus + " " + errorThrown); } }); And the server code is: [ScriptService] public class TestService : System.Web.Services.WebService{ [WebMethod] [ScriptMethod(ResponseFormat = ResponseFormat.Json)] public void HelloWorld() { string jsoncallback = HttpContext.Current.Request["jsonp"]; var response = string.Format("{0}({1});", jsoncallback, @"{'prop1' : '" + DateTime.Now.ToString() + "'}"); HttpContext.Current.Response.Write(response); } }

    Read the article

  • How to return JSON in a Webservice?

    - by BrunoLM
    I need a Hello World example... [WebService(Namespace = "xxxxx")] [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)] [ScriptService()] public class Something : System.Web.Services.WebService { public Something() { } [WebMethod] [ScriptMethod(ResponseFormat=ResponseFormat.Json)] public string HelloWorld() { return "{Message:'hello world'}"; } } Because it generates an error {"Message":"Invalid JSON primitive: value.","StackTrace":" at System.Web.Script.Serialization.JavaScriptObjectDeserializer.DeserializePrimitiveObject()\r\n at System.Web.Script.Serialization.JavaScriptObjectDeserializer.DeserializeInternal(Int32 depth)\r\n at System.Web.Script.Serialization.JavaScriptObjectDeserializer.BasicDeserialize(String input, Int32 depthLimit, JavaScriptSerializer serializer)\r\n at System.Web.Script.Serialization.JavaScriptSerializer.Deserialize(JavaScriptSerializer serializer, String input, Type type, Int32 depthLimit)\r\n at System.Web.Script.Serialization.JavaScriptSerializer.Deserialize[T](String input)\r\n at System.Web.Script.Services.RestHandler.GetRawParamsFromPostRequest(HttpContext context, JavaScriptSerializer serializer)\r\n at System.Web.Script.Services.RestHandler.GetRawParams(WebServiceMethodData methodData, HttpContext context)\r\n at System.Web.Script.Services.RestHandler.ExecuteWebServiceCall(HttpContext context, WebServiceMethodData methodData)","ExceptionType":"System.ArgumentException"} What's wrong?

    Read the article

  • how to create Cross domain asp.net web service

    - by Prithvi Raj Nandiwal
    i have create a web service. i want to access this web service using Ajax jqury. i am able to access on same domain. but i want to access thia web service to another domain. Have any one idea. how to create cross domain web service in asp.net. any setting in web,config file so that i access it on another domain. my webservice [WebService(Namespace = "http://tempuri.org/")] [System.Web.Script.Services.ScriptService] public class Service : System.Web.Services.WebService { public Service () { } [WebMethod] public string SetName(string name) { return "hello my dear friend " + name; } } JavaScript $.ajax({ type: "GET", url:'http://192.168.1.119/Service/SetName.asmx?name=pr', ContentType: "application/x-www-form-urlencoded", cache: false, dataType: "jsonp", success: onSuccess });

    Read the article

  • Calling ASP.NET web service function via GET method with jQuery

    - by the_V
    Hi, I'm trying to call web service function via GET method using jQuery, but having a problem. This is a web service code: [WebService(Namespace = "http://something.com/samples")] [ScriptService] [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)] public class TestWebService : System.Web.Services.WebService { [WebMethod] public string Test2() { string result = null; try { result = "{'result':'success', 'datetime':'" + DateTime.Now.ToString() + "'"; } catch (Exception ex) { result = "Something wrong happened"; } return result; } } That's the way I call the function: $.ajax({ type: "GET", url: "http://localhost/testwebsite/TestWebService.asmx/Test2", data: "{}", contentType: "application/json", dataType: "json", error: function (xhr, status, error) { alert(xhr.responseText); }, success: function (msg) { alert('Call was successful!'); } }); Method is called successfully, but result string gets covered by XML tags, like this: <string> {'result':'success', 'datetime':'4/26/2010 12:11:18 PM' </string> And I get an error because of this (error handler is called). Does anybody know what can be done about this?

    Read the article

  • Ajax Autocomplete Extender

    - by Jason Ulloa
    El objetivo de este post es preparar un ejemplo sobre un tema que es planteado muy frecuentemente en los Foros de MSDN, como realizar un Autocomplete contra una base de datos. Qué requerimos? Antes de poder realizar un Autocomplete debemos tener en cuenta los elementos principales que requerimos para poder hacerlo funcionar, descritos de la siguiente manera: 1. Textbox: Nuestro grandioso amigo Textbox, que será donde el usuario ingresará los datos a buscar. 2. Un Webservice: que contendrá el método que se conectara a la base de datos y devolverá una lista con la información encontrada. 3. Ajax Autocomplete Extender: este es por decirlo así, el elemento más importante. Nos servirá como medio de enlace entre el webservice que expone el método y el textbox recuperando y mostrando los datos en forma de lista desplegable. La implementación Si bien parecierá complicado, crear un autocomplete extender es bastante sencillo. Empezaremos creando un nuevo sitio asp.net, en este sitio agregaremos un textbox y dos controles muy importantes de Ajax el ToolkitScriptManager para controlar el rende rizado de los script de ajax y el AutocompleteExtender que, como mencione anteriormente, será el medio de enlace. Antes de mostrar como quedará el código de lo anterior, explicaré algunas propiedades del AutocompleteExtender para que se entienda de mejor manera: 1. El ServicePath: contiene la ruta relativa al webservice que utilizaremos. 2. MinimumPrefixLength: se refiere al número de caracteres que deben ser digitados antes de iniciar la búsqueda. 3. ServiceMethod: el nombre del metodo de nuestro webservice que se encargará de devolver los datos. 4. EnableCaching: para mantener en cache los datos consultados, obteniendo mayor velocidad. 5. TargetControlID: una de las propiedades más importantes, acá se coloca el nombre del textbox al cual se unirá el Autocomplete 6. CompletionInterval: tiempo que debe transcurrir antes de iniciar con el trabajo de los datos. Una vez, explicadas las propiedades básicas, veamos como queda implementada la primer parte de nuestro autocomplete: <form id="form1" runat="server"> <div> <asp:ToolkitScriptManager ID="manager" runat="server" /> <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox> <asp:AutoCompleteExtender ID="AutoCompleteExtender1" runat="server" ServicePath="WebService.asmx" MinimumPrefixLength="1" ServiceMethod="PersonasInfo " EnableCaching="true" TargetControlID="TextBox1" UseContextKey="True" CompletionSetCount="10" CompletionInterval="0"> </asp:AutoCompleteExtender> </div> </form>   Ahora que nuestro código html está completo, es hora de trabajar directamente con nuestro webservice, este deberá contener un método que devuelva una lista o arreglo de datos, los cuales por supuesto, serán traídos desde la base de datos. Antes de implementar este método, debemos asegurarnos de que nuestra clase del webservice tiene habilitados los espacios para ser utilizada [System.Web.Script.Services.ScriptService()] [WebService(Namespace = "http://tempuri.org/")] [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)] public class WebService : System.Web.Services.WebService {}   Ahora si, nuestro metodo principal [WebMethod()] [System.Web.Script.Services.ScriptMethod()] public string[] PersonasInfo(string prefixText, int count) { string connstring = ConfigurationManager.ConnectionStrings["LocalSqlServer"].ConnectionString;   using (SqlConnection conn = new SqlConnection(connstring)) { SqlCommand comando = new SqlCommand("select nombre from personas where nombre LIKE '%' + @param + '%' ", conn); comando.Parameters.AddWithValue("@param", prefixText); SqlDataReader dr = default(SqlDataReader); comando.Connection.Open(); dr = comando.ExecuteReader(); List<string> items = new List<string>();   while (dr.Read()) { items.Add(dr["nombre"].ToString()); } comando.Connection.Close(); return items.ToArray(); } }   Del método anterior no explicaré en profundidad, pues es bastante sencillo. Una consulta a la base de datos utilizando un datareader y devolviendo los datos en una lista como arreglo. Lo más importante serían las 2 primeras líneas [WebMethod()] y el [ScriptMethod()] las cuales habilitan nuestro método para poder ser accedido y utilizado. Por último, el código de ejemplo en C# (VB Autcomplete):

    Read the article

  • JSON and jQuery.ajax

    - by Andreas
    Hello, im trying to use the jQuery UI autocomplete to communitate with a webservice with responseformate JSON, but i am unable to do so. My webservice is not even executed, the path should be correct since the error message does not complain about this. What strikes me is the headers, response is soap but request is json, is it supposed to be like this? Response Headersvisa källkod Content-Type application/soap+xml; charset=utf-8 Request Headersvisa källkod Accept application/json, text/javascript, */* Content-Type application/json; charset=utf-8 The error message i get is as follows (sorry for the huge message, but it might be of importance): soap:ReceiverSystem.Web.Services.Protocols.SoapException: Server was unable to process request. ---> System.Xml.XmlException: Data at the root level is invalid. Line 1, position 1. at System.Xml.XmlTextReaderImpl.Throw(Exception e) at System.Xml.XmlTextReaderImpl.Throw(String res, String arg) at System.Xml.XmlTextReaderImpl.ParseRootLevelWhitespace() at System.Xml.XmlTextReaderImpl.ParseDocumentContent() at System.Xml.XmlTextReaderImpl.Read() at System.Xml.XmlTextReader.Read() at System.Web.Services.Protocols.SoapServerProtocol.SoapEnvelopeReader.Read() at System.Xml.XmlReader.MoveToContent() at System.Web.Services.Protocols.SoapServerProtocol.SoapEnvelopeReader.MoveToContent() at System.Web.Services.Protocols.SoapServerProtocolHelper.GetRequestElement() at System.Web.Services.Protocols.Soap12ServerProtocolHelper.RouteRequest() at System.Web.Services.Protocols.SoapServerProtocol.RouteRequest(SoapServerMessage message) at System.Web.Services.Protocols.SoapServerProtocol.Initialize() at System.Web.Services.Protocols.ServerProtocolFactory.Create(Type type, HttpContext context, HttpRequest request, HttpResponse response, Boolean& abortProcessing) --- End of inner exception stack trace --- This is my code: $('selector').autocomplete({ source: function(request, response) { $.ajax({ url: "../WebService/Member.asmx", dataType: "json", contentType: "application/json; charset=utf-8", type: "POST", data: JSON.stringify({prefixText: request.term}), success: function(data) { alert('success'); }, error: function(XMLHttpRequest, textStatus, errorThrown){ alert('error'); } }) }, minLength: 1, select: function(event, ui) { } }); And my webservice looks like this: [WebService(Namespace = "http://tempuri.org/")] [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)] [System.ComponentModel.ToolboxItem(false)] [ScriptService] public class Member : WebService { [WebMethod(EnableSession = true)] [ScriptMethod(ResponseFormat = ResponseFormat.Json)] public string[] GetMembers(string prefixText) { code code code } } What am i doing wrong? Thanks in advance :)

    Read the article

  • How do I fix: InvalidOperationException upon Session timeout in Ajax WebService call

    - by Ngm
    Hi All, We are invoking Asp.Net ajax web service from the client side. So the JavaScript functions have calls like: // The function to alter the server side state object and set the selected node for the case tree. function JSMethod(caseId, url) { Sample.XYZ.Method(param1, param2, OnMethodReturn); } function OnMethodReturn(result) { var sessionExpiry = CheckForSessionExpiry(result); var error = CheckForErrors(result); ... process result } And on the server side in the ".asmx.cs" file: namespace Sample [ScriptService] class XYZ : WebService { [WebMethod(EnableSession = true)] public string Method(string param1, string param2) { if (SessionExpired()) { return sessionExpiredMessage; } . . . } } The website is setup to use form based authentication. Now if the session has expired and then the JavaScript function "JSMethod" is invoked, then the following error is obtained: Microsoft JScript runtime error: Sys.Net.WebServiceFailedException: The server method 'Method' failed with the following error: System.InvalidOperationException-- Authentication failed. This exception is raised by method "function Sys$Net$WebServiceProxy$invoke" in file "ScriptResource.axd": function Sys$Net$WebServiceProxy$invoke { . . . { // In debug mode, if no error was registered, display some trace information var error; if (result && errorObj) { // If we got a result, we're likely dealing with an error in the method itself error = result.get_exceptionType() + "-- " + result.get_message(); } else { // Otherwise, it's probably a 'top-level' error, in which case we dump the // whole response in the trace error = response.get_responseData(); } // DevDiv 89485: throw, not alert() throw Sys.Net.WebServiceProxy._createFailedError(methodName, String.format(Sys.Res.webServiceFailed, methodName, error)); } So the problem is that the exception is raised even before "Method" is invoked, the exception occurs during the creation of the Web Proxy. Any ideas on how to resolve this problem

    Read the article

  • jQuery AJAX slow in Firefox, fast in IE

    - by Brandon Montgomery
    I'm using jQuery to post to an ASP .NET Web Service to implement a custom auto-complete function. The code works great, except it's slow in FireFox (can't get it to go faster than 1 second). IE is blazing fast - works great. I watch the post in Firefox using Firebug. Here's the service code: <ScriptService(), _ WebService(Namespace:="http://tempuri.org/"), _ WebServiceBinding(ConformsTo:=WsiProfiles.BasicProfile1_1), _ ToolboxItem(False)> _ Public Class TestWebSvc Inherits System.Web.Services.WebService <WebMethod(), _ ScriptMethod(ResponseFormat:=Script.Services.ResponseFormat.Json, UseHttpGet:=True)> _ Public Function GetAccounts(ByVal q As String) As Object 'Code taken out for simplicity Return result End Function End Class And the jQuery ajax call: $.ajax({ beforeSend: function (req) { req.setRequestHeader("Content-Type", "application/json"); }, contentType: "application/json; charset=utf-8", type: "GET", url: "http://localhost/Suggest/TestWebSvc.asmx/GetAccounts", data: "q='" + element.val() + "'", dataType: "json", success: testWebSvcSuccess }); As you can see, I've tried to use the HTTP GET verb instead in hopes that that would make the call faster. As it does not, I'll probably switch it back to using POST if I can. Right now I'm just focused on why it's super fast in IE and super slow in Firefox. Versions: jQuery 1.3.2; Firefox 3.0.11; IE 8.0.6001.18783 (64-bit) Thank you for any insight you can provide.

    Read the article

  • Autocomplete extender problems on user control

    - by RUtt
    I'm having trouble getting autocompleteextender (from ajaxcontroltoolkit) to fire when it is on a user control (it works fine when everything is on an aspx page. In my case I'm using a master page as well as a user control. Here's what I have. On the masterpage (path: masterpages/MasterPage.master) <asp:ToolkitScriptManager ID="ToolkitScriptManager1" runat="server" EnablePageMethods="true"> </asp:ToolkitScriptManager> On the user control (path: controls/sitenavigation/usercontrol.ascx) <asp:TextBox id="txtSearchInput" Runat="server" CssClass="searchinput" Columns="95" MaxLength="95"></asp:TextBox> <asp:AutoCompleteExtender ID="txtSearchInput_AutoCompleteExtender" runat="server" DelimiterCharacters="" Enabled="True" ServiceMethod="GetSuggestions" ServicePath="~/App_Code/WebService.asmx" TargetControlID="txtSearchInput" UseContextKey="False" MinimumPrefixLength="2"> </asp:AutoCompleteExtender> On the Webservice (path: App_Code/WebService.cs) [System.Web.Script.Services.ScriptService] public class WebService : System.Web.Services.WebService { .... [WebMethod] public string[] GetSuggestions(string prefixText, int count, string contextKey) { //my code to return string[] } It seems that my problem is with my ServicePath in the extender but I just can't seem to figure out what it should be, any help would be great. Thanks.

    Read the article

  • Login failed when a web service tries to communicate with SharePoint 2007

    - by tata9999
    Hi, I created a very simple webservice in ASP.NET 2.0 to query a list in SharePoint 2007 like this: namespace WebService1 { /// <summary> /// Summary description for Service1 /// </summary> [WebService(Namespace = "http://tempuri.org/")] [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)] [System.ComponentModel.ToolboxItem(false)] // To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line. // [System.Web.Script.Services.ScriptService] public class Service1 : System.Web.Services.WebService { [WebMethod] public string HelloWorld() { return "Hello World"; } [WebMethod] public string ShowSPMyList() { string username = this.User.Identity.Name; return GetList(); } private string GetList() { string resutl = ""; SPSite siteCollection = new SPSite("http://localhost:89"); using (SPWeb web = siteCollection.OpenWeb()) { SPList mylist = web.Lists["MySPList"]; SPQuery query = new SPQuery(); query.Query = "<Where><Eq><FieldRef Name=\"AssignedTo\"/><Value Type=\"Text\">Ramprasad</Value></Eq></Where>"; SPListItemCollection items = mylist.GetItems(query); foreach (SPListItem item in items) { resutl = resutl + SPEncode.HtmlEncode(item["Title"].ToString()); } } return resutl; } } } This web service runs well when tested using the built-in server of Visual Studio 2008. The username indicates exactly my domain account (domain\myusername). However when I create a virtual folder to host and launch this web service (still located in the same machine with SP2007), I got the following error when invoking ShowSPMyList() method, at the line to execute OpenWeb(). These are the details of the error: System.Data.SqlClient.SqlException: Cannot open database "WSS_Content_8887ac57951146a290ca134778ddc3f8" requested by the login. The login failed. Login failed for user 'NT AUTHORITY\NETWORK SERVICE'. Does anyone have any idea why this error happens? Why does the web service run fine inside Visual Studio 2008, but not when running stand-alone? I checked and in both cases, the username variable has the same value (domain\myusername). Thank you very much.

    Read the article

  • Calling a .net webservice from a plain HTML site using jQuery

    - by pwee167
    Hi guys, I wanted to know it is possible to call a hosted .net web service from a HTML page using jQuery? I tried this piece of code, but it doesn't work for me: $('#myForm').click(function() { $.ajax({ type: "POST", data: '{}', url: "http://localhost:49590/Service.asmx?op=HelloWorld", contentType: "application/json; charset=utf-8", dataType: "json", success: function(response) { alert(response.d); }, failure: function(result) { alert(result.status + ' ' + result.statusText); } }); }); And the webservice is as such: [WebService(Namespace = "http://tempuri.org/")] [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)] [System.ComponentModel.ToolboxItem(false)] // To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line. [System.Web.Script.Services.ScriptService] public class Service : System.Web.Services.WebService { [WebMethod] public string HelloWorld() { return "Hello World"; } } I have searched for this and found only examples where it is done from asp.net or asp.net mvc projects. I am not sure what I am missing but I thought this was possible from a plain HTML site with javascript, so can someone please point me in the right direction. Cheers!

    Read the article

1 2  | Next Page >