Can't make MSDNs simple example c# service - c#

I've attempt to follow MSDN simple make a service instructions
Walkthrough: Creating a Windows Service Application in the Component Designer
https://msdn.microsoft.com/en-us/library/zt39148a(v=vs.110).aspx?cs-save-lang=1&cs-lang=csharp#code-snippet-1
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Linq;
using System.ServiceProcess;
using System.Text;
namespace WindowsService1
{
public partial class Service1 : ServiceBase
{
private System.ComponentModel.IContainer components;
private System.Diagnostics.EventLog eventLog1;
public Service1()
{
InitializeComponent();
eventLog1 = new System.Diagnostics.EventLog();
if (!System.Diagnostics.EventLog.SourceExists("MySource"))
{
System.Diagnostics.EventLog.CreateEventSource("MySource", "MyNewLog");
}
eventLog1.Source = "MySource";
eventLog1.Log = "MyNewLog";
}
protected override void OnStart(string[] args)
{
eventLog1.WriteEntry("In OnStart");
}
protected override void OnStop()
{
}
}
}
I seem to fail at the 2nd hurdle, "Adding Features to the Service"
When I compile I get Ambiguity between 'WindowsService1.Service1.eventLog1' and 'WindowsService1.Service1.Service1.eventLog1' and The type 'WindowsService1.Service1' already contains a defintion for 'components'

Thanks for the comments people got me looking in the right place, seems that you don't need to do step4 it is done automatically when you add the eventlog in the design view.
Service1.designer.cs looks like this
namespace WindowsService4
{
partial class Service1
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Component Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.eventLog1 = new System.Diagnostics.EventLog();
((System.ComponentModel.ISupportInitialize)(this.eventLog1)).BeginInit();
//
// Service1
//
this.ServiceName = "Service1";
((System.ComponentModel.ISupportInitialize)(this.eventLog1)).EndInit();
}
#endregion
private System.Diagnostics.EventLog eventLog1;
}
}

Related

How can I setup multiples Windows Services?

So, I was creating a windows service and i was following this video to setup the windows service.
https://www.youtube.com/watch?v=tAF9krJu3cs
So, I have a Model, I get the Model in the controller so I can build what I want to send, then, I call that Controller on the Service. After that, I created the Installer. Problem: I have 3 and i was able to create them adding: [RunInstaller(true)] in the beggining of every service. After that, I was saying that they were not manual and "prepraring" them for the errors, starting them, and, after that I started them. But, I turned on one of them, the other turns off, and so on. I was able to turn the 3 on after a while (maybe this was a bug) but they all stopped working again..... My code:
ProjectInstaller:
enter image description here
ProjectInstaller.Designer.cs :
{
partial class ProjectInstaller
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Component Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.serviceProcessInstaller1 = new System.ServiceProcess.ServiceProcessInstaller();
this.AccountService = new System.ServiceProcess.ServiceInstaller();
this.FinInfoPrevYearService = new System.ServiceProcess.ServiceInstaller();
this.GetFinancialInfoService = new System.ServiceProcess.ServiceInstaller();
//
// serviceProcessInstaller1
//
this.serviceProcessInstaller1.Account = System.ServiceProcess.ServiceAccount.LocalService;
this.serviceProcessInstaller1.Password = null;
this.serviceProcessInstaller1.Username = null;
this.serviceProcessInstaller1.AfterInstall += new System.Configuration.Install.InstallEventHandler(this.serviceProcessInstaller1_AfterInstall);
//
// AccountService
//
this.AccountService.ServiceName = "AccountService";
this.AccountService.AfterInstall += new System.Configuration.Install.InstallEventHandler(this.AccountService_AfterInstall);
//
// FinInfoPrevYearService
//
this.FinInfoPrevYearService.ServiceName = "FinInfoPrevYearService";
this.FinInfoPrevYearService.AfterInstall += new System.Configuration.Install.InstallEventHandler(this.FinInfoPrevYearService_AfterInstall);
//
// GetFinancialInfoService
//
this.GetFinancialInfoService.ServiceName = "GetFinancialInfoService";
this.GetFinancialInfoService.AfterInstall += new System.Configuration.Install.InstallEventHandler(this.GetFinancialInfoService_AfterInstall);
//
// ProjectInstaller
//
this.Installers.AddRange(new System.Configuration.Install.Installer[] {
this.serviceProcessInstaller1,
this.AccountService,
this.FinInfoPrevYearService,
this.GetFinancialInfoService});
}
#endregion
private System.ServiceProcess.ServiceProcessInstaller serviceProcessInstaller1;
private System.ServiceProcess.ServiceInstaller AccountService;
private System.ServiceProcess.ServiceInstaller FinInfoPrevYearService;
private System.ServiceProcess.ServiceInstaller GetFinancialInfoService;
}
}
ProjectInstaller.cs:
{
[RunInstaller(true)]
public partial class ProjectInstaller : System.Configuration.Install.Installer
{
public ProjectInstaller()
{
InitializeComponent();
}
private void serviceProcessInstaller1_AfterInstall(object sender, InstallEventArgs e)
{
}
private void AccountService_AfterInstall(object sender, InstallEventArgs e)
{
}
private void GetFinancialInfoService_AfterInstall(object sender, InstallEventArgs e)
{
}
private void FinInfoPrevYearService_AfterInstall(object sender, InstallEventArgs e)
{
}
}
}
One of the services:
enter image description here
Please help me guys.. I dont know what to do anymore...

Form Components went missing Visual Studio c#

Was making a very simple text editor for practice, got the form all setup but then when I started to add the code all of the form components suddenly disappeared from the form but the still exist somewhere. Not really sure what is going on.
I have posted the code I have written so far. Alot of the features are likely going to be removed as I want this text editor to follow a free writing style. I really only plan to use the "File" drop down selection (New, Open, Save and Exit).
Thank in advance for any assistance.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Drawing.Text;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace CustomTextEditor2 {
public partial class TextEditor : Form {
public TextEditor() {
InitializeComponent();
}
#region Editor and General
#endregion
#region MainMenu
#endregion
#region Toolbar
#endregion
#region contextmenu
#endregion
#region Methods
#region file
void New()
{
Document.Clear();
}
void Open()
{
if (openWork.ShowDialog() == DialogResult.OK)
{
Document.LoadFile(openWork.FileName, RichTextBoxStreamType.PlainText);
}
}
void Save()
{
if (saveWork.ShowDialog() == DialogResult.OK)
{
try
{
Document.SaveFile(saveWork.FileName, RichTextBoxStreamType.PlainText);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}
void Exit()
{
Application.Exit();
}
#endregion
#region edit
#endregion
#region tools
void customise()
{
ColorDialog myDialog = new ColorDialog();
if (myDialog.ShowDialog() == DialogResult.OK)
{
mainMenu.BackColor = myDialog.Color;
Status.BackColor = myDialog.Color;
Tools.BackColor = myDialog.Color;
}
}
#endregion
#endregion
}
}
Okay here is the code from TextEditor.Designer.cs:
namespace CustomTextEditor2
{
partial class TextEditor
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.SuspendLayout();
//
// TextEditor
//
this.ClientSize = new System.Drawing.Size(732, 434);
this.MinimumSize = new System.Drawing.Size(748, 473);
this.Name = "TextEditor";
/this.Load += new System.EventHandler(this.TextEditor_Load_1);
this.ResumeLayout(false);
}
#endregion
private System.Windows.Forms.MenuStrip mainMenu;
private System.Windows.Forms.RichTextBox Document;
private System.Windows.Forms.StatusStrip Status;
private System.Windows.Forms.ToolStripMenuItem mM_File;
private System.Windows.Forms.ToolStripMenuItem file_New;
private System.Windows.Forms.ToolStripMenuItem file_Open;
private System.Windows.Forms.ToolStripSeparator toolStripSeparator;
private System.Windows.Forms.ToolStripMenuItem file_Save;
private System.Windows.Forms.ToolStripSeparator toolStripSeparator1;
private System.Windows.Forms.ToolStripSeparator toolStripSeparator2;
private System.Windows.Forms.ToolStripMenuItem file_Exit;
private System.Windows.Forms.ToolStripStatusLabel charCount;
private System.Windows.Forms.ToolStripStatusLabel toolStripStatusLabel1;
private System.Windows.Forms.ToolStripStatusLabel zoom;
private System.Windows.Forms.OpenFileDialog openWork;
private System.Windows.Forms.SaveFileDialog saveWork;
private System.Windows.Forms.Timer timer;
}
}

no suitable method found to override when converting from vb.net to c#

I am migrating from a vb.net application to c#, I used this tool to convert all of my code method by method. But when I finally compiled the code and I get no suitable method found to override.
I looked at this similar post No Suitable Method Found To Override
but he uses partial class but I am using an internal class
frmMain.cs Code
namespace RSCWebPoll
{
internal class frmMain : System.Windows.Forms.Form
{
const bool IsDebug = false;
const short LoopTimeInSeconds = 300;
public TFSUtilities.Logger logger = new TFSUtilities.Logger();
public System.DateTime NextPollTime;
public string WinDSSStoreName;
public string WinDSSStoreNumber;
public string WinDSSStoreCity;
public string WinDSSStoreState;
public string WinDSSRegisterNumber;
public string WinDSSTillNumber;
public string WinDSSDrawerNumber = "1";
public short RegisterStatus;
public string TillSeqType;
}
}
frmMain.Designer.cs
partial class frmMain
{
#region "Windows Form Designer generated code "
[System.Diagnostics.DebuggerNonUserCode()]
public frmMain()
: base()
{
//This call is required by the Windows Form Designer.
InitializeComponent();
}
//Form overrides dispose to clean up the component list.
[System.Diagnostics.DebuggerNonUserCode()]
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
}
any help is much appreciated...
Check your class names of those two files.it will be like below
formx.cs
namespace WindowsFormx
{
public partial class formx: Form
formx.designer.cs
namespace WindowsFormx
{
partial class formx
Check namespace of designer.cs

C# FileSystemWatcher Windows service does not start

I have created and installed C# FileSystemWatcher, this part works but nothing happens when I add a file to the source folder, the file I add to the source folder should be copied to a destination folder, but that does not happen.
This is my Filesyswatcher.designer.cs
using System;
using System.Configuration;
using System.IO;
namespace HotFolderWatch
{
partial class FileSysWatcher
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Component Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.FSWatcher = new System.IO.FileSystemWatcher();
((System.ComponentModel.ISupportInitialize)(this.FSWatcher)).BeginInit();
//
// FSWatcher
//
this.FSWatcher.Changed += new FileSystemEventHandler(FSWatcher_Changed);
this.FSWatcher.Created += new FileSystemEventHandler(FSWatcher_Created);
this.FSWatcher.Deleted += new FileSystemEventHandler(FSWatcher_Deleted);
this.FSWatcher.EnableRaisingEvents = true;
this.FSWatcher.NotifyFilter = ((System.IO.NotifyFilters)((((((System.IO.NotifyFilters.FileName | System.IO.NotifyFilters.DirectoryName)
| System.IO.NotifyFilters.Size)
| System.IO.NotifyFilters.LastWrite)
| System.IO.NotifyFilters.LastAccess)
| System.IO.NotifyFilters.CreationTime)));
//
// FileSysWatcher
//
this.ServiceName = "FileSysWatcher";
((System.ComponentModel.ISupportInitialize)(this.FSWatcher)).EndInit();
}
#endregion
private System.IO.FileSystemWatcher FSWatcher;
/* DEFINE WATCHER EVENTS... */
/// <summary>
/// Event occurs when the contents of a File or Directory are changed
/// </summary>
private void FSWatcher_Changed(object sender,
System.IO.FileSystemEventArgs e)
{
//code here for newly changed file or directory
}
/// <summary>
/// Event occurs when the a File or Directory is created
/// </summary>
private void FSWatcher_Created(object sender,
System.IO.FileSystemEventArgs e)
{
//code here for newly created file or directory
try
{
System.IO.File.Copy(e.FullPath, DestinationPath + e.Name, true);
}
catch (Exception ex)
{
//Util.WriteToErrorLogFile(ex);
}
}
/// <summary>
/// Event occurs when the a File or Directory is deleted
/// </summary>
private void FSWatcher_Deleted(object sender,
System.IO.FileSystemEventArgs e)
{
//code here for newly deleted file or directory
}
}
}
And this is my FileSysWatcher.cs file..
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration;
using System.Data;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.ServiceProcess;
using System.Text;
using System.Threading.Tasks;
namespace HotFolderWatch
{
partial class FileSysWatcher : ServiceBase
{
private string _userName;
public FileSysWatcher()
{
InitializeComponent();
}
public static string DestinationPath;
public const string MyServiceName = "FileSysWatcher";
private FileSystemWatcher watcher = null;
protected override void OnStart(string[] args)
{
FSWatcher.Path = ConfigurationManager.AppSettings["WatchPath"];
DestinationPath = ConfigurationManager.AppSettings["DestinationPath"];
_userName = Environment.UserName;
// Begin watching.
FSWatcher.EnableRaisingEvents = true;
}
protected override void OnStop()
{
// TODO: Add code here to perform any tear-down necessary to stop your service.
}
}
}
I have also tried to attach to the process while debugging but the event does not seem to occur, anyone see any mistakes that could cause this?
I have tested your code on my system (Windows 7 64): it works. A few things you should check:
Is the WatchPath / DestinationPath a local path on the system where the service is running ? Be aware that accessing a network share by a service typically requires that the service runs under a (domain) user account. Also, a mapped network drive is not seen by the service, so you should use UNC paths if acessing (SMB) file shares.
At the moment where the created event triggers, the file could be in use, so your copy may fail.
and the logging is commented beacuse that part isnt executed either.
Ok, but nevertheless, you should add more logging.
My Windows services usually contain:
protected override void OnStart(string[] args)
{
// this is not just a simple message, this has to be called very early before any worker thread
// to prevent a race condition in the .NET code of registering the event source
EventLog.WriteEntry("XxxxService is starting", EventLogEntryType.Information, 1000);
I was recently faced this issue, found this code below in above answer,
FSWatcher.EnableRaisingEvents = true;
This line of code was throwing exception previously, but later on, after adding above line, my watcher was triggering events, which makes no sense.

Popup about array rank size preventing me from saving

I have a specific user control with several properties, including one which is of another class. That class contains a public int[,] this[int x, int y] (I don't remember the exact term for that) as well as a public int[,] property and a private int[,] field. I then have a form containing that control. Whenever I attempt to edit the form and then save, it denies me from saving with the following popup appearing 3 to 6 times in a row:
Note that I don't need the information saved into these arrays in the designer; the value is set to a default each time anyways within the ExampleControl. I don't even have the ability to modify or see these arrays.
Here's all of the code needed to reproduce:
Create a new form application, and then delete the Form1.cs file generated.
Program.cs:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;
namespace ArrayRankIssue
{
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main() {
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new ExampleForm());
}
}
}
ExampleClass.cs:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ArrayRankIssue
{
public class ExampleClass
{
private int[,] data = new int[2, 2];
public int[,] Data {
get {
return data;
}
set {
if (value.GetLength(0) != data.GetLength(0) || value.GetLength(1) != data.GetLength(1)) {
throw new ArgumentException("Argument must match size of array exactly.");
}
data = value;
}
}
public int[,] this[int x, int y] {
get {
return data;
}
set {
if (value.GetLength(0) != data.GetLength(0) || value.GetLength(1) != data.GetLength(1)) {
throw new ArgumentException("Argument must match size of array exactly.");
}
data = value;
}
}
}
}
ExampleControl.cs:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace ArrayRankIssue
{
public partial class ExampleControl : UserControl
{
internal ExampleClass example = new ExampleClass();
public ExampleClass Example {
get {
return example;
}
set {
example = value;
}
}
public ExampleControl() {
InitializeComponent();
}
}
}
ExampleControl.Designer.cs:
namespace ArrayRankIssue
{
partial class ExampleControl
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing) {
if (disposing && (components != null)) {
components.Dispose();
}
base.Dispose(disposing);
}
#region Component Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent() {
components = new System.ComponentModel.Container();
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
}
#endregion
}
}
ExampleForm.cs:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace ArrayRankIssue
{
public partial class ExampleForm : Form
{
public ExampleForm() {
InitializeComponent();
}
}
}
ExampleForm.Designer.cs:
namespace ArrayRankIssue
{
partial class ExampleForm
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing) {
if (disposing && (components != null)) {
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent() {
ArrayRankIssue.ExampleClass exampleClass8 = new ArrayRankIssue.ExampleClass();
this.exampleControl1 = new ArrayRankIssue.ExampleControl();
this.SuspendLayout();
//
// exampleControl1
//
this.exampleControl1.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
this.exampleControl1.Example = exampleClass8;
this.exampleControl1.Location = new System.Drawing.Point(12, 12);
this.exampleControl1.Name = "exampleControl1";
this.exampleControl1.Size = new System.Drawing.Size(150, 150);
this.exampleControl1.TabIndex = 0;
//
// ExampleForm
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(292, 273);
this.Controls.Add(this.exampleControl1);
this.Name = "ExampleForm";
this.Text = "Form1";
this.ResumeLayout(false);
}
#endregion
private ExampleControl exampleControl1;
}
}
After creating all of these files, select Build-->Rebuild solution [note 1]. Then, double-click ExampleForm.cs, click on the outlined control, and then press left and then right on your keyboard [note 2]. Then, press Control and S, and you will be greeted with the same error message many times.
What I'm looking for is a way to keep this message from popping up (and hopefully to solve the reason why it is popping up, not just suppress it). I have found a simple workaround, which is to close the form designer window and then save, but that seems impractical. Once it is successfully saved, the form appears properly, so there also doesn't seem to be any other effects.
The one other mention of this error message was in this question, but that offered no useful solution.
Note 1: This option is only available in "Expert mode" - if you don't have it, go to Tools-->Settings-->Expert Settings)
Note 2: This is needed so that the file appears as modified by Visual Studio. If it isn't done, you can't force a second save.
Moving these lines worked for me:
From ExampleForm.Designer.cs:
ArrayRankIssue.ExampleClass exampleClass2 = new ArrayRankIssue.ExampleClass();
this.exampleControl1.Example = exampleClass2;
To ExampleForm.cs:
public partial class ExampleForm : Form
{
public ExampleForm()
{
InitializeComponent();
ArrayRankIssue.ExampleClass exampleClass2 = new ArrayRankIssue.ExampleClass();
this.exampleControl1.Example = exampleClass2;
}
}
Solution 2
If you're properties are already setup and you don't need to change them mark them with:
[ReadOnly(true)]
[Browsable(false)]
In your example add those attributes to Data and this in ExampleClass.cs.
You'll have to change your code, remove any existing controls from your form, compile then re-add

Categories