/// <summary> /// Replaces this variable within a given string. /// </summary> /// <param name="onlyCached">If true, no new content will be downloaded and only chached content will be used.</param> /// <param name="fileDate">Current file date, when downloading the modification date of the file being downloaded</param> public virtual string ReplaceInString(string value, DateTime fileDate, bool onlyCached) { if (!IsVariableUsedInString(m_Name, value)) return value; // Global variable only has static content if (onlyCached) { // We don't want to spam the log with chached only screen updates if (!onlyCached) LogDialog.Log(this, value, m_CachedContent); return (m_CachedContent == null) ? value : Replace(value, m_CachedContent); } // Ignore missing URLs etc. if (IsEmpty) return value; // Using textual content? if (m_VariableType == Type.Textual) { m_CachedContent = GetExpandedTextualContent(fileDate); LogDialog.Log(this, value, m_CachedContent); return Replace(value, m_CachedContent); } string page = string.Empty; // Get the content we need to put in string userAgent = (this.Parent == null) ? null : this.Parent.Parent.UserAgent; using (WebClient client = new WebClient(userAgent)) { try { string url = ExpandedUrl; client.SetPostData(this); page = client.DownloadString(url); } catch (ArgumentException) { throw new UriFormatException("The URL '" + Url + "' of variable '" + m_Name + "' is not valid."); } m_DownloadCount++; } // Normalise line-breaks page = page.Replace("\r\n", "\n"); page = page.Replace("\r", "\n"); // Using a regular expression? if (m_VariableType == Type.RegularExpression) { Regex regex = CreateRegex(); if (regex == null) return value; Match match = regex.Match(page); if (match.Success) { if (match.Groups.Count == 1) { m_CachedContent = match.Value; LogDialog.Log(this, value, m_CachedContent); return Replace(value, match.Value); } else if (match.Groups.Count >= 2) { // Use first group (except index 0, which is complete match) with a match for (int i = 1; i < match.Groups.Count; i++) { if (match.Groups[i].Success) { m_CachedContent = match.Groups[i].Value; LogDialog.Log(this, value, m_CachedContent); return Replace(value, match.Groups[i].Value); } } // No group matches, use complete match m_CachedContent = match.Groups[0].Value; LogDialog.Log(this, value, m_CachedContent); return Replace(value, match.Groups[0].Value); } } else { // No regex match should yield an empty result return Replace(value, string.Empty); } } // Use whole page if either start or end is missing if (string.IsNullOrEmpty(m_StartText) || string.IsNullOrEmpty(m_EndText)) { m_CachedContent = page; LogDialog.Log(this, value, m_CachedContent); return Replace(value, page); } int startPos = page.IndexOf(m_StartText); if (startPos < 0) return value; int endOfStart = startPos + m_StartText.Length; int endPos = page.IndexOf(m_EndText, endOfStart); if (endPos < 0) return value; string result = page.Substring(endOfStart, endPos - endOfStart); m_CachedContent = result; LogDialog.Log(this, value, m_CachedContent); value = Replace(value, result); return value; }
static void Main(string[] args) { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); // Set an error handler (just a message box) for unexpected exceptions in threads AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException); // Parse command line arguments CommandlineArguments arguments = new CommandlineArguments(args); // Is a database path set per command line? if (!string.IsNullOrEmpty(arguments["database"])) { DbManager.DatabasePath = arguments["database"]; } // Initialise database try { DbManager.CreateOrUpgradeDatabase(); WebRequest.DefaultWebProxy = DbManager.Proxy; if (Settings.GetValue("AuthorGuid") == null) { Settings.SetValue("AuthorGuid", Guid.NewGuid().ToString("B")); } } catch (Exception ex) { MessageBox.Show("Could not create or load the database file: " + ex.Message); return; } // Either run silently on command line... if (arguments["silent"] != null) { Kernel32.ManagedAttachConsole(Kernel32.ATTACH_PARENT_PROCESS); ApplicationJob[] jobs = DbManager.GetJobs(); Updater updater = new Updater(); updater.StatusChanged += new EventHandler <Updater.JobStatusChangedEventArgs>(updater_StatusChanged); updater.ProgressChanged += new EventHandler <Updater.JobProgressChangedEventArgs>(updater_ProgressChanged); updater.BeginUpdate(jobs, false, false); if (arguments["notify"] != null) { m_Icon = new NotifyIcon(); m_Icon.Icon = System.Drawing.Icon.FromHandle(Properties.Resources.Restart.GetHicon()); m_Icon.Text = "Ketarin is working..."; m_Icon.Visible = true; } while (updater.IsBusy) { Thread.Sleep(1000); } if (m_Icon != null) { m_Icon.Dispose(); } Kernel32.FreeConsole(); } // ...perform database operations... else if (arguments["update"] != null && arguments["appguid"] != null) { // Update properties of an application in the database ApplicationJob job = DbManager.GetJob(new Guid(arguments["appguid"])); if (job == null) { return; } if (arguments["PreviousLocation"] != null) { job.PreviousLocation = arguments["PreviousLocation"]; } job.Save(); } else if (arguments["export"] != null) { ApplicationJob[] jobs = DbManager.GetJobs(); string exportedXml = ApplicationJob.GetXml(jobs, false, System.Text.Encoding.UTF8); try { File.WriteAllText(arguments["export"] as string, exportedXml, System.Text.Encoding.UTF8); } catch (Exception ex) { Console.WriteLine("Could export to the specified location: " + ex.Message); } } else if (arguments["install"] != null) { try { // Install all applications in the given XML ApplicationJob[] appsToInstall = null; string path = arguments["install"] as string; if (Uri.IsWellFormedUriString(path, UriKind.Absolute)) { using (WebClient client = new WebClient()) { appsToInstall = ApplicationJob.ImportFromXmlString(client.DownloadString(path), false); } } else { appsToInstall = ApplicationJob.ImportFromXml(path); } InstallingApplicationsDialog dialog = new InstallingApplicationsDialog(); dialog.Applications = appsToInstall; dialog.ShowIcon = true; dialog.ShowInTaskbar = true; dialog.AutoClose = (arguments["exit"] != null); Application.Run(dialog); } catch (Exception ex) { MessageBox.Show("Setup cannot be started: " + ex.Message, Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error); } } // ...or launch the GUI. else { Application.Run(new MainForm()); } string logFile = arguments["log"]; if (!string.IsNullOrEmpty(logFile)) { try { logFile = UrlVariable.GlobalVariables.ReplaceAllInString(logFile); LogDialog.SaveLogToFile(logFile); } catch (Exception) { // ignore errors } } }
static void Main(string[] args) { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); // Set an error handler (just a message box) for unexpected exceptions in threads AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException; // Parse command line arguments CommandlineArguments arguments = new CommandlineArguments(args); // Is a database path set per command line? if (!string.IsNullOrEmpty(arguments["database"])) { DbManager.DatabasePath = arguments["database"]; } // Initialise database try { DbManager.CreateOrUpgradeDatabase(); WebRequest.DefaultWebProxy = DbManager.Proxy; if (Settings.GetValue("AuthorGuid") == null) { Settings.SetValue("AuthorGuid", Guid.NewGuid().ToString("B")); } } catch (Exception ex) { MessageBox.Show("Could not create or load the database file: " + ex.Message); return; } // Initialisation of protocols. WebRequest.RegisterPrefix("sf", new ScpWebRequestCreator()); WebRequest.RegisterPrefix("httpx", new HttpxRequestCreator()); // Either run silently on command line... if (arguments["silent"] != null) { Kernel32.ManagedAttachConsole(Kernel32.ATTACH_PARENT_PROCESS); ApplicationJob[] jobs = DbManager.GetJobs(); // Filter by application name and category. string categoryFilter = arguments["category"]; if (!string.IsNullOrEmpty(categoryFilter)) { jobs = jobs.Where(x => string.Equals(x.Category, categoryFilter, StringComparison.OrdinalIgnoreCase)).ToArray(); } string appFilter = arguments["appname"]; if (!string.IsNullOrEmpty(appFilter)) { jobs = jobs.Where(x => LikeOperator.LikeString(x.Name, appFilter, Microsoft.VisualBasic.CompareMethod.Text)).ToArray(); } Updater updater = new Updater(); updater.StatusChanged += updater_StatusChanged; updater.ProgressChanged += updater_ProgressChanged; updater.BeginUpdate(jobs, false, false); if (arguments["notify"] != null) { m_Icon = new NotifyIcon { Icon = System.Drawing.Icon.FromHandle(Properties.Resources.Restart.GetHicon()), Text = "Ketarin is working...", Visible = true }; } while (updater.IsBusy) { Thread.Sleep(1000); } m_Icon?.Dispose(); Kernel32.FreeConsole(); } // ...perform database operations... else if (arguments["update"] != null && arguments["appguid"] != null) { // Update properties of an application in the database ApplicationJob job = DbManager.GetJob(new Guid(arguments["appguid"])); if (job == null) { return; } if (arguments["PreviousLocation"] != null) { job.PreviousLocation = arguments["PreviousLocation"]; } job.Save(); } else if (arguments["export"] != null) { ApplicationJob[] jobs = DbManager.GetJobs(); string exportedXml = ApplicationJob.GetXml(jobs, false, System.Text.Encoding.UTF8); try { File.WriteAllText(arguments["export"], exportedXml, System.Text.Encoding.UTF8); } catch (Exception ex) { Console.WriteLine("Could not export to the specified location: " + ex.Message); } } else if (arguments["import"] != null) { string sourceFile = arguments["import"]; try { if (arguments["clear"] != null) { ApplicationJob.DeleteAll(); } ApplicationJob.ImportFromXml(sourceFile); } catch (Exception ex) { Console.WriteLine("Could not import from the specified location: " + ex.Message); } } else if (arguments["install"] != null) { try { // Install all applications in the given XML ApplicationJob[] appsToInstall; string path = arguments["install"]; if (Uri.IsWellFormedUriString(path, UriKind.Absolute)) { using (WebClient client = new WebClient()) { appsToInstall = ApplicationJob.ImportFromXmlString(client.DownloadString(path), false); } } else { appsToInstall = ApplicationJob.ImportFromXml(path); } InstallingApplicationsDialog dialog = new InstallingApplicationsDialog { Applications = appsToInstall, ShowIcon = true, ShowInTaskbar = true, AutoClose = (arguments["exit"] != null) }; Application.Run(dialog); } catch (Exception ex) { MessageBox.Show("Setup cannot be started: " + ex.Message, Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error); } } // ...or launch the GUI. else { Application.Run(new MainForm()); } string logFile = arguments["log"]; if (!string.IsNullOrEmpty(logFile)) { try { logFile = UrlVariable.GlobalVariables.ReplaceAllInString(logFile); LogDialog.SaveLogToFile(logFile); } catch (Exception) { // ignore errors } } }