How call WCF service from javascript? - c#

I have a WCF service in folder "Services":
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;
using System.Web.Services;
using System.ServiceModel.Activation;
using System.Web.Script.Services;
namespace Application.Services
{
[ServiceContract]
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
[ScriptService]
public class ProductTypeService
{
[OperationContract]
[WebMethod]
public string LoadMainGridProductType(string test)
{
return "Success";
}
}
}
and on page I try to call this service method from javascript:
$(document).ready(function () {
var counter = "test";
Application.Services.ProductTypeService.LoadMainGridProductType(counter, ResultLoadMainGridProductType, ErrorLoadMainGridProductType);
});
on page I also make conect to this service and javascript files:
<asp:ScriptManager ID="ScriptManager" runat="server">
<Scripts>
<asp:ScriptReference Path="~/Scripts/ProductType.js" />
</Scripts>
<Services>
<asp:ServiceReference Path="~/Services/ProductTypeService.svc" />
</Services>
</asp:ScriptManager>
but code fails on
Application.Services.ProductTypeService.LoadMainGridProductType(counter, ResultLoadMainGridProductType, ErrorLoadMainGridProductType);
Error : Error of implementation of Microsoft Jscript: "Application" is not certain.
How fix this???

Firstly, check to see if the WCF service is working correctly by navigating directly to it, e.g. http://localhost:(port-number)/Services/ProductTypeService.svc
I suspect that this wont work and give you some errors.
Secondly, check to make sure that the jsdebug javascript file has been generated and is included in the scripts loaded with the application.
Another person asked a similar question earlier.
How get namespace on javascript in asp.net web?

Related

How can i read SOAP body as one parameter in C#

This is a sample request to a web service I'm working on:
<S:Envelope xmlns:S="http://schemas.xmlsoap.org/soap/envelope/">
<S:Body>
<ns0:postRequest xmlns:ns0="http://www.mynamespace.com">
<Firstname>Mike</Firstname>
<Lastname>Adam</Lastname>
</ns0:postRequest>
</S:Body>
</S:Envelope>
Currently I read each value as single parameter in the webmethod like this:
using System;
using System.Collections.Generic;
using System.Linq;
using System.ServiceModel;
using System.Web;
using System.Web.Services;
using System.Web.Services.Protocols;
using System.Xml.Serialization;
namespace myCode
{
[WebService(Namespace = "http://www.mynamespace.com")]
public class testInt : System.Web.Services.WebService
{
[SoapRpcMethod("http://www.mynamespace.com")]
[WebMethod]
public string postRequest(string Firstname, string Lastname)
{
return Lastname.ToString();
}
}
}
But in the real case there are much more parameters.
My question is how can read them as one parameter in the webmethod noting that I can't change the request XML format.
(By the way I created a class with Firstname and Lastname as properties in it and used this class as a parameter in the webmethod but it's always null)
Thanks much
I think this is what you are after. It shows you how to make an XML model binder. https://lostechies.com/jimmybogard/2011/06/24/model-binding-xml-in-asp-net-mvc-3/
EDIT:
Something a little more pointed I just found is http://docs.asp.net/en/latest/mvc/models/model-binding.html which talks about a Microsoft.AspNet.Mvc.Formatters.Xml nuget package. That is probably your best bet.

Can't access web service methods, but can access the MethodNameCompletedEventArgs and MethodNameCompletedEventHandler

This is my first time dealing with making my own web service, and I made a basic one, which I am currently only needing to access locally:
using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Web;
using System.Web.Services;
using System.Xml;
namespace WebService1
{
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.ComponentModel.ToolboxItem(false)]
public class Service1 : System.Web.Services.WebService
{
#region Temp Conversion
[WebMethod]
public string F2C(int f)
{
double c = 5.0 / 9.0 * (f - 32);
return c.ToString();
}
}
}
This works when I run this and run the method through the browser. However I've added it to another project, a windows form application, via "Add Service Reference" < Advanced
But now within the project when I try to access the methods they don't show.
I do:
MyWebService.
I named the referenced service "MyWebService", and all thats available is:
F2CCompletedEventHandler
F2CCompletedEventArgs
Service1
as opposed to
MyWebService.F2C
On its own being available right away.
you need to create an Instance of the myWebService object can you show the code where you are consuming / creating the proxy and or instance..? sounds like you need to use fully qualified name in regards to the namespace + the class name
Example:
MyWebService.Service1 myService = new MyWebService.Service1();
to call the method do the following
myService.F2C(15); // for example

Error in owin startup class visual studio 2012

I am new to signal r and I am trying to create a basic chat application in c# visual studio 2012 but i am getting following error.
The following errors occurred while attempting to load the app.
- No assembly found containing an OwinStartupAttribute.
- The discovered startup type 'SignalRTutorials.Startup, SignalRTutorials, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null'
conflicts with the type 'Microsoft.VisualStudio.Web.PageInspector.Runtime.Startup, Microsoft.VisualStudio.Web.PageInspector.Runtime, Version=1.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a'.
Remove or rename one of the types, or reference the desired type directly.
To disable OWIN startup discovery, add the appSetting owin:AutomaticAppStartup with a value of "false" in your web.config.
To specify the OWIN startup Assembly, Class, or Method, add the appSetting owin:AppStartup with the fully qualified startup class or configuration method name in your web.config.
I have created 3 files:
1) first is Letschat.cs class as:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Microsoft.AspNet.SignalR;
using Microsoft.AspNet.SignalR.Hubs;
namespace SignalRTutorials
{
[HubName("myChatHub")]
public class LetsChat:Hub
{
public void send(string message)
{
Clients.All.addMessage(message);
}
}
}
2) second file chat.aspx as
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="Chat.aspx.cs" Inherits="SignalRTutorials.Chat" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<script src="Scripts/jquery-1.6.4.min.js"></script>
<script src="Scripts/jquery-1.6.4-vsdoc.js"></script>
<script src="Scripts/jquery-1.6.4.min.js"></script>
<script src="Scripts/jquery.signalR-2.0.0.js"></script>
<script src="Scripts/jquery.signalR-2.0.0.min.js"></script>
</head>
<body>
<form id="form1" runat="server">
<script type="text/javascript">
$(function()
{
var IWannaChat=$.connection.myChatHub;
IWannaChat.client.addMessage=function(message){
$('#listMessages').append('<li>'+message+'</li>');
};
$("#SendMessage").click(function(){
IWannaChat.server.send($('#txtMessage').val());
});
$.connection.hub.start();
});
</script>
<div>
<input type="text" id="txtMessage" />
<input type="text" id="SendMessage" value="broadcast" />
<ul id="listMessages">
</ul>
</div>
</form>
</body>
</html>
3) class Named as Startup.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Threading.Tasks;
using System.Web;
using System.Web.Routing;
using Microsoft.AspNet.SignalR;
using Microsoft.Owin.Security;
using Owin;
namespace SignalRTutorials
{
public class Startup
{
public void Configuration(IAppBuilder app)
{
app.MapSignalR();
}
}
}
I dont know where i am doing wrong any help in this regard will be appreciated.
Was facing the same problem.
Tried adding assembly level attribute, as suggested by #Praburaj
You can try the following.
using Microsoft.AspNet.SignalR;
using Microsoft.Owin.Security;
using Owin;
//add the attribute here
[assembly: OwinStartup(typeof(SignalRTutorials.Startup))]
namespace SignalRTutorials
{
public class Startup
{
public void Configuration(IAppBuilder app)
{
app.MapSignalR();
}
}
}
I had the same problem but on Visual Studio 2013.
Removing the \bin and \obj folders on my project then rebuilding it fixed the problem.
You just need to add OWIN StartUp class [i.e. StartUp1.cs] into your project.
using System;
using System.Threading.Tasks;
using Microsoft.Owin;
using Owin;
[assembly: OwinStartup(typeof(UserInterfaceLayer.Hubs.Startup))]
namespace UserInterfaceLayer.Hubs
{
public class Startup
{
public void Configuration(IAppBuilder app)
{
app.MapSignalR();
}
}
}
If you have built your project, and then renamed it, this issue might occur. Try delete all the files in the bin folder and then run your project. This worked for me.
Just add this line
[assembly: OwinStartup(typeof(SignalRTutorials.Hubs.Startup))] as described here
http://yazilimsozluk.com/no-assembly-found-containing-an-owinstartupattribute

WCF Service- Does not implement interface member

I am following a guide on how to add authorization in a WCF service located here.
Now my problem is when I create the service and remove the .DoWork() method from it, I get an error that says:
'Testing.HelloService' does not implement interface member 'Testing.IHelloService.DoWork()
This is obviously because I removed it, but is it needed? In the guide it basically said to remove the .DoWork() method from it, so I am geussing the person who wrote it missed something.
When I create it service it adds the HelloService and IHelloService files to the project. Do I need to add changes to IHelloService?
Here is the code in HelloService.svc.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;
using System.Web;
using System.ServiceModel.Activation;
namespace MLA_Test_Service
{
// NOTE: You can use the "Rename" command on the "Refactor" menu to change the class name "HelloService" in code, svc and config file together.
[AspNetCompatibilityRequirements(
RequirementsMode = AspNetCompatibilityRequirementsMode.Required)]
public class HelloService : IHelloService
{
public string HelloWorld()
{
if (HttpContext.Current.User.Identity.IsAuthenticated)
return HttpContext.Current.User.Identity.Name;
else
return "Unauthenticated Person";
}
}
}
Here is the code from IHelloService.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;
namespace MLA_Test_Service
{
// NOTE: You can use the "Rename" command on the "Refactor" menu to change the interface name "IHelloService" in both code and config file together.
[ServiceContract]
public interface IHelloService
{
[OperationContract]
void DoWork();
}
}
Your implementation needs to match your interface. If you don't want to implement the DoWork method, it needs to go from the implementation and the Interface.
In fact, you probably should just replace DoWork with the name of the method you actually want to invoke on the service and implement that method instead. It's supposed to serve as an example of how to initiate an operation on the WCF service.
its simple C#, you are inheriting an interface, you must implement all the declared methods of it in the class.
DoWork() exists in your Interface, hence implement it in your HelloService class.
Moreover, only those methods will be visible to your WCF-Service client, which will be declared in OperationContract i.e. the Interface and is marked [OperationContract]

WCF Newbie Question: Calling Methods from JavaScript

Greetings!
I'm new to WCF and I thought it would be similar to ASP.NET web services, but I'm unable to call a method from client-side JavaScript. My web form looks like this:
<form id="form1" runat="server">
<div>
<asp:ScriptManager ID="ScriptManager1" runat="server">
<Scripts>
<asp:ScriptReference Path="~/test.js" />
</Scripts>
<Services>
<asp:ServiceReference Path="~/MyService.svc" />
</Services>
</asp:ScriptManager>
</div>
<button onclick="test()">Click Me</button>
</form>
My service's interface looks like this:
namespace Test
{
[ServiceContract(Namespace = "Test")]
public interface IMyService
{
[OperationContract]
void DoWork();
[OperationContract]
string SayHi();
}
}
And here's its implementation:
namespace Test
{
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
public class MyService : IMyService
{
public void DoWork()
{
}
public string SayHi()
{
return "Hello, World!";
}
}
}
And finally the JavaScript:
function test() {
Test.MyService.SayHi(SayHiSuccess, SayHiError);
}
function SayHiSuccess(result) {
alert(result[0]);
}
function SayHiError(error) {
alert(error.toString());
}
It appears that the service's SayHi() method never executes, although I'm not sure why or how to being troubleshooting. Any suggestions?
You didn't post your web.config contents. What binding are you using? You should probably be using webHttpBinding.
Also, it may help to know your .svc file contents. Although I've never tried it, I understand that you don't have to modify web.config at all if you use WebScriptServiceHostFactory as your service host factory. That's as simple as modifying your .svc file as follows:
<%# ServiceHost Service="MyService"
Factory="System.ServiceModel.Activation.WebScriptServiceHostFactory"
%>
If all else fails, here are some resources for you:
Calling WCF Service from Javascript
Create a Simple WCF Web...
Your code looks OK. Should be working by right. You could try adding the WebService and the WebMethod attributes as well.
For debugging a WCF web service I normally use Fiddler to track HTTP calls while running the WCF code with a debugger attached (run in Visual Studio in most cases).

Categories