I am trying to connect from xamarin android emulator to my Visual Studio(2015) Wcf service but I'am getting (Connection refused) and 400 http badrequest
NOTE : I dont create web service to my localhost I am starting up from vs 2015.
public Service1() {
this.Url = "http://10.0.2.2:2486/Service1.svc";
if ((this.IsLocalFileSystemWebService(this.Url) == true)) {
this.UseDefaultCredentials = true;
this.useDefaultCredentialsSetExplicitly = false;
}
else {
this.useDefaultCredentialsSetExplicitly = true;
}
}
// From my android application
` TrackingService.Service1 client=new Service1();
var id = Android.OS.Build.Serial;
client.IamOnBoard(id, "password");`
My WCF :
[ServiceContract]
public interface IService1
{
[OperationContract]
void IamOnBoard(string id,string pass);
}
Related
I have a WCF Service written in Visual Studio 2015 (c#) that uses web sockets, this means the endpoint is configured with netHTTPBindings. I have a Delphi application that I have currently written in XE and would like to consume the WCF Service, what is the best way for a Delphi application to consume a web socket WCF Service?
// Edit ---------------------------------------------------------------------------
I am now using wsDualHttpBindings, here is some prototype code:
WCF Service interface
[ServiceContract(CallbackContract = typeof(IStatusCallback))]
public interface IStatusService
{
[OperationContract(IsOneWay = true)]
Task StartSendingStatus();
}
[ServiceContract]
public interface IStatusCallback
{
[OperationContract(IsOneWay = true)]
Task SendStatus(string aValue);
}
Implementation
public class StatusService : IStatusService
{
public async Task StartSendingStatus()
{
var callback = OperationContext.Current.GetCallbackChannel<IStatusCallback>();
while (((IChannel)callback).State == CommunicationState.Opened)
{
await callback.SendStatus(GetStatus());
await Task.Delay(1000);
}
}
private string GetStatus()
{
// For now return datetime
string dt = DateTime.UtcNow.ToString();
return Convert.ToString(dt);
}
}
Here is how I consume it in a C# application, I put the result into list box.
public partial class ClientForm : Form
{
private StatusServiceReference.StatusServiceClient StatusService;
private class CallbackHandler : StatusServiceReference.IStatusServiceCallback
{
private ListBox _listbox;
public CallbackHandler(ListBox aListBox)
{
_listbox = aListBox;
}
public void SendStatus(string aValue)
{
_listbox.Items.Add(aValue);
_listbox.SelectedIndex = _listbox.Items.Count - 1;
}
}
public ClientForm()
{
InitializeComponent();
var context = new InstanceContext(new CallbackHandler(StatusListBox));
StatusService = new StatusServiceReference.StatusServiceClient(context);
}
private void StatusBtn_Click(object sender, EventArgs e)
{
StatusService.StartSendingStatus();
}
}
This works fine, I would like to know the best way to do the above client code in Delphi. When I import the WSDL file it does not have the IStatusServiceCallback interface.
My Scenerio is that i need a SignalR self Hosted WCF Service that response and sends message to all connected users that came from Winform or WPF.
I have tried alot as follows:
I have Created WCF service with SignalR Self Hosting code as below which contains 3 Classes and 1 Interface.
namespace SignalRServiceClass
{
[ServiceContract]
public interface ISignalRServiceClass
{
[OperationContract]
string GetsMessage(string name);
[OperationContract]
void Configuration(IAppBuilder app);
[OperationContract]
void Send(string name, string message);
}
}
namespace SignalRServiceClass
{
public class SignalRServiceClass : ISignalRServiceClass
{
public string GetsMessage(string name)
{
return "Message From Service " + name + "!";
}
}
}
namespace SignalRServiceClass
{
class ClassHub : Hub
{
public void Send(string name, string message)
{
Clients.All.addMessage(name, message);
}
}
}
namespace SignalRServiceClass
{
class Startup
{
public void Configuration(IAppBuilder app)
{
// app.UseCors(CorsOptions.AllowAll);
// app.MapSignalR();
app.Map("/signalr", map =>
{
map.UseCors(CorsOptions.AllowAll);
var hubConfiguration= new HubConfiguration
{
EnableDetailedErrors=true,
EnableJSONP= true
};
map.RunSignalR(hubConfiguration);
});
}
}
}
And Secondly Winform Client. I am confused here that how to manage the client code here but i put some code for testing as below.
private void button1_Click(object sender, EventArgs e)
{
//MessageBox.Show(test.GetsMessage("This is the Test Message"));
var hubConnection = new HubConnection("http://localhost:50172/");
var serverHub = hubConnection.CreateHubProxy("MessageRecievingHub");
serverHub.On("broadCastToClients", message => MessageBox.Show(message));
hubConnection.Start().Wait();
}
Please guide me in this manner.
Your Help will be appreciated. I have tried and googled alot but in vain.
Thanks alot in Advance.
You do not want SignalR, you need XSockets WCF sample
SignalR and WCF don't interoperate in this way, and don't really need to. If you're using SignalR, there's no reason to use WCF- you can publish your hub on IIS or self-hosted (see the Getting Started tutorial and the Self-Host tutorial at asp.net/signalr), and connect to it with desktop or JavaScript/HTML clients.
You can easily create a .NET client application to communicate with your SignalR server - below is a simple WinForm .NET C# client that sends and receives a SignalR message:
namespace SignalrTestClient
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
async void Form1_Load(object sender, EventArgs e)
{
var hubConnection = new HubConnection("http://localhost:8080/");
IHubProxy hubProxy = hubConnection.CreateHubProxy("MyHub");
await hubConnection.Start();
hubProxy.On("addMessage", message => onData(message));
await hubProxy.Invoke("Send", "Hello SignalR Server!");
}
private void onData(string msg)
{
Console.WriteLine(msg);
}
}
}
In your SignalR server you just need the following hub class:
public class MyHub : Hub
{
public void Send(string message)
{
Console.WriteLine("Received a message from a client");
if (message.Contains("Hello")) {
Clients.All.addMessage("Well hello there client!");
}
}
}
It is also possible to create a C++ client for SignalR
I'm having a problem with a self-host WCF REST service.
When I try to issue a GET via browser or Fiddler, I get a 400 Bad Request. Tracing is reporting an inner exception of XmlException "The body of the message cannot be read because it is empty."
I don't have any configuration in app.config (do I need any?). I have tried changing WebServiceHost to ServiceHost, and WSDL is returned, but the operations still return 400.
What am I missing here?
// Add Reference to System.ServiceModel and System.ServiceModel.Web
using System;
using System.Diagnostics;
using System.ServiceModel;
using System.ServiceModel.Description;
using System.ServiceModel.Web;
namespace WCFRESTTest
{
class Program
{
static void Main(string[] args)
{
var baseAddress = new Uri("http://localhost:8000/");
var host = new WebServiceHost(typeof(RestService), baseAddress);
try
{
host.AddServiceEndpoint(typeof(IRestService), new WSHttpBinding(), "RestService");
var smb = new ServiceMetadataBehavior();
smb.HttpGetEnabled = true;
host.Description.Behaviors.Add(smb);
host.Open();
Console.WriteLine("Service Running. Press any key to stop.");
Console.ReadKey();
}
catch(CommunicationException ce)
{
host.Abort();
throw;
}
}
}
[ServiceContract]
public interface IRestService
{
[OperationContract]
[WebGet(UriTemplate = "Test")]
bool Test();
}
[ServiceBehavior(InstanceContextMode = InstanceContextMode.Single)]
public class RestService : IRestService
{
public bool Test()
{
Debug.WriteLine("Test Called.");
return true;
}
}
}
When you use the WebServiceHost, you typically don't need to add a service endpoint - it will add one with all behaviors required to make it a "Web HTTP" (a.k.a. REST) endpoint (i.e., an endpoint which doesn't use SOAP and you can easily consume with a tool such as Fiddler, which seems to be what you want). Also, Web HTTP endpoints aren't exposed in the WSDL, so you don't need to add the ServiceMetadataBehavior either.
Now for why it doesn't work - sending a GET request to http://localhost:8000/Test should work - and in the code below it does. Try running this code, and sending the request you were sending before with Fiddler, to see the difference. That should point out what the issue you have.
public class StackOverflow_15705744
{
[ServiceContract]
public interface IRestService
{
[OperationContract]
[WebGet(UriTemplate = "Test")]
bool Test();
}
[ServiceBehavior(InstanceContextMode = InstanceContextMode.Single)]
public class RestService : IRestService
{
public bool Test()
{
Debug.WriteLine("Test Called.");
return true;
}
}
public static void Test()
{
var baseAddress = new Uri("http://localhost:8000/");
var host = new WebServiceHost(typeof(RestService), baseAddress);
// host.AddServiceEndpoint(typeof(IRestService), new WSHttpBinding(), "RestService");
// var smb = new ServiceMetadataBehavior();
// smb.HttpGetEnabled = true;
// host.Description.Behaviors.Add(smb);
host.Open();
WebClient c = new WebClient();
Console.WriteLine(c.DownloadString(baseAddress.ToString().TrimEnd('/') + "/Test"));
Console.WriteLine("Service Running. Press any key to stop.");
Console.ReadKey();
}
}
i create a small wcf apps when i am testing this apps in my machine then it is working but when i run the wcf server end on another pc at my home in same network then i am getting error
A remote side security requirement was not fulfilled during authentication.Try increasing the ProtectionLevel and/or ImpersonationLevel.
both the pc at my home in same work group and they can access each other. i try to find out the answer but people say this is firewall issue. so i disable firewall at both the pc but still getting the problem. here is my sample code. please guide me how can i run this wcf apps in two pc at my home network. thanks
Service end
namespace WCFSample
{
[ServiceContract]
public interface IService1
{
[OperationContract]
string MyName(string name);
}
}
namespace WCFSample
{
public class Service1 : IService1
{
public string MyName(string name)
{
return string.Format("My Name... {0}", name);
}
}
}
namespace ConsoleApplication1
{
class Program
{
static ServiceHost customerHost = null;
static void Main(string[] args)
{
try
{
HostCustomerService();
Console.WriteLine();
Console.WriteLine("Press any key to stop the services.");
Console.ReadKey();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
finally
{
customerHost.Close();
}
}
private static void HostCustomerService()
{
customerHost = new ServiceHost(typeof
(Service1));
ServiceEndpoint tcpEndpoint = customerHost.AddServiceEndpoint(
typeof(IService1), new NetTcpBinding(),
"net.tcp://192.168.1.103:9020/Service1");
customerHost.Open();
Console.WriteLine("{0} {1}", tcpEndpoint.Address, tcpEndpoint.Name);
Console.WriteLine();
}
}
}
client end
namespace Client1
{
class Program
{
static void Main(string[] args)
{
IService1 channel = null;
var endPoint = new EndpointAddress(
"net.tcp://192.168.1.103:9020/Service1");
channel = ChannelFactory<IService1>.CreateChannel(new NetTcpBinding(), endPoint);
Console.WriteLine("Enter Name");
string line = Console.ReadLine();
Console.WriteLine(channel.MyName(line));
Console.ReadKey();
}
}
}
I think by default, NetTcpBinding requires a secure channel.
When you create your binding (on client and server), instead of:
new NetTcpBinding()
Try:
new NetTcpBinding(SecurityMode.None)
I have an WCF Data Service in .NET and I am consuming this service with datajs in Phonegap. I am trying to implement authentication as decribed here: http://goo.gl/0xQvC, and sending credentials with OData.read method. When I read credentials in the service with HttpContext.Current.Request.Headers["Authorization"], I found they are empty. What I am doing wrong?
Service Code:
[ServiceBehavior( IncludeExceptionDetailInFaults = true )]
public class TeyunaDataService : DataService< Meteora.TeyunaServices.Models.TeyunaContext >
{
public static void InitializeService(DataServiceConfiguration config)
{
config.SetEntitySetAccessRule("Clientes", EntitySetRights.AllRead );
config.SetEntitySetAccessRule("Transacciones", EntitySetRights.All);
config.DataServiceBehavior.MaxProtocolVersion = DataServiceProtocolVersion.V2;
config.UseVerboseErrors = true;
}
public TeyunaDataService()
{
this.ProcessingPipeline.ProcessingRequest += new EventHandler<DataServiceProcessingPipelineEventArgs>(OnRequest);
}
void OnRequest(object sender, DataServiceProcessingPipelineEventArgs e)
{
var auth = HttpContext.Current.Request.Headers["Authorization"]; //This is empty
}
}
}
Javascript Client code:
OData.read({ requestUri: url, user: "pruebausr", password: "passprb" },
function (data, request) {
// ... code to procesing data (It works fine)
}, function(err) {
$.mobile.hidePageLoadingMsg();
alert("Error al obtener clientes. " + err.message);
}
);
Service web.config here: https://gist.github.com/3746043
I am using:
WCF Data Services 5.
IIS Express.