Hello I try to create auto emails send by service file but there is some problem.
this is BrithdayEmailService.cs file.
namespace BirthdayEmailSevice
{
partial class BirthdayEmailService : ServiceBase
{
private Timer scheduleTimer = null;
private DateTime lastRun;
private bool flag;
public BirthdayEmailService()
{
InitializeComponent();
if (!System.Diagnostics.EventLog.SourceExists("EmailSource"))
{
System.Diagnostics.EventLog.CreateEventSource("EmailSource", "EmailLog");
}
eventLogEmail.Source = "EmailSource";
eventLogEmail.Log = "EmailLog";
scheduleTimer = new Timer();
scheduleTimer.Interval = 1 * 5 * 60 * 1000;
scheduleTimer.Elapsed += new ElapsedEventHandler(scheduleTimer_Elapsed);
}
protected override void OnStart(string[] args)
{
flag = true;
lastRun = DateTime.Now;
scheduleTimer.Start();
eventLogEmail.WriteEntry("Started");
}
protected void scheduleTimer_Elapsed(object sender, ElapsedEventArgs e)
{
if (flag == true)
{
ServiceEmailMethod();
lastRun = DateTime.Now;
flag = false;
}
else if (flag == false)
{
if (lastRun.Date < DateTime.Now.Date)
{
ServiceEmailMethod();
}
}
}
private void ServiceEmailMethod()
{
eventLogEmail.WriteEntry("In Sending Email Method");
EmailComponent.GetEmailIdsFromDB getEmails = new EmailComponent.GetEmailIdsFromDB();
getEmails.connectionString = ConfigurationManager.ConnectionStrings["CustomerDBConnectionString"].ConnectionString;
getEmails.storedProcName = "GetBirthdayBuddiesEmails";
System.Data.DataSet ds = getEmails.GetEmailIds();
EmailComponent.Email email = new EmailComponent.Email();
email.fromEmail = "example#gmail.com";
email.fromName = "example Name";
email.subject = "Birthday Wishes";
email.smtpServer = "smtp.gmail.com";
email.smtpCredentials = new System.Net.NetworkCredential("example1#gmail.com", "example1 password");
foreach (System.Data.DataRow dr in ds.Tables[0].Rows)
{
email.messageBody = "<h4>Hello " + dr["CustomerName"].ToString() + "</h4><br/><h3>We Wish you a very Happy" +
"Birthday to You!!! Have a bash...</h3><br/><h4>Thank you.</h4>";
bool result = email.SendEmailAsync(dr["CustomerEmail"].ToString(), dr["CustomerName"].ToString());
if (result == true)
{
eventLogEmail.WriteEntry("Message Sent SUCCESS to - " + dr["CustomerEmail"].ToString() +
" - " + dr["CustomerName"].ToString());
}
else
{
eventLogEmail.WriteEntry("Message Sent FAILED to - " + dr["CustomerEmail"].ToString() +
" - " + dr["CustomerName"].ToString());
}
}
}
}
On scheduleTimer = new Timer(); got error
(This member is defined more than one)
Error:
Ambiguity between 'BirthdayEmailService.BirthdayEmailService.scheduleTimer' and 'BirthdayEmailService.BirthdayEmailService.scheduleTimer'
Also got error on BirthdayEmailService.Designer.cs this is file of design tool of service
error is :
private void InitializeComponent()
{
this.components = new System.ComponentModel.Container();
this.eventLogEmail = new System.Diagnostics.EventLog();
**this.scheduleTimer = new System.Windows.Forms.Timer(this.components);**
((System.ComponentModel.ISupportInitialize)(this.eventLogEmail)).BeginInit();
//
// BirthdayEmailService
//
this.ServiceName = "BirthdayEmailService";
((System.ComponentModel.ISupportInitialize)(this.eventLogEmail)).EndInit();
}
those part is bold there is getting error as same as.
(This member is defined more than one)
Error:
Ambiguity between 'BirthdayEmailService.BirthdayEmailService.scheduleTimer' and 'BirthdayEmailService.BirthdayEmailService.scheduleTimer'
It could be because the name of the class and the namespace are the same one. See this post.
Related
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
I am making a birthday notification in windows service that uses jabber-net library which is a XMPP and System.Threading that must send automatic messages to user every day, but i'm getting an error in logs which says
Unable to cast object of type 'System.Threading.Timer' to type 'jabber.client.JabberClient'. at SparkSalesCrdBirthdays.SparkBirthDayGreeting.j_OnAuthenticate(Object sender)
Here's my code
protected override void OnStart(string[] args)
{
this.WriteToFile("Simple Service started {0}");
JabberClient j = new JabberClient();
// what user/pass to log in as
j.User = "user";
j.Server = "server"; // use gmail.com for GoogleTalk
j.Password = "pass";
//j.Resource = "admin";
// don't do extra stuff, please.
j.AutoPresence = false;
j.AutoRoster = false;
j.AutoReconnect = -1;
j.KeepAlive = 10;
j.AutoLogin = true;
j.AutoStartTLS = false;
j.PlaintextAuth = true;
j.OnError += new bedrock.ExceptionHandler(j_OnError);
// what to do when login completes
j.OnAuthenticate += new bedrock.ObjectHandler(j_OnAuthenticate);
// listen for XMPP wire protocol
if (VERBOSE)
{
j.OnReadText += new bedrock.TextHandler(j_OnReadText);
j.OnWriteText += new bedrock.TextHandler(j_OnWriteText);
}
// Set everything in motion
j.Connect();
// wait until sending a message is complete
done.WaitOne();
// logout cleanly
j.Close();
this.ScheduleService();
}
protected override void OnStop()
{
this.WriteToFile("Simple Service stopped {0}");
this.Schedular.Dispose();
}
private Timer Schedular;
static void j_OnWriteText(object sender, string txt)
{
if (txt == " ") return; // ignore keep-alive spaces
Console.WriteLine("SEND: " + txt);
}
static void j_OnReadText(object sender, string txt)
{
if (txt == " ") return; // ignore keep-alive spaces
Console.WriteLine("RECV: " + txt);
}
private void j_OnAuthenticate(object sender)
{
try
{
JabberClient j = (JabberClient)sender;
DataTable dt = new DataTable();
string birthdaymsg = "";
string fullname;
string department;
string query = "SELECT CONCAT(FirstName, ' ', MiddleName, ' ', LastName) as Fullname, DepartmentDescription FROM vw_EmployeeOrganization WHERE DATEPART(d, BirthDate) = DATEPART(d,GETDATE()) AND DATEPART(m, BirthDate) = DATEPART(m, GETDATE()) AND DepartmentDescription IN('Client Relations--CDO', 'E-Learning', 'Sales ', 'Client Relations', 'Sales-Davao', 'Sales-CDO', 'Client Relations--Cebu', 'Sales-Cebu')";
string constr = ConfigurationManager.ConnectionStrings["HRIS"].ConnectionString;
lstUsers.Clear();
using (SqlConnection conn = new SqlConnection(constr))
{
using (SqlCommand cmd = new SqlCommand(query))
{
cmd.Connection = conn;
using (SqlDataAdapter sda = new SqlDataAdapter(cmd))
{
sda.Fill(dt);
}
}
}
foreach (DataRow row in dt.Rows)
{
fullname = row["Fullname"].ToString();
department = row["DepartmentDescription"].ToString();
birthdaymsg = "Happy Birthday! " + fullname + " from " + department + "." +
System.Environment.NewLine + "May today be filled with sunshine and smile, laughter and love.";
string queryRecipient = "SELECT * FROM tbl_MPAlertUsers";
string constr2 = ConfigurationManager.ConnectionStrings["Constring"].ConnectionString;
using (SqlConnection conn2 = new SqlConnection(constr2))
{
using (SqlCommand cmd2 = new SqlCommand(queryRecipient))
{
cmd2.Connection = conn2;
conn2.Open();
SqlDataReader reader = cmd2.ExecuteReader();
while (reader.Read())
{
lstUsers.Add(reader["ADname"].ToString());
}
reader.Close();
conn2.Close();
}
}
//Send to Recipient
for (int i = 0; i <= lstUsers.Count - 1; i++)
{
if (lstUsers[i].ToString().Trim().Length > 1)
{
WriteToFile("Trying to send spark to: " + lstUsers[i].ToString());
j.Message(lstUsers[i], birthdaymsg);
}
}
done.Set();
}
this.ScheduleService();
}
catch (Exception ex)
{
WriteToFile("Simple Service Error on: {0} " + ex.Message + ex.StackTrace);
//Stop the Windows Service.
using (System.ServiceProcess.ServiceController serviceController = new System.ServiceProcess.ServiceController("SparkBirthDayGreeting"))
{
serviceController.Stop();
}
}
}
public void ScheduleService()
{
try
{
Schedular = new Timer(new TimerCallback(j_OnAuthenticate));
string mode = ConfigurationManager.AppSettings["Mode"].ToUpper();
this.WriteToFile("Simple Service Mode: " + mode + " {0}");
//Set the Default Time.
DateTime scheduledTime = DateTime.MinValue;
if (mode == "DAILY")
{
//Get the Scheduled Time from AppSettings.
scheduledTime = DateTime.Parse(System.Configuration.ConfigurationManager.AppSettings["ScheduledTime"]);
if (DateTime.Now > scheduledTime)
{
//If Scheduled Time is passed set Schedule for the next day.
scheduledTime = scheduledTime.AddDays(1);
}
}
if (mode.ToUpper() == "INTERVAL")
{
//Get the Interval in Minutes from AppSettings.
int intervalMinutes = Convert.ToInt32(ConfigurationManager.AppSettings["IntervalMinutes"]);
//Set the Scheduled Time by adding the Interval to Current Time.
scheduledTime = DateTime.Now.AddMinutes(intervalMinutes);
if (DateTime.Now > scheduledTime)
{
//If Scheduled Time is passed set Schedule for the next Interval.
scheduledTime = scheduledTime.AddMinutes(intervalMinutes);
}
}
TimeSpan timeSpan = scheduledTime.Subtract(DateTime.Now);
string schedule = string.Format("{0} day(s) {1} hour(s) {2} minute(s) {3} seconds(s)", timeSpan.Days, timeSpan.Hours, timeSpan.Minutes, timeSpan.Seconds);
this.WriteToFile("Simple Service scheduled to run after: " + schedule + " {0}");
//Get the difference in Minutes between the Scheduled and Current Time.
int dueTime = Convert.ToInt32(timeSpan.TotalMilliseconds);
//Change the Timer's Due Time.
Schedular.Change(dueTime, Timeout.Infinite);
}
catch (Exception ex)
{
WriteToFile("Simple Service Error on: {0} " + ex.Message + ex.StackTrace);
//Stop the Windows Service.
using (System.ServiceProcess.ServiceController serviceController = new System.ServiceProcess.ServiceController("SparkBirthDayGreeting"))
{
serviceController.Stop();
}
}
}
private void WriteToFile(string text)
{
string path = "C:\\ServiceLog.txt";
using (StreamWriter writer = new StreamWriter(path, true))
{
writer.WriteLine(string.Format(text, DateTime.Now.ToString("dd/MM/yyyy hh:mm:ss tt")));
writer.Close();
}
}
I hope someone can help me with this. I am stuck :(
Thank you.
The problem is that JabberClient's event is handled in j_OnAuthenticate and the timer's event is handled with it:
Schedular = new Timer(new TimerCallback(j_OnAuthenticate));
...
JabberClient j = new JabberClient();
j.OnAuthenticate += new bedrock.ObjectHandler(j_OnAuthenticate);
And in j_OnAuthenticate the first thing you do is cast the sender to JabberClient
private void j_OnAuthenticate(object sender)
{
try
{
JabberClient j = (JabberClient)sender;
...
}
catch (Exception ex)
{
WriteToFile("Simple Service Error on: {0} " + ex.Message + ex.StackTrace);
//Stop the Windows Service.
using (System.ServiceProcess.ServiceController serviceController = new System.ServiceProcess.ServiceController("SparkBirthDayGreeting"))
{
serviceController.Stop();
}
}
The catch block handles and logs the exception.
You would have to change the code to do different things depending on the sender e.g.
if(sender is JabberClient)
{
//do something
}
else if(sender is Timer)
{
//do something else
}
Or give the timer a different callback function
I have coded a service in C# which runs and updates a CRM solution. I am trying to get the service to re-establish a connection to the database if it has to drop for some reason. So far when I detach the database and then reattach it, the service stops by itself.. Another thing is that then I detach the database, there is no exception logged by my synch app - it just stops dead.
My partial class where I call my synch from:
namespace Vessel_Schedule_Synch
{
[DisplayName("CRM Vessel Synch")]
partial class startVessel : ServiceBase
{
System.Threading.Timer t;
VesselUpdater v;
protected override void OnStart(string[] args)
{
//System.Threading.Thread.Sleep(20000);
v = new VesselUpdater();
t = new System.Threading.Timer(new System.Threading.TimerCallback(t_TimerCallback), null, 0, 300000);
//InfoLogger.Info("Starting service " + this.ServiceName, true);
}
private void t_TimerCallback(object state)
{
t.Change(Timeout.Infinite, Timeout.Infinite);
lock (v)
{
InfoLogger.Info("Timer fired... updating vessels");
try
{
v.Process();
v.updateCRM();
}
catch (Exception e)
{
if (v == null)
{ throw e; }
else
{
InfoLogger.Exception(e);
}
}
finally
{
InfoLogger.Info("End of Timer Trigger... Restarting Timer.");
t.Change(30000, 30000);
}
}
}
protected override void OnStop()
{
InfoLogger.Info("Service Stopped " + this.ServiceName, true);
}
}
}
My synch class where I have tried to use a bool to test the connection:
namespace Vessel_Schedule_Synch
{
class VesselUpdater
{
private OrganizationServiceProxy _serviceProxy;
private IOrganizationService _service;
private Logger logger = LogManager.GetLogger("VesselUpdater");
public string ConnectionString { get; set; }
public string ServiceUrl { get; set; }
int i = 0;
private bool InitialiseCRMConnection;
public VesselUpdater()
{
InitialiseCRMConnection = true;
Console.WriteLine("Starting the service");
LogMessage("Starting service");
ServiceUrl = ConfigurationManager.AppSettings["CRMUrl"];
LogMessage(ConnectionString);
ConnectionString = ConfigurationManager.ConnectionStrings["iRoot"].ConnectionString;
LogMessage(ServiceUrl);
Console.WriteLine(ServiceUrl);
}
public void Process()
{
if (!InitialiseCRMConnection)
return;
LogMessage("Process Starting");
ClientCredentials UserCredentials = new ClientCredentials();
string UserName = ConfigurationManager.AppSettings["User"];
string Password = ConfigurationManager.AppSettings["Password"];
UserCredentials.UserName.UserName = UserName;
UserCredentials.UserName.Password = Password;
ClientCredentials DivCredentials = null;
Uri HomeRealmURI = null;
Uri serviceurl = new Uri(ServiceUrl);
_serviceProxy = new OrganizationServiceProxy(serviceurl, HomeRealmURI, UserCredentials, DivCredentials);
_serviceProxy.ServiceConfiguration.CurrentServiceEndpoint.Behaviors.Add(new ProxyTypesBehavior());
_service = (IOrganizationService)_serviceProxy;
_serviceProxy.EnableProxyTypes();
LogMessage("CRM Connection Initiated");
InitialiseCRMConnection = false;
}
public void updateCRM()
{
try
{
ProcessVesselSchedule("Insert");
ProcessVesselSchedule("Modification");
}
catch (Exception e)
{
InitialiseCRMConnection = true;
InfoLogger.Exception(e);
LogMessage("Exception " + e);
}
}
private void ProcessVesselSchedule(string Type)
{
if (InitialiseCRMConnection)
return;
try
{
LogMessage(string.Format("Processing Vessesl Schedules {0}", Type));
using (SqlConnection con = new SqlConnection(ConnectionString))
{
SqlCommand cmd = new SqlCommand("VesselScheduleInformation", con);
cmd.CommandType = System.Data.CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#Type", Type);
con.Open();
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
try
{
LogMessage("Processing Record");
LogMessage(dr["new_Name"].ToString());
string Name = dr["new_Name"].ToString() + " " + dr["new_VoyageNo"].ToString();
string Vesselname = dr["new_Name"].ToString();
int LineNo = (int)dr["Line Number"];
string NAVVesselScheduleCode = dr["new_NAVVesselScheduleCode"].ToString();
string CarrierService = dr["new_CarrierService"].ToString();
string ETA = dr["new_ETA"].ToString();
string ETD = dr["new_ETD"].ToString();
string VesselCode = dr["new_Vessel"].ToString();//Vessel Code
string VoyageNo = dr["new_VoyageNo"].ToString();
string TranshipmentVessel = dr["new_TranshipmentVessel"].ToString();
string TranshipmentVoyageNo = dr["new_TranshipmentVoyageNo"].ToString();
string Port = dr["new_Port"].ToString();
string PortOfDis = dr["new_DischargePort"].ToString();
string PortOfLoad = dr["new_LoadPort"].ToString();
//string StackStart = dr["new_StackStart"].ToString();
//string StackEnd = dr["new_StackEnd"].ToString();
bool Create = false;
LogMessage("Assigned all variables");
Console.WriteLine("Assigned all variables");
new_vesselschedule VesselS = FindVessleSchedule(NAVVesselScheduleCode, LineNo, out Create);
//if (DateTime.Parse(StackStart).ToUniversalTime() >= DateTime.Parse("1900-01-01"))
//{
// VesselS["new_stackstart"] = DateTime.Parse(StackStart).ToUniversalTime();
//}
//if (DateTime.Parse(StackEnd).ToUniversalTime() >= DateTime.Parse("1900-01-01"))
//{
// VesselS["new_stackend"] = DateTime.Parse(StackEnd).ToUniversalTime();
//}
VesselS.new_name = Name;
VesselS.new_navvesselschedulecode = NAVVesselScheduleCode;
VesselS.new_CarrierService = CarrierService;
if (DateTime.Parse(ETA).ToUniversalTime() >= DateTime.Parse("1900-01-01"))
{
VesselS.new_ETA = DateTime.Parse(ETA).ToUniversalTime();
}
if (DateTime.Parse(ETD).ToUniversalTime() >= DateTime.Parse("1900-01-01"))
{
VesselS.new_ETD = DateTime.Parse(ETD).ToUniversalTime();
}
VesselS.new_vesselcodeimport = VesselCode;
VesselS.new_vesselnameimport = Vesselname;
VesselS.new_VoyageNo = VoyageNo;
VesselS.new_TransshipmentVessel = TranshipmentVessel;
VesselS.new_TransshipmentVoyageNo = TranshipmentVoyageNo;
VesselS.new_dischargeportimport = PortOfDis;
VesselS.new_loadportimport = PortOfLoad;
if (Create)
{
LogMessage(string.Format("Created {0} {1}", NAVVesselScheduleCode, LineNo));
_serviceProxy.Create(VesselS);
}
else
{
LogMessage(string.Format("Updated {0} {1}", NAVVesselScheduleCode, LineNo));
_serviceProxy.Update(VesselS);
}
using (SqlCommand cmdUpdateMates = new SqlCommand())
{
SqlConnection con2 = new SqlConnection(ConnectionString);
con2.Open();
cmdUpdateMates.Connection = con2;
cmdUpdateMates.CommandText = "ProcessedVessSched";
cmdUpdateMates.CommandType = CommandType.StoredProcedure;
cmdUpdateMates.Parameters.AddWithValue("#VesselSched", NAVVesselScheduleCode);
cmdUpdateMates.Parameters.AddWithValue("#LineNo", LineNo);
cmdUpdateMates.ExecuteNonQuery();
i++;
Console.WriteLine("Created/Updated" + " " + i);
}
}
catch (Exception e)
{
InitialiseCRMConnection = true;
InfoLogger.Exception(e);
LogMessage("Exception " + e);
}
}
}
}
catch (SqlException e)
{
InfoLogger.Exception(e);
LogMessage("SQL Exception " + e);
}
catch (Exception e)
{
InitialiseCRMConnection = true;
InfoLogger.Exception(e);
LogMessage("Exception " + e);
}
}
public void LogMessage(string Message)
{
LogEventInfo myEvent = new LogEventInfo(LogLevel.Debug, "", Message);
myEvent.LoggerName = logger.Name;
logger.Log(myEvent);
}
private new_vesselschedule FindVessleSchedule(string NAVVesselScheduleCode, int LineNo, out bool Create)
{
QueryExpression query = new QueryExpression(new_vesselschedule.EntityLogicalName);
query.ColumnSet.AllColumns = true;
query.Criteria = new FilterExpression();
query.Criteria.AddCondition("new_navvesselschedulecode", ConditionOperator.Equal, NAVVesselScheduleCode);
query.Criteria.AddCondition("new_lineno", ConditionOperator.Equal, LineNo);
EntityCollection entitycollection = _serviceProxy.RetrieveMultiple(query);
if (entitycollection.Entities.Count == 0)
{
new_vesselschedule n = new new_vesselschedule();
n.new_navvesselschedulecode = NAVVesselScheduleCode;
n.new_lineno = LineNo;
Create = true;
return n;
}
Create = false;
return (new_vesselschedule)entitycollection.Entities[0];
}
}
}
Am I missing something here?
I found the issue in my code, I had forgotten to sent InitialiseCRMConnection = true; in my SQL Exception thus it could never go through the motions of reInitialising the connection as it would always return;
Fix:
catch (SqlException e)
{
InitialiseCRMConnection = true;
InfoLogger.Exception(e);
LogMessage("SQL Exception " + e);
}
It seems like my file system watcher is firing mulitple events and then ending up giving me an error:
The process cannot access the file, file is in use.
Here is my code:
private void button1_Click(object sender, EventArgs e)
{
// Form2 popup = new Form2();
if (Directory.Exists(this.textBox2.Text) && string.IsNullOrWhiteSpace(textBox2.Text))
{
MessageBox.Show("Please Select Source Folder");
return;
}
else if (Directory.Exists(this.textBox3.Text) && string.IsNullOrWhiteSpace(textBox3.Text))
{
MessageBox.Show("Please Select Destination Folder");
return;
}
else WatchFile();
private void WatchFile(/*string watch_folder*/)
{
FileSystemWatcher _watcher = new FileSystemWatcher();
_watcher.Path = textBox2.Text;
_watcher.NotifyFilter = NotifyFilters.LastWrite;
_watcher.Filter = "*.log";
_watcher.Changed += new FileSystemEventHandler(InitList);
_watcher.EnableRaisingEvents = true;
_watcher.IncludeSubdirectories = false;
listBox1.Items.Add("Started Monitoring Directory " + textBox2.Text);
listBox1.SelectedIndex = listBox1.Items.Count - 1;
}
private object lockObject = new Object();
public void InitList(object source, FileSystemEventArgs f)
{
_recordList = new List<MyData>();
string fileName = f.FullPath;
string filePath = f.Name;
string trPath = fileName;
string[] arrstringPath = new string[3];
arrstringPath[0] = filePath.Substring(2, 2);
arrstringPath[1] = filePath.Substring(4, 2);
arrstringPath[2] = filePath.Substring(6, 2);
string tempPath = "LG" + arrstringPath[0] + arrstringPath[1] + arrstringPath[2] + ".001";
string v15nativePath = textBox3.Text + tempPath;
_watcher.EnableRaisingEvents = false;
if (!Monitor.TryEnter(lockObject))
{
return;
}
else
try
{
//_watcher.EnableRaisingEvents = false;
_watcher.Changed -= new FileSystemEventHandler(InitList);
FileStream trFS = new FileStream(trPath, FileMode.Open, FileAccess.Read);
StreamReader trSR = new StreamReader(trFS);
// FileStream v15FS = new FileStream(v15nativePath, FileMode.Open, FileAccess.Write);
StreamWriter v15SR = new StreamWriter(v15nativePath, false);
var timeIndex = "S";
Func<string, MyData> values = new Func<string, MyData>(
(x) =>
{
if ((x[0].ToString()) == "S")
{
var temptime = x.IndexOf("S");
timeIndex = x.Substring(temptime + 1, 4);
}
if ((x[0].ToString()) == "C")
{
var trackIndex = x.IndexOf(":");
var titleidString = x.Substring(11, 6);
var trackString = x.Substring(17, 40);
var trackDuration = x.Substring(57, 5);
return new MyData { Time = timeIndex, Duration = trackDuration, TitleID = titleidString, Track = trackString };
}
else
return null;
});
while (trSR.Peek() != -1)
{
var data = trSR.ReadLine();
MyData my = values(data);
if (my != null)
_recordList.Add(my);
}
trFS.Close();
trSR.Close();
var groupData = from data in _recordList
select new
{
Name = data.Track,
Duration = data.Duration,
Time = data.Time,
ID = data.TitleID
};
foreach (var item in groupData)
{
var newstringLen = item.Name.Truncate(27);
var v15timeString = item.Duration;
var v15fileString = "C" + item.Time + ":" + "00" + item.ID + " " + newstringLen + v15timeString;
v15SR.WriteLine(v15fileString);
v15SR.Flush();
}
v15SR.Close();
this.Invoke((MethodInvoker)delegate { listBox1.Items.Add(string.Format("File is Translated")); });
_watcher.Changed += new FileSystemEventHandler(InitList);
}
catch (Exception e)
{
//listBox1.Items.Add("The process failed: "+" "+e.ToString());.
MessageBox.Show("The Process Failed:" + e.ToString());
}
finally
{
Monitor.Exit(lockObject);
_watcher.Path = textBox2.Text;
_watcher.EnableRaisingEvents = true;
GC.Collect();
GC.WaitForPendingFinalizers();
GC.Collect();
}
}
I have called _watcher.EnableRaisingEvents = false; before the try block and then make it true in the final block yet. the watching get's disabled while I do the processing then why does it run the InitList method again after it finishes. This seems like a mulitple run on the same file, and so causing this exception
I am new to programming and I have this project due on coming Tuesday. What I am trying to do is if a user enters a wrong password on the logon screen the cam takes the picture. I tried to implement my code in services but it gives me error 1053. I was wondering if somebody could fix this code for me or if file watcher is of use in my code. Please help!
namespace SampleWS
{
public partial class Service1 : ServiceBase
{
private WebCam camera;
public Service1()
{
InitializeComponent();
}
public void OnDebug()
{
OnStart(null);
}
protected virtual void OnPause(string[] args)
{
bool infinite = false;
LogonChecker(infinite);
}
protected virtual void OnContinue(string[] args)
{
bool infinite = true;
LogonChecker(infinite);
}
protected override void OnStart(string[] args)
{
bool infinite = true;
LogonChecker(infinite);
}
protected override void OnStop()
{
bool infinite = false;
LogonChecker(infinite);
}
DateTime mytime = DateTime.MinValue;
public void LogonChecker(bool infinity)
{
string queryString =
"<QueryList>" +
" <Query Id=\"\" Path=\"Security\">" +
" <Select Path=\"Security\">" +
" *[System[(Level <= 0) and" +
" TimeCreated[timediff(#SystemTime) <= 86400000]]]" +
" </Select>" +
" <Suppress Path=\"Application\">" +
" *[System[(Level = 0)]]" +
" </Suppress>" +
" <Select Path=\"System\">" +
" *[System[(Level=1 or Level=2 or Level=3) and" +
" TimeCreated[timediff(#SystemTime) <= 86400000]]]" +
" </Select>" +
" </Query>" +
"</QueryList>";
camera = new WebCam();
while (infinity)
{
EventLogQuery eventsQuery = new EventLogQuery("Security", PathType.LogName, queryString);
eventsQuery.ReverseDirection = true;
EventLogReader logReader = new EventLogReader(eventsQuery);
EventRecord eventInstance;
Int32 eventexists3 = new Int32();
EventLog mylog = new EventLog();
for (eventInstance = logReader.ReadEvent(); null != eventInstance; eventInstance = logReader.ReadEvent())
{
eventexists3 = eventInstance.Id.CompareTo(4625);
if (eventexists3 == 0)
{
if (eventInstance.TimeCreated.Value > mytime)
{
mytime = eventInstance.TimeCreated.Value;
camera.Connect();
Image image = camera.GetBitmap();
image.Save(#"D:\Audio\testimage3.jpg");
camera.Disconnect();
eventInstance = null;
break;
}
}
EventLogRecord logRecord = (EventLogRecord)eventInstance;
LogonChecker(infinity);
}
}
}
}
}
Despite my comment, this is easy. Check what the error 1053 means:
ERROR_SERVICE_REQUEST_TIMEOUT
1053 (0x41D)
The service did not respond to the start or control request in a timely fashion.
Your overrides of ServiceBase methods like OnStart need to return as soon as possible. If you want to perform any ongoing work either subscribe to events or spin up a worker thread.
The .NET documentation on MSDN doesn't really cover much about the execution model of services, for this you need to look at the Win32 documentation: About Services.
I have a windows service that is supposed to check for a record, email a report for that record, delete the record and then repeat for the table. It checks for the record, emails a report for the first record then shuts off. Any ideas??
Service code:
namespace ReportSender
{
public partial class EmailReportService : ServiceBase
{
private EmailReportApp _app = new EmailReportApp();
public Timer serviceTimer = new Timer();
public EmailReportService()
{
InitializeComponent();
}
protected override void OnStart(string[] args)
{
//Set interval (from App Settings) and enable timer
serviceTimer.Elapsed += new ElapsedEventHandler(ServiceTimer_OnElapsed);
//Use Conversion utility to determine next start date/time based on properties, use DateTime.Subtract() to find milliseconds difference between Now and the next start time
//serviceTimer.Interval = Date.AddInterval(Properties.Settings.Default.IntervalType, Properties.Settings.Default.Interval).Subtract(DateTime.Now).TotalMilliseconds;
serviceTimer.Interval = 600000;
serviceTimer.Enabled = true;
}
protected override void OnStop()
{
//Stop and disable timer
serviceTimer.Enabled = false;
}
private void ServiceTimer_OnElapsed(object source, ElapsedEventArgs e)
{
try
{
//Stop the timer to prevent overlapping runs
serviceTimer.Stop();
//Start service
//Run your app.Start() code
_app = new EmailReportApp();
_app.Start();
}
catch (Exception ex)
{
}
finally
{
//Re-start the timer
serviceTimer.Start();
}
}
}
}
Code the service is supposed to execute:
namespace ReportSender
{
class EmailReportApp
{
// Private fields
private Thread _thread;
private EventLog _log;
private void Execute()
{
try
{
// Check for a new record
DataClasses1DataContext dc = new DataClasses1DataContext();
foreach (var item in dc.reportsSent1s)
{
string matchedCaseNumber = item.CaseNumberKey;
(new MyReportRenderer()).RenderTest(matchedCaseNumber);
dc.reportsSent1s.DeleteOnSubmit(item);
dc.SubmitChanges();
}
}
catch (ThreadAbortException ex)
{
_log.WriteEntry(ex.StackTrace.ToString());
}
}
public void Start()
{
if (!EventLog.SourceExists("EventLoggerSource"))
EventLog.CreateEventSource("EventLoggerSource", "Event Logger");
_log = new EventLog("EventLoggerSource");
_log.Source = "EventLoggerSource";
_thread = new Thread(new ThreadStart(Execute));
_thread.Start();
}
public void Stop()
{
if (_thread != null)
{
_thread.Abort();
_thread.Join();
}
}
}
public class MyReportRenderer
{
private rs2005.ReportingService2005 rs;
private rs2005Execution.ReportExecutionService rsExec;
public void RenderTest(String matchedCaseNumber)
{
string HistoryID = null;
string deviceInfo = null;
string encoding = String.Empty;
string mimeType = String.Empty;
string extension = String.Empty;
rs2005Execution.Warning[] warnings = null;
string[] streamIDs = null;
rs = new rs2005.ReportingService2005();
rsExec = new rs2005Execution.ReportExecutionService();
rs.Credentials = System.Net.CredentialCache.DefaultCredentials;
rsExec.Credentials = System.Net.CredentialCache.DefaultCredentials;
rs.Url = "http://***.**.***.**/ReportServer_DEVELOPMENT/ReportService2005.asmx";
rsExec.Url = "http://***.**.***.**/ReportServer_DEVELOPMENT/ReportExecution2005.asmx";
try
{
// Load the selected report.
rsExec.LoadReport("/LawDept/LawDeptTIC", HistoryID);
// Set the parameters for the report needed.
rs2005Execution.ParameterValue[] parameters = new rs2005Execution.ParameterValue[1];
parameters[0] = new rs2005Execution.ParameterValue();
parameters[0].Name = "CaseNumberKey";
parameters[0].Value = matchedCaseNumber;
rsExec.SetExecutionParameters(parameters, "en-us");
// get pdf of report
Byte[] results = rsExec.Render("PDF", deviceInfo,
out extension, out encoding,
out mimeType, out warnings, out streamIDs);
//pass paramaters for email
DataClasses1DataContext db = new DataClasses1DataContext();
var matchedBRT = (from c in db.GetTable<vw_ProductClientInfo>()
where c.CaseNumberKey == matchedCaseNumber
select c.BRTNumber).SingleOrDefault();
var matchedAdd = (from c in db.GetTable<vw_ProductClientInfo>()
where c.CaseNumberKey == matchedCaseNumber
select c.Premises).SingleOrDefault();
//send email with attachment
MailMessage message = new MailMessage("234#acmetaxabstracts.com", "georr#gmail.com", "Report for BRT # " + matchedAdd, "Attached if the Tax Information Certificate for the aboved captioned BRT Number");
MailAddress copy = new MailAddress("a123s#gmail.com");
message.CC.Add(copy);
SmtpClient emailClient = new SmtpClient("***.**.***.**");
message.Attachments.Add(new Attachment(new MemoryStream(results), String.Format("{0}" + matchedBRT + ".pdf", "BRT")));
emailClient.Send(message);
}
catch (Exception ex)
{
}
}
}
}
The 'ServiceBase' is losing scope once the OnStart method is called. A 'ManualResetEvent' will keep the service open for you.
Use member:
ManualResetEvent stop = new ManualResetEvent(false);
Try this in your main Start():
do
{
try
{
_app = new EmailReportApp();
_app.Start();
}
catch(Exception e)
{
... handle error or log however you want
}
}
while(!stop.WaitOne(0, false))
in Stop(), make sure to do stop.Set()