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.
Related
Apologize for duplicate question. I have googled and everywhere I found only the question but no successful solution. I am facing exactly the same issue described here and here and struggling from past week,but I did not find any success, so finally I decided to ask a question here. I have tried to solve it myself by following the comments suggested in these question, but to success. I want SqlDependency onchange event to fire exactly once for any number for instance or users logged in.
This method is called once whenever a new user login into the application
public List<TransactionMaster> GetUnregisteredTransactions()
{
List<TransactionMaster> ltrans = new List<TransactionMaster>();
TransactionMaster trans = new TransactionMaster();
using (var connection = new SqlConnection(ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString))
{
string query = "SELECT TransId, ReceivedFrom,ReceivedOn,Mask FROM [dbo].TransactionMaster WHERE StageId =1";
SqlDependency.Start(ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString);
using (SqlCommand cmd = new SqlCommand(query, connection))
{
cmd.Notification = null;
DataTable dt = new DataTable();
SqlDependency dependency = new SqlDependency(cmd);
dependency.OnChange += new OnChangeEventHandler(dependency_OnChange);
if (connection.State == ConnectionState.Closed)
connection.Open();
SqlDataAdapter adapter = new SqlDataAdapter(cmd);
adapter.Fill(dt);
ltrans = dal.ConvertDataTable<TransactionMaster>(dt);
}
}
return ltrans;
}
And then again this method is called from onchange event
private void dependency_OnChange(object sender, SqlNotificationEventArgs e)
{
if (e.Type == SqlNotificationType.Change)
TransactionHub.GetUnregTransactions(GetUnregisteredTransactions());
}
For my case each time event fired I added events to the dependency
dependency.OnChange += new OnChangeEventHandler(SqlNotification.dependency_OnChange);
after I found this solution, i changed my code to :
dependency.OnChange -= new OnChangeEventHandler(SqlNotification.dependency_OnChange);
dependency.OnChange += new OnChangeEventHandler(SqlNotification.dependency_OnChange);
and this solved my problem.
Every time you call GetUnregisteredTransactions you are calling dependency.OnChange += new OnChangeEventHandler(dependency_OnChange);, This is causing a new event to registered, so now you have two events that will fire. when the two events fire it will call dependency.OnChange += new OnChangeEventHandler(dependency_OnChange); two more times making it 4 events that will fire. This number will double with every call till the object dependency is pointing at is garbage collected.
You need to either not re-register the dependency on calls from the event version (for example pass a bool to the function to know if it should do the registration or not) or you need to unregister the old notification before you create a new one.
Here is a example of unregistering.
private void dependency_OnChange(object sender, SqlNotificationEventArgs e)
{
SqlDependency dependency = (SqlDependency)sender;
dependency.OnChange -= new OnChangeEventHandler(dependency_OnChange);
if (e.Type == SqlNotificationType.Change)
TransactionHub.GetUnregTransactions(GetUnregisteredTransactions());
}
I know this is a late answer but I wanted to share my very fun experience with the SqlDependecy firing OnChange event multiple times.
So I ran into this problem as some people did and started looking for answers and quickly realized that there were no code examples that painted the whole picture of how to go about this problem.
This DatabaseWatcher class that I have snatched from
https://learn.microsoft.com/en-us/dotnet/framework/data/adonet/sql/detecting-changes-with-sqldependency, I had to modify it to prevent multiple subscriptions to OnChange events that in the end cause multiple OnChange events to be fired due to what I suspect, multiple instances of SqlDepency floating around with those OnChange subscriptions still attached.
The way I go about is by applying the solution from Scott Chamberlain and then catching the current instance of the SqlDepency when subscribing to the OnChange event to make sure to unsubscribe from the OnChange event before liquidating the DatabaseWatcher instance.
Unrelated to the subject, I also forward the OnChange event to hide it in my business class.
public class DatabaseWatcher : IDisposable
{
/// <summary>
/// Forwards the original OnChangeEventHandler event with the database table notification data
/// </summary>
public event EventHandler<SqlNotificationEventArgs> OnTableChange;
public SqlDependency CurrentSqlDependencyInstance { get; set; }
public string ConnectionString { get; set; }
public string Query { get; set; }
public DatabaseWatcher(string connectionString, string query)
{
ConnectionString = connectionString;
Query = query;
}
/// <summary>
/// Starts the database notification listener. Needs to be started before subscribing to the database notifications.
/// </summary>
public void StartDatabaseNotificationsListener()
{
// Create a dependency connection.
SqlDependency.Start(ConnectionString);
}
/// <summary>
/// Subscribes to the database table change notifications. After each notification, a new re-subscription is needed to receive the next database/table notification.
/// </summary>
public void SubscribeToDatabaseNotifications()
{
//create database connection
using (SqlConnection connection = new SqlConnection(ConnectionString))
{
//open database conneciton
connection.Open();
// Create a new SqlCommand object.
using (SqlCommand command = new SqlCommand(Query, connection))
{
// Create a dependency and associate it with the SqlCommand.
SqlDependency dependency = new SqlDependency(command);
//catch current SqlDependency instance
CurrentSqlDependencyInstance = dependency;
// Subscribe to databas/table notifications
dependency.OnChange += new OnChangeEventHandler(OnDependencyChange);
// Execute the command for the initial table snapshot to later compare with when changes arise
var affectedRowsCount = command.ExecuteNonQuery();
}
}
}
private void OnDependencyChange(object sender, SqlNotificationEventArgs e)
{
var sqlDependency = (SqlDependency)sender;
//don't unsubscribe after the subscription event
if (e.Type == SqlNotificationType.Subscribe)
return;
//unsubscribe from the OnChange event from the current instance of the SqlDepency object
sqlDependency.OnChange -= new OnChangeEventHandler(OnDependencyChange);
//don't fire the event if no changes were done to the table records
if (e.Type != SqlNotificationType.Change)
return;
if (e.Info != SqlNotificationInfo.Insert && e.Info != SqlNotificationInfo.Delete)
return;
OnTableChange = new EventHandler<SqlNotificationEventArgs>(OnTableChange);
OnTableChange?.Invoke(sender, e);
}
/// <summary>
/// Stops listening to database notifications, method is called on Dispose
/// </summary>
public void StopDatabaseNotificationsListener()
{
//unsubscribe from the OnChange event from the current instance of the SqlDepency object
CurrentSqlDependencyInstance.OnChange -= new OnChangeEventHandler(OnDependencyChange);
SqlDependency.Stop(ConnectionString);
}
public void Dispose()
{
StopDatabaseNotificationsListener();
}
}
So there it is, please leave comments, thoughts, etc,
Cheers.
I am creating an app with two forms.
On my main form1 I have a scanner that gets connected through a button.
I have a text box on my form2 and in this text box is where I want the information that gets scanned to go here.
there is no textbox on my form1.
I cant seem to figure out how to do this I was wondering if any one had any tips.
Thank you
This is the code in form 1 that allows me to set up the scanner
/// Event Handler for Scanner Setup Button
/// <param name="sender"></param>
/// <param name="e"></param>
private void scannerFormBTN_Click(object sender, EventArgs e)
{
try
{
//If the Button is yellow , disconnect the hand scanner
if (scannerBTN.BackColor == Color.LightGreen)
{
scanner.ReadStringArrived -= new ReadStringArrivedHandler(OnReadStringArrived);
scanner.Disconnect();
scanner = null;
scannerFormBTN.BackColor = Color.IndianRed;
this.scannerFormBTN.Text = "Setup Hand Scanner";
MessageBox.Show("Hand Scanner Disconnected.", "Alert");
}
//If scanner is not connected
else
{
Setupscanner scannerForm = new Setupscanner(); //Instantiate the Scanner Form
//Show the form. DialogResult = yes if Scanner is connected successfully.
DialogResult connection_successfull = scannerForm.ShowDialog();
if (connection_successfull == DialogResult.Yes)
{
this.scanner = scannerForm.sys; //Set the Local Hand Scanner variable to the successfully connected scanner
if (scanner.IsConnected)
{
scanner.ReadStringArrived += new ReadStringArrivedHandler(OnReadStringArrived); //Register Read String event.
scannerFormBTN.Text = "Hand Scanner Connected. Click to Disconnect";
scannerBTN.BackColor = Color.LightGreen; //Change the color of the Hand Scanner Button
}
}
}
}
catch (Exception ex) { MessageBox.Show("There was an error. Exception reads : \n\n " + ex.Message, "Error"); }
}
/// <summary>
/// Event that gets fired when string arrives from a connected hand scanner
/// </summary>
/// <param name="sender"></param>
/// <param name="args"></param>
private void OnReadStringArrived(Object sender, ReadStringArrivedEventArgs args)
{
SetSerNumber(args.ReadString);
}
/// <summary>
/// Used to set the Serial Number to the incoming Scanner String
/// </summary>
/// <param name="msg"></param>
private void SetSerNumber(string msg)
{
//If the event is fired on a different thread than the control was created
if (Part_Code_Text_Box.InvokeRequired)
{
SetSerialNumber S = new SetSerialNumber(SetSerNumber);
this.Invoke(S, new object[] { msg }); //Invoke the delegate S on the current thread
}
else
{
Part_Code_Text_Box.Text = msg.Trim();
}
}
Create a Property Or Field in Form 2 ..let's Call It StringFromScanner For Now .
When You Want To Show another From u will most likely Create an Object From it ...Set This Object's StringFromScanner To The String You Have ..and When You Open The Second Form Will Have The value of the string in this property and u can assign it to any control
In Form 1
Form2 objectfromform2 = new Form2();
objectfromform2.StringFromScanner = MyString;
objectfromform2.Show();
in Form 2
MytextBox.Text = StringFromScanner
You Can Also Forget About The Property and Use The Constructor To Achive The Same Result
I know there is a similar question on SO that has an answer, and after reading that and other articles, I'm still not sure why I can't get this wired up properly. I've tried quite a bit of examples and have been trying different things and simply can't get it to work. I know there are refactoring opportunities but I'm trying to keep it simple right now just to get it working first.
I have permissions to the db, and I can see that a temporary service and queue gets created. One thing I noticed though was that if I run a query, the queue does not display any records and my dependency_OnChange event does not get fired. I'm assuming it's not getting fired because nothing is entering the queue...
UPDATE: I'm getting it to fire now, however, the only event I get is Subscribe. The SqlNotificationEventArgs show Invalid for the Info, but my query and table match all the SELECT rules for sql dependency.
Global.asax:
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
SqlDependency.Start(_entityConnString);
}
protected void Application_End()
{
SqlDependency.Stop(_entityConnString);
}
InfectionPreventionHub.cs: (This is a simple SignalR Hub that starts up with a certain area)
/// <summary>
/// Sends the notifications.
/// </summary>
[HubMethodName("sendUpdates")]
private void SendUpdates()
{
var infectionPreventionItems = InfectionPreventionOperations.GetInfectionPrevention();
var vm = new InfectionPreventionViewModel
{
InfectionPrevention = infectionPreventionItems
};
var result = JsonConvert.SerializeObject(vm);
GetUpdates();
IHubContext context = GlobalHost.ConnectionManager.GetHubContext<InfectionPreventionHub>();
context.Clients.All.RecieveUpdates(result);
}
/// <summary>
/// Gets the updates.
/// </summary>
private void GetUpdates()
{
const string commandText = #"SELECT [Id], [FirstName] FROM [TestDb].[dbo].[Association]";
using (var connection = new SqlConnection(EntityConnString))
{
connection.Open();
using (var command = new SqlCommand(commandText, connection))
{
command.Notification = null;
var dependency = new SqlDependency(command);
dependency.OnChange += new OnChangeEventHandler(sqlDependency_OnChange);
if (connection.State == ConnectionState.Closed)
connection.Open();
// NOTE: You have to execute the command, or the notification will never fire.
using (var reader = command.ExecuteReader())
{
}
}
}
}
/// <summary>
/// Handles the OnChange event of the sqlDependency control.
/// </summary>
/// <param name="sender">The source of the event.</param>
/// <param name="e">The <see cref="SqlNotificationEventArgs"/> instance containing the event data.</param>
private void sqlDependency_OnChange(object sender, SqlNotificationEventArgs e)
{
// TODO: Check for the type of event
GetUpdates();
SendUpdates();
}
It was real easy to wire this up to RavenDB, but SqlServer is giving me a hard time.
GetUpdates only fires once when the hub connection happens, which I thought would start up the dependency. However, when updating or adding something to the Association table, no events get raised. I'm required to use SignalR for the UI's realtime updates and data will be entered via 3rd party tools. Any help is appreciated.
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)
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!