|
Would this be a correct approach to prevent more than one execution:
protected override void OnStart(string[] args)
{
WriteEventEntry("TestService starting...", EventLogEntryType.Information, 100, 100);
timer.Elapsed += new ElapsedEventHandler(timer_Tick);
timer.Interval = 5000;
timer.Enabled = true;
}
private void timer_Tick(object sender, EventArgs e)
{
timer.Enabled = false;
WriteEventEntry(DateTime.Now.ToString() + " timer ticked...", EventLogEntryType.Information, 100, 100);
timer.Enabled = true;
}
?
|
|
|
|
|
Yes, but I suggest you use a try/catch/finally with the timer.Enabled = true; in the finally. (Unless you want your Service to stop when it encounters an Exception.)
|
|
|
|
|
I mostly use threads, and if you want to keep the periodicity logic apart from the rest of the logic you can use something similar to this:
while(true)
{
DoStuff();
sleep(1000);
}
The good thing about this, is that you running this code through a separate thread; thus it does not interfere with the UI thread. On large processes this will save you a lot of problems with the application not responding or working slower than expected.
Anyway as someone else told you both solutions could work, I'd use timer for trivial tasks and the thread worker for more complex stuff, but that's just my choice.
|
|
|
|
|
Hmm ... windows services don't have a UI thread 
|
|
|
|
|
Touche!!
And that's why my mamma told me I need to read the question before giving an answer :$
|
|
|
|
|
I use a timer, it just seems neater.
|
|
|
|
|
JoeSchmoe007 wrote: Is there any reason to prefer worker thread approach?
It depends on what you are trying to do. Timer is used when you want to get the callback in periodic intervals. One thing to note is, timer will fire the callback even if the previous call is in progress. All it does is queuing the job to a thread pool thread.
If you don't have something to execute periodically, spawn a thread or use one from thread pool. I have seen people simulating the timer's behavior by spawning worker threads and sleeping on it, which is of course a bad design.
There is no difference internally because both are using separate thread to do the job.
Best wishes,
Navaneeth
|
|
|
|
|
Can you elaborate why sleeping on the worker thread is bad design? I see this approach used often. What design would you recommend instead when worker thread is used?
|
|
|
|
|
JoeSchmoe007 wrote: Can you elaborate why sleeping on the worker thread is bad design?
Because Thread.Sleep may or may not sleep for more time than you specified. Take a look at this[^] article.
IMO, the decision to use sleep is also subjective. If you need accuracy on the intervals, you should not use Thread.Sleep . If you are waitting for some condition to happen, say wait for an external device to be up, you should use WaitHandle instead of Thread.Sleep . Consider the following example:
A windows service which is expected to do some job at every 10 minutes accurately (Eg: downloading a webpage and indexing the contents). You start the service and 12.00 and it should run at 12.10, 12.20 and so on. Unfortunatly the work took 15 minutes to complete. Now the program won't run at 12.20 instead it will run at 12.35. You loose the accuracy!
This is where timers are useful.
JoeSchmoe007 wrote: What design would you recommend instead
A windows service is something which is active all the time. If your application is doing the work only at specific intervals then it is not a good candidate for a service. It'd be better to create it as a normal console application and schedule it using the operating system's scheduler.
Best wishes,
Navaneeth
|
|
|
|
|
I am trying to communicate with linux machine. The documentation on the server running in the linux machine tells met the following-- "The proctocl shall be synchronous. The system will not send a command over the same TCP connection until it has recieved a reply to the first command....."
From the above I am asumming, I should use synchronous communication to talk to the server on the linux machine. Is that accurate? I am not receving the correct replies to my synchronous communication. Is there any chance that it could be asynchronous?
Thanks
Jobin THomas<code></code>
-- Modified Tuesday, July 27, 2010 11:31 AM
|
|
|
|
|
This question is impossible to answer since we do not have the documentation that you are referring to. When you say that you are not receiving the correct replies it may be that you are not sending the correct requests; again only the documentation or the source code could help you to resolve it. Since it is Linux, and thus open source, you should have access to both.
It's time for a new signature.
|
|
|
|
|
You should be able to use either -- I'd use asynchronous.
|
|
|
|
|
Thanks for the help. The issue was the stupid linux machine wasnt listening to my I.P address. We had to add some script to make it listen to my I.P. Synchronous communication works pretty good.
Thanks for the help.
|
|
|
|
|
When Windows Service application is created by VS 2008 via "Windows Service" template it is created as Windows application ( /target:winexe)
For convenience of debugging I modified it so that it can be started both from the command line and as a service using this approach:
static void Main(string[] args)
{
ServiceBase[] ServicesToRun;
TestService srv = new TestService();
ServicesToRun = new ServiceBase[]
{
srv
};
if (Environment.UserInteractive)
{
char KeyChar;
srv.ManualStart(args);
Console.WriteLine("Service started in console mode, press Space key to stop");
Console.WriteLine("Press any letter or digit to send control command (ASCII code +128)");
while (true)
{
KeyChar = Console.ReadKey().KeyChar;
Console.WriteLine("");
if (KeyChar == ' ')
break;
else
{
srv.ManualCustomCommand(KeyChar + 128);
}
}
srv.ManualStop();
}
else
ServiceBase.Run(ServicesToRun);
}
In order for this to work as expected I had to change output type from "Windows Application" to "Console Application" ( /target:exe). Everything currently works the way I expect.
Is this acceptable for Windows Service to be compiled as Console application? Are there any implications? Should I have kept it as "Windows Application" and attached console to it using approach described here: http://www.csharp411.com/console-output-from-winforms-application/ ?
|
|
|
|
|
I would arrange all the stuff that you want to run as the service into another class project. Then you can have the Windows Service project reference to this project for actual usage, and create console app project or windows app project that reference the class project for debugging.
|
|
|
|
|
Windows Services have no GUI so Winexe makes no sense. I always compile service programs as console, but more to the point, I compile the actual service code in a DLL which the program calls.
I do pretty much what you show there and control my services from the command line.
Edit: When I write an application that can be used in console or WinForms mode, I compile it as console.
modified on Monday, July 26, 2010 1:21 PM
|
|
|
|
|
I have this control with numerous buttons, say about 20. Instead of showing ToolTip for each control (it does look cumbersome to me), I would show the tips text on the status strip.
Now the question is, is there a simple way to get the instance of mouse hovering events instead of listing each button's mouse hover events?
I hope I am clear!
P.S.
I happened to find this in my Visual Studio 2010. I think this one is the answer. Can anyone explain to me on how to use this...
this.Controls_MouseHover(object sender, EventArgs e)
Thanks in Advance!
|
|
|
|
|
this is what I have but this didn't show the name of control in statusStrip when hovering the numericUpDown control.
ToolStripStatusLabel tssl = new ToolStripStatusLabel();
int status = 0;
int xCurrentLoc = 0;
int yCurrentLoc = 0;
int zCurrentLoc = 0;
public MotorApp()
{
InitializeComponent();
motor.OpenPort();
rbCircle.CheckedChanged += new EventHandler(SelectAntennaShape);
rbSquare.CheckedChanged += new EventHandler(SelectAntennaShape);
statusStrip1.Items.AddRange(new System.Windows.Forms.ToolStripItem[] { tssl });
CreateMouseHoverEvents(this);
}
private void CreateMouseHoverEvents(Control currentControl)
{
foreach (Control ctrl in currentControl.Controls)
{
if (ctrl is GroupBox)
CreateMouseHoverEvents(ctrl);
else
{
ctrl.MouseHover += new EventHandler(Controls_MouseHover);
ctrl.MouseLeave += new EventHandler(Controls_MouseLeave);
}
}
}
void Controls_MouseLeave(object sender, EventArgs e)
{
tssl.Text = "";
}
void Controls_MouseHover(object sender, EventArgs e)
{
Control ctrl = (Control) sender;
tssl.Text = ctrl.Name;
}
|
|
|
|
|
Hi,
After transferring PNG images to an FTP server, I am unable to open them as they are being corrupted. My code is as below:
FtpWebRequest request = (FtpWebRequest)WebRequest.Create("ftp://... etc.");
request.UsePassive = true;
request.Method = WebRequestMethods.Ftp.UploadFile;
request.Credentials = new NetworkCredential("username", "password");
StreamReader sourceStream = new StreamReader(fileLocalDir);
byte[] fileContents = Encoding.UTF8.GetBytes(sourceStream.ReadToEnd());
sourceStream.Close();
request.ContentLength = fileContents.Length;
Stream requestStream = request.GetRequestStream();
requestStream.Write(fileContents, 0, fileContents.Length);
requestStream.Close();
FtpWebResponse response = (FtpWebResponse)request.GetResponse();
response.Close();
Another thing to add - when I download the file from the FTP server and open in IrfanView, the error below is displayed:
"C:\Folder\file.png: Can't read file header! Unknown file format or file not found! (For unicode file names, please activate the Unicode PlugIn in 'Properties -> Languages')"
Thanks for any assistance,
Anthony.
|
|
|
|
|
You're using the wrong type of stream. Maybe a BinaryReader would be better.
Panic, Chaos, Destruction.
My work here is done.
or "Drink. Get drunk. Fall over." - P O'H
|
|
|
|
|
Thanks for your response Nagy.
I have modified my code to use BinaryReader .
I'm still able to transfer the files, but they end up being ~60% the size of the originals. I'm still unable to view the files due to corruption. Please can you advise whether my code is trying to do the right thing or not (see below)?
FtpWebRequest request = (FtpWebRequest)WebRequest.Create("ftp://ftpuser...etc");
request.UsePassive = true;
request.UseBinary = true;
request.Method = WebRequestMethods.Ftp.UploadFile;
request.Credentials = new NetworkCredential("username", "password");
BinaryReader br = new BinaryReader(File.Open(fileLocalDir, FileMode.Open));
FileInfo info = new FileInfo(fileLocalDir);
byte[] testArray = new byte[info.Length];
int i;
for (i = 0; i < info.Length; i++)
{
testArray[i] = br.ReadByte();
}
request.ContentLength = i;
try
{
Stream requestStream = request.GetRequestStream();
requestStream.Write(testArray, 0, i);
requestStream.Close();
FtpWebResponse response = (FtpWebResponse)request.GetResponse();
response.Close();
}
Regards,
Anthony
|
|
|
|
|
i have created a crystal report with 3 table know i want to put a selection formula in a particular column of table but it is not working
what i have done is this
crystalReportViewer1.SelectionFormula = "{NewSampleEntrys.RecvdDate}={?EDOR}";
crystalReportViewer1.Refresh();
plz give some idea guys......
|
|
|
|
|
Hi all,
I'm trying to write a C# app to emulate the search functions in Windows Explorer, including "find in files" (otherwise I wouldn't need the help!)
I figure there must be part of the Win32 API that performs the find in files function for a set of files, but don't know the name. Can anybody give me any pointers?
Thanks,
Chris
|
|
|
|
|
c2423 wrote: I figure there must be part of the Win32 API that performs the find in files function for a set of files
Not that I know of.
c2423 wrote: Can anybody give me any pointers?
Indexed or non-indexed files? If it's indexed, you might want to interface with Windows Search[^]. Otherwise, it'd still be creating a list of files, and searching them the old-fashioned way.
I are Troll
|
|
|
|
|
Thanks for the response.
Unfortunately I've no control of whether files are indexed or not. I'll have a look at Windows Search though - maybe that will help a bit...
Not to sound completely stupid, but what do you have in mind when you say the old-fashioned way? I'm happy searching text files but not Word, Excel etc?
|
|
|
|