// stolen from http://www.codinghorror.com/blog/archives/000264.html public static DateTime RetrieveLinkerTimestamp(Assembly asmb) { try { string filePath = asmb.Location; const int c_PeHeaderOffset = 60; const int c_LinkerTimestampOffset = 8; byte[] b = new byte[2048]; using (Stream s = new FileStream(filePath, FileMode.Open, FileAccess.Read)) s.Read(b, 0, 2048); int i = System.BitConverter.ToInt32(b, c_PeHeaderOffset); int secondsSince1970 = System.BitConverter.ToInt32(b, i + c_LinkerTimestampOffset); DateTime dt = new DateTime(1970, 1, 1, 0, 0, 0); dt = dt.AddSeconds(secondsSince1970); dt = dt.AddHours(TimeZone.CurrentTimeZone.GetUtcOffset(dt).Hours); return(dt); } catch (Exception ex) { AltUtil.ShowError(ex.Message); return(DateTime.MaxValue); } }
protected void AssertIsReady() { if (State != TaskState.Ready) { AltUtil.ShowError("Task is not ready when it should have been."); throw new Util.ShouldNotHappenException(); } }
private void TimerCbk(object state) { if (_timer == null) { return; // schedule has been exited } TaskBase owner = _owner; if (owner.Owner == null || !owner.Owner.Contains(owner)) { RenewTimer(); return; } switch (owner.State) { case TaskState.Ready: System.Diagnostics.Debug.Assert(false); break; case TaskState.Busy: try { owner.Message = "Could not run task on schedule: task is already running."; } catch (Exception ex) { AltUtil.ShowError(ex.Message); } RenewTimer(); break; case TaskState.Scheduled: if (!_skip) { LastRunTime = DateTime.Now; try { owner.ScheduledRun(this); } catch (Exception ex) { AltUtil.ShowError(ex.Message); } } RenewTimer(); break; case TaskState.Paused: RenewTimer(); break; default: System.Diagnostics.Debug.Assert(false); break; } }
private void tsbClear_Click(object sender, EventArgs e) { try { _textBox.Clear(); } catch (Exception ex) { AltUtil.ShowError(ex.Message); } }
private void txtWcfEndpointBaseAddress_Validating(object sender, CancelEventArgs e) { string text = ((TextBox)sender).Text; string proto = C1ReportsSchedulerService.Defaults.WcfEndpointBaseAddress.Substring(0, C1ReportsSchedulerService.Defaults.WcfEndpointBaseAddress.IndexOf("://") + 3); if (!text.StartsWith(proto)) { AltUtil.ShowError("WCF endpoint base address must start with " + proto); e.Cancel = true; } }
private void OnEntryWritten(EntryWrittenEventArgs e) { try { _textBox.AppendText(string.Format("{0} {1}: ", e.Entry.TimeGenerated.ToShortDateString(), e.Entry.TimeGenerated.ToLongTimeString())); _textBox.AppendText(e.Entry.Message); _textBox.AppendText("\r\n"); } catch (Exception ex) { AltUtil.ShowError(ex.Message); } }
public static void SetProperty(object target, string propertyName, string propertyValue) { if (target == null) { return; } try { PropertyDescriptor pd = TypeDescriptor.GetProperties(target)[propertyName]; object value = TypeDescriptor.GetConverter(pd.PropertyType).ConvertFrom(propertyValue); pd.SetValue(target, value); } catch { AltUtil.ShowError(string.Format("SetProperty failed for {0}, value was {1}.", propertyName, propertyValue)); } }
public override bool Run() { ActionState savedState = State; State = ActionState.Running; CheckedStatus = CheckedStatus.Working; try { if (AltUtil.LogActions) { string actionLog = string.Format("Running action Id {0} (task Id {1}): Type '{2}', Output file '{3}' (Export format '{4}').", Id, _owner.Id, this.Kind, this.OutputFileName, this.ExportFormatName); AltUtil.LogMessage(actionLog); } switch (Kind) { case ActionKind.Export: return(Export()); case ActionKind.Print: return(Print()); case ActionKind.Run: return(RunProgram()); default: System.Diagnostics.Debug.Assert(false); return(false); } } catch (Exception ex) { AltUtil.ShowError(string.Format("Error running action Id {0} (task Id {1}): {2}.", Id, _owner.Id, ex.Message)); throw; } finally { State = savedState; CheckedStatus = CheckedStatus.CheckedOk; if (AltUtil.LogActions) { AltUtil.LogMessage(string.Format("Finished running action {0}.", Id)); } } }
protected override void ResetOutputFileName() { switch (Kind) { case ActionKind.Export: OutputFileName = string.Empty; break; case ActionKind.Print: try { // at least on my machine, when running as a service, no printer was marked as default. // hence we use the first one installed if could not find a default. bool found = false; for (int i = 0; i < PrinterSettings.InstalledPrinters.Count && !found; ++i) { PrinterSettings ps = new PrinterSettings(); ps.PrinterName = PrinterSettings.InstalledPrinters[i]; if (ps.IsDefaultPrinter) { OutputFileName = ps.PrinterName; found = true; } } if (!found) { AltUtil.ShowWarning(string.Format("Could not find default printer, using {0}", PrinterSettings.InstalledPrinters[0])); OutputFileName = PrinterSettings.InstalledPrinters[0]; } } catch { OutputFileName = string.Empty; } break; case ActionKind.Run: OutputFileName = string.Empty; break; default: System.Diagnostics.Debug.Assert(false); break; } }
private bool RunProgram() { string message; if (!CanRunProgram(out message)) { AltUtil.ShowError(string.Format("Cannot run program: {0}", message)); return(false); } using (Process prog = new Process()) { prog.StartInfo.FileName = _owner.FileName; prog.StartInfo.CreateNoWindow = true; prog.StartInfo.UseShellExecute = false; prog.StartInfo.RedirectStandardError = true; prog.StartInfo.RedirectStandardOutput = true; // prog.StartInfo.Arguments = ""; todo prog.ErrorDataReceived += new DataReceivedEventHandler(prog_ErrorDataReceived); prog.OutputDataReceived += new DataReceivedEventHandler(prog_OutputDataReceived); prog.Start(); prog.BeginErrorReadLine(); prog.BeginOutputReadLine(); // timeout 1 minute (todo: allow to specify timeout): int timeout = (int)(TimeSpan.TicksPerMinute / TimeSpan.TicksPerMillisecond); if (!prog.WaitForExit(timeout)) { AltUtil.ShowError(string.Format("Timeout waiting for program \"{0}\" to exit (waited {1} milliseconds).", _owner.FileName, timeout)); } else { if (AltUtil.LogActions) { AltUtil.LogMessage(string.Format("Program \"{0}\" ended, exit code {1}.", _owner.FileName, prog.ExitCode)); } } prog.Close(); } return(true); }
private bool Export() { string message; if (!CanExport(out message)) { AltUtil.ShowError(string.Format("Cannot export: {0}", message)); return(false); } // do NOT try/catch here - exceptions should be handled by the caller (Run()): Exporter exporter = _exporter; exporter.Document = _owner.Document; // Note: setting ShowOptions to false should not be needed since a test // for IsUserInteractive was added in export (2.6.20093 or later). exporter.ShowOptions = false; // todo: add action's property to store export options, set them here: exporter.Export(OutputFileName); return(true); }
private void LogOutput(Process prog, DataReceivedEventArgs e, bool error) { // ignore empty data: if (string.IsNullOrEmpty(e.Data)) { return; } if (!AltUtil.LogProgramOutput) { return; } try { string msg = string.Format("Process \"{0}\" {1}: {2}", prog.ProcessName, error ? "ERROR" : "OUTPUT", e.Data); AltUtil.LogMessage(msg); } catch (Exception ex) { AltUtil.ShowError(ex.Message); } }
/// <summary> /// Runs all actions synchronously, in the current thread. /// </summary> public override void ScheduledRun(ScheduleBase runner) { System.Diagnostics.Debug.Assert(runner == _schedule); if (State != TaskState.Scheduled) { return; // this could happen if we were caught in a transitional state } try { State = TaskState.Busy; CheckedStatus = CheckedStatus.Working; if (AltUtil.LogTasks) { string taskLog = string.Format("Running task Id {0}: Type '{1}', File '{2}' (Report name '{3}').", Id, ReportKind, FileName, ReportName); AltUtil.LogMessage(taskLog); } lock (_actions.SyncRoot) foreach (ActionBase action in _actions) { action.Run(); } // unloading task ensures that reports are regenerated on each run: UnLoad(); } catch { // Note: errors if any should've been logged by action.Run, hence we just throw them on here. // AltUtil.ShowError(string.Format("Error running task Id {0}: {1}.", Id, ex.Message)); throw; } finally { CheckedStatus = CheckedStatus.CheckedOk; State = _schedule.Enabled ? TaskState.Scheduled : TaskState.Ready; if (AltUtil.LogTasks) { AltUtil.LogMessage(string.Format("Finished running task Id {0}.", Id)); } } }
private bool Print() { string message; if (!CanPrint(out message)) { AltUtil.ShowError(string.Format("Cannot print: {0}", message)); return(false); } object document = _owner.Document; C1Report report = document as C1Report; C1PrintDocument printDoc = report == null ? (C1PrintDocument)document : report.C1Document; PrinterSettings ps = new PrinterSettings(); ps.PrinterName = OutputFileName; if (!ps.IsValid) { return(false); } printDoc.Print(ps); return(true); }
protected override void OnListChanged(ListChangedEventArgs e) { base.OnListChanged(e); TaskBase owner = _owner; if (owner == null) { return; } if (e.ListChangedType == ListChangedType.ItemAdded || e.ListChangedType == ListChangedType.ItemDeleted) { owner.CheckedStatus = CheckedStatus.Unknown; } TaskListServer tasks = owner.Owner as TaskListServer; if (tasks == null) { return; } IC1ReportsSchedulerWcfCallback wcfCallback = tasks.WcfCallback; if (wcfCallback == null) { return; } try { switch (e.ListChangedType) { case ListChangedType.ItemAdded: try { ActionServer action = (ActionServer)this[e.NewIndex]; long ownerId; long actionId; string xml; lock (action.SyncRoot) { ownerId = owner.Id; actionId = action.Id; xml = action.ToProxyXml(); } wcfCallback.ActionAdded(ownerId, e.NewIndex, actionId, xml); } catch (Exception ex) { AltUtil.ShowError(ex.Message); } break; case ListChangedType.ItemChanged: try { ActionServer action = (ActionServer)this[e.NewIndex]; long ownerId; long actionId; string xml; lock (action.SyncRoot) { ownerId = owner.Id; actionId = action.Id; xml = action.ToProxyXml(); } wcfCallback.ActionPropertyChanged(ownerId, actionId, xml, e.PropertyDescriptor.Name); } catch (Exception ex) { AltUtil.ShowError(ex.Message); } break; case ListChangedType.ItemDeleted: // we need removed task's id, hence TaskRemoved must be called from RemoveItem override: // wcfCallback.TaskRemoved(TaskId(e.NewIndex)); break; case ListChangedType.ItemMoved: break; case ListChangedType.Reset: break; } } catch (Exception ex) { AltUtil.ShowError(ex.Message); IC1ReportsSchedulerWcf wcfService = tasks.WcfService; if (wcfService != null) { wcfService.Disconnect(ex.Message); } } }