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
Related
I need to make a button that will stop downloading the file. For example, I clicked 1 time the download started and the second time it stopped.
private static async void Download()
{
foreach (string fileName in fileList)
{
string localDir = AppDomain.CurrentDomain.BaseDirectory;
localDir.Substring(0, localDir.Length - 1);
localDir += fileName;
long fileSize = await ftp.GetFileSizeAsync(fileName);
fileSize /= 1024;
form.progressBar1.Maximum = (int)fileSize;
var token = new CancellationToken();
Progress<FtpProgress> progress = new Progress<FtpProgress>(async loadedFile =>
{
if (loadedFile.Progress == 100)
{
form.progressBar1.Value = 0;
}
else
{
int x = (int)fileSize * Convert.ToInt32(loadedFile.Progress) / 100;
string value = loadedFile.TransferSpeedToString();
form.label1.Text = "Connection Speed: \n" + value;
form.progressBar1.Value = x;
}
});
await ftp.DownloadFileAsync(localDir, fileName, FtpLocalExists.Skip, FluentFTP.FtpVerify.Retry, progress, token);
}
}
First of all, you don't create directly a CancellationToken, you create a CancellationTokenSource and get it's Token.
Said that, you can imagine the use of that token, to allow to cancel the operation.
You can do something like this:
//At class level
CancellationTokenSource cancel = null;
private static async void Download()
{
if(cancel != null)
{
cancel.Cancel();
cancel.Dispose();
cancel = null;
return;
}
cancel = new CancellationTokenSource();
foreach (string fileName in fileList)
{
string localDir = AppDomain.CurrentDomain.BaseDirectory;
localDir.Substring(0, localDir.Length - 1);
localDir += fileName;
long fileSize = await ftp.GetFileSizeAsync(fileName);
fileSize /= 1024;
form.progressBar1.Maximum = (int)fileSize;
Progress<FtpProgress> progress = new Progress<FtpProgress>(async loadedFile =>
{
if (loadedFile.Progress == 100)
{
form.progressBar1.Value = 0;
cancel.Dispose();
cancel = null;
}
else
{
int x = (int)fileSize * Convert.ToInt32(loadedFile.Progress) / 100;
string value = loadedFile.TransferSpeedToString();
form.label1.Text = "Connection Speed: \n" + value;
form.progressBar1.Value = x;
}
});
try
{
await ftp.DownloadFileAsync(localDir, fileName, FtpLocalExists.Skip, FluentFTP.FtpVerify.Retry, progress, cancel.Token);
}
catch
{
//When the download is cancelled will throw an exception
//you can create a more specific handler
cancel.Dispose();
cancel = null;
}
}
}
i can succesfully read events from event log. But polling all events has very bad performance. I wonder if there is an event or something that i can subscribe to catch log entries "as they happen"?
Is this possible?
EventLog log = new EventLog("Security");
var entries = log.Entries.Cast<EventLogEntry>().Where(x => x.InstanceId == 4624).Select(x => new
{
x.MachineName,
x.Site,
x.Source,
x.UserName,
x.Message
}).ToList();
Console.WriteLine(entries[0].UserName);
You can use EventLogWatcher for this purpose. You can subscribe to desired log filter(s) and implement a handler function to execute when you receive any events.
public static void eventLogSubscription()
{
using (EventLog eventLog = new EventLog("Application"))
{
String path = Path.GetTempPath();
eventLog.Source = "Event Log Reader Application";
eventLog.WriteEvent(new EventInstance(1003, 0, EventLogEntryType.Information), new object[] { "The event log watcher has started" , path});
//eventLog.WriteEntry(arg.EventRecord.ToXml(), EventLogEntryType.Information, 1001, 1);
eventLog.Dispose();
}
EventLogWatcher watcher = null;
try
{
string eventQueryString = "*[System/EventID=4688]" +
"and " +
"*[EventData[Data[#Name = 'NewProcessName'] = 'C:\\Windows\\explorer.exe']]";
EventLogQuery eventQuery = new EventLogQuery(
"Security", PathType.LogName, eventQueryString);
watcher = new EventLogWatcher(eventQuery);
watcher.EventRecordWritten +=
new EventHandler<EventRecordWrittenEventArgs>(
handlerExplorerLaunch);
watcher.Enabled = true;
}
catch (EventLogReadingException e)
{
Console.WriteLine("Error reading the log: {0}", e.Message);
}
Console.ReadKey();
}
public static void handlerExplorerLaunch(object obj,
EventRecordWrittenEventArgs arg)
{ if (arg.EventRecord != null)
{
using (EventLog eventLog = new EventLog("Application"))
{
eventLog.Source = "Event Log Reader Application";
eventLog.WriteEvent(new EventInstance(1001, 0, EventLogEntryType.Information), new object[] {arg.EventRecord.FormatDescription() });
//eventLog.WriteEntry(arg.EventRecord.ToXml(), EventLogEntryType.Information, 1001, 1);
eventLog.Dispose();
}
}
else
{
Console.WriteLine("The event instance was null.");
}
}
I have found this to work more reliably.
using System;
using System.Diagnostics.Eventing.Reader;
static void Main(string[] args)
{
if (args is null) throw new ArgumentNullException(nameof(args));
LoadEventLogs();
Console.ReadKey();
}
private static void LoadEventLogs()
{
EventLogSession session = new EventLogSession();
EventLogQuery query = new EventLogQuery("Security", PathType.LogName, "*[System/EventID=4688]")
{
TolerateQueryErrors = true,
Session = session
};
EventLogWatcher logWatcher = new EventLogWatcher(query);
logWatcher.EventRecordWritten += new EventHandler<EventRecordWrittenEventArgs>(LogWatcher_EventRecordWritten);
try
{
logWatcher.Enabled = true;
}
catch (EventLogException ex)
{
Console.WriteLine(ex.Message);
Console.ReadLine();
}
}
private static void LogWatcher_EventRecordWritten(object sender, EventRecordWrittenEventArgs e)
{
var time = e.EventRecord.TimeCreated;
var id = e.EventRecord.Id;
var logname = e.EventRecord.LogName;
var level = e.EventRecord.Level;
var task = e.EventRecord.TaskDisplayName;
var opCode = e.EventRecord.OpcodeDisplayName;
var mname = e.EventRecord.MachineName;
Console.WriteLine($#"{time}, {id}, {logname}, {level}, {task}, {opCode}, {mname}");
}
In my application, I have option to search a directory. If the user searching local drive then I'm searching the catalog first (searching the Index), then the directories
DirectoryInfo.GetDirectories("*" + AsearchString + "*",System.IO.SearchOption.AllDirectories).
In case of network searching (network folders), I am doing only directory search. Now the problem is, the user may or may not have access permission for files or folders. I am getting unauthorized exception and background worker stops right there, my confusion is how I can catch the exception (in case of PathTooLong or unauthorized exception, this happens when I am searching network drives ) so if there is an exception just log or omit it and continue working.
I am putting my work around below, I don't know why try/catch not working, or where I should move it so in case of exception it will disregard and keep going. I had to put the lots of code below, apologies for that, I appreciate any suggestions.
UPDATE:
Ignoring the exception in do work will stop the bcw, so I figured out my exception handling was incorrect. I have updated my code.
private void bwSearch_DoWork(object sender, DoWorkEventArgs e)
{
if (e.Argument != null && e.Argument.GetType() == typeof(List<string>))
{
if (this.InvokeRequired)
{
this.BeginInvoke(new Action(() => this.Cursor = Cursors.WaitCursor));
}
else
{
this.Cursor = Cursors.WaitCursor;
}
listViewBWSearchStatus = true;
List<string> par = e.Argument as List<string>;
string path = par[0];
string searchString = par[1];
try
{
if (FileSystemHelper.PathIsNetworkPath(path))
{
DirectoryInfo dInfo = new DirectoryInfo(path);
foreach (FileInfo fi in dInfo.GetFiles("*" + searchString + "*.*", System.IO.SearchOption.AllDirectories))
{
if (bwSearch.CancellationPending)
{
e.Cancel = true;
if (this.InvokeRequired)
{
this.BeginInvoke(new Action(() => this.Cursor = Cursors.Default));
}
else
{
this.Cursor = Cursors.Default;
}
break;
}
bwSearch.ReportProgress(0, fi);
}
foreach (DirectoryInfo d in dInfo.GetDirectories("*" + searchString + "*", System.IO.SearchOption.AllDirectories))
{
if (bwSearch.CancellationPending)
{
e.Cancel = true;
break;
}
bwSearch.ReportProgress(0, d);
}
}
else
{
var connection = new OleDbConnection(#"Provider=Search.CollatorDSO;Extended Properties=""Application=Windows""");
string searchDirectoryFormated = path.Replace(#"\", #"/");
// Folder name search (case insensitive), does not search sub directories
var directorySearchQuery = #"SELECT System.ItemName,System.ItemPathDisplay FROM SystemIndex " +
#"WHERE directory = 'file:" + searchDirectoryFormated + "' AND System.ItemType = 'Directory' AND System.Itemname LIKE '%" + searchString + "%' ";
// File name search (case insensitive), does not search sub directories
var fileSearchQuery = #"SELECT System.ItemName,System.ItemPathDisplay FROM SystemIndex " +
#"WHERE directory = 'file:" + searchDirectoryFormated + "' AND System.ItemName LIKE '%" + searchString + "%' ";
connection.Open();
var command = new OleDbCommand(directorySearchQuery, connection);
Dictionary<string, string> directoryResult = new Dictionary<string, string>();
using (var r = command.ExecuteReader())
{
while (r.Read())
{
if (bwSearch.CancellationPending)
{
e.Cancel = true;
break;
}
if (!directoryResult.ContainsKey(r.GetString(1)))
{
directoryResult.Add(r.GetString(1), r.GetString(0));
DirectoryInfo dirInfoIndexed = new DirectoryInfo(r.GetString(1));
bwSearch.ReportProgress(0, dirInfoIndexed);
}
}
}
command = new OleDbCommand(fileSearchQuery, connection);
Dictionary<string, string> fileResult = new Dictionary<string, string>();
using (var r = command.ExecuteReader())
{
while (r.Read())
{
if (bwSearch.CancellationPending)
{
e.Cancel = true;
break;
}
if (!fileResult.ContainsKey(r.GetString(1)))
{
fileResult.Add(r.GetString(1), r.GetString(0));
FileInfo fileInfoIndexed = new FileInfo(r.GetString(1));
bwSearch.ReportProgress(0, fileInfoIndexed);
}
}
}
connection.Close();
DirectoryInfo dInfo = new DirectoryInfo(path);
foreach (DirectoryInfo d in dInfo.GetDirectories("*" + searchString + "*", System.IO.SearchOption.AllDirectories))
{
if (bwSearch.CancellationPending)
{
e.Cancel = true;
break;
}
bwSearch.ReportProgress(0, d);
}
foreach (FileInfo fi in dInfo.GetFiles("*" + searchString + "*.*", System.IO.SearchOption.AllDirectories))
{
if (bwSearch.CancellationPending)
{
e.Cancel = true;
break;
}
bwSearch.ReportProgress(0, fi);
}
}
}
//catch (UnauthorizedAccessException) { } // ignoring the exception will stop the background worker
catch (UnauthorizedAccessException) { throw;}
catch (System.Exception )
{
throw;// new Exception(ex.Message);
}
}
}
private void bwSearch_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
if (e.UserState != null && e.UserState.GetType() == typeof(FileInfo))
{
FileInfo fInfo = e.UserState as FileInfo;
ListViewItem[] searchInfo = this.listView.Items.Find(Path.GetFileNameWithoutExtension(fInfo.Name), false);
if (searchInfo == null || searchInfo.Count() == 0)
{
string fileFullName = fInfo.FullName;
string lastAccessTime = fInfo.LastAccessTime.ToShortDateString();
string imageKey = "";
if (this.listView.SmallImageList.Images.ContainsKey(fInfo.Extension.ToLower()))
imageKey = fInfo.Extension.ToLower();
else
imageKey = Explorer._Unknown;
string strFileType = Explorer._Unknown;
fileExtensionToFileType.TryGetValue(fInfo.Extension.ToString(), out strFileType);
if (String.IsNullOrWhiteSpace(strFileType))
strFileType = Explorer._Unknown;
ListViewItem itemL = new ListViewItem(Path.GetFileNameWithoutExtension(fInfo.Name), imageKey);
itemL.Name = fInfo.Name;
itemL.Tag = fInfo;
ListViewItem.ListViewSubItem[] subItem = new ListViewItem.ListViewSubItem[]
{
new ListViewItem.ListViewSubItem(itemL, lastAccessTime),
new ListViewItem.ListViewSubItem(itemL, strFileType),
new ListViewItem.ListViewSubItem(itemL, Explorer.SizeSuffix(fInfo.Length)),
new ListViewItem.ListViewSubItem(itemL, fileFullName)
};
itemL.SubItems.AddRange(subItem);
this.BeginInvoke(new MethodInvoker(delegate
{
this.listView.BeginUpdate();
this.listView.Items.Add(itemL);
this.listView.EndUpdate();
}));
}
}
else if (e.UserState != null && e.UserState.GetType() == typeof(DirectoryInfo))
{
DirectoryInfo dInfo = e.UserState as DirectoryInfo;
string fullName = dInfo.FullName;
ListViewItem[] searchDirectories = this.listView.Items.Find(dInfo.Name, false);
if (searchDirectories == null || searchDirectories.Count() == 0)
{
ListViewItem itemL = new ListViewItem(dInfo.Name, Strings.FolderOpen);
itemL.Name = dInfo.Name;
itemL.Tag = dInfo;
ListViewItem.ListViewSubItem[] subItem = new ListViewItem.ListViewSubItem[]
{
new ListViewItem.ListViewSubItem(itemL, dInfo.LastAccessTime.ToShortDateString()),
new ListViewItem.ListViewSubItem(itemL, "File folder"),
new ListViewItem.ListViewSubItem(itemL, ""),
new ListViewItem.ListViewSubItem(itemL, fullName)
};
itemL.SubItems.AddRange(subItem);
this.BeginInvoke(new MethodInvoker(delegate
{
this.listView.BeginUpdate();
this.listView.Items.Add(itemL);
this.listView.EndUpdate();
}));
}
}
}
private void bwSearch_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
if (e.Error != null)
{
if (e.Error.GetType() == typeof(UnauthorizedAccessException))
{
}
if (e.Error.GetType() == typeof(Exception))
{ }
}
if (e.Error == null && e.Cancelled == false)
{
_ResetEventSearch.Set();
listViewBWSearchStatus = false;
if (this.InvokeRequired)
{
this.BeginInvoke(new Action(() => this.Cursor = Cursors.Default));
}
else
{
this.Cursor = Cursors.Default;
}
}
}
UPDATE :
This part of the code searches for files or folders based on the user defined string. I didn't want to stall users thread since searching will be a pile load of work, so I introduced background worker instead. I got exception when I was trying to read directories in foreach (DirectoryInfo d in dInfo.GetDirectories("*" + searchString + "*", System.IO.SearchOption.AllDirectories)). I think, when It was trying to get directory info or file info, it got stuck since user didn't had access permission.
Initially I wasn't throwing exception, hence, after getting the exception the bcw didn't move further. Instead it reported error and raised run worker completed event. After I have added throw bcw continued working for the rest of the directories.
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);
}
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.