/// <summary> /// Starts import process. /// </summary> /// <param name="parentPage">Page requirest importing.</param> /// <param name="profile">Import profile.</param> /// <param name="defaultDate">Default date for default initialize imported objects.</param> /// <param name="dataProvider">Data provider.</param> private void _StartImportProcess(AppPages.Page parentPage, ImportProfile profile, DateTime defaultDate, IDataProvider dataProvider) { Debug.Assert(null != parentPage); // created Debug.Assert(null != profile); // created Debug.Assert(null != dataProvider); // creatde // reset state _importer = null; _geocoder = null; // subscribe to events App currentApp = App.Current; currentApp.MainWindow.Closed += new EventHandler(_MainWindow_Closed); // create background worker Debug.Assert(null == _worker); // only once SuspendBackgroundWorker worker = _CreateBackgroundWorker(); // create internal objects var tracker = new ImportCancelTracker(worker); var cancelTracker = new CancellationTracker(tracker); _informer = new ProgressInformer(parentPage, profile.Type, tracker); _informer.SetStatus("ImportLabelImporting"); var infoTracker = new ProgressInfoTracker(worker, _informer.ParentPage, _informer.ObjectName, _informer.ObjectsName); _importer = new Importer(infoTracker); if (PropertyHelpers.IsGeocodeSupported(profile.Type)) { _geocoder = new Geocoder(infoTracker); } // set precondition string message = currentApp.GetString("ImportProcessStarted", _informer.ObjectName); currentApp.Messenger.AddInfo(message); // lock GUI currentApp.UIManager.Lock(true); // run worker var parameters = new ProcessParams(profile, defaultDate, dataProvider, cancelTracker, infoTracker); worker.RunWorkerAsync(parameters); _worker = worker; }
public Model() { GeometricParams = new GeometricParams(); MaterialParams = new MaterialParams(); ProcessParams = new ProcessParams(); EmpiricCoeffs = new EmpiricCoeffs(); SolveMethodParams = new SolveMethodParams(); }
/// <summary> /// Создаёт модель с указаными параметрами /// </summary> /// <param name="W">Ширина, м</param> /// <param name="H">Глубина, м</param> /// <param name="L">Длина, м</param> /// <param name="ro">Плотность, кг/м^3</param> /// <param name="c">Средняя удельная теплоемкость, Дж/(кг*С)</param> /// <param name="T_0">Температура плавления, С</param> /// <param name="V_u">Скорость крышки, м/с</param> /// <param name="T_u">Температура крышки, C</param> /// <param name="mu_0">Коэффициент консистенции материала при температуре приведения, Па*с^n</param> /// <param name="b">Температурный коэффициент вязкости материала, 1/C</param> /// <param name="T_r">Температура приведения, С</param> /// <param name="n">Индекс течения материала</param> /// <param name="alpha_u">Коэффициент теплоотдачи от крышки канала к материалу, Вт/(м^2*С)</param> /// <param name="delta_z">Шаг расчета по длине канала, м</param> public Model(double W, double H, double L, double ro, double c, double T_0, double V_u, double T_u, double mu_0, double b, double T_r, double n, double alpha_u, double delta_z) { GeometricParams = new GeometricParams(W, H, L); MaterialParams = new MaterialParams(ro, c, T_0); ProcessParams = new ProcessParams(V_u, T_u); EmpiricCoeffs = new EmpiricCoeffs(mu_0, b, T_r, n, alpha_u); SolveMethodParams = new SolveMethodParams(delta_z); }
private Process CreateProcess(ProcessParams parameters) { var process = new Process { StartInfo = { FileName = parameters.File.Name, UseShellExecute = false, CreateNoWindow = true, RedirectStandardError = true, RedirectStandardOutput = true, WindowStyle = ProcessWindowStyle.Hidden, Arguments = !string.IsNullOrEmpty(parameters.Arguments) ? parameters.Arguments : string.Empty }, EnableRaisingEvents = true }; process.OutputDataReceived += (o, e) => { if (string.IsNullOrEmpty(e?.Data)) { return; } _logger?.Info($"{parameters.File?.Name}: {e?.Data}"); }; process.ErrorDataReceived += (o, e) => { if (string.IsNullOrEmpty(e?.Data) || e.Data.ToLower().Contains("info:")) { return; } _logger?.Error(new Exception($"{parameters.File?.Name}: {e?.Data}")); }; process.Exited += (o, e) => { _logger?.Info($"Process {parameters.File?.Name} has exited."); DestroyProcess(); }; return(process); }
/// <summary> /// Import procedure. /// </summary> /// <param name="parameters">Process parameters.</param> private void _Import(ProcessParams parameters) { Debug.Assert(null != _informer); // inited Debug.Assert(null != parameters); // created ImportProfile profile = parameters.Profile; ICancellationChecker cancelChecker = parameters.CancelChecker; // do import operation from source var projectData = new ProjectDataContext(App.Current.Project); _importer.Import(profile, parameters.DataProvider, parameters.DefaultDate, projectData, cancelChecker); cancelChecker.ThrowIfCancellationRequested(); IList <AppData.DataObject> importedObjects = _importer.ImportedObjects; // do geocode imported objects if ((null != _geocoder) && (0 < importedObjects.Count)) { Geocoder.GeocodeType type = _GetGeocodeType(profile.Settings); _geocoder.Geocode(importedObjects, type, cancelChecker); } _AddObjectsToFeatureServiceIfNeeded(importedObjects); cancelChecker.ThrowIfCancellationRequested(); // commit additions of related objects _informer.ParentPage.Dispatcher.BeginInvoke(new Action(() => { projectData.Commit(); projectData.Dispose(); }), System.Windows.Threading.DispatcherPriority.Send); cancelChecker.ThrowIfCancellationRequested(); }
protected virtual void BaseStartProcess(ProcessParams _params) { try { _processHelper = new ProcessHelper(_params); _processHelper.OnUpdateProcess += _processHelper_OnUpdateProcess; _processHelper.Launch(); RestartCnt++; NotifyStartProcess(); timer.AutoReset = true; // timer.Start(); } catch (Exception ex) { throw new Exception("Error during starting process " + _params.AppName, ex); } }
public void StartProcess(ClaymorParams _clParams) { try { this.clParams = _clParams; ProcessParams _params = new ProcessParams(_clParams.CalymoreAppPath, _clParams.ClaymorParmsString(false)); _params.ShowWindow = _clParams.ShowWindow; _params.listEnv.AddRange(_clParams.ListEnv()); _processHelper = new ClaymorProcessHelper(_params); _processHelper.Launch(); //NotifyStartProcess(); watcher = new FileSystemWatcher(); watcher.Path = _params.DirectoryName; /* Watch for changes in LastAccess and LastWrite times, and * the renaming of files or directories. */ watcher.NotifyFilter = NotifyFilters.LastAccess | NotifyFilters.LastWrite | NotifyFilters.FileName | NotifyFilters.DirectoryName; // Only watch text files. watcher.Filter = _clParams.EthLog; // Add event handlers. watcher.Changed += new FileSystemEventHandler(OnChanged); watcher.Created += new FileSystemEventHandler(OnChanged); // Begin watching. watcher.EnableRaisingEvents = true; } catch (Exception ex) { throw new Exception("Error during starting process " + _processHelper._params.AppName, ex); } }
public PrimaryService() { MessageServerLogin = true; InitializeComponent(); LoadServiceSettings(); LoadEmailSettings(); _serviceDataThread = new LocalServiceDataThread(); _serviceDataThread.OnNewServerDetails += ServerDataThread_OnNewServerDetails; _serviceDataThread.MonitorDisks = _serviceSettings.Find(Constants.Settings.MonitorDisks).GetValue <bool>(); _serviceDataThread.MonitorNetwork = _serviceSettings.Find(Constants.Settings.MonitorNetworks).GetValue <bool>(); ThreadManager.ThreadStart(_serviceDataThread, Constants.Service.ThreadLocalDataMonitoring, System.Threading.ThreadPriority.Lowest); _notifyRunAsApp.Icon = Icon.ExtractAssociatedIcon(Assembly.GetExecutingAssembly().Location); _pluginManager = new PluginManager(this, this, this, this); _pluginManager.LoadServices(); ProcessParams.PostProcessAllParams(_pluginManager); }
/// <summary> /// Helper function to call KillImage() from a thread. /// </summary> public void RunDeleteImages() { FileSystem.ProcessParams p = new ProcessParams(); p.RootFolder = this.RootPath; FileSystem.RunRecursive(p, KillImage); }
/// <summary> /// Import procedure. /// </summary> /// <param name="parameters">Process parameters.</param> private void _Import(ProcessParams parameters) { Debug.Assert(null != _informer); // inited Debug.Assert(null != parameters); // created ImportProfile profile = parameters.Profile; ICancellationChecker cancelChecker = parameters.CancelChecker; // do import operation from source var projectData = new ProjectDataContext(App.Current.Project); _importer.Import(profile, parameters.DataProvider, parameters.DefaultDate, projectData, cancelChecker); cancelChecker.ThrowIfCancellationRequested(); IList<AppData.DataObject> importedObjects = _importer.ImportedObjects; // do geocode imported objects if ((null != _geocoder) && (0 < importedObjects.Count)) { Geocoder.GeocodeType type = _GetGeocodeType(profile.Settings); _geocoder.Geocode(importedObjects, type, cancelChecker); } _AddObjectsToFeatureServiceIfNeeded(importedObjects); cancelChecker.ThrowIfCancellationRequested(); // commit additions of related objects _informer.ParentPage.Dispatcher.BeginInvoke(new Action(() => { projectData.Commit(); projectData.Dispose(); }), System.Windows.Threading.DispatcherPriority.Send); cancelChecker.ThrowIfCancellationRequested(); }
static void Main(string[] args) { Closing = false; try { AppDomain.CurrentDomain.AssemblyResolve += CurrentDomainAssemblyResolve; Configuration.Initialize(); Parameters.Initialise(args, new char[] { '-', '/' }, new char[] { ' ', ':' }); Thread.CurrentThread.CurrentCulture = new CultureInfo("en-GB"); ProcessParams.PreProcessAllParams(); if (Environment.UserInteractive) { ThreadManager.Initialise(); try { INSTANCE = new PrimaryService(); EventLog.Add("Initializing UserInteractive"); if (Parameters.OptionExists("i")) // install { try { EventLog.Add("Installing"); ManagedInstallerClass.InstallHelper(new string[] { Assembly.GetExecutingAssembly().Location }); } catch (Exception err) { if (!err.Message.Contains("The installation failed, and the rollback has been performed")) { throw; } } } else if (Parameters.OptionExists("u")) // uninstall { EventLog.Add("Uninstalling"); ManagedInstallerClass.InstallHelper(new string[] { "/u", Assembly.GetExecutingAssembly().Location }); } else { EventLog.Add("Run as Application"); ThreadManager.ThreadForcedToClose += ThreadManager_ThreadForcedToClose; INSTANCE.RunAsApplication(); Closing = true; } } catch (Exception err) { MessageBox.Show(String.Format("{0}\r\n{1}", err.Message, err.StackTrace.ToString())); EventLog.Add(err.Message); EventLog.Add(err); } finally { ThreadManager.Finalise(); } } else { System.ServiceProcess.ServiceBase[] ServicesToRun; INSTANCE = new PrimaryService(); ServicesToRun = new System.ServiceProcess.ServiceBase[] { INSTANCE }; System.ServiceProcess.ServiceBase.Run(ServicesToRun); } } catch (Exception error) { EventLog.Add(error); } }
/// <summary> /// Starts import process. /// </summary> /// <param name="parentPage">Page requirest importing.</param> /// <param name="profile">Import profile.</param> /// <param name="defaultDate">Default date for default initialize imported objects.</param> /// <param name="dataProvider">Data provider.</param> private void _StartImportProcess(AppPages.Page parentPage, ImportProfile profile, DateTime defaultDate, IDataProvider dataProvider) { Debug.Assert(null != parentPage); // created Debug.Assert(null != profile); // created Debug.Assert(null != dataProvider); // creatde // reset state _importer = null; _geocoder = null; // subscribe to events App currentApp = App.Current; currentApp.MainWindow.Closed += new EventHandler(_MainWindow_Closed); // create background worker Debug.Assert(null == _worker); // only once SuspendBackgroundWorker worker = _CreateBackgroundWorker(); // create internal objects var tracker = new ImportCancelTracker(worker); var cancelTracker = new CancellationTracker(tracker); _informer = new ProgressInformer(parentPage, profile.Type, tracker); _informer.SetStatus("ImportLabelImporting"); var infoTracker = new ProgressInfoTracker(worker, _informer.ParentPage, _informer.ObjectName, _informer.ObjectsName); _importer = new Importer(infoTracker); if (PropertyHelpers.IsGeocodeSupported(profile.Type)) { _geocoder = new Geocoder(infoTracker); } // set precondition string message = currentApp.GetString("ImportProcessStarted", _informer.ObjectName); currentApp.Messenger.AddInfo(message); // lock GUI currentApp.UIManager.Lock(true); // run worker var parameters = new ProcessParams(profile, defaultDate, dataProvider, cancelTracker, infoTracker); worker.RunWorkerAsync(parameters); _worker = worker; }
public bool Process(ProcessParams processParams, out string returnedErrors) { if (processParams.Properties == null) { throw new ArgumentNullException("properties"); } if (processParams.Customer == null) { throw new ArgumentNullException("customer"); } var result = true; var errors = ""; Action <string> fail = message => { result = false; if (errors != "") { errors += Environment.NewLine; } errors += message; }; var splitProperties = processParams.Properties.Split('|'); bool temporary = false; var widgetColor = WidgetColor.SomeShadeOfGrey; var endDate = new DateTime(); var dataAccess = new DataAccess(); if (!processParams.Properties.StartsWith("<record>")) { for (int i = 0; i < splitProperties.Length; i++) { var kv = splitProperties[i].Split('='); if (kv.Length != 2) { throw new BadCodeException("invalid value found in properties"); continue; } var key = kv[0]; var value = kv[1]; switch (key) { case "temporary": if (!bool.TryParse(value, out temporary)) { fail("invalid temporary value"); } break; case "color": switch (value) { case "blue": widgetColor = WidgetColor.Blue; break; case "red": widgetColor = WidgetColor.Red; break; case "green": widgetColor = WidgetColor.Green; break; case "someshadeofgrey": widgetColor = WidgetColor.SomeShadeOfGrey; break; default: result = false; if (errors != "") { errors += Environment.NewLine; } errors += "invalid widget color"; break; } break; case "endDate": if (!DateTime.TryParse(value, out endDate)) { result = false; if (errors != "") { errors += Environment.NewLine; } errors += "invalid endDate"; } break; default: result = false; if (errors != "") { errors += Environment.NewLine; } errors += "invalid endDate"; break; } } } else { var document = new XmlDocument(); try { document.Load(new StringReader(processParams.Properties)); } catch (Exception e) { result = false; if (errors != "") { errors += Environment.NewLine; } errors += "invalid xml"; } foreach (XmlElement node in document.ChildNodes) { switch (node.Name) { case "temporary": if (!bool.TryParse(node.Value, out temporary)) { result = false; if (errors != "") { errors += Environment.NewLine; } errors += "invalid temporary value"; } break; case "color": switch (node.Value) { case "blue": widgetColor = WidgetColor.Blue; break; case "red": widgetColor = WidgetColor.Red; break; case "green": widgetColor = WidgetColor.Green; break; case "someshadeofgrey": widgetColor = WidgetColor.SomeShadeOfGrey; break; default: result = false; if (errors != "") { errors += Environment.NewLine; } errors += "invalid widget color"; break; } break; case "endDate": if (!DateTime.TryParse(node.Value, out endDate)) { result = false; if (errors != "") { errors += Environment.NewLine; } errors += "invalid endDate"; } break; default: result = false; if (errors != "") { errors += Environment.NewLine; } errors += "invalid endDate"; break; } } } if (widgetColor == WidgetColor.Blue && processParams.Customer == "AB") { temporary = false; } if (temporary) { if (endDate >= DateTime.Now) { try { var message = ""; var dbOk = dataAccess.Update(processParams.Customer, widgetColor.ToString(), endDate, out message); if (!dbOk) { result = false; if (errors != "") { errors += Environment.NewLine; } errors += message; } } catch (Exception e) { result = false; if (errors != "") { errors += Environment.NewLine; } errors += e.ToString(); } } else { try { var message = ""; var dbOk = dataAccess.UpdateTemporaryStore(processParams.Customer, widgetColor.ToString(), out message); if (!dbOk) { result = false; if (errors != "") { errors += Environment.NewLine; } errors += message; } } catch (Exception e) { result = false; if (errors != "") { errors += Environment.NewLine; } errors += e.ToString(); } } } else { try { var message = ""; var dbOk = dataAccess.Update(processParams.Customer, widgetColor.ToString(), endDate, out message); if (!dbOk) { result = false; if (errors != "") { errors += Environment.NewLine; } errors += message; } } catch (Exception e) { result = false; if (errors != "") { errors += Environment.NewLine; } errors += e.ToString(); } } returnedErrors = errors; return(result); }
/// <summary> /// Manager function that calls all other standardization functions. /// </summary> public void Standardize(ProcessParams p_params) { string modedPath = p_params.FilePath; ThreadMessageStruct thdMsg = new ThreadMessageStruct(); thdMsg.Type = TMSType.Progress1; thdMsg.Data1 = modedPath; if (Progress != null) Progress(thdMsg); modedPath = StandardizeGeneral(modedPath); modedPath = StandardizeImage(modedPath); modedPath = StandardizeMusic(modedPath); // modedPath = OpenZip(modedPath); }
public ProcessHelper(ProcessParams _params) : base(_params) { }
public static void ReplaceFileName(ProcessParams p_params) { // get formatted parameters string filePath = p_params.FilePath; string regLit = p_params.Parameter1.ToString(); // regLit = regLit.Replace(@"\", @"\\"); // regLit = regLit.Replace(@".", @"\."); regLit = regLit.Replace(@"$", @"\$"); regLit = regLit.Replace(@"^", @"\^"); regLit = regLit.Replace(@"{", @"\{"); regLit = regLit.Replace(@"(", @"\("); regLit = regLit.Replace(@"|", @"\|"); regLit = regLit.Replace(@")", @"\)"); regLit = regLit.Replace(@"*", @"\*"); regLit = regLit.Replace(@"+", @"\+"); regLit = regLit.Replace(@"?", @"\?"); Regex m_matchText = new Regex(regLit); string fileName = Path.GetFileName(filePath); string changeTo = p_params.Parameter2.ToString(); // create file with substituted name string newFileName = null; string newFilePath = null; if (m_matchText.IsMatch(fileName)) { newFileName = m_matchText.Replace(fileName, changeTo); newFilePath = Path.GetDirectoryName(filePath); newFilePath = Path.Combine(newFilePath, newFileName); File.Move(filePath, newFilePath); } // notify any calling control ThreadMessageStruct tms = new ThreadMessageStruct(); tms.Type = TMSType.Progress1; tms.Data1 = filePath; tms.Data2 = newFilePath; if (Progress != null) Progress(tms); }
public bool Process(ProcessParams processParams, out string returnedErrors) { if(processParams.Properties == null) { throw new ArgumentNullException("properties"); } if(processParams.Customer == null) { throw new ArgumentNullException("customer"); } var result = true; var errors = ""; Action<string> fail = message => { result = false; if (errors != "") { errors += Environment.NewLine; } errors += message; }; var splitProperties = processParams.Properties.Split('|'); bool temporary = false; var widgetColor = WidgetColor.SomeShadeOfGrey; var endDate = new DateTime(); var dataAccess = new DataAccess(); if (!processParams.Properties.StartsWith("<record>")) { for (int i = 0; i < splitProperties.Length; i++) { var kv = splitProperties[i].Split('='); if (kv.Length != 2) { throw new BadCodeException("invalid value found in properties"); continue; } var key = kv[0]; var value = kv[1]; switch (key) { case "temporary": if (!bool.TryParse(value, out temporary)) { fail("invalid temporary value"); } break; case "color": switch (value) { case "blue": widgetColor = WidgetColor.Blue; break; case "red": widgetColor = WidgetColor.Red; break; case "green": widgetColor = WidgetColor.Green; break; case "someshadeofgrey": widgetColor = WidgetColor.SomeShadeOfGrey; break; default: result = false; if (errors != "") { errors += Environment.NewLine; } errors += "invalid widget color"; break; } break; case "endDate": if (!DateTime.TryParse(value, out endDate)) { result = false; if (errors != "") { errors += Environment.NewLine; } errors += "invalid endDate"; } break; default: result = false; if (errors != "") { errors += Environment.NewLine; } errors += "invalid endDate"; break; } } } else { var document = new XmlDocument(); try { document.Load(new StringReader(processParams.Properties)); } catch (Exception e) { result = false; if (errors != "") { errors += Environment.NewLine; } errors += "invalid xml"; } foreach (XmlElement node in document.ChildNodes) { switch (node.Name) { case "temporary": if (!bool.TryParse(node.Value, out temporary)) { result = false; if (errors != "") { errors += Environment.NewLine; } errors += "invalid temporary value"; } break; case "color": switch (node.Value) { case "blue": widgetColor = WidgetColor.Blue; break; case "red": widgetColor = WidgetColor.Red; break; case "green": widgetColor = WidgetColor.Green; break; case "someshadeofgrey": widgetColor = WidgetColor.SomeShadeOfGrey; break; default: result = false; if (errors != "") { errors += Environment.NewLine; } errors += "invalid widget color"; break; } break; case "endDate": if (!DateTime.TryParse(node.Value, out endDate)) { result = false; if (errors != "") { errors += Environment.NewLine; } errors += "invalid endDate"; } break; default: result = false; if (errors != "") { errors += Environment.NewLine; } errors += "invalid endDate"; break; } } } if (widgetColor == WidgetColor.Blue && processParams.Customer == "AB") { temporary = false; } if (temporary) { if (endDate >= DateTime.Now) { try { var message = ""; var dbOk = dataAccess.Update(processParams.Customer, widgetColor.ToString(), endDate, out message); if (!dbOk) { result = false; if (errors != "") { errors += Environment.NewLine; } errors += message; } } catch (Exception e) { result = false; if (errors != "") { errors += Environment.NewLine; } errors += e.ToString(); } } else { try { var message = ""; var dbOk = dataAccess.UpdateTemporaryStore(processParams.Customer, widgetColor.ToString(), out message); if (!dbOk) { result = false; if (errors != "") { errors += Environment.NewLine; } errors += message; } } catch (Exception e) { result = false; if (errors != "") { errors += Environment.NewLine; } errors += e.ToString(); } } } else { try { var message = ""; var dbOk = dataAccess.Update(processParams.Customer, widgetColor.ToString(), endDate, out message); if (!dbOk) { result = false; if (errors != "") { errors += Environment.NewLine; } errors += message; } } catch (Exception e) { result = false; if (errors != "") { errors += Environment.NewLine; } errors += e.ToString(); } } returnedErrors = errors; return result; }
/// <summary> /// Deletes image from system. /// </summary> public void KillImage(ProcessParams p_params) { string filePath = p_params.FilePath; ThreadMessageStruct thdMsg = new ThreadMessageStruct(); thdMsg.Type = TMSType.Progress1; thdMsg.Data1 = filePath; if (Progress != null) Progress(thdMsg); string status = "begin"; try { if (FileSystem.IsImage(filePath) == true) { File.Delete(filePath); status = "Image Deleted"; } else { status = "Not An Image"; } } catch (Exception ex) { status = "Error: " + ex.Message; } finally { thdMsg.Type = TMSType.Progress2; thdMsg.Data1 = filePath; thdMsg.Data2 = status; if (Progress != null) Progress(thdMsg); } }
/// <summary> /// Call the process-function on all file paths inside of the parameter root folder. /// Sample function is SetImageKeyword(). /// </summary> public static void RunRecursive(ProcessParams p_params, ProcessFunction p_processFunc) { DirectoryInfo dirInfo = new DirectoryInfo(p_params.RootFolder); Utility.LogRight.WriteLog(p_params.RootFolder); // call on all subfolders DirectoryInfo[] subDirInfo = dirInfo.GetDirectories(); ProcessParams createParams = new ProcessParams(); createParams.Parameter1 = p_params.Parameter1; createParams.Parameter2 = p_params.Parameter2; for (int d = 0; d < subDirInfo.Length; d++) { createParams.RootFolder = subDirInfo[d].FullName; RunRecursive(createParams, p_processFunc); } // process the current folder FileInfo[] fileInfos = dirInfo.GetFiles(); for (int f = 0; f < fileInfos.Length; f++) { string filePath = fileInfos[f].FullName; createParams.FilePath = filePath; try { p_processFunc(createParams); } catch (Exception ex) { throw ex; } } }
/// <summary> /// Set the file names in the parameters list according to /// "<keywords> <number_000>" or "<sort><number_000> <keywords>" /// </summary> public static void RunCreateEntryFN(string[] p_filePaths, string p_keywords, string p_sort) { // iterate through files and format file name int[] indeces = new int[10]; Regex digitRx = new Regex(@"(?<digit>[0-9])"); Regex findArtist = new Regex(@"(?<artist>\([a-zA-Z_]+[0-9a-zA-Z_\.\-]+\))"); List<string> newFilenames = new List<string>(); for (int f = 0; f < p_filePaths.Length; f++) { // get current data string origPath = p_filePaths[f]; string fileDir = Path.GetDirectoryName(origPath); string fileName = Path.GetFileName(origPath); string artist = ""; if (findArtist.IsMatch(fileName) == true) { Match m = findArtist.Match(fileName); artist = m.Groups["artist"].Value; } // create new file name int placeH = 0, count; if (digitRx.IsMatch(fileName)) { Match m = digitRx.Match(fileName); string digit = m.Groups["digit"].Value; if (Int32.TryParse(digit, out placeH) == false) placeH = 0; } count = indeces[placeH] +1; // start at 1, not 0 indeces[placeH] = indeces[placeH] + 1; string digits = ""; if (placeH != 0) digits = (count + placeH * 100).ToString(); else digits = Utility.StringFormat.GetZeroPadded(count, 3); string newName; if (string.IsNullOrEmpty(p_sort) == true) newName = p_keywords + " " + digits + " " + artist + " TEMP" + Path.GetExtension(fileName); else newName = p_sort + digits + " " + p_keywords + " " + artist + " TEMP" + Path.GetExtension(fileName); string newPath = Path.Combine(fileDir, newName); // rename file in system File.Move(origPath, newPath); newFilenames.Add(newPath); } // second job: set image keyword for newly sorted file names for (int f = 0; f < newFilenames.Count; f++) { string filePath = newFilenames[f]; FileSystem.ProcessParams pp = new ProcessParams(); pp.FilePath = filePath; ImageProcessor.SetImageKeyword(pp); } // clean up: remove TEMP keyword from newly renamed files FileSystem fp = new FileSystem(); for (int f = 0; f < newFilenames.Count; f++) { string filePath = newFilenames[f]; fp.StandardizeGeneral(filePath); } }
/// <summary> /// Helper function to call Standardize() from a thread. /// </summary> public void RunStandardizor() { FileSystem.ProcessParams p = new ProcessParams(); p.RootFolder = this.RootPath; FileSystem.RunRecursive(p, Standardize); }
public ClaymorProcessHelper(ProcessParams _params) : base(_params) { }