convert html to word not working as example - html

I am trying to convert html to word. I have found so many codes over the net but none of them works. They are worked with string builder or some with others. I have given a code. In debugger it goes through all the codes without error but no file is getting downloaded.
public void converToWord(string htmlContent,string name)
{
HttpContext.Current.Response.Clear();
HttpContext.Current.Response.Charset = "";
HttpContext.Current.Response.ContentType = "application/msword";
string strFileName = name + ".doc";
HttpContext.Current.Response.AddHeader("Content-Disposition", "inline;filename=" + strFileName);
StringBuilder strHTMLContent = new StringBuilder();
strHTMLContent.Append("<html xmlns:v=\"urn:schemas-microsoft-com:vml\" xmlns:o=\"urn:schemas-microsoft-com:office:office\" xmlns:x=\"urn:schemas-microsoft-com:office:word\" xmlns=\"http://www.w3.org/TR/REC-html40\"><head></head><body>");
strHTMLContent.Append(htmlContent);
strHTMLContent.Append("</body></html>");
HttpContext.Current.Response.Write(strHTMLContent);
HttpContext.Current.Response.End();
HttpContext.Current.Response.Flush();
}
i got an error it says {Unable to evaluate expression because the code is optimized or a native frame is on top of the call stack.}

while the button is in update panel and it does not work properly.everything seems fine but it does not get downloaded.it is a very common problem that happens.just put o a trigger to the button that is firing the event and it will start to work just very much fine.

Related

Parsing html page content without using selector

I am going to parse some web pages using Java program. For this purpose I wrote a small code for parsing page content by using xpath as selector. For parsing different sites you need to find the appropriate xpath per each site. The problem is for doing that you need an operator to find the write xpath for you. (for example using firepath firefox addon) Suppose you dont know what page you should parse or the number of sites get really big for operator to find right xpath. In this case you need a way for parsing pages without using any selector. (same scenario exist for CSS selector) Or there should be a way to find xpath automatically! I was wondering what is the method of parsing web pages in this way?
Here is the small code which I wrote for this purpose, please feel free to extend that in presenting your solutions.
public downloadHTML(String url) throws IOException{
CleanerProperties props = new CleanerProperties();
// set some properties to non-default values
props.setTranslateSpecialEntities(true);
props.setTransResCharsToNCR(true);
props.setOmitComments(true);
// do parsing
TagNode tagNode = new HtmlCleaner(props).clean(
new URL(url)
);
// serialize to xml file
new PrettyXmlSerializer(props).writeToFile(
tagNode, "c:\\TEMP\\clean.xml", "utf-8"
);
}
public static void testJavaxXpath(String pattern)
throws ParserConfigurationException, SAXException, IOException,
FileNotFoundException, XPathExpressionException {
DocumentBuilder b = DocumentBuilderFactory.newInstance()
.newDocumentBuilder();
org.w3c.dom.Document doc = b.parse(new FileInputStream(
"c:\\TEMP\\clean.xml"));
// Evaluate XPath against Document itself
javax.xml.xpath.XPath xPath = XPathFactory.newInstance().newXPath();
NodeList nodes = (NodeList) xPath.evaluate(pattern,
doc.getDocumentElement(), XPathConstants.NODESET);
for (int i = 0; i < nodes.getLength(); ++i) {
Element e = (Element) nodes.item(i);
System.out.println(e.getFirstChild().getTextContent());
}
}

OWA Signature Update with Exchange Web Services

We're using Exchange Web Services to set user signature in Outlook Web Access. It works great, we see the signature under Options>Settings and the "Automatically include my signature on messages I send" check box is checked. We also set this programmatically.
However, when the user creates a new e-mail message in OWA the signature does not show up. A work around for this is to go to Options>Setting, uncheck the "Automatically include my signature on messages I send" check box , Save, check the check box again and save.
The code we use to set the signature looks something like this:
Folder rootFolder;
UserConfiguration OWAConfig;
rootFolder = Folder.Bind(service, WellKnownFolderName.Root);
OWAConfig = UserConfiguration.Bind(service, "OWA.UserOptions",rootFolder.ParentFolderId, UserConfigurationProperties.All);
OWAConfig.Dictionary["signaturehtml"] = "Hello World";
OWAConfig.Dictionary["autoaddsignature"] = "True";
OWAConfig.Update();
Any idea how to get around this problem?
I have some old code that does the same thing which is working fine. I have pasted the code below. There are a few minor differences between my code and yours. I am not sure if they make a difference but you may want to try it out. Here is an extract of my code with the differences highlighted with a comment:
private void SetSettingValue(UserConfiguration owaConfig, string propName, object propValue)
{
if (owaConfig.Dictionary.ContainsKey(propName))
{
owaConfig.Dictionary[propName] = propValue;
}
else
{
// Adds a key if it does not explicitly exist.
// I am not sure if it makes a difference.
owaConfig.Dictionary.Add(propName, propValue);
}
}
public void AddSignature()
{
// Extract
UserConfiguration OWAConfig = UserConfiguration.Bind(
service,
"OWA.UserOptions",
WellKnownFolderName.Root, // Binding to Root and not Root.ParentFolderId.
UserConfigurationProperties.Dictionary // Binds to Dictionary and not to All.
);
SetSettingValue(OWAConfig, "autoaddsignature", true);
SetSettingValue(OWAConfig, "signaturehtml", html);
OWAConfig.Update();
}

LibTiff.NET append mode bug?

I've started using LibTiff.NET for writing tiff IPTC tags lately and discovered strange behavior on some files that i have here. I'm using sample code that ships with LibTiff.NET binaries, and it works fine with most of the images, but some files are having image data corruption after these lines:
class Program
{
private const TiffTag TIFFTAG_GDAL_METADATA = (TiffTag)42112;
private static Tiff.TiffExtendProc m_parentExtender;
public static void TagExtender(Tiff tif)
{
TiffFieldInfo[] tiffFieldInfo =
{
new TiffFieldInfo(TIFFTAG_GDAL_METADATA, -1, -1, TiffType.ASCII,
FieldBit.Custom, true, false, "GDALMetadata"),
};
tif.MergeFieldInfo(tiffFieldInfo, tiffFieldInfo.Length);
if (m_parentExtender != null)
m_parentExtender(tif);
}
public static void Main(string[] args)
{
// Register the extender callback
// It's a good idea to keep track of the previous tag extender (if any) so that we can call it
// from our extender allowing a chain of customizations to take effect.
m_parentExtender = Tiff.SetTagExtender(TagExtender);
string destFile = #"d:\00000641(tiffed).tif";
File.Copy(#"d:\00000641.tif", destFile);
//Console.WriteLine("Hello World!");
// TODO: Implement Functionality Here
using (Tiff image = Tiff.Open(destFile, "a"))
{
// we should rewind to first directory (first image) because of append mode
image.SetDirectory(0);
// set the custom tag
string value = "<GDALMetadata>\n<Item name=\"IMG_GUID\">" +
"817C0168-0688-45CD-B799-CF8C4DE9AB2B</Item>\n<Item" +
" name=\"LAYER_TYPE\" sample=\"0\">athematic</Item>\n</GDALMetadata>";
image.SetField(TIFFTAG_GDAL_METADATA, value);
// rewrites directory saving new tag
image.CheckpointDirectory();
}
// restore previous tag extender
Tiff.SetTagExtender(m_parentExtender);
Console.Write("Press any key to continue . . . ");
Console.ReadKey(true);
}
}
After opening i see mostly blank white image or multiple black and white lines instead of text that have been written there (i don't need to read\write tags to produce this behavior). I noticed this happens when image already has a custom tag (console window alerts about it) or one of tags have got 'bad value' (console window in this case says 'vsetfield:%pathToTiffFile%: bad value 0 for "%TagName%" tag').
Original image: http://dl.dropbox.com/u/1476402/00000641.tif
Image after LibTiff.NET: http://dl.dropbox.com/u/1476402/00000641%28tiffed%29.tif
I would be grateful for any help provided.
You probably should not use CheckpointDirectory method for files opened in append mode. Try using RewriteDirectory method instead.
It will rewrite the directory, but instead of place it at it's old
location (as WriteDirectory() would) it will place them at the end of
the file, correcting the pointer from the preceeding directory or file
header to point to it's new location. This is particularly important
in cases where the size of the directory and pointed to data has
grown, so it won’t fit in the space available at the old location.
Note that this will result in the loss of the previously used
directory space.

AJAX HTMLEditorExtender on postback tables don't display

I am currently using an Ajax tool; HTMLEditorExtender to turn a textbox into a WYSIWYG editor, in a C# ASP.NET project. On the initial page load I place a large amount of formated text and tables into the editor which appears fine; even the tables.
The data is loaded into an asp:panel and the items/display from the panel is what is actually loaded into the extender and displayed.
However, if I want to have a button that saves all of the data that is in the editor to a Session and after the button press still display everything in the WYSIWG editor on the page postback everything that loads in the the textbox is fine except for the tables. They come up with the tags. Is there anyway around this?
The code I am using to initially load the page is this:
ContentPlaceHolder cphMain = (ContentPlaceHolder)this.Master.FindControl("MainContent");
Panel pnlContent = (Panel)cphMain.FindControl("innerFrame");
StringBuilder sb = new StringBuilder();
StringWriter sw = new StringWriter(sb);
HtmlTextWriter hw = new HtmlTextWriter(sw);
pnlContent.RenderControl(hw);
txtPN.Text = sb.ToString();
pnlContent.Visible = false;
On the button click I am having this saved:
string strHTMLText = txtPN.Text;
Session["ProgressNoteHTML"] = strHTMLText;
And I am loading it on the postback like this:
txtPN.Text = (string)Session["ProgressNoteHTML"];
ContentPlaceHolder cphMain = (ContentPlaceHolder)this.Master.FindControl("MainContent");
Panel pnlContent = (Panel)cphMain.FindControl("innerFrame");
pnlContent.Visible = false;
Any ideas as to why any postbacks would make the tags appear and in the original page load they do not?
The solution offered by Erik won't work for table tags containing property values. For instance: <table align="right"> will not be decoded. I have also found that <img> tags are encoded by the HTMLEditorExtender as well.
The easier solution is to use the Server.HTMLDecode() method.
TextBox_Editor.Text = Server.HtmlDecode(TextBox_Editor.Text) 'fixes encoding bug in ajax:HTMLEditor
I have the same problem, It seems to have something to do with the default sanitizing that the extension performs on the HTML content. I haven't found a way to switch it off, but the workaround is pretty simple.
Write an Anti-Sanitizing function that replaces the cleansed tags with proper tags. Below is mine written in VB.Net. A C# version would look very similar:
Protected Function FixTableTags(ByVal input As String) As String
'find all the matching cleansed tags and replace them with correct tags.
Dim output As String = input
'replace Cleansed table tags.
output = output.Replace("<table>", "<table>")
output = output.Replace("</table>", "</table>")
output = output.Replace("<tbody>", "<tbody>")
output = output.Replace("</tbody>", "</tbody>")
output = output.Replace("<tr>", "<tr>")
output = output.Replace("<td>", "<td>")
output = output.Replace("</td>", "</td>")
output = output.Replace("</tr>", "</tr>")
Return output
End Function

call code behind functions with html controls

I have a simple function that I want to call in the code behind file name Move
and I was trying to see how this can be done and Im not using asp image button because not trying to use asp server side controls since they tend not to work well with ASP.net MVC..the way it is set up now it will look for a javascript function named Move but I want it to call a function named move in code behind of the same view
<img alt='move' id="Move" src="/Content/img/hPrevious.png" onclick="Move()"/>
protected void Move(){
}
//based on Search criteria update a new table
protected void Search(object sender EventArgs e)
{
for (int i = 0; i < data.Count; i++){
HtmlTableRow row = new HtmlTableRow();
HtmlTableCell CheckCell = new HtmlTableCell();
HtmlTableCell firstCell = new HtmlTableCell();
HtmlTableCell SecondCell = new HtmlTableCell();
CheckBox Check = new CheckBox();
Check.ID = data[i].ID;
CheckCell.Controls.Add(Check);
lbl1.Text = data[i].Date;
lbl2.Text = data[i].Name;
row.Cells.Add(CheckCell);
row.Cells.Add(firstCell);
row.Cells.Add(SecondCell);
Table.Rows.Add(row);
}
}
Scott Guthrie has a very good example on how to do this using routing rules.
This would give you the ability to have the user navigate to a URL in the format /Search/[Query]/[PageNumber] like http://site/Search/Hippopotamus/3 and it would show page 3 of the search results for hippopotamus.
Then in your view just make the next button point to "http://site/Search/Hippopotamus/4", no javascript required.
Of course if you wanted to use javascript you could do something like this:
function Move() {
var href = 'http://blah/Search/Hippopotamus/2';
var slashPos = href.lastIndexOf('/');
var page = parseInt(href.substring(slashPos + 1, href.length));
href = href.substring(0, slashPos + 1);
window.location = href + (++page);
}
But that is much more convoluted than just incrementing the page number parameter in the controller and setting the URL of the next button.
You cannot do postbacks or call anything in a view from JavaScript in an ASP.NET MVC application. Anything you want to call from JavaScript must be an action on a controller. It's hard to say more without having more details about what you're trying to do, but if you want to call some method "Move" in your web application from JavaScript, then "Move" must be an action on a controller.
Based on comments, I'm going to update this answer with a more complete description of how you might implement what I understand as the problem described in the question. However, there's quite a bit of information missing from the question so I'm speculating here. Hopefully, the general idea will get through, even if some of the details do not match TStamper's exact code.
Let's start with a Controller action:
public ActionResult ShowMyPage();
{
return View();
}
Now I know that I want to re-display this page, and do so using an argument passed from a JavaScript function in the page. Since I'll be displaying the same page again, I'll just alter the action to take an argument. String arguments are nullable, so I can continue to do the initial display of the page as I always have, without having to worry about specifying some kind of default value for the argument. Here's the new version:
public ActionResult ShowMyPage(string searchQuery);
{
ViewData["SearchQuery"] = searchQuery;
return View();
}
Now I need to call this page again in JavaScript. So I use the same URL I used to display the page initially, but I append a query string parameter with the table name:
http://example.com/MyControllerName/ShowMyPage?searchQuery=tableName
Finally, in my aspx I can call a code behind function, passing the searchQuery from the view data. Once again, I have strong reservations about using code behind in an MVC application, but this will work.
How to call a code-behind function in aspx:
<% Search(ViewData["searchQuery"]); %>
I've changed the arguments. Since you're not handling an event (with a few exceptions, such as Page_Load, there aren't any in MVC), the Search function doesn't need the signature of an event handler. But I did add the "tablename" argument so that you can pass that from the aspx.
Once more, I'll express my reservations about doing this in code behind. It strikes me that you are trying to use standard ASP.NET techniques inside of the MVC framework, when MVC works differently. I'd strongly suggest going through the MVC tutorials to see examples of more standard ways of doing this sort of thing.