WCF start failure message box - wcf

I have a WCF project using C#, Visual Studio. When i want to start my project in debug mode i have this error: "Cannot start service from the command line or debugger. ...". I shouln't install my service using installutil program.
In my code i have a wrapper for starting program in debug mode to prevent this error:
#if DEBUG
MyService service = new MyService();
service.MyMethod();
#else
ServiceBase[] services;
services= new ServiceBase[]
{
new MyService()
};
ServiceBase.Run(services);
#endif
But error is still there. It appears before going inside to the method MyMethod() [F11]

In my opinion, please make sure that the account running the window service has the required permissions, preferably using localsystem, which could be configured in the ServcieProcessInstaller.
If the service needs to interact with the database, you can use a specific user to run the service so that the service can properly connect to the database.
Feel free to let me know if the problem still exists.

Related

Topshelf Windows Service times out Error 7000 7009

I have a windows service programmed in vb.NET, using Topshelf as Service Host.
Once in a while the service doesn't start. On the event log, the SCM writes errors 7000 and 7009 (service did not respond in a timely fashion). I know this is a common issue, but I (think) I have tried everything with no result.
The service only relies in WMI, and has no time-consuming operations.
I read this question (Error 1053: the service did not respond to the start or control request in a timely fashion), but none of the answers worked for me.
I Tried:
Set topshelf's start timeout.
Request additional time in the first line of "OnStart" method.
Set a periodic timer wich request additional time to the SCM.
Remove TopShelf and make the service with the Visual Studio Service Template.
Move the initialization code and "OnStart" code to a new thread to return inmediately.
Build in RELEASE mode.
Set GeneratePublisherEvidence = false in the app.config file (per application).
Unchecked "Check for publisher’s certificate revocation" in the internet settings (per machine).
Deleted all Alternate Streams (in case some dll was marked as web and blocked).
Removed any "Debug code"
Increased Window's general service timeout to 120000ms.
Also:
The service doesn't try to communicate with the user's desktop in any way.
The UAC is disabled.
The Service Runs on LOCAL SYSTEM ACCOUNT.
I believe that the code of the service itself is not the problem because:
It has been on production for over two years.
Usually the service starts fine.
There is no exception logged in the Event Log.
The "On Error" options for the service dosn't get called (since the service doesn't actually fails, just doesn't respond to the SCM)
I've commented out almost everything on it, pursuing this error! ;-)
Any help is welcome since i'm completely out of ideas, and i've been strugling with this for over 15 days...
For me the 7009 error was produced by my NET core app because I was using this construct:
var builder = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json");
and appsettings.json file obviously couldn't be found in C:\WINDOWS\system32.. anyway, changing it to Path.Combine(AppContext.BaseDirectory, "appsettings.json") solved the issue.
More general help - for Topshelf you can add custom exception handling where I finally found some meaningfull error info, unlike event viewer:
HostFactory.Run(x => {
...
x.OnException(e =>
{
using (var fs = new StreamWriter(#"C:\log.txt"))
{
fs.WriteLine(e.ToString());
}
});
});
I've hit the 7000 and 7009 issue, which fails straight away (even though the error message says A timeout was reached (30000 milliseconds)) because of misconfiguration between TopShelf and what the service gets installed as.
The bottom line - what you pass in HostConfigurator.SetServiceName(name) needs to match exactly the SERVICE_NAME of the Windows service which gets installed.
If they don't match it'll fail straight away and you get the two event log messages.
I had this start happening to a service after Windows Creator's Edition update installed. Basically it made the whole computer slower, which is what I think triggered the problem. Even one of the Windows services had a timeout issue.
What I learned online is that the constructor for the service needs to be fast, but OnStart has more leeway with the SCM. My service had a C# wrapper and it included an InitializeComponent() that was called in the constructor. I moved that call to OnStart and the problem went away.

How to run a WCF project locally?

I am trying to debug a WCF project. So can someone tell me a simple way to run this WCF project locally?
I loaded it in Visual Studio and when I tell it to run it says "A project of Output Type Class Library cannot be started." or something like that.
From there I come here, because I've exhausted my knowledge of WCF. Any answers may need to be severely "dumbed down".
This error simply means you have not set any start up project for WCF project. Try to set service host project as start up project if there is any. If you dont have any of them try to make service host project locally and add a reference to that project in your service host project.
A simple console hosting project will look like this
using System.ServiceModel;
namespace WcfDemoHost
{
class Program
{
static void Main(string[] args)
{
try
{
ServiceHost svchost = new ServiceHost(typeof(yourServiceClassNameHere));
svchost.Open();
Console.WriteLine("Service Started");
Console.ReadLine();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
}
}
there are also several method for hosting WCF services locally like hosting in Windows service, IIS, Console, in windows form etc.You also need to add App.config file for configuring your service like service endpoint and many things. I am providing you some youtube tutorial link that will help you a lot in understanding WCF. I hope this tutorial will help you a lot.
https://www.youtube.com/watch?v=QmfPmqMk9Xs&list=PL6n9fhu94yhVxEyaRMaMN_-qnDdNVGsL1
Go from part 3 and for hosting follow tutorial 24-30.
Rajput's answer may work, but another developer here showed me an easier way (for me). Our WCF project already has a hosting class (I did not know this). He showed me to set that as the startup project and then start the project. Then a browser window opens. I copy the URL that appears in that browser and paste that URL into the web.config endpoint settings like this:
<endpoint address="http://localhost:44798/ControlService.svc ...
Now I can step into the running code in the WCF project.
Set your WCF Service as Set As Startup Project and RUN project.
For testing, best way to check your methods through Postman tool instead of creating client for your WCF Service. You just need to take service URL like "http://localhost:35710/yourservicename.svc" after running your project and use in Postman.

WCF NetNamedPipeBinding TimeoutException on Windows Server 2008

I have a problem with WCF NetNamedPipeBinding. When I run my server and client code through Visual Studio 2008 on a Windows XP machine everything works fine. But as soon as I deploy my server as a Windows Service and install my client app in Windows Server 2008 I get a TimeoutException on the client end whenever I try to use any of the contract methods. It seems that I can successfully create the client and open it, but can't call any of the methods.
Service initialisation code:
Uri baseAddress = new Uri("http://localhost:8500/xNet/xNetService");
string address = "net.pipe://localhost/xNet/xNetService";
_xNetAPIServiceHost = new ServiceHost(typeof(xNetService), baseAddress);
NetNamedPipeBinding binding = new NetNamedPipeBinding(NetNamedPipeSecurityMode.None);
_xNetAPIServiceHost.AddServiceEndpoint(typeof(IServiceAPI), binding, address);
// Add a mex endpoint
ServiceMetadataBehavior smb = new ServiceMetadataBehavior();
smb.HttpGetEnabled = true;
smb.HttpGetUrl = new Uri("http://localhost:8501/xNet/xNetService/mex");
_xNetAPIServiceHost.Description.Behaviors.Add(smb);
_xNetAPIServiceHost.Open();
Client initialisation code:
string address = "net.pipe://localhost/xNet/xNetService";
NetNamedPipeBinding binding = new NetNamedPipeBinding(NetNamedPipeSecurityMode.None);
_serviceClient = new ServiceAPIClient(binding, new EndpointAddress(address));
_serviceClient.Open();
The Windows service runs as "Local System Account". I'm at a loss as to what the problem is. I don't know if it's a security account problem, or if the named pipe is even open? I would assume since I can successfully create and open the client side it would appear it at least found the named pipe. I just can't call any of the service methods without a TimeoutException.
After trying out various bindings and going back to basics I noticed that the sample programs worked, but mine didn't work unless I was using Visual Studio to debug. I decided at that point that it must be something going on with my own code. To simplify debugging I turned off all security in the binding.
I started commenting out most of the statements in my service's OnStart method in order to determine what could be going on. I commented out everything except for the code that initialises the ServiceHost. Magically, my client could now successfully communicate with the service. I then started uncommenting each line of code in the OnStart method until my client suddenly started giving me a TimeoutException again.
My service class, say "MyAPI", implements the contract "IMyAPI". As well as using "MyAPI" class as the WCF service, I was also using an instance of the "MyAPI" class internally in my service to do various things ("internal" methods). In my OnStart method I first created an instance of the "MyAPI" class and then created the ServiceHost:
MyAPI API = new MyAPI();
ServiceHost service = new ServiceHost(typeof(MyAPI));
I was not getting any errors or exceptions, so it appeared everything is fine, but really I couldn't connect to the service using a client. As soon as I changed the order of the above statements, the client started working again:
ServiceHost service = new ServiceHost(typeof(MyAPI));
MyAPI API = new MyAPI();
I'm not sure WHY this is occuring, all I know is that I can use my API internally and as a service without any client connection issues. Maybe someone out there will provide some light on the reasons behind this, or maybe my code is not properly designed.

WCF service operations not updated

I´m creating a new WCF service. I initially had only three operations. But after some time I decided to add two more. This operations doesn't appear in the Microsoft test client, neither in the list of operations when I try to add a service reference from my WPF client. Also I tried to comment one of the initial operations. It still apears in the Microsoft test client and can be invoked. I Tried also delete the dlls generated by the service and regenerate again. No luck. There are some kind of "cache" where Visual Studio stores the WCF services libraries that I can delete?
UPDATE: I'm working with the service running in the ASP.NET devolopment server.
You need to understand the order in which things happen.
You change your code, adding methods with [OperationContract] on them, or removing them, or changing their parameters or return values.
You then must build your service, producing a .DLL that contains the changes.
You must then deploy the changed DLL to the server it's going to run on
You must then restart the service (this may happen automatically depending on the server. For instance, IIS will recycle the service when it sees that the DLL changed)
You must then update your client, either the WCF Test Client, or "Add Service Reference", or the equivalent.
This last will have the effect of sending a request to the service for the new metadata or WSDL. Only then can the client see the changes you made to the definition of the service.
I don't know why, but I created a new project and copied the definitions of the operations from the problematic project and the problem is gone. One case more for Microsoft mysteries.
Make sure you are updating the services after adding the new operations.
Also make sure they have the attribute [OperationContract].
One thing we have discovered is that when you deploy the dlls that they must be in the bin, and cannot reside in the debug or release folder.
For me worked: just rebuild the wcf project
Did you close the client connection in client side
as showing your service
class Test
{
static void Main()
{
LocationClient client = new LocationClient();
// Use the 'client' variable to call operations on the service.
// Always close the client.
client.Close();
}
}
SOLUTION HERE :
Make sure your dataContract does NOT contain any enum
(You can use integer instead)
Be sure to reference a project in the solution and not a dll on your disk
Remove your "bin" and "obj" folders
Recompile
In IIS recycle the application pool
In IIS restart your service
In IIS "Browse" your service
=> You got it

Unable to debug web service project in Visual Studio 2008

I've been assigned a web app written in VB using VStudio.net 2003. I am trying to configure the source on my localhost (VStudio 2008) so I can explore and learn about the current app (before I begin any real changes) and I cannot get debugging working for the web service project(s).
Symptom 1:
"Unable to automatically step into the server. The remote procedure could not be debugged.
This usually indicates that debugging has not been enabled on the server.
See help for more information".
This happens when I try to F11 (stepInto) the proxy class which invokes my actual web method.
Symptom 2: Pre-setting a breakpoint in my .asmx file code on the statement that will be invoked does not work (i.e. the debugger simply doesn't stop).
Having described the situation, here's how my VStudio Solution is configured:
Service1 - project created from the VB - WEB - ASP.NET Web Service Application template; this Service1 project contains my main .asmx source code I want to debug. Web.config for this project contains compilation defaultLanguage="vb" debug="true"
ProxyService1 - a separate project created from the Windows - [VB]Class Library template; here the form1.vb file was deleted; I visited "Add Service Reference" -> Discover (Services in solution) and then in the "Compatibility" section I click "Add Web Reference". Then choosing the above Service1, I assign it a "web reference name" of WSservice1. This results in a Reference.VB file and when I build the ProxyService1 class a .DLL of the same name in the projects bin\Debug folder; this project has an App.Config file with compilation defaultLanguage="vb" debug="true"
Project1 - the main UI project with the .aspx and .vb files that call the webservice; project1 has a reference to ProxyService1.DLL; Web.config for this project contains compilation defaultLanguage="vb" debug="true". I arrive at a breakpoint in one of the files in this project called message.vb which looks roughly like this:
Public Class Message
Dim wsZipeee As New ProxyService1.WSservice1.myService
Dim dsMessage As DataSet
Public Function GetMessageByType(ByVal iMsgType As Integer) As DataSet
dsMessage = wsZipeee.GetMessageByType(iMsgType)
If I rightmouse/go to definition on the stmt above, here is the code in Reference.vb in my ProxyService1 project:
<System.Web.Services.Protocols.SoapDocumentMethodAttribute("http://tempuri.org/ZipeeeWebService/Zipeee/Get Message By Type", RequestElementName:="Get Message By Type", RequestNamespace:="http://tempuri.org/ZipeeeWebService/Zipeee", ResponseElementName:="Get Message By TypeResponse", ResponseNamespace:="http://tempuri.org/ZipeeeWebService/Zipeee", Use:=System.Web.Services.Description.SoapBindingUse.Literal, ParameterStyle:=System.Web.Services.Protocols.SoapParameterStyle.Wrapped)> _
Public Function GetMessageByType(ByVal iMsgType As Integer) As <System.Xml.Serialization.XmlElementAttribute("Get Message By TypeResult")> System.Data.DataSet
Dim results() As Object = Me.Invoke("GetMessageByType", New Object() {iMsgType})
Return CType(results(0),System.Data.DataSet)
End Function
For completeness, here is the corresponding webmethod in the .asmx file of the Service1 project:
<WebMethod(MessageName:="Get Message By Type")> _
Public Function GetMessageByType(ByVal iMsgType As Integer) As DataSet
con = New SqlConnection(sConnZipeee)
con.Open()
Everyplace in IIS I know to check and within the project properties I have checked for the proper Debug setting to be checked or set on. I've debugged other things that are set up like this but I am truly stuck on what I've missed on this "solution".
For info - if you have got here looking how to debug a .NET4 web service from VS2008/.NET3.5 app, you need to start the service in VS2010, set a break point in the service and then run your app from VS2008 as normal. The break point will be hit.
Without running the service in VS2010, you will get the error described by John above.
When I debug webservices, I usually select the option "Don't open a page. Wait for a request from an external application" in the Web section of my project properties (more info here). I also usually run the project in 2 instances of VS, one for webservice and one for client. I can put break points in the webservice and everything hits and I can see what is happening.
try to attach debugger on running aspnet_wp.exe process
I normally put of the logic to debug in class library that I can start with a console application for debug. This link will be useful too if you must debug as a service.