I am trying to load a word document into Rich Textbox control so that user can edit the contents and eventually save it. Following is the code I use:
string fileName = #"..\..\Files\test.doc";
TextRange range;
FileStream fStream;
if (File.Exists(fileName))
{
range = new TextRange(RTB.Document.ContentStart, RTB.Document.ContentEnd);
fStream = new FileStream(fileName, FileMode.OpenOrCreate);
range.Load(fStream, DataFormats.Rtf);
fStream.Close();
}
When I run it I get the following error:
Unrecognized structure in data format 'Rich Text Format'.Parameter name: stream
I have made sure that that document contains no images.
A word document isn't a rich text document.
The doc would need to be first saved as an RTF file before you can do this.
Related
In my application, there are two buttons(export & import ). Using the export button I can download an excel file, in that downloaded excel file, there are lots of blanks fields.
I need to upload the same file using import button but if I upload the same file then I can get many mandatory fields validation message because of blank fields. Instead of uploading the same file I have another excel file, in which every blank field are filled.
In the exported file, there is a unique id which is generated in the run time and I have to set the same unique id into another excel file, in which every blank field are filled same as the exported file but unique id is different. otherwise, I will get a validation message.
I want to replace the epricer quote number 8766876 to 4181981 in new import file.
Possibly duplicate of following question :
update excel cell in selenium webdriver
Possible solution from link :
InputStream inp = new FileInputStream("workbook.xls");
Workbook wb = WorkbookFactory.create(inp);
Sheet sheet = wb.getSheetAt(0);
Row row = sheet.getRow(2);
Cell cell = row.getCell(3);
if (cell == null)
cell = row.createCell(3);
cell.setCellType(Cell.CELL_TYPE_STRING);
cell.setCellValue("a test");
// Write the output to a file
FileOutputStream fileOut = new FileOutputStream("workbook.xls");
wb.write(fileOut);
fileOut.close();
You cannot update Excel using Selenium, Selenium is a series of libraries that are used to drive a browser, they cannot interact with Excel documents.
If you want to interact with Excel documents you will need to use a library specifically designed to do that, some options are:
Apache POI
DocX4J
JExcelAPI
I need to search an expression inside a xps document then list all matches (with the page number of each match).
I searched in google, but no reference or sample found which addresses this issue .
SO: How can I search a xps document and get this information?
The first thing to note is that an XPS file is an Open Packaging package. It can be opened and the contents accessed via the System.IO.Packaging.Package class. This makes any operations on the contents much easier.
Here's an example of how to search the page content with a given regex, while also tracking which page the match occurs on.
var regex = new Regex(#"th\w+", RegexOptions.Compiled | RegexOptions.IgnoreCase | RegexOptions.Multiline);
using(var xps = System.IO.Packaging.Package.Open(#"C:\path\to\regex.oxps"))
{
var pages = xps.GetParts()
.Where (p => p.ContentType == "application/vnd.ms-package.xps-fixedpage+xml")
.ToList();
for (var i = 0; i < pages.Count; i++)
{
var page = pages[i];
using(var reader = new StreamReader(page.GetStream()))
{
var s = reader.ReadToEnd();
var matches = regex.Matches(s);
if (matches.Count > 0)
{
var matchText = matches
.Cast<Match>()
.Aggregate (new StringBuilder(), (agg, m) => agg.AppendFormat("{0} ", m.Value));
Console.WriteLine("Found matches on page {0}: {1}", i + 1, matchText);
}
}
}
}
It is not going to be as simple as you might have thought. XPS files are compressed (zipped) files containing a somewhat complex folder structure containing all the text, fonts, graphics and other items. You can use compression tools such as 7-Zip or WinZip etc. to extract the entire folder structure from an XPS file.
Having said that, you can use the following sequence of steps to do what you want:
Extract the contents of your XPS file programmatically in a temp folder. You can use the new ZipFile class for this purpose if you're using .NET 4.5 or better.
The extracted folder will have the following folder structure:
_rels
Documents
1
_rels
MetaData
Pages
_rels
Resources
Fonts
MetaData
Go to Documents\1\Pages\ subfolder. Here you'll find one or more .fpage files, one for each page of your document. These files are in XML format and contain all text contained in the page in a structured manner.
Use simple loop to iterate through all .fpage files, opening each of them using an XML reader such as XDocument or XmlDocument and search for required text in node values using RegEx.IsMatch(). If found, note down the page number in a List and move ahead.
As in Excel multiple rows are present, having different set of data and I want to take screenshot for each and every step like this
driver.get("http://www.google.com/");
File scrFile = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
// Now you can do whatever you need to do with it, for example copy somewhere
FileUtils.copyFile(scrFile, new File("c:\\tmp\\screenshot1.png"));
driver.get("http://www.yahoo.com/");
File scrFile1 = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
// Now you can do whatever you need to do with it, for example copy somewhere
FileUtils.copyFile(scrFile1, new File("c:\\tmp\\screenshot2.png"));
How the same will be repeated for each Excel row.
As if I hardcode the value of "Screenshot1, ...2, etc." at the end I will get only 2 screenshots instead of 2 screenshots for each row record.
Create a FileName string instead of hardcoded file path, You can pass row number in screenshot file name for better identifications of screenshot file.
File ScreenShot = ((TakesScreenshot) driver)
.getScreenshotAs(OutputType.FILE);
StringBuilder FileName = new StringBuilder("C:\\tmp");
FileName.append(ScreenshotName);
FileName.append("_");
FileName.append(rownumber);
FileName.append(".jpeg");
FileUtils.copyFile(ScreenShot, new File(FileName.toString()));
I found how to programmatically parse/load a XAML string by using XamlReader.Load(), however if I were to have a user drag/drop a ".xaml" file onto my Silverlight application, how would I go about parsing that file to a XAML file and reading in the contents as a string to serve up to the XamlReader.Load() method.
Or is there a more efficient/better way through using reflection?
I'd like to allow the user to use a "silverlight for dummies" silverlight designer (within reason) to design a simple control. (i.e. a label and a textbox).
Then save this or export it as a XAML file (or maybe I can simply have them save it as a TXT file?)
Then they'd drop this file into my Silverlight application and it would parse the text into a XamlReader.Load(), then I can add my newly programmatically created object to a listbox.
I have the logic for drag/drop file and for loading up the XAML string, but that middle point of getting the contents of a ".xaml" file is what I'm confusing myself on...
EDIT
#nicholas, that's exactly what I went with. I don't know what was going on yesterday but I think I just had a major 'brain-fart'.
This is how I ended up going: (still have some cleanup and refactoring, but this was to test)
IDataObject data = e.Data;
if (data.GetDataPresent(DataFormats.FileDrop))
{
FileInfo[] files = data.GetData(DataFormats.FileDrop) as FileInfo[];
if (files.Length > 1)
{
//TODO
}
else
{
FileInfo file = files[0];
extension = file.Extension;
string xaml = string.Empty;
using (Stream stream = file.OpenRead())
{
xaml = StreamUtils.StreamToString(stream);
}
if (!xaml.IsEmpty())
{
try
{
myListBox.Items.Add(XamlReader.Load(xaml);
}
catch (Exception ex)
{
//TODO
}
}
}
So you have a Drop event handler, from which you receive event args with Data property, an IDataObject. From MSDN you find out how to get a FileStream for the dropped file, which you can then load into a string (eg use StreamReader) to be parsed by XamlReader.Load().
If I understood you correctly there will be three different steps:
Parse the content of .xaml file or any type of file into a "string"
(it can be a .txt file or any other format)
Use XamlReader.Load() to generate an UI element out of this string
from step 1
Insert the UI element from step 2 to ListBox.Items collection
Does that help?
I have a requirement to print the WPF form contents on a Save button click. The content is plain text and will be name value pairs on each line. I don't need page breaks on consecutive Saves.
I have tried out the samples for PrintDialog, FlowDocument and FixedDocument and could not avoid the page break.
Is there any particular setting I am missing ?
Any alternative to PrintDialog ?
Code:
Paragraph myParagraph = new Paragraph();
myParagraph.Margin = new Thickness(0);
**myParagraph.BreakPageBefore = false;**
foreach (string line in textToPrint.Split(new string[] { Environment.NewLine }, StringSplitOptions.None))
{
myParagraph.Inlines.Add(new Run(line));
}
flowDocument.Blocks.Add(myParagraph);
DocumentPaginator paginator = ((IDocumentPaginatorSource)flowDocument).DocumentPaginator;
printDialog.PrintDocument(paginator, "Test Page");
A new Print job (Document) starts with a new page as far as I know. If you don't want page breaks gather all the values you want to print and then print them.