/// <summary> /// /// </summary> /// <param name="theUrl"></param> /// <param name="doc"></param> /// <returns></returns> public static bool GetDocumentFromUrl(string theUrl, out HtmlDocument doc) { doc = new HtmlDocument(); try { String content = GetWebContent(theUrl); doc.LoadHtml(content); if (doc.ParseErrors != null && doc.ParseErrors.Count() > 0) { // Handle any parse errors as required //return false; } return(true); } catch (Exception e) { e.Data.Add("theUrl", theUrl); XLogger.Error(e); return(false); } }
public static void ParseTrupar(string truparURL, out string partCode, out decimal truparPrice) { partCode = string.Empty; truparPrice = -1; try { if (!HtmlAgility.UrlIsValid(truparURL)) { throw new ArgumentException("invalid url", "truparURL"); } HAP.HtmlDocument docSearch; HtmlAgility.GetDocumentFromUrl(truparURL, out docSearch); var strPrice = HtmlAgility.ScrapElement(docSearch, ConfigurationManager.AppSettings["Trupar.Price"])?.Trim('$'); partCode = HtmlAgility.ScrapElement(docSearch, ConfigurationManager.AppSettings["Trupar.PartCode"]); /* - details * var detailsUrl = HtmlAgility.GetUrlFromAnchor(docSearch, ConfigurationManager.AppSettings["Trupar.Details"]); * HAP.HtmlDocument docDetails; * HtmlAgility.GetDocumentFromUrl(detailsUrl, out docDetails); * var strPrice = HtmlAgility.ScrapElement(docSearch, ConfigurationManager.AppSettings["Trupar.Price"])?.Trim('$'); * partCode = HtmlAgility.ScrapElement(docSearch, ConfigurationManager.AppSettings["Trupar.PartCode"]); * // IList<HAP.HtmlNode> nodes = doc.QuerySelectorAll("span .itemprop > ul li"); */ decimal.TryParse(strPrice, out truparPrice); } catch (Exception x) { x.Data.Add("truparURL", truparURL); XLogger.Error(x); } }
public static ExecutionResult GenerateContact(string outputFolder, Contact contact, REF.Scope generatePerContact, string templateFile) { try { GenerateContactCore(outputFolder, generatePerContact, contact, templateFile); CallUpdateStatus("Operation passed and filled templates are generated in the Output folder"); return(ExecutionResult.Successful); } catch (Exception x) { if (!x.Data.Contains("outputFolder")) { x.Data.Add("outputFolder", outputFolder); } if (!x.Data.Contains("generatePerContact")) { x.Data.Add("generatePerContact", generatePerContact); } if (!x.Data.Contains("templateFile")) { x.Data.Add("templateFile", templateFile); } if (!x.Data.Contains("contact.OppName")) { x.Data.Add("contact.OppName", contact.OppName); } XLogger.Error(x); CallUpdateStatus("There was a problem in generating all the contacts files"); return(ExecutionResult.ErrorOccured); } }
private static string PostAndGetWebContentCore3(string url, string user, string pass) { try { throw new NotImplementedException(); /* * using (var client = new HttpClient()) * { * var values = new Dictionary<string, string> * { * { "thing1", user }, * { "thing2", pass } * }; * * var content = new FormUrlEncodedContent(values); * * var response = await client.PostAsync("http://www.example.com/recepticle.aspx", content); * * var responseString = await response.Content.ReadAsStringAsync(); * return responseString; * } */ } catch (Exception x) { XLogger.Error(x); return(""); } }
// private static string PostAndGetWebContentCore1(string url, string user, string pass) { try { var request = (HttpWebRequest)WebRequest.Create(url); var postData = String.Concat("thing1=", user); postData += String.Concat("&thing2=", pass); var data = Encoding.ASCII.GetBytes(postData); request.Method = "POST"; request.ContentType = "application/x-www-form-urlencoded"; request.ContentLength = data.Length; using (var stream = request.GetRequestStream()) { stream.Write(data, 0, data.Length); } var response = (HttpWebResponse)request.GetResponse(); var responseString = new StreamReader(response.GetResponseStream()).ReadToEnd(); return(responseString); } catch (Exception x) { XLogger.Error(x); return(""); } }
public static List <String> ScrapeElementsAndGetNodes(HtmlDocument doc, string itemsXpath, out List <HtmlNode> nodes) { List <String> results = new List <string>(); nodes = new List <HtmlNode>(); try { var nodesCore = doc.DocumentNode.SelectNodes(itemsXpath); if (nodesCore == null) { throw new ApplicationException("Invalid path for items, no items could be read"); } else { nodes.AddRange(nodesCore.ToList()); } //var theNodesUrls = theNodes.Select(n => n.ParentNode.Attributes["href"].Value); var theNodesTexts = nodes.Select(n => n.InnerText.Cleanup()); results.AddRange(theNodesTexts); } catch (Exception x) { x.Data.Add("itemsXpath", itemsXpath); XLogger.Error(x); } return(results); }
public static bool ConfirmReady() { try { CurrentDriver.WaitForLoad2(); //IWebElement field = Waiter.Until(SeleniumExtras.WaitHelpers.ExpectedConditions.ElementIsVisible(By.CssSelector(".highcharts-credits"))); //return field.Text.Equals("Highcharts.com"); return(true); #region trials /* * //sometimes we only have 4 boxes * IWebElement field = Waiter.Until(SeleniumExtras.WaitHelpers.ExpectedConditions.ElementIsVisible(By.Id("result_4"))); * * //not a good idea, chart control loads before all the result boxes appear * IWebElement field = Waiter.Until(SeleniumExtras.WaitHelpers.ExpectedConditions.ElementIsVisible(By.CssSelector(".highcharts-credits"))); * return field.Text.Equals("Highcharts.com"); * * //not working * IWebElement field = Waiter.Until(SeleniumExtras.WaitHelpers.ExpectedConditions.ElementIsVisible(By.CssSelector(".highcharts-legend"))); * IWebElement field = Waiter.Until(SeleniumExtras.WaitHelpers.ExpectedConditions.ElementToBeClickable(By.CssSelector(".highcharts-navigator"))); * * //fails miserably * CurrentDriver.WaitForLoad(); * CurrentDriver.WaitForPageLoad(); */ #endregion trials } catch (Exception x) { XLogger.Error(x); return(false); } }
private static IWebDriver IE() { try { /* * string IEbin = Environment.Is64BitOperatingSystem ? * @"IEDriverServer_64.exe" : * @"IEDriverServer_32.exe"; * string IEbinClear = Environment.Is64BitOperatingSystem ? "IEDriverServer.exe" : "InternetExplorerDriver.exe"; */ //*** better to use 32 bit version blindly //http://stackoverflow.com/questions/8850211/why-is-selenium-internetexplorerdriver-webdriver-very-slow-in-debug-mode-visual // string IEbin = "IEDriverServer_32.exe"; string IEbinClear = "InternetExplorerDriver.exe"; if (!File.Exists(IEbinClear)) { File.Move(@"drivers\" + IEbin, @"drivers\" + IEbinClear); } IWebDriver driver = new InternetExplorerDriver("drivers"); return(driver); } catch (Exception x) { XLogger.Error(x); throw; } }
/// <summary> /// /// </summary> /// <param name="dialogTitle"></param> /// <param name="buttonText"></param> /// <returns></returns> public static bool ClickDialogButton(string dialogTitle, string buttonText) { try { int dialogHanlde = GetWindowHandle(dialogTitle); AutomationElement dialog = AutomationElement.FromHandle((IntPtr)dialogHanlde); var buttons = dialog.FindAll(TreeScope.Children, new PropertyCondition(AutomationElement.ControlTypeProperty, ControlType.Button)).Cast <AutomationElement>(); AutomationElement theButton = buttons.FirstOrDefault(b => b.Current.Name.Equals(buttonText)); if (theButton == null) { return(false); } var invokePattern = theButton.GetCurrentPattern(InvokePattern.Pattern) as InvokePattern; invokePattern.Invoke(); /* * // NO clickable point! * System.Windows.Point p = theButton.GetClickablePoint(); * AutoItX3Lib.AutoItX3Class au3; * au3 = new AutoItX3Lib.AutoItX3Class(); * au3.AutoItSetOption("MouseCoordMode", 0); * au3.MouseClick("LEFT", (int)p.X, (int)p.Y, 1, -1); */ return(true); } catch (Exception x) { XLogger.Error(x); return(false); } }
/// <summary> /// /// </summary> /// <param name="filename"></param> /// <returns></returns> public static bool HandleSaveAs_OldIE(string filename) { try { int dialogHanlde = GetWindowHandle("Save As"); AutomationElement dialog = AutomationElement.FromHandle((IntPtr)dialogHanlde); var textBoxes = dialog.FindAll(TreeScope.Children, new PropertyCondition(AutomationElement.ControlTypeProperty, ControlType.Edit)).Cast <AutomationElement>(); var buttons = dialog.FindAll(TreeScope.Children, new PropertyCondition(AutomationElement.ControlTypeProperty, ControlType.Button)).Cast <AutomationElement>(); AutomationElement theEdit = textBoxes.FirstOrDefault(t => t.Current.Name.Equals("File name:")); AutomationElement theButton = buttons.FirstOrDefault(b => b.Current.Name.Equals("Save")); if (theButton == null || theEdit == null) { return(false); } InsertTextUsingUIAutomation(theEdit, filename); var invokePattern = theButton.GetCurrentPattern(InvokePattern.Pattern) as InvokePattern; invokePattern.Invoke(); return(true); } catch (Exception x) { XLogger.Error(x); return(false); } }
private void btnOutputFolder_Click(object sender, EventArgs e) { try { var dlgOpenFolder = new Ookii.Dialogs.VistaFolderBrowserDialog() { UseDescriptionForTitle = true, Description = "Please select the generated messages output folder", ShowNewFolderButton = false, RootFolder = System.Environment.SpecialFolder.MyComputer, //NewStyle = false, }; if (!String.IsNullOrEmpty(myUI.ContactsFile)) { dlgOpenFolder.SelectedPath = Path.GetDirectoryName(myUI.ContactsFile); } if (dlgOpenFolder.ShowDialog() == System.Windows.Forms.DialogResult.OK) { if (!Directory.Exists(dlgOpenFolder.SelectedPath)) { MessageBox.Show(MSG.InvalidFolderPath); } else { myUI.OutputFolder = dlgOpenFolder.SelectedPath; } } } catch (Exception x) { XLogger.Error(x); } }
private void DoProcess() { try { var config = myUI.BuildConfig(); if (!File.Exists(REF.envelopFile)) { throw new ApplicationException($"Missing envelop template file: {REF.envelopFile}"); } Engine.Variables.ExecutionTime.Start(); Stopwatch timer = Stopwatch.StartNew(); XLogger.Info("BEGIN:\t Task Execution"); Engine.DoTask(config); var elapsed = timer.Elapsed.ToStandardElapsedFormat(); XLogger.Info($"END:{elapsed}\t Task Execution"); } catch (Exception x) { Engine.ExecutionStatus.Result = Engine.ExecutionResult.ErrorOccured; if (x is ApplicationException) { Engine.ExecutionStatus.Message = x.Message; } else { Engine.ExecutionStatus.Message = MSG.UnknownError; } XLogger.Error(x); } }
private string ReadPrice(SiteConfig siteConfig, string pageSource) { try { string res = ""; if (siteConfig == null || String.IsNullOrEmpty(pageSource)) { throw new ApplicationException("the inputs are invalid"); } Regex regex = new Regex(siteConfig.Match); Match match = regex.Match(pageSource); if (match.Success) { Console.WriteLine(match.Value); res = match.Groups[siteConfig.Group].Value.TrimStart('$'); } return(res); } catch (Exception x) { XLogger.Error(x); throw; } }
private void btnOutputFolder_Click(object sender, EventArgs e) { try { var dlgOpenFolder = new VistaFolderBrowserDialog() { RootFolder = Environment.SpecialFolder.MyComputer, Description = "Please input the folder where the generated artifacts will be placed", UseDescriptionForTitle = true, }; if (dlgOpenFolder.ShowDialog() == System.Windows.Forms.DialogResult.OK) { if (!Directory.Exists(dlgOpenFolder.SelectedPath)) { MessageBox.Show(MSG.InvalidFolderPath); } else { myUI.OutputFolder = dlgOpenFolder.SelectedPath; } } } catch (Exception x) { XLogger.Error(x); } }
private async void bgwProcess_DoWork(object sender, DoWorkEventArgs e) { try { BackgroundWorker worker = sender as BackgroundWorker; if (worker.CancellationPending) { e.Cancel = true; Engine.Variables.CancellationPending = true; } else { AttachEvents(); await DoProcess(); //DetachEvents(); } } catch (Exception x) { XLogger.Error(x); e.Cancel = true; MarkCompleted(MSG.OperationFailed); } }
public static bool HandleLogin(string user, string pass) { try { int dialogHanlde = GetWindowHandle("Windows Security"); AutomationElement dialog = AutomationElement.FromHandle((IntPtr)dialogHanlde); var textBoxes = dialog.FindAll(TreeScope.Children, new PropertyCondition(AutomationElement.ControlTypeProperty, ControlType.Edit)).Cast <AutomationElement>(); var buttons = dialog.FindAll(TreeScope.Children, new PropertyCondition(AutomationElement.ControlTypeProperty, ControlType.Button)).Cast <AutomationElement>(); AutomationElement userEdit = textBoxes.FirstOrDefault(t => t.Current.Name.Equals("User name")); AutomationElement passEdit = textBoxes.FirstOrDefault(t => t.Current.Name.Equals("Password")); AutomationElement okButton = buttons.FirstOrDefault(b => b.Current.Name.Equals("OK")); if (okButton == null || userEdit == null || passEdit == null) { return(false); } InsertTextUsingUIAutomation(userEdit, user); InsertTextUsingUIAutomation(passEdit, pass); var invokePattern = okButton.GetCurrentPattern(InvokePattern.Pattern) as InvokePattern; invokePattern.Invoke(); //SendKeys.SendWait("{Enter}"); return(true); } catch (Exception x) { XLogger.Error(x); return(false); } }
public static void ParseLiftParts(string liftPartsUrl, out string liftPartsPartCode, out decimal liftPartsPrice) { liftPartsPrice = -1; liftPartsPartCode = string.Empty; try { if (!HtmlAgility.UrlIsValid(liftPartsUrl)) { throw new ArgumentException("invalid url", "liftPartsUrl"); } HAP.HtmlDocument docSearch; HtmlAgility.GetDocumentFromUrl(liftPartsUrl, out docSearch); var strPrice = HtmlAgility.ScrapElement(docSearch, ConfigurationManager.AppSettings["LiftParts.Price1"])?.Trim('$').Trim(); decimal.TryParse(strPrice, out liftPartsPrice); if (liftPartsPrice == 0) { strPrice = HtmlAgility.ScrapElement(docSearch, ConfigurationManager.AppSettings["LiftParts.Price2"])?.Trim('$').Trim(); } decimal.TryParse(strPrice, out liftPartsPrice); liftPartsPartCode = HtmlAgility.ScrapElement(docSearch, ConfigurationManager.AppSettings["LiftParts.PartCode1"]); if (string.IsNullOrWhiteSpace(liftPartsPartCode)) { liftPartsPartCode = HtmlAgility.ScrapElement(docSearch, ConfigurationManager.AppSettings["LiftParts.PartCode2"]); } } catch (Exception x) { x.Data.Add("liftPartsUrl", liftPartsUrl); XLogger.Error(x); } }
private SiteConfig ReadSiteConfig() { try { Configuration config = ConfigurationManager.OpenExeConfiguration(Application.ExecutablePath); string theNodeXPath = "//Sites/add[@Site='trupar']"; XmlDocument doc = new XmlDocument(); doc.Load(config.FilePath); var theNode = doc.DocumentElement.SelectSingleNode(theNodeXPath);//.Attributes["value"].Value; //priceHtmlRegex string value = doc.DocumentElement.SelectSingleNode("/configuration/appSettings/add[@key='MyKeyName']").Attributes["value"].Value; var siteConfig = new SiteConfig() { Site = theNode.Attributes["Site"].Value, Match = theNode.Attributes["Match"].Value, Group = int.Parse(theNode.Attributes["Group"].Value) }; return(siteConfig); } catch (Exception x) { XLogger.Error(x); throw; } }
/// <summary> /// /// </summary> /// <param name="url"></param> /// <returns></returns> private static string GetWebConentCore1(string url, bool useProxy = false) { System.IO.Stream st = null; System.IO.StreamReader sr = null; if (!url.StartsWith("http://")) { url = "http://" + url; } try { // make a Web request System.Net.HttpWebRequest req = HttpWebRequest.Create(url) as HttpWebRequest; if (useProxy) { // Create proxy authentication object NetworkCredential netCred = new NetworkCredential(); netCred.UserName = "******"; netCred.Password = "******"; netCred.Domain = "vf-eg"; req.Credentials = netCred; WebProxy wp = new WebProxy(); wp.Credentials = netCred; wp.Address = new Uri("http://10.230.233.30:5110/proxy.pac"); req.Proxy = wp; } // get the response and read from the result stream HttpWebResponse resp = req.GetResponse() as HttpWebResponse; st = resp.GetResponseStream(); sr = new System.IO.StreamReader(st, Encoding.UTF8); // read all the text in it return(sr.ReadToEnd()); } catch (Exception x) { x.Data.Add("url", url); XLogger.Error(x); return(string.Empty); } finally { // always close readers and streams if (sr != null) { sr.Close(); } if (st != null) { st.Close(); } } }
private bool LoadSettings(out string exeVersion) { exeVersion = ""; try { List <String> missingKeys = new List <string>(); Configuration config = ConfigurationManager.OpenExeConfiguration(Application.ExecutablePath); exeVersion = ConfigurationManager.AppSettings[ConfigKeys.Config.ExeVersion]; //------------------------------------------------------------------------------------------ //------------------------------------------------------------------------------------------ if (config.AppSettings.Settings.AllKeys.Contains(ConfigKeys.Inputs.Url)) { myUI.Url = ConfigurationManager.AppSettings[ConfigKeys.Inputs.Url]; } else { missingKeys.Add(ConfigKeys.Inputs.Url); } //------------------------------------------------------------------------------------------ //if (config.AppSettings.Settings.AllKeys.Contains(ConfigKeys.Inputs.Username)) // myUI.Username = ConfigurationManager.AppSettings[ConfigKeys.Inputs.Username]; //else // missingKeys.Add(ConfigKeys.Inputs.Username); //------------------------------------------------------------------------------------------ //if (config.AppSettings.Settings.AllKeys.Contains(ConfigKeys.Inputs.Password)) // myUI.Password = ConfigurationManager.AppSettings[ConfigKeys.Inputs.Password]; //else // missingKeys.Add(ConfigKeys.Inputs.Password); //------------------------------------------------------------------------------------------ //------------------------------------------------------------------------------------------ if (config.AppSettings.Settings.AllKeys.Contains(ConfigKeys.Outputs.OutputFolder)) { myUI.OutputFolder = ConfigurationManager.AppSettings[ConfigKeys.Outputs.OutputFolder]; } else { missingKeys.Add(ConfigKeys.Outputs.OutputFolder); } //------------------------------------------------------------------------------------------ if (missingKeys.Count > 0) { throw new ApplicationException(String.Concat(MSG.MissingConfigKeys, String.Join(", ", missingKeys))); } return(true); } catch (Exception x) { XLogger.Error(x); return(false); } }
public static void Main(String[] args) { try { //Engine.Tests.readChoiceText(); } catch (Exception x) { XLogger.Error(x); } }
private static Statistics WorkWithDocument(string inputFile) { try { var contents = File.ReadAllText(inputFile); var defsFile = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "Definitions.json"); //var cam = new Icu.Locale("km-KH"); //var bi = new Icu.RuleBasedBreakIterator(Icu.BreakIterator.UBreakIteratorType.WORD, cam); //bi.SetText(contents); //var count = 0; //while (bi.MoveNext() > 0) // count++; // txtNumWords.Text = count.ToString(); var words = BreakIterator.Split(BreakIterator.UBreakIteratorType.WORD, "km-KH", contents).ToList(); //var sentences = BreakIterator.Split(BreakIterator.UBreakIteratorType.SENTENCE, "km-KH", contents); //var longestSentence = sentences.OrderByDescending(s=>s.Length).FirstOrDefault(); var chars = BreakIterator.Split(BreakIterator.UBreakIteratorType.CHARACTER, "km-KH", contents).ToList(); var sentences = contents.Split(new string[] { "។" }, StringSplitOptions.None).ToList(); var longestSentence = sentences.OrderByDescending(s => s.Length).FirstOrDefault(); var longestSentenceWords = longestSentence.Split(new string[] { "។" }, StringSplitOptions.None); var longestSentenceWordsAPI = BreakIterator.Split(BreakIterator.UBreakIteratorType.WORD, "km-KH", longestSentence).ToList(); var longestWord = words.OrderByDescending(s => s.Length).FirstOrDefault(); var longestWordChars = BreakIterator.Split(BreakIterator.UBreakIteratorType.CHARACTER, "km-KH", longestWord).ToList(); var defs = JsonConvert.DeserializeObject <Definitions>(File.ReadAllText(defsFile)); return(new Statistics() { //Sentences = (bi.Boundaries.Length + 1).ToString(), Sentences = sentences.Count().ToString(), Words = words.Count().ToString(), Consonants = chars.Intersect(defs.Consonants.ToList()).Count().ToString(), Vowels = chars.Intersect(defs.Vowels.ToList()).Count().ToString(), LongestSentence = longestSentence, LongestSentenceWords = longestSentenceWordsAPI.Count().ToString(), //LongestSentenceWords = longestSentence?.Count().ToString(), LongestWord = longestWord, LongestWordChars = longestWordChars.Count().ToString(), WordList = String.Join(Environment.NewLine, words), AddingZWSP = String.Join("\u200B", words), }); } catch (Exception x) { XLogger.Error(x); return(null); } }
internal static void LoadSite(string url, By waitElement) { try { CurrentDriver.Navigate().GoToUrl(url); IWebElement userField = Waiter.Until(SeleniumExtras.WaitHelpers.ExpectedConditions.ElementToBeClickable(waitElement)); } catch (Exception x) { XLogger.Error(x); } }
private static void TestReadTOC() { try { var TOCPath = Path.GetFullPath(@"TOCs\Redemap.xlsx"); var screenshots = Engine.ReadTOC(TOCPath); } catch (Exception x) { XLogger.Error(x); } }
private string ReadPageSource() { try { return(HtmlAgility.GetWebContent(txtProductUrl.Text)); } catch (Exception x) { XLogger.Error(x); throw; } }
public static bool ScanFile(string inputFile, string outputFile) { XLogger.Info($"input file path: {Path.GetFullPath(inputFile)}"); XLogger.Info($"output file path: {Path.GetFullPath(outputFile)}"); #region health checks if (!File.Exists(inputFile)) { throw new ArgumentException("File not found: " + inputFile, "inputFile"); } #endregion health checks string fullCommand = "", commandOutput = ""; StringBuilder sb = new StringBuilder(Environment.NewLine); var exePath = Path.Combine(RootFolder, "Bin", "ICUconsole.exe"); try { string tempBatch = Path.Combine(RootFolder, "scanFile.bat"); tempBatch.DeleteFile(); fullCommand = string.Format( @"{0} ""{1}"" ""{2}"" @echo off echo %ERRORLEVEL% ", exePath, inputFile, outputFile); File.WriteAllText(tempBatch, fullCommand); string arguments = ""; bool res = ExecuteCommand(tempBatch, Environment.CurrentDirectory, arguments, out commandOutput); sb.AppendLine("commandOutput: " + commandOutput); var outputLines = commandOutput.Split(new string[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries).ToList(); var lastLine = outputLines.Last(); XLogger.Info(sb.ToString()); //res &= !String.IsNullOrWhiteSpace(fileCommandOutput); return(lastLine.Trim() == "0"); } catch (Exception x) { x.Data.Add("fullCommand", fullCommand); x.Data.Add("fileCommandOutput", commandOutput); XLogger.Error(x); return(false); } }
public static bool ConfirmValidConfiguration() { try { IWebElement field = Waiter.Until(SeleniumExtras.WaitHelpers.ExpectedConditions.ElementIsVisible(By.Id("top_message"))); return(!field.Text.Equals("No data Found", StringComparison.InvariantCultureIgnoreCase)); } catch (Exception x) { XLogger.Error(x); return(false); } }
public static void ExecuteJavascript(string js) { try { WebDriverWait wait = new WebDriverWait(CurrentDriver, TimeSpan.FromSeconds(300)); wait.Until(d => ((IJavaScriptExecutor)CurrentDriver).ExecuteScript(js).Equals("complete")); } catch (Exception x) { XLogger.Error(x); } }
internal static void SearchLocation(string suburb, string street, string streetNo) { try { IWebElement userField = Waiter.Until(SeleniumExtras.WaitHelpers.ExpectedConditions.ElementToBeClickable(Identifiers.Buttons["Home.Search"])); userField.Click(); Selenium.EditTextField(Identifiers.Combos["Search.Suburb"], suburb); } catch (Exception x) { XLogger.Error(x); } }
private static List <ReportEntry> ReadPrices() { var res = new List <ReportEntry>(); try { PartUrl.GetRefs(Path.Combine(Environment.CurrentDirectory, ConfigurationManager.AppSettings["InputFile"])); //var currentRef = PartUrl.refs.FirstOrDefault(r => r.idx == 1); ParallelOptions options = new ParallelOptions() { MaxDegreeOfParallelism = NThreads }; //foreach (var currentRef in PartUrl.refs) Parallel.ForEach(PartUrl.refs, options, (currentRef) => { string hgmPartCode, trupartPartCode, liftPartsCode; decimal hgmPrice, truparPrice, liftPartsPrice; Engine.ParseHGM(currentRef.hgmURL, out hgmPartCode, out hgmPrice); Engine.ParseTrupar(currentRef.TruparURL, out trupartPartCode, out truparPrice); Engine.ParseLiftParts(currentRef.liftPartsURL, out liftPartsCode, out liftPartsPrice); var rep = new ReportEntry() { idx = currentRef.idx, HGMPartCode = hgmPartCode, TruparPartCode = trupartPartCode, LiftPartsPartCode = liftPartsCode, HGMPrice = hgmPrice, TruparPrice = truparPrice, LiftPartsPrice = liftPartsPrice, DifferenceTrupar = Math.Round(truparPrice - hgmPrice, 2), DifferenceTruparPCT = Math.Round((truparPrice - hgmPrice) / hgmPrice * 100, 2), DifferenceLiftParts = Math.Round(liftPartsPrice - hgmPrice, 2), DifferenceLiftPartsPCT = Math.Round((liftPartsPrice - hgmPrice) / hgmPrice * 100, 2) }; res.Add(rep); } ); return(res.OrderBy(r => r.idx).ToList()); } catch (Exception x) { XLogger.Error(x); } return(res); }
public XConfig(HttpRequest request, XLogger log) { System.Configuration.Configuration confg = System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration(request.ApplicationPath); if (confg.AppSettings.Settings.Count > 0) { System.Configuration.KeyValueConfigurationElement portPair = confg.AppSettings.Settings["XebraServerPort"]; if (null != portPair) { this.port = int.Parse(portPair.Value); } else { log.Error("Missing property in web.config: XebraServerPort"); } System.Configuration.KeyValueConfigurationElement hostPair = confg.AppSettings.Settings["XebraServerHost"]; if (null != hostPair) { this.host = hostPair.Value; } else { log.Error("Missing property in web.config: XebraServerHost"); } System.Configuration.KeyValueConfigurationElement maxUploadSizePair = confg.AppSettings.Settings["MaxUploadSize"]; if (null != maxUploadSizePair) { this.maxUploadSize = int.Parse(maxUploadSizePair.Value); } else { log.Error("Missing property in web.config: MaxUploadSize"); } System.Configuration.KeyValueConfigurationElement uploadSavePathPair = confg.AppSettings.Settings["UploadSavePath"]; if (null != uploadSavePathPair) { this.uploadSavePath = uploadSavePathPair.Value; if (!this.uploadSavePath.EndsWith("\\")) { this.uploadSavePath += "\\"; } } else { log.Error("Missing property in web.config: UploadSavePath"); } } else { log.Error("No properties found in web.config"); } }