C# Saving screenshot with incrementing number - c#

I have created a different class which to call screenshot. Below is my code
Program.cs
static int i=1;
[TestFixture(typeof(FirefoxDriver))]
[TestFixture(typeof(InternetExplorerDriver))]
[TestFixture(typeof(ChromeDriver))]
public class TestWithMultipleBrowsers<TWebDriver> where TWebDriver : IWebDriver, new()
{
[Test]
public void Initialize()
{
PropertiesCollection.driver = new TWebDriver();
CredentialPageObject objSignin = new CredentialPageObject();
string pathfile = #"..\..\a.xlsx";
string sheetName = "SignIn";
var excelFile = new ExcelQueryFactory(pathfile);
var abc = from a in excelFile.Worksheet(sheetName) select a;
foreach (var a in abc)
{
PropertiesCollection.driver.Navigate().GoToUrl(a["URL"]);
}
PropertiesCollection.driver.Manage().Window.Maximize();
foreach (var a in abc)
{
objSignin.Login(a["ID"], a["Pass"]);
}
Result.screenshoot();
FunctionPageObject objFunc = new FunctionPageObject();
}
screenshot is called from Result.cs class which contains
class Result
{
public static void screenshot()
{
ITakesScreenshot screenshotDriver = PropertiesCollection.driver as ITakesScreenshot;
Screenshot screenCapture = screenshotDriver.GetScreenshot();
string path = #"..\..\Results\";
string timestamp = DateTime.Now.ToString("yy-MM-dd hh-mm-ss");
screenCapture.SaveAsFile(#path + i + ". " + timestamp + ".png", System.Drawing.Imaging.ImageFormat.Png);
}
}
And this one is my FunctionPageObject.cs
[FindsBy(How = How.Name, Using = "Login")]
public IWebElement clickLogin { get; set; }
[FindsBy(How = How.XPath, Using = "/html/body/form/table/tbody/tr[1]/td[2]/span/select/option[2]")]
public IWebElement Title { get; set; }
[FindsBy(How = How.Id, Using = "Initial")]
public IWebElement Initial { get; set; }
[FindsBy(How = How.Id, Using = "FirstName")]
public IWebElement FN { get; set; }
[FindsBy(How = How.Id, Using = "MiddleName")]
public IWebElement MN { get; set; }
[FindsBy(How = How.XPath, Using = "/html/body/form/table/tbody/tr[5]/td[2]/input[1]")]
public IWebElement Gender { get; set; }
[FindsBy(How = How.Name, Using = "Hindi")]
public IWebElement Language { get; set; }
public void CuteEditor()
{
Thread.Sleep(3000);
Title.Click();
Result.screenshot();
Initial.EnterText("PS");
Result.screenshot();
FN.EnterText("Pramukh");
Result.screenshot();
MN.EnterText("Swami");
Result.screenshot();
Gender.Click();
Result.screenshot();
Language.Click();
Result.screenshot();
Now, what I am doing here is calling Screenshot page from Result.Cs and calling it in main and FunctionPageObject class but it does create screenshot but it is not incrementing.
Actual Result: It remains 1 all the time
Expected Result: Should increment all the time.

This will solve the problem
class Result
{
static int i = 1 ;
public static void screenshot()
{
ITakesScreenshot screenshotDriver = PropertiesCollection.driver as ITakesScreenshot;
Screenshot screenCapture = screenshotDriver.GetScreenshot();
string path = #"..\..\Results\";
string timestamp = DateTime.Now.ToString("yy-MM-dd hh-mm-ss");
screenCapture.SaveAsFile(#path + i + ". " + timestamp + ".png", System.Drawing.Imaging.ImageFormat.Png);
i++;
}
}

Related

Table Row (//tr) HtmlNodes seem to have issue with rows being skipped

I'm currently trying to scrape a cannabis strain database as it is no longer being maintained. I seem to be running into an issue where table rows are skipped in my logic but it really doesn't make sense, it's like a break is being called when I'm iterating through the //tr elements of the table that is storing the chemical reports.
Is it something like the δ α symbols in the next row. I've tried regex replacing them out to now luck. Any help would be appreciated all code is in a single class console app.
Issue is in the table.ChildNodes not iterating all the way through. Located in the ParseChemical() method.
Sample Page: http://ocpdb.pythonanywhere.com/ocpdb/420/
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations.Schema;
using System.ComponentModel.Design;
using System.IO.IsolatedStorage;
using System.Linq;
using System.Linq.Expressions;
using System.Net;
using System.Net.Http;
using System.Reflection.Emit;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using HtmlAgilityPack;
using Microsoft.VisualBasic.CompilerServices;
namespace CScrape
{
class Program
{
private static readonly HttpClient Client = new HttpClient();
private static readonly string BaseUri = "http://ocpdb.pythonanywhere.com/ocpdb/";
private static int _startId = 420;
private static int _endId = 1519;
private static List<Lab> _labs = new List<Lab>();
private static List<ChemicalItem> _chemicalItems = new List<ChemicalItem>();
private static List<UnitOfMeasure> _uoms = new List<UnitOfMeasure>();
private static List<Strain> _strains = new List<Strain>();
static void Main(string[] args)
{
Client.DefaultRequestHeaders.Accept.Clear();
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls13;
_uoms.AddRange(GetUoms());
for (var i = _startId; i <= _endId; i++)
{
var result = GetUri($"{BaseUri}{i}").Result;
_strains.Add(ParseChemical(result));
}
}
private static long AddChemicalItem(ChemicalItem item)
{
if (ChemicalExists(item.Symbol))
return _chemicalItems.FirstOrDefault(ci => ci.Symbol == item.Symbol)?.Id ?? -1;
item.Id = _chemicalItems.Count + 1;
_chemicalItems.Add(item);
return item.Id;
}
private static void UpdateChemicalItem(ChemicalItem item)
{
if (!ChemicalExists(item.Symbol)) return;
var index = _chemicalItems.IndexOf(item);
if (!(index >= 0)) return;
_chemicalItems.RemoveAt(index);
AddChemicalItem(item);
}
private static long AddLab(Lab lab)
{
if (LabExists(lab.Name))
return _labs.FirstOrDefault(l => l.Name == lab.Name)?.Id ?? -1;
lab.Id = _labs.Count + 1;
_labs.Add(lab);
return lab.Id;
}
private static async Task<string> GetUri(string uri)
{
var response = await Client.GetByteArrayAsync(uri);
return Encoding.UTF8.GetString(response, 0, response.Length - 1);
}
private static Strain ParseChemical(string html)
{
html = Regex.Replace(html, #"Δ", "Delta");
HtmlDocument htmlDoc = new HtmlDocument();
htmlDoc.LoadHtml(html);
var strain = new Strain();
strain.Reports ??= new List<ChemicalReport>();
try
{
strain.Name = htmlDoc.DocumentNode.SelectSingleNode("/html/body/div/div[1]/div[1]/h3/b").InnerText;
}
catch (Exception e)
{
// TODO: DOcument Exception
Console.WriteLine(e.Message);
}
if (string.IsNullOrWhiteSpace(strain.Name)) return null;
try
{
var ocpId = htmlDoc.DocumentNode.SelectSingleNode("/html/body/div/div[1]/div[2]/p/b/text()[1]");
strain.OcpId = SanitizeHtml(ocpId.InnerText).Split(':')[1];
}
catch (Exception e)
{
// TODO: Document Exception
Console.WriteLine(e.Message);
}
if (string.IsNullOrWhiteSpace(strain.OcpId)) return null;
try
{
var date = htmlDoc.DocumentNode.SelectSingleNode("/html/body/div/div[1]/div[2]/p/text()");
}
catch (Exception e)
{
// TODO: Document Exception
Console.WriteLine(e.Message);
}
var chemReport = new ChemicalReport();
chemReport.Items ??= new List<ReportItem>();
try
{
var table = htmlDoc.DocumentNode.SelectSingleNode("/html/body/div/div[2]/div[1]/table/tbody");
var children = table.ChildNodes.ToList();
// On the sample page there are 200 children here
// However it only interates through the first few and then just breaks out of the loop
foreach (var child in children)
{
var name = child.Name;
if (child.Name == "tr")
{
var infos = child.SelectNodes("th|td");
foreach (var info in infos)
{
if(string.IsNullOrWhiteSpace(info.InnerText)) continue;
if (info.InnerText.Contains("Report")) continue;
if (double.TryParse(info.InnerText, out var isNumber))
{
var last = chemReport.Items.LastOrDefault();
if (last == null) continue;
if (last.Value <= 0.0000) last.Value = isNumber;
else
{
var further = chemReport.Items.ToArray()[chemReport.Items.Count - 2];
if (further.Value <= 0.0000)
further.Value = isNumber;
}
continue;
}
var _ = new ChemicalItem
{
Name = info.InnerText,
Symbol = info.InnerText
};
_.Id = AddChemicalItem(_);
var report = new ReportItem
{
Chemical = _,
ChemicalItemId = _.Id,
UnitOfMeasureId = 1,
UoM = GetUoms()[0]
};
chemReport.Items.Add(report);
}
}
}
strain.Reports.Add(chemReport);
}
catch (Exception e)
{
// TODO: Document exception
Console.Write(e.Message);
}
return strain;
}
private static List<UnitOfMeasure> GetUoms()
{
return new List<UnitOfMeasure>
{
new UnitOfMeasure {Name = "Milligrams per Gram", Symbol = "mg/g"},
new UnitOfMeasure {Name = "Percent", Symbol = "%"}
};
}
private static string SanitizeHtml(string text, string replacement = "")
{
return Regex.Replace(text, #"<[^>]+>| |α|\n|\t", replacement);
}
private static string GetLabName(string[] split)
{
var strip = split[0].Split(':')[1];
for(var i = 1; i < split.Length - 2; i ++)
{
if (string.IsNullOrWhiteSpace(split[i])) break;
strip += $" {split[i]}";
}
return strip;
}
private static string GetSampleId(string[] split)
{
var found = false;
foreach (var item in split)
{
if (found)
return item.Split(':')[1];
if (item == "Sample") found = true;
}
return "NA";
}
private static bool LabExists(string name)
{
return _labs.Any(lab => lab.Name == name);
}
private static bool ChemicalExists(string name)
{
return _chemicalItems.Any(ci => ci.Symbol == name);
}
private static ReportItem GetReportItem(string text)
{
if (string.IsNullOrWhiteSpace(text)) return null;
ReportItem ri = null;
try
{
var clean = SanitizeHtml(text);
var check = 0;
var split = clean.Split(':');
var label = split[0];
if (string.IsNullOrWhiteSpace(label)) return null;
if (double.TryParse(label, out var invalidType)) return null;
var val = string.Empty;
if (split.Length == 1)
{
if (split[0].Contains("Total"))
{
Regex re = new Regex(#"([a-zA-Z]+)(\d+)");
Match result = re.Match(split[0]);
label = result.Groups[1].Value;
val = result.Groups[2].Value;
}
}
if(split.Length > 1)
val = split[1];
if (!ChemicalExists(label)) AddChemicalItem(new ChemicalItem {Id = _chemicalItems.Count + 1,Symbol = label});
ri = new ReportItem();
ri.Chemical = _chemicalItems.FirstOrDefault(ci => ci.Symbol == label);
ri.UoM = val.Contains("%")
? _uoms.FirstOrDefault(uom => uom.Symbol == "%")
: _uoms.FirstOrDefault(uom => uom.Symbol == "mg/g");
if (string.IsNullOrWhiteSpace(val)) return ri;
var value = val.Contains("%") ? split[1].Substring(0, val.Length - 1) : val;
ri.Value = Convert.ToDouble(value);
}
catch (Exception e)
{
// TODO: Document Exception
Console.WriteLine(e.Message);
}
return ri;
}
//private static ChemicalItem GetChemicalItem(string text)
//{
//}
public class Strain
{
public long Id { get; set; }
public string Name { get; set; }
public DateTime Created { get; set; }
public string OcpId { get; set; }
public bool IsHidden { get; set; } = false;
public virtual ICollection<ChemicalReport> Reports { get; set; }
}
public class Lab
{
public long Id { get; set; }
public string Name { get; set; }
public virtual ICollection<ChemicalReport> Reports { get; set; }
}
public class ChemicalReport
{
public long Id { get; set; }
[ForeignKey("Lab")]
public long LabId { get; set; }
public virtual Lab Lab { get; set; }
public string SampleId { get; set; }
public DateTime Created { get; set; }
public virtual ICollection<ReportItem> Items { get; set; }
[ForeignKey("Strain")]
public long StrainId { get; set; }
public virtual Strain Strain { get; set; }
}
public class ChemicalItem
{
public long Id { get; set; }
public string Name { get; set; }
public string Symbol { get; set; }
}
public class ReportItem
{
public long Id { get; set; }
[ForeignKey("Chemical")]
public long ChemicalItemId { get; set; }
public virtual ChemicalItem Chemical { get; set; }
public double Value { get; set; }
[ForeignKey("UoM")]
public long UnitOfMeasureId { get; set; }
public virtual UnitOfMeasure UoM { get; set; }
}
public class UnitOfMeasure
{
public long Id { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public string Symbol { get; set; }
}
}
}

Unable to Locate email and password element on Nordstrom Website where we try and sign up

Following the below process:
Navigate to Nordstrom rack website and click Sign Up
When the pop up shows up enter the email and password and create account
Following is the code:
class EntryPoint
{
static void Main(string[] args)
{
String parentHandle = Driver.driver.CurrentWindowHandle;
EmailSignUp signup = new EmailSignUp();
Driver.driver.Navigate().GoToUrl("https://www.nordstromrack.com/");
Thread.Sleep(1000);
signup.SignUpLink.Click();
foreach (String winHandle in Driver.driver.WindowHandles)
{
Driver.driver.SwitchTo().Window(winHandle);
}
**signup.EmailInput.Click();
signup.EmailInput.SendKeys(Config.Credentials.Valid.BaseEmail);** //Unable to find these elements
Thread.Sleep(1000);
**signup.Password.Click();
signup.Password.SendKeys(Config.Credentials.Valid.Password);** //unable to locate these elements
Thread.Sleep(1000);
signup.CreateAccount.Click();
Thread.Sleep(5000);
Driver.driver.Quit();
}
}
WebElements definition Class where the elements email and password a defined
using OpenQA.Selenium;
using OpenQA.Selenium.Support.PageObjects;
namespace NordstromRack.UI_Elements
{
public class EmailSignUp
{
public EmailSignUp()
{
PageFactory.InitElements(Driver.driver, this);
}
[FindsBy(How = How.ClassName, Using = "form-label__input form-label__input--password")]
public IWebElement Password { get; set; }
[FindsBy(How = How.ClassName, Using = "form-label__input form-label__input--email")]
public IWebElement EmailInput { get; set; }
[FindsBy(How = How.ClassName, Using = "secondary-nav__link")]
public IWebElement SignUpLink { get; set; }
[FindsBy(How = How.ClassName, Using = "cta-button__content")]
public IWebElement CreateAccount { get; set; }
}
}
You need to get rid of the space and replace it with a dot when specifying your CSS selector. Try replacing your top two selectors with
[FindsBy(How = How.CssSelector, Using = "input.form-label__input.form-label__input--password")]
public IWebElement Password { get; set; }
[FindsBy(How = How.CssSelector, Using = "input.form-label__input.form-label__input--email")]
public IWebElement EmailInput { get; set; }
Any better?

Slow parsing of 23 kB XML file with more than half second

I'm trying to build objects based on xmlreader:
List<Element> units = new List<Element>();
string path = "D:\\Item\\Unit.xml";
XElement xelement = XElement.Load(path);
IEnumerable<XElement> elements = xelement.Elements();
foreach (var c in elements)
{
Element stb = new Element();
stb.Name = c.Element("Name").Value;
stb.Picture = c.Element("Picture").Value;
//and next 30 options included try / catch for int.Parse
}
XML:
<?xml version="1.0" encoding="UTF-8"?>
<rows>
<row id="1">
<Name>Freighter</Name>
<Picture>Item\Freighter.gif</Picture>
... and 30 next rows with data for each "unit"
</row>
... and 30 next units...
<rows>
As I told, XML is 23kB file with 30 rows per each unit, with total 30 units in file. Not sure why this code is so slow: it took 670 miliseconds (i3 processor).
The slowest part is obiect fillig, but not sure how to improve it.
The complete code looks exactly:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;
using System.Diagnostics;
namespace element_reader
{
class Program
{
static void Main(string[] args)
{
CustomStopwatch sw = new CustomStopwatch();
sw.Start();
List<Element> ships = new List<Element>();
string path = "D:\\Ship_test.xml";
XElement xelement = XElement.Load(path);
IEnumerable<XElement> elements = xelement.Elements();
sw.Stop();
Console.WriteLine("Stopwatch elapsed: {0}, StartAt: {1}, EndAt: {2}", sw.ElapsedMilliseconds, sw.StartAt.Value, sw.EndAt.Value);
sw.Start();
foreach (var c in elements)
{
Element stb = new Element();
stb.Name = c.Element("Name").Value;
stb.Picture = c.Element("Picture").Value;
try
{
stb.Prt = int.Parse(c.Element("PRT").Value);
}
catch
{ stb.Prt = 0; }
try
{
stb.Lrt = int.Parse(c.Element("LRT").Value);
}
catch
{ stb.Lrt = 0; }
stb.Special = c.Element("Special").Value;
try
{
stb.Wep = int.Parse(c.Element("Wep").Value);
}
catch
{ stb.Wep = 0; }
try
{
stb.Con = int.Parse(c.Element("Con").Value);
}
catch
{ stb.Con = 0; }
try
{
stb.Ene = int.Parse(c.Element("Ene").Value);
}
catch
{ stb.Ene = 0; }
try
{
stb.Ele = int.Parse(c.Element("Ele").Value);
}
catch
{ stb.Ele = 0; }
try
{
stb.Prp = int.Parse(c.Element("Prp").Value);
}
catch
{ stb.Prp = 0; }
try
{
stb.Bio = int.Parse(c.Element("Bio").Value);
}
catch
{ stb.Bio = 0; }
try
{
stb.Mass = int.Parse(c.Element("Mass").Value);
}
catch
{ stb.Mass = 0; }
try
{
stb.Iro = int.Parse(c.Element("Iro").Value);
}
catch
{ stb.Iro = 0; }
try
{
stb.Bor = int.Parse(c.Element("Bor").Value);
}
catch
{ stb.Bor = 0; }
try
{
stb.Ger = int.Parse(c.Element("Ger").Value);
}
catch
{ stb.Ger = 0; }
try
{
stb.Res = int.Parse(c.Element("Res").Value);
}
catch
{ stb.Res = 0; }
ships.Add(stb);
}
sw.Stop();
Console.WriteLine("Stopwatch elapsed: {0}, StartAt: {1}, EndAt: {2}", sw.ElapsedMilliseconds, sw.StartAt.Value, sw.EndAt.Value);
Console.Read();
}
}
public class Element
{
public string Name;
public string Picture;
public int Prt;
public int Lrt;
public string Special;
public int Con;
public int Wep;
public int Ene;
public int Ele;
public int Prp;
public int Bio;
public int Mass;
public int Iro;
public int Bor;
public int Ger;
public int Res;
}
public class CustomStopwatch : Stopwatch
{
public DateTime? StartAt { get; private set; }
public DateTime? EndAt { get; private set; }
public void Start()
{
StartAt = DateTime.Now;
base.Start();
}
public void Stop()
{
EndAt = DateTime.Now;
base.Stop();
}
}
}
When the part of XML looks exactly:
<?xml version="1.0" encoding="UTF-8"?>
<rows>
<row id="1">
<Name>Small Freighter</Name>
<Picture>Item\Ship\Ship01_1.gif</Picture>
<Description></Description>
<PRT></PRT>
<LRT></LRT>
<Special></Special>
<Ene>0</Ene>
<Wep>0</Wep>
<Prp>0</Prp>
<Con>0</Con>
<Ele>0</Ele>
<Bio>0</Bio>
<Slot1>-150, 0, Engine, 1, 1, 1</Slot1>
<Slot2>-50, 0, Cargo, 70, 1, 1</Slot2>
<Slot3>50, 0, DEF, 1, 1, 1</Slot3>
<Slot4>150, 0, SEM, 1, 1, 1</Slot4>
<Mass>25</Mass>
<Res>20</Res>
<Iro>12</Iro>
<Res>0</Res>
<Ger>17</Ger>
<Fuel>130</Fuel>
<Cargo>70</Cargo>
<HPD_arm>25</HPD_arm>
<Initiative>0</Initiative>
</row>
</rows>
Result is 70ms for 1kB file !!!
If I have 20 files to load with 20-30 rows each this method is completely useless.
Please notice that I do not use all data located in file.
You didn't provide full xml file content, so I just only can suggest you one thing.
Use int.TryParse instead of int.Parse. I bet your code throws hundreds of exceptions which are very CPU expensive.
Usually the code should look like this :
List<Element> elements = xelement.Descendants("TagName").Select(x => new Element() {
Name = (string)x.Element("Name"),
Picture = (string)x.Element("Picture")
}).ToList();
Here is the comparison of the times
Time 1 = '11.0082', Time 2 = '4.0032'
Here is code :
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;
using System.Xml.Serialization;
namespace ConsoleApplication1
{
class Program
{
const string FILENAME = #"c:\temp\test.xml";
static void Main(string[] args)
{
Element newElement = new Element() {
Name = "John",
Picture = "Dorian Grey",
Data1 = "1",
Data2 = "1",
Data3 = "1",
Data4 = "1",
Data5 = "1",
Data6 = "1",
Data7 = "1",
Data8 = "1",
Data9 = "1",
Data10 = "1",
Data11 = "1",
Data12 = "1",
Data13 = "1",
Data14 = "1",
Data15 = "1",
Data16 = "1",
Data17 = "1",
Data18 = "1",
Data19 = "1",
Data20 = "1",
Data21 = "1",
Data22 = "1",
Data23 = "1",
Data24 = "1",
Data25 = "1",
Data26 = "1",
Data27 = "1",
Data28 = "1",
Data29 = "1",
Data30 = "1"
};
Root root = new Root();
for (int i = 0; i < 29; i++)
{
root.elements.Add(newElement);
}
XmlWriterSettings setting = new XmlWriterSettings();
setting.Indent = true;
XmlWriter writer = XmlWriter.Create(FILENAME, setting);
XmlSerializer serializer = new XmlSerializer(typeof(Root));
serializer.Serialize(writer, root);
writer.Flush();
writer.Close();
XDocument doc = XDocument.Load(FILENAME);
DateTime start1 = DateTime.Now;
List<Element> units = new List<Element>();
List<XElement> elements = doc.Root.Elements().ToList();
foreach (var c in elements)
{
Element stb = new Element();
stb.Name = c.Element("Name").Value;
stb.Picture = c.Element("Picture").Value;
stb.Data1 = c.Element("Data1").Value;
stb.Data2 = c.Element("Data2").Value;
stb.Data3 = c.Element("Data3").Value;
stb.Data4 = c.Element("Data4").Value;
stb.Data5 = c.Element("Data5").Value;
stb.Data6 = c.Element("Data6").Value;
stb.Data7 = c.Element("Data7").Value;
stb.Data8 = c.Element("Data8").Value;
stb.Data9 = c.Element("Data9").Value;
stb.Data10 = c.Element("Data10").Value;
stb.Data11 = c.Element("Data11").Value;
stb.Data12 = c.Element("Data12").Value;
stb.Data13 = c.Element("Data13").Value;
stb.Data14 = c.Element("Data14").Value;
stb.Data15 = c.Element("Data15").Value;
stb.Data16 = c.Element("Data16").Value;
stb.Data17 = c.Element("Data17").Value;
stb.Data18 = c.Element("Data18").Value;
stb.Data19 = c.Element("Data19").Value;
stb.Data20 = c.Element("Data20").Value;
stb.Data21 = c.Element("Data21").Value;
stb.Data22 = c.Element("Data22").Value;
stb.Data23 = c.Element("Data23").Value;
stb.Data24 = c.Element("Data24").Value;
stb.Data25 = c.Element("Data25").Value;
stb.Data26 = c.Element("Data26").Value;
stb.Data27 = c.Element("Data27").Value;
stb.Data28 = c.Element("Data28").Value;
stb.Data29 = c.Element("Data29").Value;
stb.Data30 = c.Element("Data30").Value;
units.Add(stb);
}
DateTime end1 = DateTime.Now;
DateTime start2 = DateTime.Now;
List<Element> elements2 = doc.Descendants("elements").Select(x => new Element()
{
Name = (string)x.Element("Name"),
Picture = (string)x.Element("Picture"),
Data1 = (string)x.Element("Data1"),
Data2 = (string)x.Element("Data2"),
Data3 = (string)x.Element("Data3"),
Data4 = (string)x.Element("Data4"),
Data5 = (string)x.Element("Data5"),
Data6 = (string)x.Element("Data6"),
Data7 = (string)x.Element("Data7"),
Data8 = (string)x.Element("Data8"),
Data9 = (string)x.Element("Data9"),
Data10 = (string)x.Element("Data10"),
Data11 = (string)x.Element("Data11"),
Data12 = (string)x.Element("Data12"),
Data13 = (string)x.Element("Data13"),
Data14 = (string)x.Element("Data14"),
Data15 = (string)x.Element("Data15"),
Data16 = (string)x.Element("Data16"),
Data17 = (string)x.Element("Data17"),
Data18 = (string)x.Element("Data18"),
Data19 = (string)x.Element("Data19"),
Data20 = (string)x.Element("Data20"),
Data21 = (string)x.Element("Data21"),
Data22 = (string)x.Element("Data22"),
Data23 = (string)x.Element("Data23"),
Data24 = (string)x.Element("Data24"),
Data25 = (string)x.Element("Data25"),
Data26 = (string)x.Element("Data26"),
Data27 = (string)x.Element("Data27"),
Data28 = (string)x.Element("Data28"),
Data29 = (string)x.Element("Data29"),
Data30 = (string)x.Element("Data30"),
}).ToList();
DateTime end2 = DateTime.Now;
string results = string.Format("Time 1 = '{0}', Time 2 = '{1}'", (end1 - start1).TotalMilliseconds, (end2 - start2).TotalMilliseconds);
Console.ReadLine();
}
}
public class Root
{
[XmlElement]
public List<Element> elements = new List<Element>();
}
public class Element
{
public string Name { get; set; }
public string Picture { get; set; }
public string Data1 { get; set; }
public string Data2 { get; set; }
public string Data3 { get; set; }
public string Data4 { get; set; }
public string Data5 { get; set; }
public string Data6 { get; set; }
public string Data7 { get; set; }
public string Data8 { get; set; }
public string Data9 { get; set; }
public string Data10 { get; set; }
public string Data11 { get; set; }
public string Data12 { get; set; }
public string Data13 { get; set; }
public string Data14 { get; set; }
public string Data15 { get; set; }
public string Data16 { get; set; }
public string Data17 { get; set; }
public string Data18 { get; set; }
public string Data19 { get; set; }
public string Data20 { get; set; }
public string Data21 { get; set; }
public string Data22 { get; set; }
public string Data23 { get; set; }
public string Data24 { get; set; }
public string Data25 { get; set; }
public string Data26 { get; set; }
public string Data27 { get; set; }
public string Data28 { get; set; }
public string Data29 { get; set; }
public string Data30 { get; set; }
}
}

C#: How to create a folder for a specific function?

I am using Selenium for automation purpose. I have a class for screenshot and Page Object method to call all my element in different class for every page. Now I am calling get screenshot of page in every class. But here is the think how to do I create a folder name get the screenshot in that folder.
Result.cs
class Result
{
static int i = 1;
public static void screenshot()
{
ITakesScreenshot screenshotDriver = myCollection.driver as ITakesScreenshot;
Screenshot screenCapture = screenshotDriver.GetScreenshot();
string path = #"..\..\..\Results\ScreenShots\";
string timestamp = DateTime.Now.ToString("yy-MM-dd hh-mm-ss");
{
screenCapture.SaveAsFile(#path + i + timestamp + ".png", System.Drawing.Imaging.ImageFormat.Png);
i++;
}
}
}
LoginPageObject.cs
[FindsBy(How = How.Name, Using = "txtusername")]
public IWebElement userName { get; set;}
[FindsBy(How = How.Name, Using = "Password")]
public IWebElement pwd { get; set; }
[FindsBy(How = How.ClassName, Using = "login_button")]
public void Login(string uname, string paswd)
{
userName.EnterText(uname);
pwd.EnterText(paswd);
clickLogin.Click();
Result.screenshot();
Thread.Sleep(4000);
}
Same for HomePageObject
main.cs
[Test]
public void Initialize()
{
myCollection.driver = new TWebDriver();
LoginPageObject objLogin = new LoginPageObject();
string pathfile = #"..\..\a.xlsx";
string sheetName = "Common";
var excelFile = new ExcelQueryFactory(pathfile);
var abc = from a in excelFile.Worksheet(sheetName) select a;
foreach (var a in abc)
{
myCollection.driver.Navigate().GoToUrl(a["URL"]);
}
myCollection.driver.Manage().Window.Maximize();
foreach (var a in abc)
{
objLogin.Login(a["uname"], a["paswd"]);
}
HomePagePbject objHome = new HomePageObject();
objHome.HomeFunction();
}
Here my main function is Initialize. So now how would I add all screenshots to that folder. For Now, I am adding it to screenshot folder.
You can write something like it: Create a folter to Logs and after append a screenshot folder inside it. If the folder does not exist, create it.
Using NUnit (but you can do the same with a similar sintax in VisualStudio.TestTools):
public void SaveScreenShot(string screenshotFirstName)
{
var folderLocation = ConfigurationManager.AppSettings["LogPath"] +"\\ScreenShot\\";
if (!Directory.Exists(folderLocation))
Directory.CreateDirectory(folderLocation);
var screenshot = ((ITakesScreenshot) _driver).GetScreenshot();
var image = ScreenshotToImage(screenshot);
var filename = new StringBuilder(folderLocation);
filename.Append(screenshotFirstName);
filename.Append(".png");
image.Save(filename.ToString(), ImageFormat.Png);
}
private static Image ScreenshotToImage(Screenshot screenshot)
{
Image screenshotImage;
using (var memStream = new MemoryStream(screenshot.AsByteArray))
{
screenshotImage = Image.FromStream(memStream);
}
return screenshotImage;
}
[TearDown]
public static void Cleanup()
{
Browser.Dispose();
var dateTimeNow = DateTime.Now;
var data = dateTimeNow.ToString("dd/MM/yyyy HH:mm:ss");
IntegrationTest.WriteInLog("Test ends at: " + data);
IntegrationTest.WriteInLog("Time to execute: " + (dateTimeNow - InicioTeste).TotalSeconds + " seconds");
var takeScreenShoot = false;
if (TestContext.CurrentContext.Result.Outcome.Equals(ResultState.Failure))
{
IntegrationTest.WriteInLog("FAILS");
takeScreenShoot = true;
}
else if(TestContext.CurrentContext.Result.Outcome.Equals(ResultState.Error))
{
IntegrationTest.WriteInLog("ERROR");
takeScreenShoot = true;
}
else if(TestContext.CurrentContext.Result.Outcome.Equals(ResultState.SetUpError))
{
IntegrationTest.WriteInLog("SETUP ERROR");
takeScreenShoot = true;
}
else if(TestContext.CurrentContext.Result.Outcome.Equals(ResultState.SetUpFailure))
{
IntegrationTest.WriteInLog("SETUP FAILURE");
takeScreenShoot = true;
}
else if(TestContext.CurrentContext.Result.Outcome.Equals(ResultState.Inconclusive))
{
IntegrationTest.WriteInLog("INCONCLUSIVE");
}
else if (TestContext.CurrentContext.Result.Outcome.Equals(ResultState.Success))
{
IntegrationTest.WriteInLog("SUCESS");
}
else
{
IntegrationTest.WriteInLog("UNKNOW");
}
if (takeScreenShoot)
{
Browser.SaveScreenShot(TestContext.CurrentContext.Test.Name.ToUpper()));
IntegrationTest.WriteInLog("Screenshot saved as " + TestContext.CurrentContext.Test.Name.ToUpper()));
}
IntegrationTest.WriteInLog("\n");
}

Getting variable data from string in c#

I have got data downloaded from url it is as follows.
//[
{
"id": "2932675",
"t": "GNK",
"e": "LON",
"l": "915.00",
"l_fix": "915.00",
"l_cur": "GBX915.00",
"s": "0",
"ltt": "5:08PM GMT",
"lt": "Dec 11,
"5": 08PM
"GMT",
"
"lt_dts": "2015-12-11T17:08:26Z",
"c": "-7.50",
"c_fix": "-7.50",
"cp": "-0.81",
"cp_fix": "-0.81",
"ccol": "chr",
"pcls_fix": "922.5"
}
]
and want following variable t : GNK and l:915 from above string and done following
void method1()
{
string scrip = textBox1.Text;
string s;
WebClient wc = new WebClient();
string url = ("http://finance.google.com/finance/infoclient=ig&q=NSE:" + scrip);
s = wc.DownloadString(url);
textBox2.Text = s.Substring(58, 6);
textBox3.Text = s;
}
public class LatestPrice
{
public string id { get; set; }
public string Name { get; set; }
public string type { get; set; }
public string l { get; set; }
public string l_fix { get; set; }
public string l_cur { get; set; }
public string s { get; set; }
public string lt { get; set; }
public string lt_dts { get; set; }
public string c { get; set; }
public string c_fix { get; set; }
public string cp { get; set; }
public string cp_fix { get; set; }
public string ccol { get; set; }
public string pcls_fix { get; set; }
}
public string[][] convert_string()
{
string[][] stockprice = null;
string stockprice1 = null;
string getdownloadstr = getstring();
stockprice1 = getdownloadstr.Replace("//", "").Trim();
var v = JsonConvert.DeserializeObject<List<LatestPrice>>(stockprice1);
}
i have made changes to program -- but how to access the t : gnk value or l = 915 value
You can convert to JArray to JObject and can get the value directly through JOject parameter key.
string jsonStr = "[{ \"id\":\"2932675\", \"t\" : \"GNK\" , \"e\" : \"LON\" , \"l\" : \"915.00\" , \"l_fix\" : \"915.00\" , \"l_cur\" : \"GBX915.00\" , \"s\": \"0\" , \"ltt\":\"5:08PM GMT\" , \"lt\" : \"Dec 11 5:08PM GMT\"}]";
var obj = JsonConvert.DeserializeObject<JArray>(jsonStr).ToObject<List<JObject>>().FirstOrDefault();
Console.WriteLine("t = " + obj["t"]);
Console.WriteLine("l = " + obj["l"]);
The above print the output as
t = GNK
l = 915.00
You can refer to this fiddle created for your question.
Parse it either split at , and then (split on : ) add each line to dictionary using the t as the key and the other as the value.
Then you could simply access by t and also by l .
Split the entire string by commas you have a list of item : value, then split on colon and add to dictionary. Then look up info in dictionary getvalue = Dictionary[key] ;
You could use Regex to match the data you need:
string t = Regex.Match(str, "\"t\" : \"[A-Z]{3}\"").Value;
string l = Regex.Match(str, "\"l\" : \"\\d{3}.\\d{2}\"").Value;
Where str is the data string you have downloaded.
String t matches a substring that is in the format "t" : "XXX", where XXX can contain any uppercase characters.
String l matches a substring that is in the format "l" : "XXX.XX", where XXX.XX can contain any digit.
1 . Add NewtonSoft.Json in your Reference in Solution Explorer. Steps(Reference [rightClick]-> Manage NuGetPackage -> Search for "Json.Net" -> Install them)
Add using Newtonsoft.Json;
code :
public class CurrentValue
{
public string id { get; set; }
public string Name { get; set; }
public string type { get; set; }
public string l { get; set; }
public string l_fix { get; set; }
public string l_cur { get; set; }
public string s { get; set; }
public string lt { get; set; }
public string lt_dts { get; set; }
public string c { get; set; }
public string c_fix { get; set; }
public string cp { get; set; }
public string cp_fix { get; set; }
public string ccol { get; set; }
public string pcls_fix { get; set; }
}
Create a method and use following code
Uri url = new Uri("http://www.google.com/finance/info?q=NSE%3A" + NameofCompany);
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.ContentType = "application/json; charset=utf-8";
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
string Responsecontent = new StreamReader(response.GetResponseStream()).ReadToEnd();
string CurrentContent = Responsecontent.Replace("//", "").Trim();
var v = JsonConvert.DeserializeObject<List<CurrentValue>>(CurrentContent);
Now "var v" have all the data of the class "CurrentValue".
You can load a xml file containing all " NameofCompany " and Load it on FormLoad. Use a for loop to get data of all " NameofCompany "
i have done in follwing way
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Web;
using System.Timers;
using System.IO;
using System.Net;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System.Text.RegularExpressions;
namespace google_downloader
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
WebClient wc = new WebClient();
string s= wc.DownloadString("http://finance.google.com/finance/info?client=ig&q=NSE:sbin");
//index for t
int index7= s.IndexOf('t');
int index8 = s.IndexOf('e');
textBox1.Text = ("frist index is" + index7 + "second indes is " + index8);
textBox1.Text = s.Substring(index7+6,(index8-index7)-10);
}
}
}

Categories