Windows Service starting issue in c# - c#

When i try to start a windows service after install using nssm then is shows me below error
Added Code
#region Private Members
private Timer timer1 = null;
#endregion
#region Constructor
public Service1()
{
InitializeComponent();
}
#endregion
#region Methods
/// <summary>
/// This function run on Windows service Start event
/// </summary>
/// <param name="args">args</param>
protected override void OnStart(string[] args)
{
try
{
timer1 = new Timer();
this.timer1.Interval = 60000; //1 Minute=60000, 2 Minute=120000,5 Minute=300000
this.timer1.Elapsed += new System.Timers.ElapsedEventHandler(this.timer1_Tick);
timer1.Enabled = true;
Library.WriteErrorLog(" ============================ ");
Library.WriteErrorLog(" Windows Service Started. ");
}
catch (Exception ex)
{
Library.WriteErrorLog(" WCF Service Error Given In OnStart() Is : " + ex.Message);
}
}
/// <summary>
/// OnStop event will hit when Windows service Stop
/// </summary>
protected override void OnStop()
{
timer1.Enabled = false;
Library.WriteErrorLog(" Windows Service Stopped. ");
}
/// <summary>
/// timer1_Tick event will call in every Timer Interval as well Window Service Started
/// </summary>
/// <param name="state"></param>
private void timer1_Tick(object sender, ElapsedEventArgs e)
{
Library.WriteErrorLog("---------------------------------");
Library.WriteErrorLog(" Windows Service Timer Ticked and Doing His Job Succcessfully. ");
Library.WriteErrorLog(" Windows Service Timer Call After 1 Minute. ");
Library.WriteErrorLog(" WCF Service Call Started. ");
TimerCalled();
}
/// <summary>
/// This function will called in 'x' time interval. common function will call from OnElapsedTime event
/// </summary>
/// <param name="b"></param>
private void TimerCalled()
{
try
{
Library.WriteErrorLog(" WCF Service Call By Using Windows Service Timer. ");
DbChecker obj = new DbChecker();
Boolean bl = obj.checkRecord();
Library.WriteErrorLog(" Windows Service Timer Call End. ");
Library.WriteErrorLog("---------------------------------");
}
catch (Exception ex)
{
Library.WriteErrorLog(" WCF Service Error Given In TimerCalled() Is : " + ex.Message);
}
}
#endregion
When I debug my solution at that time I don't get any error or warning...service run perfectly but I thought may be it is an windows server error

This could be due to almost anything, depending on the code you've written. The only reasons I can think of for receiving that message are: (1) an unhandled exception; or even a handled one that allows the service process to end; and (2) a service that behaves more like a start-process-finish app: when it starts, it will do a little processing and then end, resulting in that message.
Look for hints along both of those lines in your code. Hope it helps!

Related

UWP SpeechRecognizer throw exception:Operation is not valid due to the current state of the object

I am developing UWP and want to use SpeechRecognizer. When I run the application, the first try is right but next tries will throw a System.InvalidOperationException at
SpeechRecognitionResult speechRecognitionResult = await speechRecognizer.RecognizeAsync();.
The error message is
"Operation is not valid due to the current state of the object."
And another situation is that when I click the button to speak, the function RecognizeAsync() seems not to be called and I immediately get the MessageDialog with blank content and the return value of the program is 1(0x1). I don't get exception in this way but if I click the button quickly, it will throw the exception above.
I have searched a lot of pages online but none of them could figure out
this problem. Any help will be greatly appreciated. Thanks.
Here is my full code
public sealed partial class VoiceMainPage : Page
{
public VoiceMainPage()
{
InitializeComponent();
}
private async void OnListenAsync(object sender, RoutedEventArgs e)
{
// Create an instance of SpeechRecognizer.
var speechRecognizer = new SpeechRecognizer();
// Compile the dictation grammar by default.
await speechRecognizer.CompileConstraintsAsync();
// Start recognition.
SpeechRecognitionResult speechRecognitionResult = await speechRecognizer.RecognizeAsync();
var messageDialog = new MessageDialog(speechRecognitionResult.Text, "Text spoken");
await messageDialog.ShowAsync();
}
}
Check this official sample code. Here is an adaptation of your code reusing part of the github sample :
public class VoiceMainPage
{
private SpeechRecognizer speechRecognizer;
private CoreDispatcher dispatcher;
private IAsyncOperation<SpeechRecognitionResult> recognitionOperation;
public VoiceMainPage()
{
InitializeComponent();
}
/// <summary>
/// When activating the scenario, ensure we have permission from the user to access their microphone, and
/// provide an appropriate path for the user to enable access to the microphone if they haven't
/// given explicit permission for it.
/// </summary>
/// <param name="e">The navigation event details</param>
protected async override void OnNavigatedTo(NavigationEventArgs e)
{
// Save the UI thread dispatcher to allow speech status messages to be shown on the UI.
dispatcher = CoreWindow.GetForCurrentThread().Dispatcher;
bool permissionGained = await AudioCapturePermissions.RequestMicrophonePermission();
if (permissionGained)
{
// Enable the recognition buttons.
await InitializeRecognizer(SpeechRecognizer.SystemSpeechLanguage);
buttonOnListen.IsEnabled = true;
}
else
{
// Permission to access capture resources was not given by the user; please set the application setting in Settings->Privacy->Microphone.
buttonOnListen.IsEnabled = false;
}
}
private async void OnListenAsync(object sender, RoutedEventArgs e)
{
buttonOnListen.IsEnabled = false;
// Start recognition.
try
{
recognitionOperation = speechRecognizer.RecognizeAsync();
SpeechRecognitionResult speechRecognitionResult = await recognitionOperation;
// If successful, display the recognition result.
if (speechRecognitionResult.Status == SpeechRecognitionResultStatus.Success)
{
// Access to the recognized text through speechRecognitionResult.Text;
}
else
{
// Handle speech recognition failure
}
}
catch (TaskCanceledException exception)
{
// TaskCanceledException will be thrown if you exit the scenario while the recognizer is actively
// processing speech. Since this happens here when we navigate out of the scenario, don't try to
// show a message dialog for this exception.
System.Diagnostics.Debug.WriteLine("TaskCanceledException caught while recognition in progress (can be ignored):");
System.Diagnostics.Debug.WriteLine(exception.ToString());
}
catch (Exception exception)
{
var messageDialog = new Windows.UI.Popups.MessageDialog(exception.Message, "Exception");
await messageDialog.ShowAsync();
}
buttonOnListen.IsEnabled = true;
}
/// <summary>
/// Ensure that we clean up any state tracking event handlers created in OnNavigatedTo to prevent leaks.
/// </summary>
/// <param name="e">Details about the navigation event</param>
protected override void OnNavigatedFrom(NavigationEventArgs e)
{
base.OnNavigatedFrom(e);
if (speechRecognizer != null)
{
if (speechRecognizer.State != SpeechRecognizerState.Idle)
{
if (recognitionOperation != null)
{
recognitionOperation.Cancel();
recognitionOperation = null;
}
}
speechRecognizer.StateChanged -= SpeechRecognizer_StateChanged;
this.speechRecognizer.Dispose();
this.speechRecognizer = null;
}
}
/// <summary>
/// Initialize Speech Recognizer and compile constraints.
/// </summary>
/// <param name="recognizerLanguage">Language to use for the speech recognizer</param>
/// <returns>Awaitable task.</returns>
private async Task InitializeRecognizer(Language recognizerLanguage)
{
if (speechRecognizer != null)
{
// cleanup prior to re-initializing this scenario.
speechRecognizer.StateChanged -= SpeechRecognizer_StateChanged;
this.speechRecognizer.Dispose();
this.speechRecognizer = null;
}
// Create an instance of SpeechRecognizer.
speechRecognizer = new SpeechRecognizer(recognizerLanguage);
// Provide feedback to the user about the state of the recognizer.
speechRecognizer.StateChanged += SpeechRecognizer_StateChanged;
// Add a web search topic constraint to the recognizer.
var webSearchGrammar = new SpeechRecognitionTopicConstraint(SpeechRecognitionScenario.WebSearch, "webSearch");
speechRecognizer.Constraints.Add(webSearchGrammar);
// Compile the constraint.
SpeechRecognitionCompilationResult compilationResult = await speechRecognizer.CompileConstraintsAsync();
if (compilationResult.Status != SpeechRecognitionResultStatus.Success)
{
buttonOnListen.IsEnabled = false;
}
/// <summary>
/// Handle SpeechRecognizer state changed events by updating a UI component.
/// </summary>
/// <param name="sender">Speech recognizer that generated this status event</param>
/// <param name="args">The recognizer's status</param>
private async void SpeechRecognizer_StateChanged(SpeechRecognizer sender, SpeechRecognizerStateChangedEventArgs args)
{
await dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
{
MainPage.Current.NotifyUser("Speech recognizer state: " + args.State.ToString(), NotifyType.StatusMessage);
});
}
}
The button buttonOnListen shall have its enable state set to false during the speech recognition procedure to prevent click handler reentrance. In addition it is preferrable to have the SpeechRecognizer object initialized once during page navigation landing (OnNavigatedTo) and dispose it while leaving the page (OnNavigatedFrom)

Use a transparent, click-through form to monitor for activity

A client has a problem with employees opening a program displaying sensitive information and walking away without closing it. They've asked me to monitor when the application is open and close it after a certain amount of inactivity.
What I've done is created a new program that launches the original, but with another form on top of it. If my form is transparent, I can click through the form with no problems, and manipulate the underlying program. If my form is (slightly) opaque, clicks will register with my program, but will not pass through.
What I need is a way to let my form register that a click has happened, reset its timer, and pass the click through to the underlying application. I can reset the timer, or I can pass the click through, but not both.
Here's the code I'm currently trying. The first section defines my form as transparent and keeps it on top of the other application.
private void Form1_Load(object sender, EventArgs e)
{
this.Opacity = 0.40;
this.TopMost = true;
}
I thought this would let me monitor for a click, reset the timer, then pass it through, but it's not working, so I must be missing something. EDIT: WT_NCHITTEST = 0x84, and HTTRANSPARENT = -1, as indicated here: https://msdn.microsoft.com/en-us/library/windows/desktop/ms645618%28v=vs.85%29.aspx?f=255&MSPPError=-2147217396
[System.Security.Permissions.PermissionSet(System.Security.Permissions.SecurityAction.Demand, Name = "FullTrust")]
protected override void WndProc(ref Message m)
{
if (m.Msg == WM_NCHITTEST) // m.Msg 0x84 means that Windows is asking our form whether it is "transparent" or not.
{
timeToClose = 10;
m.Result = new IntPtr(HTTRANSPARENT); // tell Windows yes, to pass everything through.
}
base.WndProc(ref m);
}
That is way over engineered, I implement inactivity checks with System.Timers.Timer and PInvoke GetLastInputInfo. Run a second application that monitors for workstation inactivity and close sensitive applications when the threshold is violated.
Initialize the timer with an interval and set it to auto-reset, then just check for inactivity every time the timer elapses. If the inactivity time is greater than your threshold, shut it down.
Here is the code for GetLastInputInfo.
public static class Tracker
{
/// <summary>
/// Reference to the GetLastInputInfo in the user32.dll file.
/// </summary>
/// <param name="plii">LASTINPUTINFO struct</param>
/// <returns></returns>
[DllImport("user32.dll")]
private static extern bool GetLastInputInfo(ref LASTINPUTINFO plii);
/// <summary>
/// Polls the system for the milliseconds elapsed since last user input.
/// </summary>
/// <returns>Milliseconds since last user input.</returns>
public static uint GetIdleTime()
{
LASTINPUTINFO lastInput = new LASTINPUTINFO();
lastInput.cbSize = (uint)Marshal.SizeOf(lastInput);
GetLastInputInfo(ref lastInput);
return ((uint)Environment.TickCount - lastInput.dwTime);
}
}
/// <summary>
/// Struct required and populated by the user32.dll GetLastInputInfo method.
/// </summary>
internal struct LASTINPUTINFO
{
public uint cbSize; //Size of the struct.
public uint dwTime; //TickCount at last input.
}
My inactivity timer implementation looks like this:
public void InitializeTimer()
{
ActivityTimer = new System.Timers.Timer(Configuration.TimeoutSettings["IntervalMilliseconds"]);
ActivityTimer.AutoReset = true;
ActivityTimer.Elapsed += OnElapsedPollForActivity;
ActivityTimer.Start();
}
/// <summary>
/// Method is called in ValidationForm_FormClosing, unsubscribes handler from event and stops the clock.
/// </summary>
public void TerminateTimer()
{
ActivityTimer.Elapsed -= OnElapsedPollForActivity;
ActivityTimer.Stop();
}
/// <summary>
/// Fires on ActivityTimer.Elapsed, polls workstation for time since last user input.
/// </summary>
private void OnElapsedPollForActivity(object sender, System.Timers.ElapsedEventArgs e)
{
if (Tracker.GetIdleTime() > Configuration.TimeoutSettings["TriggerMilliseconds"])
{
Logger.LogException(CurrentSession.SessionID, DateTime.Now, new InactivityException("Detected extended period of workstation inactivity."));
Application.Exit();
}
}

Sql Dependency onchange event not firing every time c#

I have implemented sql dependency in windows service. when data will be changed in table then onchange event will fire and from there I am invoking a web service.
I will share my full code. I tested many time on my PC before installing the windows service on production PC it works. Suppose if I install on production PC today then it works for today but when I test next day then its onchange event was not firing.
so I found onchange event firing only first day and from the next day onchange event not firing. May be I have made some mistake in code. so it is my request please some one see my code in details and help me where I have made the mistake for which it is not working properly.
public partial class PartIndexer : ServiceBase
{
static string connectionString = "server=xxx;uid=xxx;password=xxx;database=xxx;Pooling=true;Connect Timeout=20;";
SqlDependency dep;
public PartIndexer()
{
InitializeComponent();
}
private string GetLoggedInUser()
{
string userName = "";
if (System.Security.Principal.WindowsIdentity.GetCurrent() != null)
{
userName = System.Security.Principal.WindowsIdentity.GetCurrent().Name;
}
return userName;
}
#region OnStart
protected override void OnStart(string[] args)
{
BBALogger.Write("PartIndexer Service OnStart called start", BBALogger.MsgType.Info);
RegisterNotification();
MailSend(); // notification mail send
BBALogger.Write("PartIndexer Service OnStart called end, logged in user " + GetLoggedInUser(), BBALogger.MsgType.Info);
}
#endregion
#region RegisterNotification
/// <summary>
/// RegisterNotification
/// this is main routine which will monitor data change in ContentChangeLog table
/// </summary>
private void RegisterNotification()
{
string tmpdata = "";
BBALogger.Write("PartIndexer Service RegisterNotification called start", BBALogger.MsgType.Info);
System.Data.SqlClient.SqlDependency.Stop(connectionString);
System.Data.SqlClient.SqlDependency.Start(connectionString);
try
{
using (SqlConnection conn = new SqlConnection(connectionString))
{
conn.Open();
SqlCommand cmd = conn.CreateCommand();
cmd.CommandText = "SELECT TestTable FROM [dbo].ContentChangeLog";
dep = new SqlDependency(cmd);
dep.OnChange += new OnChangeEventHandler(OnDataChange);
SqlDataReader dr = cmd.ExecuteReader();
{
if (dr.HasRows)
{
dr.Read();
tmpdata = dr[0].ToString();
}
}
dr.Dispose();
cmd.Dispose();
}
}
catch (Exception ex)
{
BBALogger.Write("PartIndexer Service RegisterNotification Error "+ex.Message.ToString(), BBALogger.MsgType.Error);
}
finally
{
BBALogger.Write("PartIndexer Service RegisterNotification called end", BBALogger.MsgType.Info);
}
}
#endregion
#region OnDataChange
/// <summary>
/// OnDataChange
/// OnDataChange will fire when after data change found in ContentChangeLog table
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
void OnDataChange(object sender, SqlNotificationEventArgs e)
{
((SqlDependency)sender).OnChange -= OnDataChange;
BBALogger.Write("PartIndexer Service RegisterNotification called end", BBALogger.MsgType.Info);
if (e.Source == SqlNotificationSource.Timeout)
{
MailSend(); // notification mail send
BBALogger.Write("PartIndexer Service SqlNotificationSource.Timeout error", BBALogger.MsgType.Error);
Environment.Exit(1);
}
else if (e.Source != SqlNotificationSource.Data)
{
MailSend(); // notification mail send
BBALogger.Write("PartIndexer Service SqlNotificationSource.Data", BBALogger.MsgType.Error);
Environment.Exit(1);
}
else if (e.Type == SqlNotificationType.Change)
{
StartIndex();
BBALogger.Write("PartIndexer Service Data changed", BBALogger.MsgType.Info);
}
else
{
BBALogger.Write(string.Format("Ignored change notification {0}/{1} ({2})", e.Type, e.Info, e.Source), BBALogger.MsgType.Warnings);
}
RegisterNotification();
}
#endregion
#region StartIndex
/// <summary>
/// StartIndex
/// this routine will call web service in bba reman website which will invoke routine to re-index data
/// </summary>
void StartIndex()
{
// calling web service if change is notified
}
#endregion
#region MailSend
/// <summary>
/// MailNotify
/// fire mail when apps start & exit
/// </summary>
/// <param name="strStatus"></param>
void MailSend()
{
// mail send code
}
#endregion
#region OnStop
protected override void OnStop()
{
BBALogger.Write("PartIndexer Service StartIndex called end, logged in user " + GetLoggedInUser(), BBALogger.MsgType.Info);
System.Data.SqlClient.SqlDependency.Stop(connectionString);
MailNotify("STOPPED");
}
#endregion
}
Another issue I noticed that when I start my windows service and leave it run for one day then when I try to stop or restart the the windows service then I windows service cannot be stopped. It means definitely there is some flaw in my code which I am not being able to point out. so please help me. thanks
i just noticed that you used
System.Data.SqlClient.SqlDependency.Stop(connectionString);
System.Data.SqlClient.SqlDependency.Start(connectionString);
sql dependency start and stop inside RegisterNotification() function, but its not correct way, and it may cause the problem to call event next time. it may work one time correctly.
you just try to use in windows start function
#region OnStart
protected override void OnStart(string[] args)
{
System.Data.SqlClient.SqlDependency.Stop(connectionString);
System.Data.SqlClient.SqlDependency.Start(connectionString);
BBALogger.Write("PartIndexer Service OnStart called start", BBALogger.MsgType.Info);
RegisterNotification();
MailSend(); // notification mail send
BBALogger.Write("PartIndexer Service OnStart called end, logged in user " + GetLoggedInUser(), BBALogger.MsgType.Info);
}
#endregion
i hope it will resolve your issue, thanks.

Threading.Timer with Autoreset or Single Thread?

I want to create a class that reads SMS messages from a GSM device.
I created a timer(system.threading) that reads for incoming message every second.
public void ReadMessage(){
//read sms messages
//and store it into the database
}
Sometimes ReadMessage() takes more than a second. How can I prevent the timer
from calling this procedure when the previous one is not yet finished?
1. Are AutoResetEvent and WaitOne good for this?
2. Is Threading.Timer a good choice? or should I do it on a single thread?
You should use a System.Timers.Timer, which is easier to work with.
(It's a friendlier wrapper around Threading.Timer)
Set AutoReset to false, then Start() the timer again at the end of the handler.
Don't use a dedicated thread; there's no point in keeping a thread around doing nothing so that you can wake it up every second.
Although this question is quite old, you can inspire by this code. It doesn't use any additional thread and it doesn't count time during execution of your code.
/// <summary>
/// Single thread timer class.
/// </summary>
public class SingleThreadTimer: IDisposable
{
private readonly Timer timer;
private readonly Action timerAction;
/// <summary>
/// Initializes a new instance of the <see cref="SingleThreadTimer"/> class.
/// </summary>
/// <param name="interval">The interval time.</param>
/// <param name="timerAction">The timer action to execute.</param>
/// <exception cref="System.ArgumentNullException">timerAction</exception>
/// <exception cref="System.ArgumentException">interval</exception>
public SingleThreadTimer(double interval, Action timerAction)
{
if (timerAction == null)
throw new ArgumentNullException("timerAction");
if (interval <= 0)
throw new ArgumentException(string.Format("Invalid value '{0}' for parameter 'interval'.", interval), "interval");
this.timerAction = timerAction;
this.timer = new Timer(interval)
{
AutoReset = false
};
timer.Elapsed += timer_Elapsed;
timer.Start();
}
public void Dispose()
{
if (timer != null)
timer.Dispose();
}
private void timer_Elapsed(object sender, ElapsedEventArgs e)
{
try
{
timerAction();
}
finally
{
// Enable timer again to continue elapsing event.
timer.Enabled = true;
}
}
}
I cannot see any need for an explicit timer trigger at all. If you thread this off:
while(true){
ReadMessage();
Thread.Sleep(1000);
};
..does this not do exactly what you want, all nicely encapsulated in one thread?
Rgds,
Martin

DispatcherTimer Keeps Firing After Stop() in Win 2k8 SP2

I got an interesting bug report today.
I have a DispatcherTimer whose Tick calls an EventHandler which contains a Stop() method call. This stops the timer on the platforms we use in development (Windows XP SP3 and Windows 7), but the timer does not seem to stop when run on a Windows Server 2008 SP2 machine.
This is a .NET 3.5 project.
I am wondering if this is a known bug in System.Windows.Threading in Win 2k8 or if I am doing something wrong in my code.
The relevant parts of the code are below:
public DispatcherTimer UserDelayTimer;
private void _HierTreeControlWPF_Loaded(object sender, RoutedEventArgs e)
{
UserDelayTimer = new DispatcherTimer();
UserDelayTimer.Interval = new TimeSpan(0, 0, 0, 0, 500); //500 ms
UserDelayTimer.Tick += new EventHandler(OnTimerEvent);
UserDelayTimer.Start();
}
/// <summary>
/// Timer to run update after the user has stopped making selections in the hierarchy view.
/// </summary>
/// <param name="source"></param>
/// <param name="e"></param>
void OnTimerEvent(object sender, EventArgs e)
{
if (HierTreeAfterCheck_Event != null && !HierTreeCheckEvent_Suppressed)
HierTreeAfterCheck_Event();
UserDelayTimer.Stop();
}
//This method is run whenever the mouse moves or makes a selection in the hierarchy tree.
//The idea is that HierTreeAfterCheck_Event() will only run after the user has stopped making
//selections for a certain amount of time.
public void ResetUserDelayTimer(object sender, MouseButtonEventArgs e)
{
if (UserDelayTimer.IsEnabled) //if the timer is running, restart it to buy more time.
{
UserDelayTimer.Stop();
UserDelayTimer.Start();
}
}
Many thanks in advance!
Figured it out. Turns out I had to modify the sender of OnTimerEvent, instead of the public instance of the timer itself.

Categories