How to copy data from HTML div in Selenium C#? - c#

I want to copy alter table data from webpage div and paste it into a .txtfile, screenshot is attached below:
Below is the HTML for above screenshot:
Can i do this by storing this in a variable like below but how can i copy all data at once in a variable from div ?
string value = driver.FindElement(By.XPath("//td[#style='padding:0px;
white-space: nowrap;']")).Text;
Below is the code of my test case in which i am selecting a file to convert from a tool after conversion i want to store the alter table script in a separate .txt file for which i created a create function to create file :
public void TestMethod1()
{
try
{
string dir = #"D:\test\input"; //path
var directory = new DirectoryInfo(dir); //folder ko access
foreach (FileInfo file in directory.GetFiles()) //loop
IWebDriver driver = new ChromeDriver(); //driver object
driver.Navigate().GoToUrl("http:abcurl//convPLSQL.html");
//site url
driver.Manage().Window.Maximize(); //browser maximize
string param = dir.Replace("/", "\\"); // ye code file
param += "\\";
param += file.Name;
driver.FindElement(By.Id("fileuploader")).SendKeys(param);
driver.FindElement(By.Id("keyinput")).SendKeys("convUser001");//Key
driver.FindElement(By.Id("translatebutton")).Click();//Translate Button
driver.FindElement(By.LinkText("Download Results")).Click();//Download
// string data= driver.FindElement(By.XPath("//td[#style='padding:0px;
// white-space:nowrap;']")).Text;
create(); // call create function to create .txt file
}
public void create()
{
try
{
string fileName = #"D:\test\output\Mahesh.txt";
// Check if file already exists. If yes, delete it.
if (System.IO.File.Exists(fileName))
{
System.IO.File.Delete(fileName);
}
// Create a new file
using (FileStream fs = System.IO.File.Create(fileName))
{
// Add some text to file
Byte[] title = new UTF8Encoding(true).GetBytes("New Text File");
fs.Write(title, 0, title.Length);
byte[] author = new UTF8Encoding(true).GetBytes("Mahesh Chand");
fs.Write(author, 0, author.Length);
}
// Open the stream and read it back.
using (StreamReader sr = System.IO.File.OpenText(fileName))
{
string s = "";
while ((s = sr.ReadLine()) != null)
{
System.Console.WriteLine(s);
}
}

Get all child elements of div containing the spans having the needed text. Something like:
var spans = driver.FindElements(By.XPath("//td/div[2]/span"));
Then concatenate text from each span element. Replace special characters like "&nbsp" with space. Use string builder or add text to string generic collection and join later if the text is big.
Example:
var text = string.Empty;
foreach(var span in spans)
{
text += span.Text.Replace("&nbsp", " ");
}

Related

How do I append only updated texts?

I have a Winform control to write notes whose contents are periodically uploaded to the server.
I need to create a local file as a backup to save the contents of the notes.
When I type text into the notebox, the content remains in the note box and gets saved into the local text file. However, when I enter more texts to the note-box, the previous content as well as the new content gets appended to the local file.
How do I make sure that only the recent content gets appended to the local file? If i clear the note-box content, no content gets logged on to the server.
private void btnNote_Click(object sender, EventArgs e)
{
Note noteFrm = new Note();
//set Note Text
noteFrm.NoteText = _timeCard.NoteText;
if (noteFrm.ShowDialog() == DialogResult.OK)
{
//Save notes locally as well
string path = #"C:\QB Notes\";
if (!Directory.Exists(path))
{
Directory.CreateDirectory(path);
}
string projname = this._timeCard.Project.ProjectName.TrimEnd()+".txt";
string fileloc = path + projname;
// FileStream fs = null;
if (!File.Exists(fileloc))
{
using (TextWriter txt = new StreamWriter(fileloc))
{
// TextWriter txt = new StreamWriter(fileloc);
txt.Write(noteFrm.NoteText + Environment.NewLine);
txt.Close();
}
}
else if (File.Exists(fileloc))
{
using (var txt = new StreamWriter(fileloc, true))
{
txt.BaseStream.Seek(0, SeekOrigin.End);
txt.Write(noteFrm.NoteText + Environment.NewLine);
txt.Close();
}
}
//noteFrm.NoteText="";
//get Note Text
_timeCard.NoteText = noteFrm.NoteText;
Utils.LogManager.write("New Note Text: " + noteFrm.NoteText);
}
}
If you want the file to always match what is in the text box, then I'd suggest that you replace your whole if (!File.Exists(fileloc)) block with just this:
File.WriteAllText(fileloc, noteFrm.NoteText + Environment.NewLine);
That will create the file if needed, open the file, replace all the contents with what is in the text box, and close the file.

how to store and retrieve multiple values inside single session variable

i am using dropzone to upload multiple files to the server. files will be uploaded to server while file names will be stored in table.
i am trying to add file names in session.
the problem here is that it doesn't add multiple file names inside single session
here is my code :
string imageSessList = context.Session["imageNames"].ToString(); //if i put this line at the begining, then the debugger doesn't even moves to foreach block
foreach (string s in context.Request.Files)
{
HttpPostedFile file = context.Request.Files[s];
string fileName = file.FileName;
string fileExtension = file.ContentType;
string strUploadFileExtension = fileName.Substring(fileName.LastIndexOf(".") + 1);
string strAllowedFileTypes = "***jpg***jpeg***png***gif***bmp***"; //allowed file types
string destFileName = "";
List<string> lstImageNames = new List<string>();
// else upload file
if (!string.IsNullOrEmpty(fileName))
{
if (strAllowedFileTypes.IndexOf("***" + strUploadFileExtension + "***") != -1) //check extension
{
if (context.Request.Files[0].ContentLength < 5 * 1024 * 1024) //check filesize
{
// generate file name
destFileName = Guid.NewGuid().ToString() + "." + strUploadFileExtension;
string destFilePath = HttpContext.Current.Server.MapPath("/resourceContent/") + destFileName;
//Save image names to session
lstImageNames.Add(destFileName);
context.Session["imageNames"] = lstImageNames;
file.SaveAs(destFilePath);
strMessage = "Success " + destFileName;
}
else
{
strMessage = "File Size can't be more than 5 MB.";
}
}
else
{
strMessage = "File type not supported!";
}
}
} // foreach
context.Response.Write(strMessage);
}
here i am able to add only single filename to session, not multiple.
how to store and maintain multiple file names in single session :
context.Session["imageNames"]
you need to get current list from session
List<string> lstImageNames= (List<string>)Session["imageNames"];
if(lstImageNames==null)
lstImageNames = new List<string>(); // create new list in the first time
now add new item to it.
lstImageNames.Add(destFileName);
set back to session
context.Session["imageNames"] = lstImageNames;

Rally C#: How to upload a collection of attachments and associate with a user story?

I have refereed to the other examples on this website, but found a major difference in my method. (Please be patient)
I am trying to iterate over a directory of files and upload each file as an attachment and associate to a user story.
I am only able to attach 1 file for a user story as of now.
I see that every attachment has to be encoded to a base 64 string and it must have a the size in bytes.
Here is my code so far:
public void createUsWithAttachmentList(string workspace, string project, string userStoryName, string userStoryDescription)
{
//authentication
this.EnsureRallyIsAuthenticated();
//DynamicJSONObject for AttachmentContent
DynamicJsonObject myAttachmentContent = new DynamicJsonObject();
//Length calculated from Base64String converted back
int imageNumberBytes = 0;
//Userstory setup
DynamicJsonObject toCreate = new DynamicJsonObject();
toCreate["Workspace"] = workspace;
toCreate["Project"] = project;
toCreate["Name"] = userStoryName;
toCreate["Description"] = userStoryDescription;
//Trying to get a list of all the file paths within a given directory, this directory would contain .png files that need to be associated to a user story.
string[] attachmentPath = Directory.GetFiles("C:\\Users\\user\\Desktop\\RallyAttachments");
This foreach loop is confusing. I am trying to iterate over each file in the directory in order to convert it into a base64 string, and at the same time acquire the number of bytes for each file as an int.
foreach (string fileName in attachmentPath)
{
Image myImage = Image.FromFile(fileName);
string imageBase64String = imageToBase64(myImage, System.Drawing.Imaging.ImageFormat.Png);
imageNumberBytes = Convert.FromBase64String(imageBase64String).Length;
//I am stuck here to be exact because there are multiple imageBase64Strings due to the collection of files located inside the directory. AND the below line is wrong because I have a list of imageBase64Strings that were generated from iterating through the string[] attachmentPath.
myAttachmentContent[RallyField.content] = imageBase64String;
}
try
{
//create user story
CreateResult createUserStory = _api.Create(RallyField.attachmentContent, myAttachmentContent);
//create attachment
CreateResult myAttachmentContentCreateResult = _api.Create(RallyField.attachmentContent, myAttachmentContent);
String myAttachmentContentRef = myAttachmentContentCreateResult.Reference;
//DynamicJSONObject for Attachment Container
//I assume I would need a separate container for each file in my directory containing the attachments.
DynamicJsonObject myAttachment = new DynamicJsonObject();
myAttachment["Artifact"] = createUserStory.Reference;
myAttachment["Content"] = myAttachmentContentRef;
myAttachment["Name"] = "AttachmentFromREST.png";
myAttachment["Description"] = "Email Attachment";
myAttachment["ContentType"] = "image/png";
myAttachment["Size"] = imageNumberBytes;
//create & associate the attachment
CreateResult myAttachmentCreateResult = _api.Create(RallyField.attachment, myAttachment);
Console.WriteLine("Created User Story: " + createUserStory.Reference);
}
catch (WebException e)
{
Console.WriteLine(e.Message);
}
}
Note: I am planning on extending this method to support multiple file types, and I thing I would need to get the file type of each file in the directory and proceed accordingly.
Any ideas on how to go about writing this?
You've got all the parts implemented- we just need to move it around a little bit. Create the story once at the beginning, and then each time through the loop make a new AttachmentContent and a new Attachment for each file.
public void createUsWithAttachmentList(string workspace, string project, string userStoryName, string userStoryDescription)
{
//authentication
this.EnsureRallyIsAuthenticated();
//Userstory setup
DynamicJsonObject toCreate = new DynamicJsonObject();
toCreate["Workspace"] = workspace;
toCreate["Project"] = project;
toCreate["Name"] = userStoryName;
toCreate["Description"] = userStoryDescription;
//Create the story first
try
{
//create user story
CreateResult createUserStory = _api.Create(RallyField.userStory, toCreate);
//now loop over each file
string[] attachmentPath = Directory.GetFiles("C:\\Users\\user\\Desktop\\RallyAttachments");
foreach (string fileName in attachmentPath)
{
//DynamicJSONObject for AttachmentContent
DynamicJsonObject myAttachmentContent = new DynamicJsonObject();
Image myImage = Image.FromFile(fileName);
string imageBase64String = imageToBase64(myImage, System.Drawing.Imaging.ImageFormat.Png);
int imageNumberBytes = Convert.FromBase64String(imageBase64String).Length;
myAttachmentContent[RallyField.content] = imageBase64String;
//create the AttachmentConent
CreateResult myAttachmentContentCreateResult = _api.Create(RallyField.attachmentContent, myAttachmentContent);
String myAttachmentContentRef = myAttachmentContentCreateResult.Reference;
//create an Attachment to associate to story
DynamicJsonObject myAttachment = new DynamicJsonObject();
myAttachment["Artifact"] = createUserStory.Reference;
myAttachment["Content"] = myAttachmentContentRef;
myAttachment["Name"] = "AttachmentFromREST.png";
myAttachment["Description"] = "Email Attachment";
myAttachment["ContentType"] = "image/png";
myAttachment["Size"] = imageNumberBytes;
//create & associate the attachment
CreateResult myAttachmentCreateResult = _api.Create(RallyField.attachment, myAttachment);
}
}
catch (WebException e)
{
Console.WriteLine(e.Message);
}
}

how to save data that has been edited in the console to a file

I have an original file that needs editing, I have managed to open this file and used code to correct the problems I have been asked to this has been done by changed the original file into a string, Now I need to save these changes, how do I save to a new file what is being displayed on the console? I have tried using stream writer but don't know how to save the edited string.
New answer based on new/detailed requirements:
I modified your code and added some new lines.
string path = #"c:\temp\MyIOFile.txt";
try
{
string file = File.ReadAllText(path);
//The code wrote to the right hand side finds the file listed from my C drive
string longstr = file;
string[] strs = longstr.Split(':', '*');
foreach (string ss in strs)
{
Console.WriteLine(ss);
}
//before text is written, you say you want to modify it
string newText = "*enter new file contents here*";
//you can add new text (Append) or
//change all the contents of the file
//set the value of whatToDo to "Append" to add new text to the file
//set the value of whatToDo to any value other than "Append" to replace
//the entire contents of the filw with the data in variable newText
string whatToDo = "Append";
if (whatToDo == "Append")
{
//append to existing text
//variable file contains old text
//varaible newText contains the new text to be appended
File.AppendAllText(path, newText);
}
else
{
//creates new contents in the file.
//varaiable new text contains the new text representing
//file contents
File.WriteAllText(path, newText);
}
//string file = File.AppendAllText(#"C:\Users\path\.......");
}
catch (Exception ex)
{
Console.WriteLine("*** Error:" + ex.Message);
}
Console.WriteLine("*** Press Enter key to exit");
Console.ReadLine();
}
Original Answer
May be this could help:
string path = #"c:\temp\MyIOFile.txt";
if (!File.Exists(path))
{
// File does not exist - What do you want to do?
}
try
{
// Open the file to read from and store result in a string variable
string readText = File.ReadAllText(path);
// modify the text somehow before appending to file
string appendText =readText+ Environment.NewLine+ "This is extra text";
File.AppendAllText(path, appendText, Encoding.UTF8);
}
catch (Exception ex)
{
Console.WriteLine ("***Error:" + ex.Message);
// display errors
}
string file = File.ReadAllText(#"C:\Users\path.......");
//The code wrote to the right hand side finds the file listed from my C drive
string longstr = file;
string[] strs = longstr.Split(':', '*');
foreach (string ss in strs)
{
Console.WriteLine(ss);
}
string file = File.AppendAllText(#"C:\Users\path\.......");
Console.ReadLine();

Rewriting a text file after reading it

i got a file that is store in my appliction directory, and he got some site list.
i dont have any problem reading it, but when i want to write to it, i get
System.ArgumentException: Stream is not writeable
this is how i accsess the file:
FileStream theTextFileStream = new FileStream(Environment.CurrentDirectory + "/fourmlinks.txt",FileMode.OpenOrCreate);
and this is the function that throw me the expection:
public static void WriteNewTextToFile(string text, FileStream theFile)
{
string fileText = GetAllTextFromFile(theFile);
ArrayList fileLIst = populateListFromText(fileText);
using (StreamWriter fileWriter = new StreamWriter(theFile))
{
fileWriter.Write(String.Empty);
for (int i = 0; i < fileLIst.Count; i++)
{
fileWriter.WriteLine(fileLIst[i].ToString());
}
}
}
the function read the old and new text and add it to an arry. then i clean the file from every thing, and rewriting it with the old and new data from the arry i made.
i dont know if that will help but here is the file proprites:
Build Action: None
Copy To Out Put Directory: Copy always
why i cant rewrite the file?
this is the function i use to read the file content:
public static string GetAllTextFromFile(FileStream theFile)
{
string fileText = "";
using (theFile)
{
using (StreamReader stream = new StreamReader(theFile))
{
string currentLine = "";
while ((currentLine = stream.ReadLine()) != null)
{
fileText += currentLine + "\n";
}
}
}
return fileText;
}
You have to use Read/Write file access as third parameter -
FileStream theTextFileStream = new FileStream(Environment.CurrentDirectory + "/fourmlinks.txt",FileMode.OpenOrCreate, FileAccess.ReadWrite
);
Important - Remove using(theFile) statement:
public static string GetAllTextFromFile(FileStream theFile)
{
string fileText = "";
using (StreamReader stream = new StreamReader(theFile))
{
string currentLine = "";
while ((currentLine = stream.ReadLine()) != null)
{
fileText += currentLine + "\n";
}
}
return fileText;
}
Do not use using construct in your case as it will close the underlying stream as in your case you have to manually open and close stream objects.
This will allow you to write in the file as well.
For more information refer following links -
FileStream Constructor
FileAccess Enumeration

Categories