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");
}
Related
I am developing a Download Manager. It works fine for one single file but, for multiple files it is not working properly: what is wrong?
When I enter first url, it works fine, but when I click on pause and try a second url after clicking on download, the first file's progress bar starts from 0, and the first file starts downloading automatically without clicking on resume.
When I click on pause, both files pause, when I click on resume both files start downloading. Why this is happening? When I click pause on first url downloading window, I want only the first file to pause, and when I click on resume, only that file should be resumed.
ViewModel:
namespace DownloadManager
{
public class ViewModel : INotifyPropertyChanged
{
public ICommand _Download { get; set; }
public ICommand Pause { get; set; }
public ICommand Resume { get; set; }
public ViewModel()
{
_Download = new Command(Start, canExecuteMethod);
Pause = new Command(Pause_Download, canExecuteMethod);
Resume = new Command(Resume_Download, canExecuteMethod);
}
private bool canExecuteMethod(object parameter)
{
return true;
}
private void Start(object parameter) //Download Method
{
new Add_URL().Button_Click_1(link);
}
private void Pause_Download(object parameter) //Pause Download
{
new Add_URL().Pause();
}
private void Resume_Download(object parameter) //Resume Download
{
new Add_URL().Resume();
}
public event PropertyChangedEventHandler? PropertyChanged;
private string link;
public string Link
{
get { return link; }
set { link = value; OnPropertyChanged(Link); }
}
private void OnPropertyChanged(string property)
{
if(PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(property));
}
}
}
}
Model:
public static bool CheckForInternetConnection()
{
try
{
using (var client = new WebClient())
using (var stream = client.OpenRead("http://www.google.com"))
{
return true;
}
}
catch
{
return false;
}
}
static Download fw;
static int row = 0;
public void Button_Click_1(string link)
{
Uri uri = null;
if (CheckForInternetConnection())
{
{
uri = new Uri(link);
if (!uri.IsFile)
{
WarningUrl.Content = "File Found";
file = true;
}
}
}
else
{
WarningUrl.Content = "No Internet";
}
if (file)
{
String name = link;
Add_URL a = new Add_URL();
String FileName = System.IO.Path.GetFileName(uri.AbsolutePath);
MainWindow mainwindow = new MainWindow();
string check = mainwindow.Check(FileName);
MainWindow m = Application.Current.MainWindow as MainWindow;
//Extension
string extension = System.IO.Path.GetExtension(FileName);
var s = GetFileSize(uri);
int x = Int32.Parse(s); //size in KB
var fileSizeInMegaByte = Math.Round(Convert.ToDouble(s) / 1024.0 / 1024.0, 2).ToString();
String size = fileSizeInMegaByte + " MB"; // For addgin in list (MB)
String time = DateTime.Now.ToString("g");
Download download = new Download();
// var method2 = new Action(() => { download.pb.Value = 90; });
var method2 = new Action<int>(i =>
{
download.pb.Value = i;
MainWindow m = Application.Current.MainWindow as MainWindow;
if (i< 100)
{
m.change(download, i.ToString(), row, FileName);
}
download.FileName1.Content = FileName;
});
var method3 = new Action(() =>
{
download.pb.Value = 100;
string a = "100";
m.change(download, a, row, FileName);
row++;
download.Status.Content = "Completed";
download.Close();
});
fw = new Download(name, path + #"\" + FileName, x);
CancellationTokenSource tokenSource = new CancellationTokenSource();
CancellationToken token = tokenSource.Token;
mre.Set();
new Thread(() =>
{
while (!fw.Done)
{
mre.WaitOne();
double receive = double.Parse(fw.BytesWritten.ToString());
double Filesize = x;
double Percentage = receive / Filesize * 100;
int per = int.Parse(Math.Truncate(Percentage).ToString());
try
{
Thread.Sleep(300);
this.Dispatcher.Invoke(() =>
{
method2(per);
if (fw.Done)
{
method3();
}
});
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}).Start();
fw.Start();
download.Show();
m.AddItem(a, FileName, extension, time, size);
Close();
}
}
public void Pause()
{
fw.Pause1();
}
public void Resume()
{
fw.Start();
}
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++;
}
}
I'm trying to upload files to a folder using SharePoint and C#.
I managed to create folders with my code and it works fine.
This is my Document class:
[DataContractAttribute]
public class Document
{
[DataMemberAttribute]
public string Name { get; set; }
[DataMemberAttribute]
public byte[] Content { get; set; }
[DataMemberAttribute]
public bool ReplaceExisting { get; set; }
[DataMemberAttribute]
public string Folder { get; set; }
[DataMemberAttribute]
public Dictionary<string, object> Properties { get; set; }
public Document()
{
Properties = new Dictionary<string, object>();
}
public Document(string name, byte[] content)
{
Name = name;
ReplaceExisting = false;
Content = content;
Properties = new Dictionary<string, object>();
}
public Document(string name, byte[] content, bool replace)
{
Name = name;
Content = content;
ReplaceExisting = replace;
Properties = new Dictionary<string, object>();
}
}
And this is the class where I use it to upload files (Document) to an existing share point folder:
public class SharePointHandler : IDisposable
{
private static string sharePointSite = "My Site";
private static string documentLibraryName = "Root folder";
public SharePointHandler() { }
public void Upload(List<Document> documents, string company, int year, string quarter)
{
string Year = year.ToString();
try
{
using (ClientContext context = new ClientContext(sharePointSite))
{
var list = context.Web.Lists.GetByTitle(documentLibraryName);
context.Load(list);
var root = list.RootFolder;
context.Load(root);
context.ExecuteQuery();
.
.
.
foreach (var document in documents)
{
var fileCreationInformation = new FileCreationInformation();
fileCreationInformation.Content = document.Content;
fileCreationInformation.Overwrite = true;
fileCreationInformation.Url = list.RootFolder.ServerRelativeUrl + "/" + company + "/" + Year + "/" + quarter + "/" + document.Name;
Microsoft.SharePoint.Client.File uploadFile = quarterFolder.Files.Add(fileCreationInformation);
foreach (KeyValuePair<string, object> property in document.Properties)
uploadFile.ListItemAllFields[property.Key] = property.Value;
try
{
uploadFile.CheckOut();
context.ExecuteQuery();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
uploadFile.ListItemAllFields.Update();
context.ExecuteQuery();
uploadFile.CheckIn("", CheckinType.MajorCheckIn);
context.ExecuteQuery();
}
}
}
catch (Exception ex)
{
EventLog.WriteEntry(ex.Message, EventLogEntryType.Error);
return;
}
}
public void Dispose() { }
}
When I run the code I have one document with:
Content: {byte[11430]}
Folder: null
Name: Testing.docx
Properties: Count = 0
ReplaceExisting: false
Everything works fine and I get the URL needed.
But when I get to these commands:
try
{
uploadFile.CheckOut();
context.ExecuteQuery();
}
The program falls and I get error that says: File not found.
What am I doing wrong?
Thank you for your help!
Here is a working example of an upload to SharePoint via CSOM:
using (ClientContext conext = new ClientContext(site.url))
{
List projectFiles = projects.Web.Lists.GetByTitle("Project Files");
context.Load(projectFiles.RootFolder, w => w.ServerRelativeUrl);
context.ExecuteQuery();
FileStream documentStream = System.IO.File.OpenRead(filePath);
byte[] info = new byte[documentStream.Length];
documentStream.Read(info, 0, (int)documentStream.Length);
string fileURL = projectFiles.RootFolder.ServerRelativeUrl + "/Folder/FileName.ext";
FileCreationInformation fileCreationInformation = new FileCreationInformation();
fileCreationInformation.Overwrite = true;
fileCreationInformation.Content = info;
fileCreationInformation.Url = fileURL;
Microsoft.SharePoint.Client.File uploadFile = projectFiles.RootFolder.Files.Add(fileCreationInformation);
context.Load(uploadFile, w => w.MajorVersion, w => w.MinorVersion);
context.ExecuteQuery();
}
In your case, I would upload the file and ExecuteQuery() and then add your metadata and execute a second query, make sure you add a context.Load after your files.Add(). You are trying to do too many things at once, so just use this code to get the file uploaded and work your way through your other needs after. Also, the file add will not create folders for you so make sure you are specifying a valid path.
I will add a new node to parent node on my xml file. Unit test for this code says "success", it is passing but no added node in xml.
Also, some of tests i'm getting the error;
<< Access is denied. (Exception from HRESULT: 0x80070005 (E_ACCESSDENIED)) >>
on the line SaveToFileAsync
what is wrong with me? and there is an alternative way to do this?
public string ConnectionPath { get; set; }
protected string XPath { get; set; }
protected string XParentPath { get; set; }
protected XmlDocument Source { get; set; }
protected StorageFolder SFolder { get; set; }
protected StorageFile SFile { get; set; }
public RepositoryBase(string connectionPath)
{
this.ConnectionPath = connectionPath;
}
public async void Insert(T entity)
{
SFolder = Package.Current.InstalledLocation;
SFile = await SFolder.GetFileAsync(this.ConnectionPath);
var content = await FileIO.ReadTextAsync(SFile);
if (!string.IsNullOrEmpty(content))
{
Source = new XmlDocument();
Source.LoadXml(content);
}
var tagName = typeof(T).Name;
if (tagName != null)
{
IXmlNode parentNode = Source.SelectSingleNode(XParentPath);
if (parentNode != null)
{
XmlElement newNode = Source.CreateElement(tagName);
newNode.InnerText = GetContent(entity);
parentNode.AppendChild(newNode);
}
}
await Source.SaveToFileAsync(SFile);
}
* PlaceRepositoryClass ;
public class PlaceRepository : RepositoryBase<Place>
{
public PlaceRepository()
: base("Data\\bla\\bla.xml")
{
XPath = "/Country[Id=1]/Cities/City[Id=1]/Places/Place";
XParentPath = "/Country[Id=1]/Cities/City[Id=1]/Places";
}
}
Unit Test Method ;
[TestMethod]
public void AppendNode()
{
Place place = new Place()
{
Id = 40,
Name = "xxxxx",
SummaryPath = "yyyyy",
Logo = "xy.png",
LogoSmall = "xy_small.png",
Latitude = "32.423",
Longitude = "34.23424",
Content = new PlaceContent() { Items = new List<ContentItem>() { new ContentItem() { TextPath = "aaaa", Header = "bbbbb", AudioFilePath = "x.mp3" } } },
Gallery = new PhotoGallery() { Photos = new List<Photo>() { new Photo() { Path = "ab.png", Text = "abab" } } }
};
PlaceRepository repository = new PlaceRepository();
repository.Insert(place);
}
You are trying to write to a file that's part of the application package, and that's read only. You could copy the file to local storage and make the modifications there perhaps.
I am using SQLite for a data entry windows 8 app I am working on. I can create the db, insert data, retrieve a column count, and read data, but cannot get the column names.
The underlying framework is from this post.
I read about the PRAGMA table_info(table_name); command but I cannot seem to send and read back this query properly. I have been googling for 3 days!
MainPage.xaml.cs:
using SQLite;
using SqlLiteTest.Model;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using Windows.Storage;
using Windows.UI.Popups;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
namespace SqlLiteTest
{
public sealed partial class MainPage : Page
{
public MainPage()
{
this.InitializeComponent();
txtPath.Text = ApplicationData.Current.LocalFolder.Path;
}
private async void createDB(object sender, RoutedEventArgs e)
{
// access local folder
var qvLocalFolder = Windows.Storage.ApplicationData.Current.LocalFolder;
try
{
//Create a blank carrier file
StorageFile qvLocalFileCarrier = await qvLocalFolder.CreateFileAsync("qvdbLocal.db", CreationCollisionOption.FailIfExists);
//Write the blank carrier file
await FileIO.WriteTextAsync(qvLocalFileCarrier, "");
}
catch { }
// connect
var path = Windows.Storage.ApplicationData.Current.LocalFolder.Path + #"\qvdbLocal.db";
var db = new SQLiteAsyncConnection(path);
// create table
await db.CreateTableAsync<qvdb>();
// insert data
var insertRecords = new List<qvdb>()
{
new qvdb
{
qvdbRecord = 1,
qvdbNotes = "Notes1",
qvdb001 = "Variable 1.1",
qvdb002 = "Variable 2.1"
},
new qvdb
{
qvdbRecord = 1,
qvdbNotes = "Notes1",
qvdb001 = "Variable 1.1",
qvdb002 = "Variable 2.1"
},
new qvdb
{
qvdbRecord = 1,
qvdbNotes = "Notes1",
qvdb001 = "Variable 1.1",
qvdb002 = "Variable 2.1"
},
};
await db.InsertAllAsync(insertRecords);
// read count
var allUsers = await db.QueryAsync<qvdb>("SELECT * FROM qvdb");
var count = allUsers.Any() ? allUsers.Count : 0;
Debug.WriteLine(count);
}
private async void updateDB(object sender, RoutedEventArgs e)
{
var path = Windows.Storage.ApplicationData.Current.LocalFolder.Path + #"\qvdbLocal.db";
var db = new SQLiteAsyncConnection(path);
var tempCell = db.QueryAsync<qvdb>("UPDATE qvdb SET qvdbNotes ='!##$%$%^^&*()+)(*&^%$##!{:L<>?' WHERE qvdbRecord = 10");
await db.UpdateAsync(tempCell);
}
private async void readDB(object sender, RoutedEventArgs e)
{
var path = Windows.Storage.ApplicationData.Current.LocalFolder.Path + #"\qvdbLocal.db";
var db = new SQLiteAsyncConnection(path);
var query = db.Table<qvdb>();
var result = await query.ToListAsync();
foreach (var item in result)
{
MessageDialog dialog = new MessageDialog(string.Format("{0} {1} {2}", item.qvdbRecord, item.qvdbNotes, item.qvdb001));
await dialog.ShowAsync();
}
}
private void readColNames(object sender, RoutedEventArgs e)
{
}
}
}
qvdb.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using SQLite;
namespace SqlLiteTest.Model
{
public class qvdb
{
[PrimaryKey, AutoIncrement]
public int qvdbRecord { get; set; }
[MaxLength(3000)]
public string qvdbNotes { get; set; }
[MaxLength(1000)]
public string qvdb001 { get; set; }
[MaxLength(1000)]
public string qvdb002 { get; set; }
}
}
Thanks CL for the info. I added the class but still do not know how to access them. Some more code...
// this works
// read record count
var allRecords = await db.QueryAsync<qvdb>("SELECT * FROM qvdb");
var countRecords = allRecords.Any() ? allRecords.Count : 0;
this.textboxLog.Text = this.textboxLog.Text + Environment.NewLine + "There are " + countRecords + " records.";
// ??
// read column names
var allColumns = await db.QueryAsync<qvdb>("PRAGMA table_info(qvdb)");
foreach (var item in allColumns) {
//read name
this.textboxLog.Text = this.textboxLog.Text + Environment.NewLine + "columbn names";
}
The records returned by PRAGMA table_info look like this:
public class table_info_record
{
public int cid { get; set; }
public string name { get; set; }
public string type { get; set; }
public int notnull { get; set; }
public string dflt_value { get; set; }
public int pk { get; set; }
}
Use it like this:
db.QueryAsync<table_info_record>("PRAGMA table_info(...)");
o end the loop on CL's advice, this code successfully reads the column names:
// read column names
var query = await db.QueryAsync<table_info_record>("PRAGMA table_info(MY_TABLE_NAME_HERE)");
foreach (var item in query)
{
Debug.WriteLine(string.Format("{0}", item.name) + " is a column.");
}