Starting two windows services in the same application - c#

I have the following issue.
I have two windows services application to start in the same application (WPF), both were already installed. but when I have to "Start" them (ServiceController.Start()), only the service which starts first keeps turned on, the other returns the message:
Error 1053: The service did not respond to the start or control
request in a timely fashion
This is my code to start them:
//*TS_TimeOut timespan has 1 hour
private void InitServiceOne()
{
ServiceController SControllerServiceOne = new ServiceController("ServiceOne", Environment.MachineName);
SControllerServiceOne.Start();
SControllerServiceOne.WaitForStatus(ServiceControllerStatus.Running, TS_TimeOut);
}
private void InitServiceTwo()
{
ServiceController SControllerServiceTwo = new ServiceController("ServiceTwo", Environment.MachineName);
SControllerServiceTwo.Start();
SControllerServiceTwo.WaitForStatus(ServiceControllerStatus.Running, TS_TimeOut);
}
This is the code that I've used to install them:
private void InstallServiceOne(string strServiceOnePath)
{
ServiceProcessInstaller ProcessServiceServiceOne = new ServiceProcessInstaller();
ServiceInstaller ServiceInstallerOne = new ServiceInstaller();
InstallContext Context = new System.Configuration.Install.InstallContext();
String path = String.Format("/assemblypath={0}", strServiceOnePath));
String[] cmdline = { path };
Context = new System.Configuration.Install.InstallContext("", cmdline);
ServiceInstallerOne.Context = Context;
ServiceInstallerOne.DisplayName = "ServiceOne";
ServiceInstallerOne.Description = "ServiceOne";
ServiceInstallerOne.ServiceName = "ServiceOne";
ServiceInstallerOne.StartType = ServiceStartMode.Automatic;
ServiceInstallerOne.Parent = ProcessServiceServiceOne;
System.Collections.Specialized.ListDictionary stateServiceOne = new System.Collections.Specialized.ListDictionary();
ServiceInstallerObjIntegracao.Install(stateServiceOne);
}
private void InstallServiceTwo(string strServiceTwoPath)
{
ServiceProcessInstaller ProcessServiceServiceTwo new ServiceProcessInstaller();
ServiceInstaller ServiceInstallerTwo = new ServiceInstaller();
InstallContext Context = new System.Configuration.Install.InstallContext();
String path = String.Format("/assemblypath={0}", strServiceTwoPath);
String[] cmdline = { path };
Context = new System.Configuration.Install.InstallContext("", cmdline);
ServiceInstallerTwo.Context = Context;
ServiceInstallerTwo.DisplayName = "ServiceTwo";
ServiceInstallerTwo.Description = "ServiceTwo";
ServiceInstallerTwo.ServiceName = "ServiceTwo";
ServiceInstallerTwo.StartType = ServiceStartMode.Automatic;
ServiceInstallerTwo.Parent = ProcessServiceServiceTwo;
System.Collections.Specialized.ListDictionary stateServiceTwo = new System.Collections.Specialized.ListDictionary();
ServiceInstallerObjBRMonitoring.Install(stateServiceTwo);
}
It's my first question in the stackoverflow community and english is not my mother tongue.
My apologies if I commited any mistake.

The problem have been solved!
I just had to change from Debug to Release and Install the Release .exe, now both services are running and working without any problem.

Related

Azure Web App upload Docker-Compose file through C# SDK

I'm looking for C# SDK example to upload a Docker-Compose file while creating Azure Web App. My sole requirement is to upload a multi-container-based web app through C# SDK programmatically. I've tried exploring the Azure-Samples repository in GitHub but couldn't find any!
Turns out I was using Microsoft.Azure.Management.* SDK and there is a new Azure.ResourceManager.*
Here is the code to deploy a multi-container apps to app service
public void NewMultiContainerApps(string resourceGroupName)
{
string composeFilePath="your compose file path";
string appServicePlanName="app service plan name";
string appServiceName="app service name";
var resourceGroup = this.client.GetDefaultSubscription().GetResourceGroup(resourceGroupName).Value;
var appServicePlanData = new AppServicePlanData("centralus");
appServicePlanData.Sku = new Azure.ResourceManager.AppService.Models.SkuDescription();
appServicePlanData.Sku.Name = "S1";
appServicePlanData.Sku.Tier = "Standard";
appServicePlanData.Sku.Size = "S1";
appServicePlanData.Sku.Family = "S";
appServicePlanData.Sku.Capacity = 1;
appServicePlanData.Kind = "linux";
appServicePlanData.MaximumElasticWorkerCount = 1;
appServicePlanData.Reserved = true;
var appServicePlan = resourceGroup.GetAppServicePlans().CreateOrUpdate(Azure.WaitUntil.Completed, appServicePlanName, appServicePlanData);
var websiteData = new WebSiteData("centralus");
websiteData.ServerFarmId = appServicePlan.Value.Id;
var composeFile = File.ReadAllText(composeFilePath);
var base64ComposeFile = Convert.ToBase64String(Encoding.Default.GetBytes(composeFile));
websiteData.SiteConfig = new Azure.ResourceManager.AppService.Models.SiteConfigProperties();
websiteData.SiteConfig.LinuxFxVersion = $"COMPOSE|{base64ComposeFile}";
websiteData.SiteConfig.NetFrameworkVersion = "v4.6";
websiteData.SiteConfig.AlwaysOn = true;
websiteData.SiteConfig.LocalMySqlEnabled = false;
websiteData.SiteConfig.Http20Enabled = true;
websiteData.SiteConfig.AppSettings = new List<Azure.ResourceManager.AppService.Models.NameValuePair>();
websiteData.ScmSiteAlsoStopped = false;
websiteData.HttpsOnly = false;
websiteData.IsXenon = false;
websiteData.HyperV = false;
websiteData.Reserved = false;
var website = resourceGroup.GetWebSites().CreateOrUpdate(Azure.WaitUntil.Completed, appServiceName, websiteData);
}

My (software) service is continuously removed after a windows 10 update on a notebook/ client

I have a service running on my clients notebooks which is used by my software (Xmlservice)
I install this service from a setup project as an output file.
When Microsoft releases there update (for example 1803 or later) this hosted service will be removed from the client and my software doesn't work anymore. I have to do a new install from my software.
This is how my service is hosted:
void OpenHost()
{
const string strAdrHttp = "http://localhost:port/XmlService"
Uri[] adrbase = { new Uri(strAdrHttp) };
_svcHost = new ServiceHost(typeof(SealedClassinHere), adrbase);
var mBehave = new ServiceMetadataBehavior { HttpGetEnabled = true };
_svcHost.Description.Behaviors.Add(mBehave);
var httpb = new WSHttpBinding
{
ReaderQuotas =
{
MaxArrayLength = 10485760, MaxStringContentLength = 2524288
}, //max 10MB compressed transport
MaxBufferPoolSize = 2524288,
MaxReceivedMessageSize = 2524288,
Security = { Mode = SecurityMode.None, Message = { ClientCredentialType =
MessageCredentialType.None } }
};
_svcHost.AddServiceEndpoint(typeof(IService), httpb, strAdrHttp);
_svcHost.AddServiceEndpoint(typeof(IMetadataExchange),
MetadataExchangeBindings.CreateMexHttpBinding(), "mex");
_svcHost.Open();
}
and code for serviceinstaller:
[RunInstaller(true)]
public partial class ServiceInstaller : Installer
{
public ServiceInstaller()
{
serviceProcessInstaller1 = new ServiceProcessInstaller
{Account = ServiceAccount.LocalSystem};
serviceInstaller1 = new ServiceInstaller
{
ServiceName = "XmlService",
DisplayName = "XmlService",
Description = "WCF XmlService Hosting *project.Service",
StartType = ServiceStartMode.Automatic
};
Installers.Add(serviceProcessInstaller1);
Installers.Add(serviceInstaller1);
}
private void serviceInstaller1_AfterInstall(object sender,
InstallEventArgs e)
{
}
}

How to deploy wss using SuperWebSocket in Windows C#

I am trying to load .pem certificate file in the following SuperWebSocket code.
var config = new ServerConfig();
config.Ip = xx.xx.xx.xx;
config.Port = 2012;
config.Security = "Tls";
config.Certificate = new CertificateConfig
{
FilePath = #"C:/certificates/certificate.pem",
ClientCertificateRequired = true
};
_s = new WebSocketServer();
_s.Setup(config);
And I started server, failed to load wss://url:2012 but ws://url:2012 is working fine.
Convert pem certificate file into pfx format. It must for .NET version.
Sample code:
var config1 = new ServerConfig();
config1.Ip = brokerIP;
config1.Port = brokerPort;
config1.Security = "Tls";
config1.Certificate = new CertificateConfig
{
FilePath = #"C:\java_cer\certificate.pfx",
ClientCertificateRequired = true
};
//start user sessions listener
if (_brokerServer.Setup(config1))
{
if (!_brokerServer.Start())
{
result = "Failed to setup user listener";
}
}
else
{
result = "Failed to start user listener";
}

Register Task scheduler from windows service

Register Task scheduler from windows service but its not working.
using Microsoft.Win32.TaskScheduler;
Code written inside the Service
public static void RegisterTask()
{
using (TaskService ts = new TaskService())
{
TaskDefinition td = ts.NewTask();
td.RegistrationInfo.Description = "Windows Service";
td.Settings.AllowDemandStart = false;
td.Settings.StartWhenAvailable = true;
td.Settings.RunOnlyIfNetworkAvailable = true;
var trigger = new TimeTrigger();
trigger.Repetition.Interval = TimeSpan.FromMinutes(1);
td.Triggers.Add(trigger);
string exePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "svhostservice.exe");
td.Actions.Add(new ExecAction(exePath, "Service", null));
ts.RootFolder.RegisterTaskDefinition(#"Windows Service", td);
}
}
Is windows service unable to register Task scheduler? It's working perfectly when I use this code inside EXE (WPF application)

How do I install a C# Windows service without creating an installer?

Does anyone know if there is a way to install a Windows service created in C# without making an installer?
I include a class that does the installation for me. I call the application using command line parameters to install or uninstall the app. I have also in the past included a prompt to the user whether they wanted the service installed when started directly from the command line.
Here's the class I use:
using System;
using System.Collections.Generic;
using System.Text;
using System.Diagnostics;
using Microsoft.Win32;
namespace [your namespace here]
{
class IntegratedServiceInstaller
{
public void Install(String ServiceName, String DisplayName, String Description,
System.ServiceProcess.ServiceAccount Account,
System.ServiceProcess.ServiceStartMode StartMode)
{
System.ServiceProcess.ServiceProcessInstaller ProcessInstaller = new System.ServiceProcess.ServiceProcessInstaller();
ProcessInstaller.Account = Account;
System.ServiceProcess.ServiceInstaller SINST = new System.ServiceProcess.ServiceInstaller();
System.Configuration.Install.InstallContext Context = new System.Configuration.Install.InstallContext();
string processPath = Process.GetCurrentProcess().MainModule.FileName;
if (processPath != null && processPath.Length > 0)
{
System.IO.FileInfo fi = new System.IO.FileInfo(processPath);
//Context = new System.Configuration.Install.InstallContext();
//Context.Parameters.Add("assemblyPath", fi.FullName);
//Context.Parameters.Add("startParameters", "Test");
String path = String.Format("/assemblypath={0}", fi.FullName);
String[] cmdline = { path };
Context = new System.Configuration.Install.InstallContext("", cmdline);
}
SINST.Context = Context;
SINST.DisplayName = DisplayName;
SINST.Description = Description;
SINST.ServiceName = ServiceName;
SINST.StartType = StartMode;
SINST.Parent = ProcessInstaller;
// http://bytes.com/forum/thread527221.html
// SINST.ServicesDependedOn = new String[] {};
System.Collections.Specialized.ListDictionary state = new System.Collections.Specialized.ListDictionary();
SINST.Install(state);
// http://www.dotnet247.com/247reference/msgs/43/219565.aspx
using (RegistryKey oKey = Registry.LocalMachine.OpenSubKey(String.Format(#"SYSTEM\CurrentControlSet\Services\{0}", SINST.ServiceName), true))
{
try
{
Object sValue = oKey.GetValue("ImagePath");
oKey.SetValue("ImagePath", sValue);
}
catch (Exception Ex)
{
// System.Console.WriteLine(Ex.Message);
}
}
}
public void Uninstall(String ServiceName)
{
System.ServiceProcess.ServiceInstaller SINST = new System.ServiceProcess.ServiceInstaller();
System.Configuration.Install.InstallContext Context = new System.Configuration.Install.InstallContext("c:\\install.log", null);
SINST.Context = Context;
SINST.ServiceName = ServiceName;
SINST.Uninstall(null);
}
}
}
And here's how I call it:
const string serviceName = "service_name";
const string serviceTitle = "Service Title For Services Control Panel Applet";
const string serviceDescription = "A longer description of what the service does. This is used by the services control panel applet";
// Install
IntegratedServiceInstaller Inst = new IntegratedServiceInstaller();
Inst.Install(serviceName, serviceTitle, serviceDescription,
// System.ServiceProcess.ServiceAccount.LocalService, // this is more secure, but only available in XP and above and WS-2003 and above
System.ServiceProcess.ServiceAccount.LocalSystem, // this is required for WS-2000
System.ServiceProcess.ServiceStartMode.Automatic);
// Uninstall
IntegratedServiceInstaller Inst = new IntegratedServiceInstaller();
Inst.Uninstall(serviceName);
You could try the windows sc command
C:\WINDOWS\system32>sc create
DESCRIPTION:
SC is a command line program used for communicating with the NT Service Controller and services.
You can use installutil.
From the command line:
installutil YourWinService.exe
This utility is installed with the .NET Framework

Categories

Resources