public AddinScanner(AddinDatabase database, AddinScanResult scanResult, IProgressStatus monitor) { this.database = database; if (!scanResult.CheckOnly) { // If there is a local copy of the cecil reflector, use it instead of the one in the gac Type t; string asmFile = Path.Combine (Path.GetDirectoryName (GetType().Assembly.Location), "Mono.Addins.CecilReflector.dll"); if (File.Exists (asmFile)) { Assembly asm = Assembly.LoadFrom (asmFile); t = asm.GetType ("Mono.Addins.CecilReflector.Reflector"); } else { string refName = GetType().Assembly.FullName; int i = refName.IndexOf (','); refName = "Mono.Addins.CecilReflector.Reflector, Mono.Addins.CecilReflector" + refName.Substring (i); t = Type.GetType (refName, false); } if (t != null) reflector = (IAssemblyReflector) Activator.CreateInstance (t); else reflector = new DefaultAssemblyReflector (); if (monitor.LogLevel > 1) monitor.Log ("Using assembly reflector: " + reflector.GetType ()); reflector.Initialize (scanResult); coreAssembly = reflector.LoadAssembly (GetType().Assembly.Location); } }
public static void InitializeAddins() { AddinManager.Initialize(ApplicationContext.CommandLine.Contains("uninstalled") ? "." : Paths.ApplicationData); IProgressStatus monitor = ApplicationContext.CommandLine.Contains("debug-addins") ? new ConsoleProgressStatus(true) : null; AddinManager.AddinLoadError += (o, a) => { try { AddinManager.Registry.DisableAddin(a.AddinId); } catch {} Log.Error(a.Message, a.Exception); }; if (ApplicationContext.Debugging) { AddinManager.Registry.Rebuild(monitor); } else { AddinManager.Registry.Update(monitor); } }
public static bool PublishQueuedItems(Item triggerItem, Database[] targets, IProgressStatus progress = null) { if (ManuallyAddedCandidates.Count == 0) { return(false); } foreach (var database in targets) { if (progress != null) { progress.ReportStatus("> Publishing {0} synced item{2} in queue to {1}", MessageType.Debug, ManuallyAddedCandidates.Count, database.Name, ManuallyAddedCandidates.Count == 1 ? string.Empty : "s"); } var publishOptions = new PublishOptions(triggerItem.Database, database, PublishMode.SingleItem, triggerItem.Language, DateTime.UtcNow) { RootItem = triggerItem }; var result = new Publisher(publishOptions).PublishWithResult(); if (progress != null) { progress.ReportStatus("> Published synced items to {0} (New: {1}, Updated: {2}, Deleted: {3} Skipped: {4})", MessageType.Debug, database.Name, result.Statistics.Created, result.Statistics.Updated, result.Statistics.Deleted, result.Statistics.Skipped); } } return(true); }
protected virtual void WriteDataWithStatus(IProgressMonitor progressMonitor, ref IProgressStatus status, TextWriter writer, BindingListSource bindingListSource, DsvWriter dsvWriter) { IList <RowItem> rows = Array.AsReadOnly(bindingListSource.Cast <RowItem>().ToArray()); IList <PropertyDescriptor> properties = bindingListSource.GetItemProperties(new PropertyDescriptor[0]).Cast <PropertyDescriptor>().ToArray(); dsvWriter.WriteHeaderRow(writer, properties); var rowCount = rows.Count; int startPercent = status.PercentComplete; for (int rowIndex = 0; rowIndex < rowCount; rowIndex++) { if (progressMonitor.IsCanceled) { return; } int percentComplete = startPercent + (rowIndex * (100 - startPercent) / rowCount); if (percentComplete > status.PercentComplete) { status = status.ChangeMessage(string.Format(Resources.AbstractViewContext_WriteData_Writing_row__0___1_, (rowIndex + 1), rowCount)) .ChangePercentComplete(percentComplete); progressMonitor.UpdateProgress(status); } dsvWriter.WriteDataRow(writer, rows[rowIndex], properties); } }
internal bool Install(IProgressStatus monitor, params Package[] packages) { PackageCollection packs = new PackageCollection(); packs.AddRange(packages); return(Install(monitor, packs)); }
public bool LookupProteinMetadata(ref IProgressStatus progressStatus) { using (var proteomeDb = ProteomeDb.OpenProteomeDb(_pathProteome, _isTemporary)) { _progressStatus = progressStatus.ChangeMessage( string.Format(Resources.BackgroundProteomeManager_LoadBackground_Resolving_protein_details_for__0__proteome, _nameProteome)); bool result = false; // Well formatted Uniprot headers don't require web access, so do an inital pass in hopes of finding those, then a second pass that requires web access for (var useWeb = 0; useWeb <= 1; useWeb++) { if (_progressStatus.IsCanceled) { break; } if (useWeb == 1 && !_manager.FastaImporter.HasWebAccess()) // Do we even have web access? { _progressStatus = _progressStatus.ChangeMessage(Resources.DigestHelper_LookupProteinMetadata_Unable_to_access_internet_to_resolve_protein_details_) .ChangeWarningMessage(Resources.DigestHelper_LookupProteinMetadata_Unable_to_access_internet_to_resolve_protein_details_).Cancel(); result = false; } else { bool done; result |= proteomeDb.LookupProteinMetadata(this, ref _progressStatus, _manager.FastaImporter, useWeb == 0, out done); // first pass, just parse descriptions, second pass use web. if (done) { break; } } } progressStatus = _progressStatus; return(result); } }
public static IProgressMonitor GetProgressMonitor (IProgressStatus status) { if (status == null) return new NullProgressMonitor (); else return new ProgressStatusMonitor (status); }
public UpdateProgressResponse UpdateProgress(IProgressStatus status) { _broker.ProgressValue = status.PercentComplete; _broker.Message = status.Message; Status = status; return(UpdateProgressResponse.normal); }
public bool ProgressEqual(IProgressStatus status) { var multiProgressStatus = status as MultiProgressStatus; if (multiProgressStatus == null) { return(PercentComplete == status.PercentComplete); } else if (ProgressList.Count != multiProgressStatus.ProgressList.Count) { return(false); } else { for (int i = 0; i < ProgressList.Count; i++) { var s1 = ProgressList[i]; var s2 = multiProgressStatus.ProgressList[i]; if (!ReferenceEquals(s1.Id, s2.Id)) { return(false); } if (s1.PercentComplete != s2.PercentComplete) { return(false); } } } return(true); }
public void BuildPackage(IProgressStatus statusMonitor, string targetDirectory, params string[] filePaths) { foreach (string file in filePaths) { BuildPackageInternal(statusMonitor, targetDirectory, file); } }
internal static void ExecuteCommand (IProgressStatus monitor, string registryPath, string startupDir, string name, params string[] args) { string asm = new Uri (typeof(SetupProcess).Assembly.CodeBase).LocalPath; string verboseParam = monitor.VerboseLog ? "v " : "nv"; Process process = new Process (); if (Util.IsWindows) process.StartInfo = new ProcessStartInfo (asm, verboseParam + " " + name + " " + string.Join (" ", args)); else process.StartInfo = new ProcessStartInfo ("mono", "--debug " + asm + " " + verboseParam + " " + name + " " + string.Join (" ", args)); process.StartInfo.WorkingDirectory = AppDomain.CurrentDomain.BaseDirectory; process.StartInfo.UseShellExecute = false; process.StartInfo.RedirectStandardInput = true; process.StartInfo.RedirectStandardOutput = true; process.StartInfo.RedirectStandardError = true; process.EnableRaisingEvents = true; try { process.Start (); } catch (Exception ex) { Console.WriteLine (ex); throw; } process.StandardInput.WriteLine (registryPath); process.StandardInput.WriteLine (startupDir); process.StandardInput.Flush (); // string rr = process.StandardOutput.ReadToEnd (); // Console.WriteLine (rr); ProcessProgressStatus.MonitorProcessStatus (monitor, process.StandardOutput); process.WaitForExit (); if (process.ExitCode != 0) throw new ProcessFailedException (); }
/// <summary> /// Loads an add-in description /// </summary> /// <param name="progressStatus"> /// Progress tracker. /// </param> /// <param name="file"> /// Name of the file to load /// </param> /// <returns> /// An add-in description /// </returns> /// <remarks> /// This method loads an add-in description from a file. The file can be an XML manifest or an /// assembly that implements an add-in. /// </remarks> public AddinDescription GetAddinDescription(IProgressStatus progressStatus, string file) { if (currentDomain == AddinDatabase.UnknownDomain) { return(null); } string outFile = Path.GetTempFileName(); try { database.ParseAddin(progressStatus, currentDomain, file, outFile, false); } catch { File.Delete(outFile); throw; } try { AddinDescription desc = AddinDescription.Read(outFile); if (desc != null) { desc.AddinFile = file; desc.OwnerDatabase = database; } return(desc); } catch { // Errors are already reported using the progress status object return(null); } finally { File.Delete(outFile); } }
private BlibDb(String path) { FilePath = path; SessionFactory = BlibSessionFactoryFactory.CreateSessionFactory(path, false); DatabaseLock = new ReaderWriterLock(); _progressStatus = new ProgressStatus(string.Empty); }
public void MinimizeToFile(string targetFile, CacheFormat cacheFormat) { var targetSkydFile = ChromatogramCache.FinalPathForName(targetFile, null); using (var skydSaver = new FileSaver(targetSkydFile, true)) using (var scansSaver = new FileSaver(targetSkydFile + ChromatogramCache.SCANS_EXT, true)) using (var peaksSaver = new FileSaver(targetSkydFile + ChromatogramCache.PEAKS_EXT, true)) using (var scoreSaver = new FileSaver(targetSkydFile + ChromatogramCache.SCORES_EXT, true)) { var minimizer = Document.Settings.MeasuredResults.GetChromCacheMinimizer(Document); var settings = new ChromCacheMinimizer.Settings().ChangeCacheFormat(cacheFormat); var lockObject = new object(); ProgressMonitor.UpdateProgress(_progressStatus = _progressStatus.ChangeMessage(Resources.SrmDocumentSharing_MinimizeToFile_Writing_chromatograms)); minimizer.Minimize(settings, stats => { if (ProgressMonitor.IsCanceled) { throw new OperationCanceledException(); } lock (lockObject) { ProgressMonitor.UpdateProgress(_progressStatus = _progressStatus.ChangePercentComplete(stats.PercentComplete)); } }, skydSaver.FileStream, scansSaver.FileStream, peaksSaver.FileStream, scoreSaver.FileStream); skydSaver.Commit(); } }
public void GetAddinDescription(IProgressStatus monitor, string registryPath, string startupDir, string addinsDir, string databaseDir, string file, string outFile) { AddinDatabase.RunningSetupProcess = true; AddinRegistry reg = new AddinRegistry(registryPath, startupDir, addinsDir, databaseDir); reg.ParseAddin(monitor, file, outFile); }
public static AddinScanDataIndex LoadFromFolder(IProgressStatus monitor, string path) { var file = Path.Combine(path, "dir.addindata"); if (File.Exists(file)) { try { using (Stream s = File.OpenRead(file)) { BinaryXmlReader reader = new BinaryXmlReader(s, typeMap); reader.ContextData = file; return((AddinScanDataIndex)reader.ReadValue("data")); } } catch (Exception ex) { if (monitor != null) { monitor.ReportError("Could not load dir.addindata file", ex); } // The addindata file is corrupted or changed format. // It is not useful anymore, so remove it try { File.Delete(file); } catch { // Ignore error deleting. Maybe there is a permission issue. } } } return(null); }
public AddinRepository RegisterRepository (IProgressStatus monitor, string url, bool updateNow) { if (!url.EndsWith (".mrep")) url = url + "/main.mrep"; RepositoryRecord rr = FindRepositoryRecord (url); if (rr != null) return rr; RegisterRepository (url, false); try { if (updateNow) { UpdateRepository (monitor, url); rr = FindRepositoryRecord (url); Repository rep = rr.GetCachedRepository (); rr.Name = rep.Name; } service.SaveConfiguration (); return rr; } catch (Exception ex) { if (monitor != null) monitor.ReportError ("The repository could not be registered", ex); if (ContainsRepository (url)) RemoveRepository (url); return null; } }
public bool Install (IProgressStatus statusMonitor, params AddinRepositoryEntry[] addins) { Package[] packages = new Package [addins.Length]; for (int n=0; n<addins.Length; n++) packages [n] = AddinPackage.FromRepository (addins [n]); return Install (statusMonitor, packages); }
private IList <IncludeEntry> GetPresetName(IProgressStatus progress) { string presetName = Request.QueryString["preset"] ?? "default"; progress.ReportStatus("Using preset name {0}", MessageType.Info, presetName); return(SerializationUtility.GetPreset(presetName)); }
private IList<IncludeEntry> GetPresetName(IProgressStatus progress) { string presetName = Request.QueryString["preset"] ?? "default"; progress.ReportStatus("Using preset name {0}", MessageType.Info, presetName); return SerializationUtility.GetPreset(presetName); }
/// <summary> /// Registers an instance of the <see cref="IProgressStatus"/> interface to automatically updates the work progress. /// </summary> /// <param name="progressStatus">The instance of <see cref="IProgressStatus"/> to register.</param> /// <param name="updateAsync">Indicate whether progress update must be processed asynchronously via the <see cref="UpdateProgressAsync"/> method.</param> public void RegisterProgressStatus(IProgressStatus progressStatus, bool updateAsync) { registeredProgressStatus = progressStatus; progressStatusUpdateAsync = updateAsync; progressStatus.ProgressChanged += ProgressChanged; Minimum = 0; Maximum = 1; }
public bool Install (IProgressStatus statusMonitor, params string[] files) { Package[] packages = new Package [files.Length]; for (int n=0; n<files.Length; n++) packages [n] = AddinPackage.FromFile (files [n]); return Install (statusMonitor, packages); }
protected override void Process(IProgressStatus progress) { var configurations = ResolveConfigurations(); foreach (var configuration in configurations) { var logger = configuration.Resolve<ILogger>(); using (new LoggingContext(new WebConsoleLogger(progress), configuration)) { try { logger.Info("Control Panel Sync: Processing Unicorn configuration " + configuration.Name); var beginArgs = new UnicornSyncBeginPipelineArgs(configuration); CorePipeline.Run("unicornSyncBegin", beginArgs); if (beginArgs.Aborted) { logger.Error("Unicorn Sync Begin pipeline was aborted. Not executing sync for this configuration."); continue; } if (beginArgs.SyncIsHandled) { logger.Info("Unicorn Sync Begin pipeline signalled that it handled the sync for this configuration."); continue; } var pathResolver = configuration.Resolve<PredicateRootPathResolver>(); var retryer = configuration.Resolve<IDeserializeFailureRetryer>(); var consistencyChecker = configuration.Resolve<IConsistencyChecker>(); var loader = configuration.Resolve<SerializationLoader>(); var roots = pathResolver.GetRootSerializedItems(); var index = 0; loader.LoadAll(roots, retryer, consistencyChecker, item => { progress.Report((int)(((index + 1) / (double)roots.Length) * 100)); index++; }); CorePipeline.Run("unicornSyncComplete", new UnicornSyncCompletePipelineArgs(configuration)); logger.Info("Control Panel Sync: Completed syncing Unicorn configuration " + configuration.Name); } catch (Exception ex) { logger.Error(ex); break; } } } CorePipeline.Run("unicornSyncEnd", new UnicornSyncEndPipelineArgs(configurations)); }
protected override void Process(IProgressStatus progress) { var configurations = ResolveConfigurations(); foreach (var configuration in configurations) { var logger = configuration.Resolve <ILogger>(); using (new LoggingContext(new WebConsoleLogger(progress), configuration)) { try { logger.Info("Control Panel Sync: Processing Unicorn configuration " + configuration.Name); var beginArgs = new UnicornSyncBeginPipelineArgs(configuration); CorePipeline.Run("unicornSyncBegin", beginArgs); if (beginArgs.Aborted) { logger.Error("Unicorn Sync Begin pipeline was aborted. Not executing sync for this configuration."); continue; } if (beginArgs.SyncIsHandled) { logger.Info("Unicorn Sync Begin pipeline signalled that it handled the sync for this configuration."); continue; } var pathResolver = configuration.Resolve <PredicateRootPathResolver>(); var retryer = configuration.Resolve <IDeserializeFailureRetryer>(); var consistencyChecker = configuration.Resolve <IConsistencyChecker>(); var loader = configuration.Resolve <SerializationLoader>(); var roots = pathResolver.GetRootSerializedItems(); var index = 0; loader.LoadAll(roots, retryer, consistencyChecker, item => { progress.Report((int)(((index + 1) / (double)roots.Length) * 100)); index++; }); CorePipeline.Run("unicornSyncComplete", new UnicornSyncCompletePipelineArgs(configuration)); logger.Info("Control Panel Sync: Completed syncing Unicorn configuration " + configuration.Name); } catch (Exception ex) { logger.Error(ex); break; } } } CorePipeline.Run("unicornSyncEnd", new UnicornSyncEndPipelineArgs(configurations)); }
public static ProgressMonitorImpl NewProgressMonitorImpl(IProgressStatus currentStatus, Func <int, bool> updateProgress) { return(new ProgressMonitorImpl( () => !updateProgress.Invoke(currentStatus.PercentComplete), status => { currentStatus = status; updateProgress(status.PercentComplete); })); }
private void UpdateSearchEngineProgress(IProgressStatus status) { var newEntry = new ProgressEntry(DateTime.Now, status.Message); _progressTextItems.Add(newEntry); txtSearchProgress.AppendText($@"{newEntry.ToString(showTimestampsCheckbox.Checked)}{Environment.NewLine}"); UpdateTaskbarProgress(TaskbarProgress.TaskbarStates.Normal, status.PercentComplete); progressBar.Value = status.PercentComplete; }
/// <summary> /// Constructor for ProgressDialogWindow. /// </summary> /// <param name="progressWindowTitle">Window title.</param> /// <param name="ps">IProgressStatus providing the status information and updates. /// A sample implementation of the IProgressStatus Interface based on the Prism MVVM framework is provided in the seperate ProgressDialogStatus nuget package. This implementation is ready-to-use for projects using Prism for the MVMM pattern. /// </param> /// <param name="owner">Window owning this dialog. This dialog will be centered on the owner. If not provided, dialog will still work, but not be centered.</param> public ProgressDialogWindow(string progressWindowTitle, IProgressStatus ps, Window owner = null) { ProgressStatus = ps ?? throw new ArgumentNullException(nameof(ps)); DataContext = ps; Title = progressWindowTitle; InitializeComponent(); Closing += ProgressDialogWindow_Closing; Owner = owner; }
protected virtual void ProcessInternal(IProgressStatus progress) { // this bad-ass ASCII art is from http://www.ascii-art.de/ascii/uvw/unicorn.txt - original credit to 'sk' const string unicorn = @"<pre> / .7 \ , // |\.--._/|// /\ ) ) ).'/ /( \ // / _ _ _ _ ___ ____ ___ ____ _ _ /( J`((_/ \ | | | | \ | |_ _/ ___/ _ \| _ \| \ | | / ) | _\ / | | | | \| || | | | | | | |_) | \| | /|) \ eJ L | |_| | |\ || | |__| |_| | _ <| |\ | | \ L \ L L \___/|_| \_|___\____\___/|_| \_\_| \_| / \ J `. J L | ) L \/ \ / \ J (\ / | \ \ \``` </pre>"; // note: these logs are intentionally to progress and not loggingConsole as we don't need them in the Sitecore logs progress.ReportStatus(unicorn, MessageType.Warning); progress.ReportTransientStatus("Executing."); var heartbeat = new Timer(3000); var startTime = DateTime.Now; heartbeat.AutoReset = true; heartbeat.Elapsed += (sender, args) => { var elapsed = Math.Round((args.SignalTime - startTime).TotalSeconds); progress.ReportTransientStatus("Executing for {0} sec.", elapsed.ToString(CultureInfo.InvariantCulture)); }; heartbeat.Start(); try { using (new SecurityDisabler()) { using (new ItemFilterDisabler()) // disable all item filtering (if we're running in live mode we need this to get unadulterated items) { Process(progress); } } } finally { heartbeat.Stop(); } progress.Report(100); progress.ReportTransientStatus("Completed."); progress.ReportStatus(_isAutomatedTool ? "\r\n" : "<br>"); progress.ReportStatus("Completed. Want to <a href=\"?verb=\">return to the control panel?</a>"); }
public void Scan (IProgressStatus monitor, AddinRegistry registry, string scanFolder, string[] filesToIgnore) { AddinRegistry reg = new AddinRegistry (registry.RegistryPath, registry.StartupDirectory, registry.DefaultAddinsFolder, registry.AddinCachePath); reg.CopyExtensionsFrom (registry); StringCollection files = new StringCollection (); for (int n=0; n<filesToIgnore.Length; n++) files.Add (filesToIgnore[n]); reg.ScanFolders (monitor, scanFolder, files); }
internal static void ExecuteCommand (IProgressStatus monitor, string registryPath, string startupDir, string addinsDir, string databaseDir, string name, string arg1, params string[] args) { string verboseParam = monitor.LogLevel.ToString (); // Arguments string StringBuilder sb = new StringBuilder (); sb.Append (verboseParam).Append (' ').Append (name); sb.Append (" \"").Append (arg1).Append ("\""); foreach (string arg in args) sb.Append (" \"").Append (arg).Append ("\""); Process process = new Process (); string asm = null; try { asm = CreateHostExe (); if (!Util.IsMono) process.StartInfo = new ProcessStartInfo (asm, sb.ToString ()); else { asm = asm.Replace(" ", @"\ "); process.StartInfo = new ProcessStartInfo ("mono", "--debug " + asm + " " + sb.ToString ()); } process.StartInfo.WorkingDirectory = AppDomain.CurrentDomain.BaseDirectory; process.StartInfo.UseShellExecute = false; process.StartInfo.CreateNoWindow = true; process.StartInfo.RedirectStandardInput = true; process.StartInfo.RedirectStandardOutput = true; process.StartInfo.RedirectStandardError = true; process.EnableRaisingEvents = true; process.Start (); process.StandardInput.WriteLine (registryPath); process.StandardInput.WriteLine (startupDir); process.StandardInput.WriteLine (addinsDir); process.StandardInput.WriteLine (databaseDir); process.StandardInput.Flush (); // string rr = process.StandardOutput.ReadToEnd (); // Console.WriteLine (rr); StringCollection progessLog = new StringCollection (); ProcessProgressStatus.MonitorProcessStatus (monitor, process.StandardOutput, progessLog); process.WaitForExit (); if (process.ExitCode != 0) throw new ProcessFailedException (progessLog); } catch (Exception ex) { Console.WriteLine (ex); throw; } finally { if (asm != null) { try { File.Delete (asm); } catch { } } } }
public bool ResolveDependencies(IProgressStatus statusMonitor, AddinRepositoryEntry[] addins, out PackageCollection resolved, out PackageCollection toUninstall, out DependencyCollection unresolved) { resolved = new PackageCollection(); for (int n = 0; n < addins.Length; n++) { resolved.Add(AddinPackage.FromRepository(addins [n])); } return(ResolveDependencies(statusMonitor, resolved, out toUninstall, out unresolved)); }
/// <summary> /// Forces the loading of an add-in. /// </summary> /// <param name="statusMonitor"> /// Status monitor to keep track of the loading process. /// </param> /// <param name="id"> /// Full identifier of the add-in to load. /// </param> /// <remarks> /// This method loads all assemblies that belong to an add-in in memory. /// All add-ins on which the specified add-in depends will also be loaded. /// Notice that in general add-ins don't need to be explicitely loaded using /// this method, since the add-in engine will load them on demand. /// </remarks> public void LoadAddin(IProgressStatus statusMonitor, string id) { CheckInitialized(); if (LoadAddin(statusMonitor, id, true)) { var adn = GetAddin(id); adn.EnsureAssembliesLoaded(); } }
protected virtual void Process(IProgressStatus progress, ILogger additionalLogger) { var configurations = ResolveConfigurations(); int taskNumber = 1; foreach (var configuration in configurations) { var logger = configuration.Resolve<ILogger>(); var helper = configuration.Resolve<SerializationHelper>(); using (new LoggingContext(additionalLogger, configuration)) { try { logger.Info(configuration.Name + " is being synced."); using (new TransparentSyncDisabler()) { var pathResolver = configuration.Resolve<PredicateRootPathResolver>(); var roots = pathResolver.GetRootSerializedItems(); var index = 0; helper.SyncTree(configuration, item => { WebConsoleUtility.SetTaskProgress(progress, taskNumber, configurations.Length, (int)((index / (double)roots.Length) * 100)); index++; }, roots); } } catch (DeserializationSoftFailureAggregateException ex) { logger.Error(ex); // allow execution to continue, because the exception was non-fatal } catch (Exception ex) { logger.Error(ex); break; } } taskNumber++; } try { CorePipeline.Run("unicornSyncEnd", new UnicornSyncEndPipelineArgs(progress, configurations)); } catch (Exception exception) { Log.Error("Error occurred in unicornSyncEnd pipeline.", exception); progress.ReportException(exception); } }
protected virtual void Process(IProgressStatus progress, ILogger additionalLogger) { var configurations = ResolveConfigurations(); int taskNumber = 1; foreach (var configuration in configurations) { var logger = configuration.Resolve <ILogger>(); var helper = configuration.Resolve <SerializationHelper>(); using (new LoggingContext(additionalLogger, configuration)) { try { logger.Info(configuration.Name + " is being synced."); using (new TransparentSyncDisabler()) { var pathResolver = configuration.Resolve <PredicateRootPathResolver>(); var roots = pathResolver.GetRootSerializedItems(); var index = 0; helper.SyncTree(configuration, item => { WebConsoleUtility.SetTaskProgress(progress, taskNumber, configurations.Length, (int)((index / (double)roots.Length) * 100)); index++; }, roots); } } catch (DeserializationSoftFailureAggregateException ex) { logger.Error(ex); // allow execution to continue, because the exception was non-fatal } catch (Exception ex) { logger.Error(ex); break; } } taskNumber++; } try { CorePipeline.Run("unicornSyncEnd", new UnicornSyncEndPipelineArgs(progress, configurations)); } catch (Exception exception) { Log.Error("Error occurred in unicornSyncEnd pipeline.", exception); progress.ReportException(exception); } }
protected virtual void ProcessInternal(IProgressStatus progress) { // this bad-ass ASCII art is from http://www.ascii-art.de/ascii/uvw/unicorn.txt - original credit to 'sk' const string unicorn = @"<pre> / .7 \ , // |\.--._/|// /\ ) ) ).'/ /( \ // / _ _ _ _ ___ ____ ___ ____ _ _ /( J`((_/ \ | | | | \ | |_ _/ ___/ _ \| _ \| \ | | / ) | _\ / | | | | \| || | | | | | | |_) | \| | /|) \ eJ L | |_| | |\ || | |__| |_| | _ <| |\ | | \ L \ L L \___/|_| \_|___\____\___/|_| \_\_| \_| / \ J `. J L | ) L \/ \ / \ J (\ / | \ \ \``` </pre>"; // note: these logs are intentionally to progress and not loggingConsole as we don't need them in the Sitecore logs progress.ReportStatus(unicorn, MessageType.Warning); progress.ReportTransientStatus("Executing."); var heartbeat = new Timer(3000); var startTime = DateTime.Now; heartbeat.AutoReset = true; heartbeat.Elapsed += (sender, args) => { var elapsed = Math.Round((args.SignalTime - startTime).TotalSeconds); progress.ReportTransientStatus("Executing for {0} sec.", elapsed.ToString(CultureInfo.InvariantCulture)); }; heartbeat.Start(); try { using (new SecurityDisabler()) { using (new ItemFilterDisabler()) // disable all item filtering (if we're running in live mode we need this to get unadulterated items) { Process(progress); } } } finally { heartbeat.Stop(); } progress.Report(100); progress.ReportTransientStatus("Completed."); progress.ReportStatus(_isAutomatedTool ? "\r\n" : "<br>"); progress.ReportStatus("Completed. Want to <a href=\"?verb=\">return to the control panel?</a>"); }
protected virtual void Process(IProgressStatus progress, ILogger additionalLogger) { var configurations = ResolveConfigurations(); int taskNumber = 1; foreach (var configuration in configurations) { var logger = configuration.Resolve <ILogger>(); using (new LoggingContext(additionalLogger, configuration)) { try { var timer = new Stopwatch(); timer.Start(); logger.Info(string.Empty); logger.Info(configuration.Name + " is being reserialized."); using (new TransparentSyncDisabler()) { var targetDataStore = configuration.Resolve <ITargetDataStore>(); var helper = configuration.Resolve <SerializationHelper>(); // nuke any existing items in the store before we begin. This is a full reserialize so we want to // get rid of any existing stuff even if it's not part of existing configs logger.Warn("[D] Clearing existing items from {0} (if any)".FormatWith(targetDataStore.FriendlyName)); targetDataStore.Clear(); var roots = configuration.Resolve <PredicateRootPathResolver>().GetRootSourceItems(); int index = 1; foreach (var root in roots) { helper.DumpTree(root, new[] { configuration }); WebConsoleUtility.SetTaskProgress(progress, taskNumber, configurations.Length, (int)((index / (double)roots.Length) * 100)); index++; } } timer.Stop(); CorePipeline.Run("unicornReserializeComplete", new UnicornReserializeCompletePipelineArgs(configuration)); logger.Info("{0} reserialization complete in {1}ms.".FormatWith(configuration.Name, timer.ElapsedMilliseconds)); } catch (Exception ex) { logger.Error(ex); break; } taskNumber++; } } }
protected virtual void Process(IProgressStatus progress, ILogger additionalLogger) { var configurations = ResolveConfigurations(); int taskNumber = 1; foreach (var configuration in configurations) { var logger = configuration.Resolve<ILogger>(); using (new LoggingContext(additionalLogger, configuration)) { try { var timer = new Stopwatch(); timer.Start(); logger.Info(string.Empty); logger.Info(configuration.Name + " is being reserialized."); using (new TransparentSyncDisabler()) { var targetDataStore = configuration.Resolve<ITargetDataStore>(); var helper = configuration.Resolve<SerializationHelper>(); // nuke any existing items in the store before we begin. This is a full reserialize so we want to // get rid of any existing stuff even if it's not part of existing configs logger.Warn("[D] Clearing existing items from {0} (if any)".FormatWith(targetDataStore.FriendlyName)); targetDataStore.Clear(); var roots = configuration.Resolve<PredicateRootPathResolver>().GetRootSourceItems(); int index = 1; foreach (var root in roots) { helper.DumpTree(root, new[] { configuration }); WebConsoleUtility.SetTaskProgress(progress, taskNumber, configurations.Length, (int)((index / (double)roots.Length) * 100)); index++; } } timer.Stop(); CorePipeline.Run("unicornReserializeComplete", new UnicornReserializeCompletePipelineArgs(configuration)); logger.Info("{0} reserialization complete in {1}ms.".FormatWith(configuration.Name, timer.ElapsedMilliseconds)); } catch (Exception ex) { logger.Error(ex); break; } taskNumber++; } } }
void VisitFolderInternal(IProgressStatus monitor, string path, string domain, bool recursive) { // Avoid folders including each other if (!visitedFolders.Add(path) || ScanContext.IgnorePath(path)) { return; } OnVisitFolder(monitor, path, domain, recursive); }
public bool Install(IProgressStatus statusMonitor, params AddinRepositoryEntry[] addins) { Package[] packages = new Package [addins.Length]; for (int n = 0; n < addins.Length; n++) { packages [n] = AddinPackage.FromRepository(addins [n]); } return(Install(statusMonitor, packages)); }
public bool Install(IProgressStatus statusMonitor, params string[] files) { Package[] packages = new Package [files.Length]; for (int n = 0; n < files.Length; n++) { packages [n] = AddinPackage.FromFile(files [n]); } return(Install(statusMonitor, packages)); }
public UpdateProgressResponse UpdateProgress(IProgressStatus status) { if (ProgressUpdateEvent != null) { var args = new ProgressUpdateEventArgs(status); ProgressUpdateEvent(this, args); return(args.Response); } return(UpdateProgressResponse.normal); }
void StoreScanDataFile(IProgressStatus monitor, string file, AddinDescription config) { // Save a binary data file next to the scanned file var scanDataFile = file + ".addindata"; database.SaveDescription(monitor, config, scanDataFile); var md5 = Util.GetMD5(scanDataFile); scanDataIndex.Files.Add(new AddinScanData(file, md5)); }
public WebConsoleLogger(IProgressStatus progress, string logLevelValue) { _progress = progress; MessageType type; if(logLevelValue == null || !Enum.TryParse(logLevelValue, true, out type)) type = MessageType.Debug; _logLevel = type; }
/// <summary> /// Sets the progress of the whole based on the progress within a percentage range of the main progress (e.g. 0-100% of a task within the global range of 0-20%) /// </summary> /// <param name="progress"></param> /// <param name="startPercentage">The percentage the task began at</param> /// <param name="endPercentage">The percentage the task ends at</param> /// <param name="taskPercent">The percentage complete of the sub-task (0-100)</param> private static void SetRangeTaskProgress(IProgressStatus progress, int startPercentage, int endPercentage, int taskPercent) { int range = endPercentage - startPercentage; if (range <= 0) throw new ArgumentException("endPercentage must be greater than startPercentage"); int offset = (int)Math.Round(range * (taskPercent / 100d)); progress.Report(Math.Min(startPercentage + offset, 100)); }
/// <summary> /// Regenerates the cached data of the add-in registry. /// </summary> /// <param name="monitor"> /// Progress monitor to keep track of the rebuild operation. /// </param> public void Rebuild(IProgressStatus monitor) { database.Repair(monitor, currentDomain); // A full rebuild may cause the domain to change if (!string.IsNullOrEmpty(startupDirectory)) { currentDomain = database.GetFolderDomain(null, startupDirectory); } }
/// <summary> /// Default constructor /// </summary> /// <param name="taskName">Name of the subtask to run</param> /// <param name="mainTask">The progress status of the main task (or parent subtask)</param> /// <param name="subtaskIndex">The index of this subtask among total subtask count (used to calculate offset progress)</param> /// <param name="subtaskCount">The total number of subtasks in the main task (or parent subtask)</param> /// <param name="automaticTransientStatus">If true, transient status will be automatically managed for you for this subtask ($taskname running for xx seconds). Make sure to dispose the subtask!</param> public SubtaskProgressStatus(string taskName, IProgressStatus mainTask, int subtaskIndex, int subtaskCount, bool automaticTransientStatus) { _subtaskIndex = subtaskIndex; _subtaskCount = subtaskCount; _mainTask = mainTask; _taskName = taskName; _automaticTransientStatus = automaticTransientStatus; InitializeStatus(); }
/// <summary> /// Sets the progress of the whole based on the progress within a sub-task of the main progress (e.g. 0-100% of a task within the global range of 0-20%) /// </summary> /// <param name="progress"></param> /// <param name="taskNumber">The index of the current sub-task</param> /// <param name="totalTasks">The total number of sub-tasks</param> /// <param name="taskPercent">The percentage complete of the sub-task (0-100)</param> public static void SetTaskProgress(IProgressStatus progress, int taskNumber, int totalTasks, int taskPercent) { if (taskNumber < 1) throw new ArgumentException("taskNumber must be 1 or more"); if (totalTasks < 1) throw new ArgumentException("totalTasks must be 1 or more"); if (taskNumber > totalTasks) throw new ArgumentException("taskNumber was greater than the number of totalTasks!"); int start = (int)Math.Round(((taskNumber - 1) / (double)totalTasks) * 100d); int end = start + (int)Math.Round((1d / totalTasks) * 100d); SetRangeTaskProgress(progress, Math.Max(start, 0), Math.Min(end, 100), taskPercent); }
protected override void Process(IProgressStatus progress) { var configurations = ResolveConfigurations(); int taskNumber = 1; foreach (var configuration in configurations) { var logger = configuration.Resolve<ILogger>(); var helper = configuration.Resolve<SerializationHelper>(); using (new LoggingContext(new WebConsoleLogger(progress), configuration)) { try { logger.Info(string.Empty); logger.Info(configuration.Name + " is being synced."); using (new TransparentSyncDisabler()) { var pathResolver = configuration.Resolve<PredicateRootPathResolver>(); var roots = pathResolver.GetRootSerializedItems(); var index = 0; helper.SyncTree(configuration, item => { SetTaskProgress(progress, taskNumber, configurations.Length, (int)((index / (double)roots.Length) * 100)); index++; }, roots); } } catch (Exception ex) { logger.Error(ex); break; } } taskNumber++; } try { CorePipeline.Run("unicornSyncEnd", new UnicornSyncEndPipelineArgs(progress, configurations)); } catch (Exception exception) { Log.Error("Error occurred in unicornSyncEnd pipeline.", exception); progress.ReportException(exception); } }
public void GetAddinDescription (IProgressStatus monitor, AddinRegistry registry, string file, string outFile) { RemoteProgressStatus remMonitor = new RemoteProgressStatus (monitor); try { RemoteSetupDomain rsd = GetDomain (); rsd.GetAddinDescription (remMonitor, registry.RegistryPath, registry.StartupDirectory, registry.DefaultAddinsFolder, registry.AddinCachePath, file, outFile); } catch (Exception ex) { throw new ProcessFailedException (remMonitor.ProgessLog, ex); } finally { System.Runtime.Remoting.RemotingServices.Disconnect (remMonitor); ReleaseDomain (); } }
protected virtual void ProcessInternal(IProgressStatus progress) { if (_headingService != null && !_isAutomatedTool) { progress.ReportStatus(_headingService.GetHeadingHtml()); } // note: these logs are intentionally to progress and not loggingConsole as we don't need them in the Sitecore logs progress.ReportTransientStatus("Executing."); var heartbeat = new Timer(3000); var startTime = DateTime.Now; heartbeat.AutoReset = true; heartbeat.Elapsed += (sender, args) => { var elapsed = Math.Round((args.SignalTime - startTime).TotalSeconds); try { progress.ReportTransientStatus("Executing for {0} sec.", elapsed.ToString(CultureInfo.InvariantCulture)); } catch { // e.g. HTTP connection disconnected - prevent infinite looping heartbeat.Stop(); } }; heartbeat.Start(); try { using (new SecurityDisabler()) { using (new ItemFilterDisabler()) // disable all item filtering (if we're running in live mode we need this to get unadulterated items) { Process(progress); } } } finally { heartbeat.Stop(); } progress.Report(100); progress.ReportTransientStatus("Completed."); progress.ReportStatus(_isAutomatedTool ? "\r\n" : "<br>"); progress.ReportStatus("Completed. Want to <a href=\"?verb=\">return to the control panel?</a>"); }
protected override void Process(IProgressStatus progress) { foreach (var configuration in ResolveConfigurations()) { var logger = configuration.Resolve<ILogger>(); using (new LoggingContext(new WebConsoleLogger(progress), configuration)) { try { var timer = new Stopwatch(); timer.Start(); logger.Info(configuration.Name + " is being reserialized"); using (new TransparentSyncDisabler()) { var targetDataStore = configuration.Resolve<ITargetDataStore>(); var helper = configuration.Resolve<SerializationHelper>(); // nuke any existing items in the store before we begin. This is a full reserialize so we want to // get rid of any existing stuff even if it's not part of existing configs logger.Warn("[D] Clearing existing items from {0}".FormatWith(targetDataStore.FriendlyName)); targetDataStore.Clear(); var roots = configuration.Resolve<PredicateRootPathResolver>().GetRootSourceItems(); int index = 1; foreach (var root in roots) { helper.DumpTree(root, configuration); progress.Report((int) ((index/(double) roots.Length)*100)); index++; } } timer.Stop(); logger.Info("{0} reserialization complete in {1}ms".FormatWith(configuration.Name, timer.ElapsedMilliseconds)); } catch (Exception ex) { logger.Error(ex); break; } } } }
public static bool PublishQueuedItems(Item triggerItem, Database[] targets, IProgressStatus progress = null) { if (ManuallyAddedCandidates.Count == 0) return false; foreach (var database in targets) { if (progress != null) progress.ReportStatus("> Publishing {0} synced item{2} in queue to {1}", MessageType.Debug, ManuallyAddedCandidates.Count, database.Name, ManuallyAddedCandidates.Count == 1 ? string.Empty : "s"); var publishOptions = new PublishOptions(triggerItem.Database, database, PublishMode.SingleItem, triggerItem.Language, DateTime.UtcNow) { RootItem = triggerItem }; var result = new Publisher(publishOptions).PublishWithResult(); if (progress != null) progress.ReportStatus("> Published synced items to {0} (New: {1}, Updated: {2}, Deleted: {3} Skipped: {4})", MessageType.Debug, database.Name, result.Statistics.Created, result.Statistics.Updated, result.Statistics.Deleted, result.Statistics.Skipped); } return true; }
protected override void Process(IProgressStatus progress) { foreach (var configuration in ResolveConfigurations()) { var logger = configuration.Resolve<ILogger>(); using (new LoggingContext(new WebConsoleLogger(progress), configuration)) { try { logger.Info("Control Panel Reserialize: Processing Unicorn configuration " + configuration.Name); var predicate = configuration.Resolve<IPredicate>(); var serializationProvider = configuration.Resolve<ISerializationProvider>(); var roots = configuration.Resolve<PredicateRootPathResolver>().GetRootSourceItems(); int index = 1; foreach (var root in roots) { var rootReference = serializationProvider.GetReference(root); if (rootReference != null) { logger.Warn("[D] existing serialized items under {0}".FormatWith(rootReference.DisplayIdentifier)); // TODO: this doesn't really account for excluded children - it just nukes everything. // ideally it would leave excluded serialized items alone. rootReference.Delete(); } logger.Info("[U] Serializing included items under root {0}".FormatWith(root.DisplayIdentifier)); Serialize(root, predicate, serializationProvider, logger); progress.Report((int) ((index/(double) roots.Length)*100)); index++; } logger.Info("Control Panel Reserialize: Finished reserializing Unicorn configuration " + configuration.Name); } catch (Exception ex) { logger.Error(ex); break; } } } }
protected override void Process(IProgressStatus progress) { // load the requested (or default) preset var presets = GetPresetName(progress); if (presets == null) { progress.ReportStatus("Preset did not exist in configuration.", MessageType.Error); return; } for (int i = 0; i < presets.Count; i++) { using (var subtask = new SubtaskProgressStatus("Syncing preset path " + new ItemReference(presets[i].Database, presets[i].Path), progress, i+1, presets.Count)) { ProcessPreset(presets[i], subtask); } } }
protected override void Process(IProgressStatus progress) { progress.ReportStatus("Starting WebForms demonstration..."); for (int i = 0; i <= 100; i++) { // slight delay to see loading time System.Threading.Thread.Sleep(50); // advance the progress bar status (you can use x % as well as x of y total items) progress.Report(i); // demonstrate setting a substatus of the progress bar (e.g. "making database backup") if (i % 10 == 0) progress.ReportTransientStatus(string.Format("{0}/{1}", i, 100)); // write some stuff to the console to demonstrate detailed output progress.ReportStatus("At {0}", MessageType.Info, i); if (i == 90) progress.ReportStatus("Oops, fake error", MessageType.Error); if (i == 91) progress.ReportStatus("Warning: this can be harmful if misused.", MessageType.Warning); if (i == 92) { progress.ReportStatus("You can also {0} {1}", MessageType.Debug, "use", "string formatting"); } if (i == 95) { progress.ReportStatus("I'm about to throw an exception and write its data to the console!"); // code that can throw an exception should have it caught and written to the console // normally you might wrap the whole processing in a try-catch block try { throw new Exception("I'm giving it all she's got Jim!", new Exception("Warp core breach")); } catch(Exception ex) { progress.ReportException(ex); } } } progress.ReportStatus("WebForms demo complete. See the <a href=\"Tasks.aspx\">tasks demo</a> and the <a href=\"customized.aspx\">customization demo</a>"); }
protected override void Process(IProgressStatus progress) { var configurations = ResolveConfigurations(); foreach (var configuration in configurations) { var logger = configuration.Resolve<ILogger>(); var helper = configuration.Resolve<SerializationHelper>(); using (new LoggingContext(new WebConsoleLogger(progress), configuration)) { try { logger.Info("Control Panel Sync: Processing Unicorn configuration " + configuration.Name); using (new TransparentSyncDisabler()) { var pathResolver = configuration.Resolve<PredicateRootPathResolver>(); var roots = pathResolver.GetRootSerializedItems(); var index = 0; helper.SyncTree(configuration, item => { progress.Report((int) (((index + 1)/(double) roots.Length)*100)); index++; }, roots); } logger.Info("Control Panel Sync: Completed syncing Unicorn configuration " + configuration.Name); } catch (Exception ex) { logger.Error(ex); break; } } } CorePipeline.Run("unicornSyncEnd", new UnicornSyncEndPipelineArgs(configurations)); }
protected void ExecuteTask(IProgressStatus progress) { for (int i = 0; i <= 100; i++) { // slight delay to see loading time Thread.Sleep(10); // demonstrate setting a substatus of the progress bar (e.g. "making database backup") if (i % 10 == 0) { progress.ReportTransientStatus(string.Format("{0}/{1}", i, 100)); // write some stuff to the console to demonstrate detailed output progress.ReportStatus("Task percent {0}", MessageType.Info, i); } // advance the progress bar status (you can use x % as well as x of y total items) progress.Report(i); } }
private static void ProcessPreset(IncludeEntry preset, IProgressStatus progress) { try { using (new SecurityDisabler()) { new SerializationLoader().LoadTree( new AdvancedLoadOptions(preset) { Progress = progress, ForceUpdate = false, DeleteOrphans = true }); } } catch (Exception ex) { if(Debugger.IsAttached) Debugger.Break(); progress.ReportException(ex); } }
protected override void Process(IProgressStatus progress) { foreach (var configuration in ResolveConfigurations()) { var logger = configuration.Resolve<ILogger>(); using (new LoggingContext(new WebConsoleLogger(progress), configuration)) { try { logger.Info("Control Panel Reserialize: Processing Unicorn configuration " + configuration.Name); using (new TransparentSyncDisabler()) { var helper = configuration.Resolve<SerializationHelper>(); var roots = configuration.Resolve<PredicateRootPathResolver>().GetRootSourceItems(); int index = 1; foreach (var root in roots) { helper.DumpTree(root); progress.Report((int) ((index/(double) roots.Length)*100)); index++; } } logger.Info("Control Panel Reserialize: Finished reserializing Unicorn configuration " + configuration.Name); } catch (Exception ex) { logger.Error(ex); break; } } } }
protected override void Process(IProgressStatus progress) { progress.ReportStatus("Starting WebForms tasks demonstration..."); const int subtasks = 3; for (int i = 1; i <= subtasks; i++) { using (var subtask = new SubtaskProgressStatus("Demonstration sub-task #" + i.ToString(CultureInfo.InvariantCulture), progress, i, subtasks + 1, false)) { ExecuteTask(subtask); } progress.ReportStatus("Sub-task {0}/{1} done. Waiting a sec.", i, subtasks); Thread.Sleep(1000); } progress.ReportStatus("Demonstrating nested sub-tasks..."); // you can also nest subtasks // many times this might be used if a method that accepts an IProgressStatus itself calls sub-methods that also take an IProgressStatus // methods that accept an IProgressStatus should *ALWAYS* presume that their progress should be reported as 0-100 (ie that they are running in a subtask) using (var subtask = new SubtaskProgressStatus("Demonstration parent sub-task", progress, subtasks+1, subtasks + 1)) { using (var innerSubtask = new SubtaskProgressStatus("Inner task 1", subtask, 1, 2)) { ExecuteTask(innerSubtask); } using (var innerSubtask2 = new SubtaskProgressStatus("Inner task 2", subtask, 2, 2)) { ExecuteTask(innerSubtask2); } } progress.ReportStatus("WebForms tasks demo complete."); progress.ReportStatus("Done."); }