Hi everyone I am trying to calla wcf service from a javascript function for some reason asp.net is not recognizing the namespace and give me an error on runtime, any help will be greatly appreciated following is code:
Default aspx page
<form id="form1" runat="server">
<asp:ScriptManager ID="ScriptManager1" runat="server">
<Services>
<asp:ServiceReference Path="~/WeatherService.svc"/>
</Services>
</asp:ScriptManager>
Enter a zipcode:
<input id="zipCodeInput" type="text" />
<br/>
<input id="getForecastButton" type="button" value="Get Forecast" onclick="onGetForecast()"/>
<br/>
<div id="resultsDiv">
</div>
</form>
Javasript
<script language="javascript" type="text/javascript">
function onGetForecast() {
var zip = document.getElementById("zipCodeInput").value;
//alert(zip);
UltimateServices.GetForecast(zip, onGetForecastComplete, onGetForecastError, zip);
}
function onGetForecastComplete(result, userData) {
document.getElementById("resultsDiv").innerHTML = "Weather for " + userData + " is going to be " + result;
}
function onGetForecastError(err) {
alert("There was a error " + err.get_message());
}
</script>
WeatherService.cs file(codebehind)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Activation;
using System.ServiceModel.Web;
using System.Text;
[ServiceContract(Namespace = "UltimateServices")]
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
public class WeatherService
{
private static Random _rand = new Random();
[OperationContract]
public string GetForecast(string zipcode)
{
string forecast = "";
switch(_rand.Next(3))
{
case 0:
forecast = "Sunny and Warm";
break;
case 1:
forecast = "Chilly and overcast";
break;
case 2:
forecast = "Hot and humid";
break;
}
return forecast;
}
// Add more operations here and mark them with [OperationContract]
}
web.config file
<system.serviceModel>
<behaviors>
<endpointBehaviors>
<behavior name="WeatherServiceAspNetAjaxBehavior">
<enableWebScript />
</behavior>
</endpointBehaviors>
</behaviors>
<serviceHostingEnvironment aspNetCompatibilityEnabled="true"
multipleSiteBindingsEnabled="true" />
<services>
<service name="WeatherService">
<endpoint address="" behaviorConfiguration="WeatherServiceAspNetAjaxBehavior"
binding="webHttpBinding" contract="WeatherService" />
</service>
</services>
</system.serviceModel>
here i call simple hello world from WCF using javascript
Service.cs
using System;
using System.Collections.Generic;
using System.Linq;`
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Web;
using System.Text;
using System.ServiceModel.Activation;
// NOTE: You can use the "Rename" command on the "Refactor" menu to change the class name "Service" in code, svc and config file together.
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
public class Service : IService
{
[WebGet(ResponseFormat = WebMessageFormat.Json)]
public string helloworld(string name)
{
name = "Hello " + name;
return name;
}
}
web.config
<?xml version="1.0"?>
<configuration>
<system.web>
<compilation debug="true" targetFramework="4.0"/>
</system.web>
<system.serviceModel>
<services>
<service name="Service" behaviorConfiguration="DefaultBehavior">
<endpoint address="" binding="webHttpBinding" contract="IService" name="RunningBarbus.Services.RunningBarbusService" behaviorConfiguration="AjaxBehavior">
<identity>
<dns value="localhost"/>
</identity>
</endpoint>
<endpoint contract="IMetadataExchange" binding="mexHttpBinding" address="mex"/>
</service>
</services>
<bindings>
<webHttpBinding>
<binding crossDomainScriptAccessEnabled="true">
<security mode="None"/>
</binding>
</webHttpBinding>
</bindings>
<behaviors>
<serviceBehaviors>
<behavior name="DefaultBehavior">
<!-- To avoid disclosing metadata information, set the value below to false and remove the metadata endpoint above before deployment -->
<serviceMetadata httpGetEnabled="true"/>
<!-- To receive exception details in faults for debugging purposes, set the value below to true. Set to false before deployment to avoid disclosing exception information -->
<serviceDebug includeExceptionDetailInFaults="true"/>
</behavior>
</serviceBehaviors>
<endpointBehaviors>
<behavior name="AjaxBehavior">
<!--<enableWebScript/>-->
<webHttp helpEnabled="true" automaticFormatSelectionEnabled="false" />
</behavior>
</endpointBehaviors>
</behaviors>
<serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="true" />
<standardEndpoints>
<webScriptEndpoint>
<standardEndpoint crossDomainScriptAccessEnabled="true" name="">
</standardEndpoint>
</webScriptEndpoint>
</standardEndpoints>
</system.serviceModel>
<system.webServer>
<httpProtocol>
<customHeaders>
<add name="access-control-allow-headers" value="content-type, Accept" />
<add name="Access-Control-Allow-Origin" value="*" />
<add name="Access-Control-Allow-Methods" value="POST,GET,OPTIONS" />
<add name="Access-Control-Max-Age" value="1728000" />
</customHeaders>
</httpProtocol>
<modules runAllManagedModulesForAllRequests="true"/>
</system.webServer>
</configuration>
javascript code
<%# Page Language="C#" AutoEventWireup="true" CodeFile="jsonp.aspx.cs" Inherits="jsonp" %>
<!DOCTYPE html >
<html>
<head runat="server">
<title></title>
<script src="js/jquery-1.10.2.min.js" type="text/javascript"></script>
<script type="text/javascript">
var name="";
var Type;
var Url = "http://192.168.X.X/WCFjavascript/Service.svc/helloworld?name=world";
var Data;
var ContentType;
var DataType;
var ProcessData;
var method;
//Generic function to call WCF Service
function CallService() {
$.ajax({
type: Type, //GET or POST or PUT or DELETE verb
url: Url, // Location of the service
// data: name, //Data sent to server
contentType: ContentType, // content type sent to server
//data: '[{"name":"' + name + '"}]',
dataType: DataType, //Expected data format from server
processdata: ProcessData, //True or False
success: function (msg) {//On Successfull service call
ServiceSucceeded(msg);
},
error: ServiceFailed// When Service call fails
});
}
function ServiceFailed(xhr) {
alert(xhr.responseText);
if (xhr.responseText) {
var err = xhr.responseText;
if (err)
error(err);
else
error({ Message: "Unknown server error." })
}
return;
}
function ServiceSucceeded(result) {
debugger;
if (DataType == "jsonp") {
alert(result);
resultObject = result.helloworld;
var string = result.name ;
alert(string);
}
}
function helloworld() {
debugger;
var uesrid = "";
Type = "GET";
// Url = "http://192.168.X.X/WCFjavascript/Service.svc/helloworld?'"+uesrid+'"';
Url = Url;
DataType = "jsonp"; ProcessData = false;
method = "helloworld";
CallService();
}
$(document).ready(
function () {
helloworld();
}
);
enter code here
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
</div>
</form>
</body>
</html>
You seem to lack the ScriptService/ScriptMethod attributes on your service/service methods.
Related
I'm trying to call a function exposed by WCF service using ajax but the success method is always returning 'undefined' even though the function itself on the WCF side is returning the right answer
I tried debugging and printing everything and the WCF is returning the right answer but when the ajax call enters the success method object it receives is undefined
WCF:
[OperationContract]
[ WebInvoke (
Method = "POST",
BodyStyle = WebMessageBodyStyle.WrappedRequest,
ResponseFormat = WebMessageFormat.Json,
RequestFormat = WebMessageFormat.Json
)]
public Result_Login LoginAdmin(string email, string password)
{
System.Diagnostics.Debug.WriteLine("LoginAdmin called");
#region Declaration And Initialization Section.
Result_Login resultLogin = new Result_Login();
#endregion
#region Body Section
try
{
BLC.BLC oBLC_Default = new BLC.BLC();
BLCInitializer oBLCInitializer = new BLCInitializer();
oBLCInitializer.ConnectionString = ConfigurationManager.AppSettings["CONN_STR"];
System.Diagnostics.Debug.WriteLine("Connection string: "+ConfigurationManager.AppSettings["CONN_STR"]);
using(BLC.BLC oBLC = new BLC.BLC(oBLCInitializer))
{
resultLogin.login = oBLC.SignInAdmin(email, password);
}
}
catch(Exception ex)
{
if(ex.GetType().FullName != "BLC.BLCException")
{
resultLogin.ExceptionMsg = string.Format("Get_Persons : {0}", ex.Message);
}
else
{
resultLogin.ExceptionMsg = ex.Message;
}
}
#endregion
#region Return Section
return resultLogin;//giving the right result before ajax return method
#endregion
}
public override string ToString()
{
return base.ToString();
}
// Add more operations here and mark them with [OperationContract]
}
#region Action_Result
public partial class Action_Result
{
#region Properties.
public string ExceptionMsg { get; set; }
#endregion
#region Constructor
public Action_Result()
{
#region Declaration And Initialization Section.
#endregion
#region Body Section.
this.ExceptionMsg = string.Empty;
#endregion
}
#endregion
}
#endregion
#region Result_Login
public partial class Result_Login : Action_Result
{
#region Properties.
public bool login { get; set; }
#endregion
}
Javascript:
function IsAuthenticated_JSON() {
try {
_Params1 = new Object();
_Params1.email = $("#Login1_UserName").val();
_Params1.password = $("#Login1_Password").val();
_Params = JSON.stringify(_Params1);
_Service_Method = "LoginAdmin";
CallService(_Service_Method, IsClientAuthenticated_Completed, Service_Call_InCompleted);
}
catch (e) {
alert("IsAuthenticated_JSON: " + e.Message);
}
}
function IsClientAuthenticated_Completed(i_Input) {
try {
localStorage.setItem("UserInfo", JSON.stringify(i_Input.My_Result));
console.log("unstringify: " + JSON.stringify(i_Input.My_Result));//undefined
if (localStorage.getItem('UserInfo') != null) {
_UserInfo = JSON.parse(localStorage.getItem('UserInfo'));
_Ticket = _UserInfo.Ticket;
alert("done");
}
}
catch (e) {
console.log("error "+e.Message + " " + e.log)
}
}
function CallService(i_Service_Method, i_Success_Method, i_Failure_Method) {
var url = "";
url = js_Prepare_WCF_Url_For_Call();
var request = $.ajax({
type: "POST",
url: url,
data: _Params,
contentType: "application/json; charset=utf-8",
dataType: "json",
async: true,
success: function (msg) {
console.log("data: "+msg.data +"status: "+ msg.status +"message: " + msg.Message);//undefined
i_Success_Method(msg);
},
error: function (msg) {
console.log("fail: " + msg.responseText + msg.statusText)
}
});
}
Web.config:
<?xml version="1.0" encoding="utf-8"?>
<!--
For more information on how to configure your ASP.NET application, please visit
https://go.microsoft.com/fwlink/?LinkId=169433
-->
<configuration>
<configSections>
<!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 -->
<section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
</configSections>
<connectionStrings>
<add name="FuelAppEntities" connectionString="metadata=res://*/DALC.csdl|res://*/DALC.ssdl|res://*/DALC.msl;provider=System.Data.SqlClient;provider connection string="data source=.;initial catalog=FuelApp;integrated security=True;multipleactiveresultsets=True;application name=EntityFramework"" providerName="System.Data.EntityClient" />
</connectionStrings>
<appSettings>
<add key="CONN_STR" value="Data Source=.;Database=FuelApp;User ID=sa;Password=sa" />
</appSettings>
<system.web>
<compilation debug="true" targetFramework="4.6.1" />
<httpRuntime targetFramework="4.6.1" />
</system.web>
<system.codedom>
<compilers>
<compiler language="c#;cs;csharp" extension=".cs" type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.CSharpCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=2.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" warningLevel="4" compilerOptions="/langversion:default /nowarn:1659;1699;1701" />
<compiler language="vb;vbs;visualbasic;vbscript" extension=".vb" type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.VBCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=2.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" warningLevel="4" compilerOptions="/langversion:default /nowarn:41008 /define:_MYTYPE=\"Web\" /optionInfer+" />
</compilers>
</system.codedom>
<entityFramework>
<defaultConnectionFactory type="System.Data.Entity.Infrastructure.LocalDbConnectionFactory, EntityFramework">
<parameters>
<parameter value="mssqllocaldb" />
</parameters>
</defaultConnectionFactory>
<providers>
<provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
</providers>
</entityFramework>
<system.serviceModel>
<behaviors>
<endpointBehaviors>
<behavior name="project.Service1AspNetAjaxBehavior">
<enableWebScript />
</behavior>
<behavior name="My_Behavior">
<webHttp defaultOutgoingResponseFormat="Json" />
</behavior>
</endpointBehaviors>
<serviceBehaviors>
<behavior name="">
<serviceMetadata httpGetEnabled="true" />
<serviceDebug includeExceptionDetailInFaults="true" />
</behavior>
</serviceBehaviors>
</behaviors>
<bindings>
<customBinding>
<binding name="project.WCF.customBinding0">
<binaryMessageEncoding />
<httpTransport />
</binding>
</customBinding>
<webHttpBinding>
<binding maxBufferPoolSize="1048576" maxReceivedMessageSize="1048576" maxBufferSize="1048576" name="jsonpWebHttpBinding" useDefaultWebProxy="false" crossDomainScriptAccessEnabled="false" />
</webHttpBinding>
</bindings>
<serviceHostingEnvironment aspNetCompatibilityEnabled="true"
multipleSiteBindingsEnabled="true" minFreeMemoryPercentageToActivateService="0"/>
<services>
<service name="project.WCF">
<endpoint address="a" behaviorConfiguration="project.Service1AspNetAjaxBehavior"
binding="webHttpBinding" contract="project.WCF" />
<endpoint address="" binding="webHttpBinding" bindingConfiguration="jsonpWebHttpBinding" contract="project.WCF" behaviorConfiguration="My_Behavior" />
<endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange" />
</service>
</services>
</system.serviceModel>
<runtime>
<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
<dependentAssembly>
<assemblyIdentity name="Newtonsoft.Json" publicKeyToken="30ad4fe6b2a6aeed" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-7.0.0.0" newVersion="7.0.0.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="PushSharp.Apple" publicKeyToken="cf74b75eab2c0170" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-2.2.1.0" newVersion="2.2.1.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="PushSharp.Android" publicKeyToken="cf74b75eab2c0170" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-2.2.1.0" newVersion="2.2.1.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="PushSharp.WindowsPhone" publicKeyToken="cf74b75eab2c0170" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-2.2.1.0" newVersion="2.2.1.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="PushSharp.Blackberry" publicKeyToken="cf74b75eab2c0170" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-2.2.1.0" newVersion="2.2.1.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="PushSharp.Windows" publicKeyToken="cf74b75eab2c0170" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-2.2.1.0" newVersion="2.2.1.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="System.Net.Http" publicKeyToken="b03f5f7f11d50a3a" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-2.0.0.0" newVersion="2.0.0.0" />
</dependentAssembly>
</assemblyBinding>
</runtime>
Not sure why you meet this problem , I have copied your code and have a test, but I could get the response.
Below is my code.
[ServiceContract]
public class MyTestRestService
{
[OperationContract]
[WebInvoke(
Method = "POST",
BodyStyle = WebMessageBodyStyle.WrappedRequest,
ResponseFormat = WebMessageFormat.Json,
RequestFormat = WebMessageFormat.Json
)]
public Result_Login LoginAdmin(string email, string password)
{
Result_Login resultLogin = new Result_Login();
resultLogin.ExceptionMsg = "exception";
resultLogin.login = true;
return resultLogin;
}
}
Model
public partial class Action_Result
{
public string ExceptionMsg { get; set; }
public Action_Result()
{
this.ExceptionMsg = string.Empty;
}
}
public partial class Result_Login : Action_Result
{
public bool login { get; set; }
}
Endpoint config.
<service name="Service.Rest.MyTestRestService" >
<endpoint binding="webHttpBinding" contract="Service.Rest.MyTestRestService" behaviorConfiguration="web"></endpoint>
</service>
To enable cross origin request, if your wcf rest server and your client are not at the same origin.
<system.webServer>
<httpProtocol>
<customHeaders>
<add name="Access-Control-Allow-Origin" value="*" />
<add name="Access-Control-Allow-Methods" value="POST,GET,OPTIONS" />
<add name="Access-Control-Allow-Headers" value="*"/>
</customHeaders>
</httpProtocol>
protected void Application_EndRequest(object sender, EventArgs e)
{
if(HttpContext.Current.Request.HttpMethod == "OPTIONS")
{
HttpContext.Current.Response.StatusCode = 200;
}
}
The result.
It worked after adding
<webHttp defaultOutgoingResponseFormat="Json" />
to the service behavior in web.config
Ajax is not sending the data to the specified URL. Here is my controller:
#Controller
public class HomeController {
private List<User> userList = new ArrayList<User>();
#RequestMapping(value = "AddUsers.htm", method = RequestMethod.GET)
public String showForm() {
return "AddUsers";
}
#RequestMapping(value = "User.htm", method = RequestMethod.POST)
public #ResponseBody
String addUser(#ModelAttribute(value = "user") User user,
BindingResult result) {
String returnText;
if (!result.hasErrors()) {
userList.add(user);
returnText = "User has been added to the list. Total number of users are"
+ userList.size();
} else {
returnText = "Sorry, an error has occur. User has not been added to list.";
}
return returnText;
}
#RequestMapping(value = "ShowUsers.htm")
public String showUsers(ModelMap model) {
model.addAttribute("Users", userList);
return "ShowUsers";
}
}
AddUser.jsp page
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%# page session="false" %>
<html>
<head>
<title>Home</title>
</head>
<script src="/AjaxWithSpringMVC2Annotations/js/jquery.js"></script>
<script type="text/javascript">
function AjaxCall() {
alert('ready');
//get the form variables....
var name = $('#name').val();
var education = $('#education').val();
$.ajax({
type: "POST",
url: "AddUsers.htm",
data: " name=" + name + "&education=" + education,
success: function (response) {
$('#info').html(response);
$('#name').val('');
$('#education').val('');
},
error: function (e) {
alert('ERROR : ' + e);
}
});
}
</script>
<body>
<h1>Welcome to the AddUsers page. </h1>
<table>
<tr><td>Enter your name : </td><td> <input type = "text" id="name"></td></tr>
<tr><td>Educational qualification : </td><td> <input type = "text" id="education"></td></tr>
<tr><td colspan = "2"><input type="button" value="Add Users" onclick="AjaxCall()"></td></tr>
<tr><td colspan = "2"><div id ="info"></div></td></tr>
</table>
Show users
</body>
</html>
I have inserted an alert within the ajax which never comes up. So I believe there is something wrong with the ajax method.
web.xml:
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="2.5" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web- app_2_5.xsd">
<!-- The definition of the Root Spring Container shared by all Servlets and Filters -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/spring/root-context.xml</param-value>
</context-param>
<!-- Creates the Spring Container shared by all Servlets and Filters -->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!-- Processes application requests -->
<servlet>
<servlet-name>appServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/spring/appServlet/servlet-context.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>appServlet</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
I have also created a domain class which would store the student information:
public class User {
private String name = null;
private String education = null;
public void SetName(String name) {
this.name = name;
}
public String GetName() {
return name;
}
public void SetEdu(String education) {
this.education = education;
}
public String GetEdu() {
return education;
}
}
There is also a warning:
WARN : org.springframework.web.servlet.PageNotFound - No mapping found for HTTP request with
URI [/sum/] in DispatcherServlet with name 'appServlet'>`
Dispatch servlet:
<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns:beans="http://www.springframework.org/schema/beans" xmlns="http://www.springframework.org/schema/mvc" xmlns:context="http://www.springframework.org/schema/context" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
<!-- DispatcherServlet Context: defines this servlet's request-processing infrastructure -->
<!-- Enables the Spring MVC #Controller programming model -->
<annotation-driven />
<!-- Handles HTTP GET requests for /resources/** by efficiently serving up static resources
in the ${webappRoot}/resources directory -->
<resources mapping="/resources/**" location="/resources/" />
<!-- Resolves views selected for rendering by #Controllers to .jsp resources in the /WEB-
INF/views directory -->
<beans:bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<beans:property name="prefix" value="/WEB-INF/views/" />
<beans:property name="suffix" value=".jsp" />
</beans:bean>
<context:component-scan base-package="com.faisal.sum" />
</beans:beans>
I corrected the upper case problem ($.ajax instead of $.Ajax). Thanks for pointing out.
Now I have a different error:
POST http://localhost:8080/sum/AddUsers.htm 405 (Method Not Allowed)
change url:"AddUsers.htm" to url: "${pageContext. request. contextPath}/AddUsers.htm" and try.
the url you are calling is this
type: "POST",
url: "AddUsers.htm",
Which is POST, the controller method is GET. Hecne the 405 error, method not supported.
You try to send POST request but mapped your method call with GET method
#RequestMapping(value = "AddUsers.htm", method = RequestMethod.GET)
try to change RequestMethod.GET to POST
For the last many hours, I've been banging my head to make this work. I have a chat application using SignalR but am getting the javascript error "Object doesn't support property or method " while running it. I am using IIS to host the site.
I am guessing the javascript error is because the startup is not getting fired.
Please help.
after some time I found that owin startup is not getting hit.
[assembly: OwinStartup( typeof( SignalrSimpleChat.Startup ) )]
namespace SignalrSimpleChat
{
public class Startup
{
public void Configuration( IAppBuilder app )
{
app.MapSignalR( ); // not getting hit!!!!
}
}
}
my nugget installs are
<?xml version="1.0" encoding="utf-8"?>
<packages>
<package id="jQuery" version="2.0.3" targetFramework="net45" />
<package id="json2" version="1.0.2" targetFramework="net45" />
<package id="Microsoft.AspNet.SignalR" version="2.0.1" targetFramework="net45" />
<package id="Microsoft.AspNet.SignalR.Core" version="2.0.1" targetFramework="net45" />
<package id="Microsoft.AspNet.SignalR.JS" version="2.0.1" targetFramework="net40" />
<package id="Microsoft.AspNet.SignalR.Owin" version="1.2.0" targetFramework="net45" />
<package id="Microsoft.AspNet.SignalR.SystemWeb" version="2.0.1" targetFramework="net45" />
<package id="Microsoft.Owin" version="2.1.0-rc1" targetFramework="net45" />
<package id="Microsoft.Owin.Host.SystemWeb" version="2.1.0-rc1" targetFramework="net45" />
<package id="Microsoft.Owin.Security" version="2.1.0-rc1" targetFramework="net45" />
<package id="Newtonsoft.Json" version="5.0.8" targetFramework="net45" />
<package id="Owin" version="1.0" targetFramework="net45" />
</packages>
here is my page
<head>
<title>Index</title>
<script src="../../Scripts/jquery-2.0.3.js"></script>
<script src="../../Scripts/jquery.signalR-2.0.1.js"></script>
<script src="../../Scripts/json2.js"></script>
<script src="#Url.Content("~/signalr/hubs")"></script>
</head>
<body>
<div>
<input type="text" disabled id="userName" />
<input type="text" disabled id="groupName" />
<input type="text" id="msg" />
<input type="button" id="broadcast" value="broadcast" />
<input type="button" id="groupcast" value="groupcast" />
<ul id="messages">
</ul>
</div>
<script type="text/javascript">
$(function () {
var chat = $.connection.chat;
$('#userName').val(prompt('Enter your name:', ''));
$('#groupName').val(prompt('Enter your groupName:', ''));
chat.userName = $('#userName').val();
chat.groupName = $('#groupName').val();
chat.addMessage = function (userName, groupName, message) {
$('#messages').append('<li><b>' + groupName + "." + userName + ":</b>" + message + '</li>');
$('#msg').val('');
};
$("#broadcast").click(function () {
chat.sendAll(chat.userName, chat.groupName, $('#msg').val());
});
$("#groupcast").click(function () {
chat.sendGroup(chat.userName, chat.groupName, $('#msg').val());
});
$.connection.hub.start().done(function () {
chat.join(chat.groupName); //throws exception!!!!!!!!!
});
$.connection.hub.start();
});
and my code behind
namespace SignalrSimpleChat.Models.Helpers
{
public class Chat : Hub
{
public void SendAll( string userName, string groupName, string message )
{
Clients.All.addMessage( userName, groupName, message );
}
public void SendGroup( string userName, string groupName, string message )
{
Clients.Group( groupName ).addMessage( userName, groupName, message );
}
public void Join( string groupName )
{
Groups.Add( Context.ConnectionId, groupName );
}
}
}
Starting in SignalR 1.0, client and server methods can only be accessed through the client and server namespaces respectively. State also got it's own namespace.
This change was made to avoid collisions between client and server methods. Your JS code would change to look like this:
$(function () {
var chat = $.connection.chat;
$('#userName').val(prompt('Enter your name:', ''));
$('#groupName').val(prompt('Enter your groupName:', ''));
chat.state.userName = $('#userName').val();
chat.state.groupName = $('#groupName').val();
chat.client.addMessage = function (userName, groupName, message) {
$('#messages').append('<li><b>' + groupName + "." + userName + ":</b>" + message + '</li>');
$('#msg').val('');
};
$("#broadcast").click(function () {
chat.server.sendAll(chat.userName, chat.groupName, $('#msg').val());
});
$("#groupcast").click(function () {
chat.server.sendGroup(chat.userName, chat.groupName, $('#msg').val());
});
$.connection.hub.start().done(function () {
chat.server.join(chat.groupName); //should no longer throw exception!!!!!!!!!
});
$.connection.hub.start();
});
Try using
$.connection.hub.start().done(function () {
chat.server.join('test');
});
If doesnt work, try without local variable:
$.connection.hub.start().done(function () {
$.connection.chat.server.join('test');
});
Some resources:
http://www.asp.net/signalr/overview/signalr-20/getting-started-with-signalr-20/tutorial-getting-started-with-signalr-20
I have setup a WCF service that returns json format data with my configuration file setup as follows:
<system.web>
<compilation debug="true" strict="false" explicit="true" targetFramework="4.0" />
</system.web>
<system.serviceModel>
<bindings>
<webHttpBinding>
<binding name="webHttpBindingJsonP" crossDomainScriptAccessEnabled="true" />
</webHttpBinding>
</bindings>
<behaviors>
<serviceBehaviors>
<behavior name="webHttpBehavior">
<serviceMetadata httpGetEnabled="true" />
<serviceDebug includeExceptionDetailInFaults="true" />
</behavior>
</serviceBehaviors>
<endpointBehaviors>
<behavior name="webHttpBehavior">
<webHttp/>
</behavior>
</endpointBehaviors>
</behaviors>
<services>
<service behaviorConfiguration="webHttpBehavior" name="Services.Service1">
<endpoint address="mex"
binding="webHttpBinding" bindingConfiguration="webHttpBindingJsonP"
contract="Services.IService1" behaviorConfiguration="webHttpBehavior"/>
</service>
</services>
</system.serviceModel>
<system.webServer>
<modules runAllManagedModulesForAllRequests="true"/>
</system.webServer>
My service WebInvoke function:
<OperationContract()>
<WebInvoke(Method:="GET", BodyStyle:=WebMessageBodyStyle.WrappedRequest, Responseformat:=WebMessageFormat.Json)>
Function RetrieveData(ByVal screenName As String) As Stream
And Finally my dojo based website's function to call the webservice:
<script type="text/javascript">
dojo.ready(function () {
dojo.io.script.get({ url:
"http://xxx.xxx.x.xxx/Services/Service/Service1.svc/GetData?item=Tweet",
callbackParamName: "callback",
content: { username: "me", password: "you" }
}).then(function (data){
return data.results;
})
});
</script>
The problem is that I cannot get the data to flow through to the dojo application. First I get the error callback undefined. Now I am not sure if I am clear on this callback thing: is it the name of the function in the dojo application as I have above but the function is not named or is it the name of the function the returns the json response in the web service which by the way is installed on a different domain.
this is what I do with .NET:
My service:
[OperationContract]
[WebGet(UriTemplate = "/GetMyStuff", ResponseFormat = WebMessageFormat.Json)]
public String GetMyStuff()
{
var myStuff = getFromService("foo");
return new { label = "name", identifier = "Id", items = myStuff.Select(w => new { Id = w.Id, name = w.Description }) }.ToJSON();
}
I use this ToJSON() helper function declared as this:
public static class LinqUtils
{
public static string ToJSON(this object obj)
{
JavaScriptSerializer serializer = new JavaScriptSerializer();
return serializer.Serialize(obj);
}
}
In web.config:
<system.serviceModel>
<serviceHostingEnvironment multipleSiteBindingsEnabled="true" aspNetCompatibilityEnabled="false">
<serviceActivations>
<add relativeAddress="Services/StuffServiceJson.svc" service="MyStuff.MyStuffService" /> <!-- This is an actual URL mapping to your service endpoint -->
</serviceActivations>
</serviceHostingEnvironment>
<!-- other stuff -->
<services>
<service name="MyStuff.MyStuffService">
<endpoint binding="webHttpBinding" contract="MyStuff.MyStuffService" address="" behaviorConfiguration="webHttp"/> <!-- This is a service endpoint to your implementation class mapping -->
</service>
</services>
</system.serviceModel>
In Dojo:
require(["dojo/_base/xhr"], function(xhr) {
xhr.get({
url: "/Services/StuffServiceJson.svc/GetMyStuff",
handleAs: "json",
preventCache: true
}).then(function (data) {
//Do something with DATA
}, function (error) {
//Do something with error OMG
});
});
If you get a problem with the data being returned as string anyway (happens in .NET sometimes) then you're gonna have to take your data and do
require(["dojo/json"], function(json){
json.parse(data)
});
Luck,
I have a DataList and Update Panel in my page. After implementation, I checked that the response is talking very long time after using Update panels...Here is the study material. I have a Delete Command event in Datalist and works find in the above mentioned case. I was trying to implement Delete Command using Page Methods. Any Idea how to do that?
I basically want to find hidden controls in this event and have to delete the record in `database. Any help will be highly appreciated.
Rest Services
The full application can be downloaded from:
http://sdrv.ms/LJJz1K
This sample uses rest services in ASP.Net (the same concepts can be applied to a MVC application)
The clearer advantage when using rest services vs page methods, is testability.
I will guide you step by step to configure the service:
You need the following references:
System.Web.ServiceModel.dll
System.Web.ServiceModel.Activation.dll
System.Web.ServiceModel.Web.dll
Nuget packages:
jQuery
jQuery plugins:
jQuery Block UI (it’s available as a single script file)
Service info
[ServiceContract]
public interface IMyService
{
[OperationContract]
[WebInvoke(
ResponseFormat = WebMessageFormat.Json,
RequestFormat = WebMessageFormat.Json,
UriTemplate = "/DeleteFromService",
Method = "DELETE")]
void Delete(int id);
}
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
public class MyService : IMyService
{
public void Delete(int id)
{
// delete your product
// simulate a long process
Thread.Sleep(5000);
}
}
In Global.asax
void Application_Start(object sender, EventArgs e)
{
// Code that runs on application startup
RouteTable.Routes.Ignore("{resource}.axd/{*pathInfo}");
RouteTable.Routes.Add(new ServiceRoute("",
new WebServiceHostFactory(),
typeof(MyService)));
}
In web.config
<system.serviceModel>
<serviceHostingEnvironment aspNetCompatibilityEnabled="true" />
<standardEndpoints>
<webHttpEndpoint>
<standardEndpoint name="" helpEnabled="true"
automaticFormatSelectionEnabled="true" />
</webHttpEndpoint>
</standardEndpoints>
</system.serviceModel>
Register scripts (they can be registered in a master page)
<script type="text/javascript" src="Scripts/jquery-1.7.2.min.js" language="javascript" ></script>
<script language="javascript" type="text/javascript" src="Scripts/jquery.blockui.1.33.js"></script>
In a ASP.Net content page (in this sample, I am using a master page)
<asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent">
<input type="button" value="Delete" id="myButton" />
</asp:Content>
<asp:Content ID="HeaderContent" runat="server" ContentPlaceHolderID="HeadContent">
<script type="text/javascript" language="javascript">
function deleteFromService() {
if (!confirm("Are you sure you want to delete?")) {
return;
}
$.blockUI();
$.ajax({
cache: false,
type: "DELETE",
async: true,
url: "/DeleteFromService",
data: "3", // get your id to delete
contentType: "application/json",
dataType: "json",
success: function () {
$(document).ajaxStop($.unblockUI);
alert("done");
},
error: function (xhr) {
$(document).ajaxStop($.unblockUI);
alert(xhr.responseText);
}
});
}
jQuery().ready(function () {
$("#myButton").click(deleteFromService);
});
</script>
</asp:Content>
And that’s it, ajax commands the easy way =)