MVC Open binary in Microsoft Word - google-chrome

I support a web application on an intranet which has a word icon the user can click which will then retrieve bytes from a SQL server and then open Microsoft Word to display the document.
While this works well, our organisation is moving from IE to Chrome, and this doesn't work in Chrome, and from what I have heard Chrome doesn't support ActiveX which is what is used to open Microsoft Word.
So we are looking for a solution that will work in Chrome.
A quick example of what we do.
Javascript fired by onclick event
var wordObject = new ActiveXObject("Word.Application");
wordObject.Documents.open('http://localhost:8080/Document/Download/MyDocument.docx?documentId=12345');
wordObject.Visible = true;
Action in Controller
[HttpGet]
public ActionResult Download(int documentId)
{
var result = DocumentService.GetLatestDocumentVersion(documentId);
if (!result.Succeeded)
{
return HttpNotFound();
}
return new DocumentResult(result.Data.FileData, result.Data.FileType, result.Data.FullName);
}
public class DocumentResult : FileContentResult
{
private ContentDisposition _contentDisposition;
public DocumentResult (byte[] fileContents, FileType fileType, string fileDownloadName)
: base(fileContents, fileType.ToMimeType())
{
string disposition = fileType == FileType.Pdf ? DispositionTypeNames.Inline : DispositionTypeNames.Attachment;
_contentDisposition = new ContentDisposition(disposition);
_contentDisposition.FileName = fileDownloadName;
}
}
I want the same functionality but in Chrome, any ideas?

So instead of opening word through javascript you simply replace the url with something like
Document
This uses office uri schemas see https://learn.microsoft.com/en-us/office/client-developer/office-uri-schemes?redirectedfrom=MSDN
Thanks to MS Premier Support.

Related

Best way to turn sql selected data into a table on excel using asp.net

I have an sql statements that selects a table of data that i want to export to excel in the .xls format,
i added this table to a grid view then rendered that grid view to create an html writer and write it on excel file using asp.net.
But i keep having this warning that the file format and extension does not match.
The issue is that the file you are creating is not a genuine Excel file. It's HTML with a .xls extension.
Please, i need to know what is the best way to export these selected data to the xls file without the warning.
I Have also tried exporting from the dataTable directly, but i still get the warning when tying to open the excel.
// these namespaces need to be added to your code behind file
using System.Configuration;
using System.Data.SqlClient;
using System.Data;
namespace MySpot.UserPages
{
public partial class Journal : System.Web.UI.Page
{
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["MySpotDBConnStr"].ConnectionString);
DataTable dt = new DataTable();
// regular page_load from .aspx file
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
}
}
// added a button with ID=btnDownload and double clicked it's onclick event to auto create method
protected void btnDownload_Click(object sender, EventArgs e)
{
string queryStr = "SELECT * from table";
SqlDataAdapter sda = new SqlDataAdapter(queryStr, conn);
sda.Fill(dt);
ExportTableData(dt);
}
// this does all the work to export to excel
public void ExportTableData(DataTable dtdata)
{
string attach = "attachment;filename=journal.xls";
Response.ClearContent();
Response.AddHeader("content-disposition", attach);
Response.ContentType = "application/ms-excel";
if (dtdata != null)
{
foreach (DataColumn dc in dtdata.Columns)
{
Response.Write(dc.ColumnName + "\t");
//sep = ";";
}
Response.Write(System.Environment.NewLine);
foreach (DataRow dr in dtdata.Rows)
{
for (int i = 0; i < dtdata.Columns.Count; i++)
{
Response.Write(dr[i].ToString() + "\t");
}
Response.Write("\n");
}
Response.End();
}
}
}
}
http://blogs.msdn.com/b/vsofficedeveloper/archive/2008/03/11/excel-2007-extension-warning.aspx
The current design does not allow you to open HTML content from a web site in Excel unless the extension of the URL is .HTM/.HTML/.MHT/.MHTML. So ASP pages that return HTML and set the MIME type to something like XLS to try to force the HTML to open in Excel instead of the web browser (as expected) will always get the security alert since the content does not match the MIME type. If you use an HTML MIME type, then the web browser will open the content instead of Excel. So there is no good workaround for this case because of the lack of a special MIME type for HTML/MHTML that is Excel specific. You can add your own MIME type if you control both the web server and the client desktops that need access to it, but otherwise the best option is to use a different file format or alert your users of the warning and tell them to select Yes to the dialog.

Uri to open third party apps for wp8

I tried to create an app that opens some third party apps with the help of its Uri from a Tile. Well, it actually works in opening the third party apps but the problem is, first it launches my app(i.e MainPage is visible for a second) and then only it opens the respective app. Is there any way to make my app's MainPage invisible before opening an app or am i missing anything in Capabilities?
Here is my code :
IconicTileData iconicTileData1 = new IconicTileData();
iconicTileData1.Title = name;
iconicTileData1.SmallIconImage = new Uri("/Icons/Small.png", UriKind.Relative);
iconicTileData1.IconImage = new Uri("/Icons/Metro/" + name + "Medium.png", UriKind.Relative);
IconicTileData iconicTileData2 = iconicTileData1;
Uri navigationUri = new Uri("/MainPage.xaml?target=ms-settings-bluetooth:", UriKind.Relative);
ShellTile.Create(navigationUri, (ShellTileData)iconicTileData2, true);
Thanks in advance for your help.
You could try to specify a "custom" page target (instead of MainPage.xaml) and then make a UriMapper that will allow your app to redirect. Here is a nice blog post on creating a UriMapper. Here is some pseudo-code to help:
public class SettingsUriMapper : UriMapperBase
{
public override Uri MapUri(Uri uri)
{
if (uri.OriginalString.StartsWith == "/LaunchSettings.xaml")
{
// parse which settings to go to
// launch settings uri
}
return uri;
}
}

Get HTML from Frame using WebBrowser control - unauthorizedaccessexception

I'm looking for a free tool or dlls that I can use to write my own code in .NET to process some web requests.
Let's say I have a URL with some query string parameters similar to http://www.example.com?param=1 and when I use it in a browser several redirects occur and eventually HTML is rendered that has a frameset and a frame's inner html contains a table with data that I need. I want to store this data in the external file in a CSV format. Obviously the data is different depending on the querystring parameter param. Let's say I want to run the application and generate 1000 CSV files for param values from 1 to 1000.
I have good knowledge in .NET, javascript, HTML, but the main problem is how to get the final HTML in the server code.
What I tried is I created a new Form Application, added a webbrowser control and used code like this:
private void FormMain_Shown(object sender, EventArgs e)
{
var param = 1; //test
var url = string.Format(Constants.URL_PATTERN, param);
WebBrowserMain.Navigated += WebBrowserMain_Navigated;
WebBrowserMain.Navigate(url);
}
void WebBrowserMain_Navigated(object sender, WebBrowserNavigatedEventArgs e)
{
if (e.Url.OriginalString == Constants.FINAL_URL)
{
var document = WebBrowserMain.Document.Window.Frames[0].Document;
}
}
But unfortunately I receieve unauthorizedaccessexception because probably frame and the document are in different domains. Does anybody has an idea of how to work around this and maybe another brand new approach to implement functionality like this?
Thanks to the Noseratio's comments I managed to do that with the WebBrowser control. Here are some major points that might help others who have similar questions:
1) DocumentCompleted event should be used. For Navigated event body of the document is NULL.
2) Following answer helped a lot: WebBrowserControl: UnauthorizedAccessException when accessing property of a Frame
3) I was not aware about IHTMLWindow2 similar interfaces, for them to work correctly I added references to following COM libs: Microsoft Internet Controls (SHDocVw), Microsoft HTML Object Library (MSHTML).
4) I grabbed the html of the frame with the following code:
void WebBrowserMain_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
{
if (e.Url.OriginalString == Constants.FINAL_URL)
{
try
{
var doc = (IHTMLDocument2) WebBrowserMain.Document.DomDocument;
var frame = (IHTMLWindow2) doc.frames.item(0);
var document = CrossFrameIE.GetDocumentFromWindow(frame);
var html = document.body.outerHTML;
var dataParser = new DataParser(html);
//my logic here
}
5) For the work with Html, I used the fine HTML Agility Pack that has some pretty good XPath search.

Rendering an email throws a TemplateCompilationException using RazorEngine 3 in a non-MVC project

I am trying to render emails in a windows service host.
I use RazorEngine 3 forked by coxp which has support for Razor 2.
https://github.com/coxp/RazorEngine/tree/release-3.0/src
This works fine for a couple of emailtemplates but there is one causing me problems.
#model string
Click here to enter a new password for your account.
This throws a CompilationException: The name 'WriteAttribute' does not exist in the current context. So passing in a string as model and putting it in the href-attribute causes problems.
I can make it work by changing this line by:
#Raw(string.Format("Klik hier.", #Model))
but this makes the template very unreadable and harder to pass along to a marketing department for further styling.
I like to add that referencing the RazorEngine by using a Nuget package is not a solution since it is based on Razor 1 and somewhere along the process the DLL for system.web.razor gets replaced by version 2 which breaks any code using RazorEngine. It seems more interesting to use Razor 2 to benefit from the new features and to be up to date.
Any suggestions on how to fix this would be great. Sharing your experiences is also very welcome.
UPDATE 1
It seems like calling SetTemplateBaseType might help, but this method does not exist anymore, so I wonder how to be able to bind the templatebasetype?
//Missing method in the new RazorEngine build from coxp.
Razor.SetTemplateBaseType(typeof(HtmlTemplateBase<>));
I use Windsor to inject the template service rather than using the Razor object. Here is a simplified part of the code that shows how to set the base template type.
private static ITemplateService CreateTemplateService()
{
var config = new TemplateServiceConfiguration
{
BaseTemplateType = typeof (HtmlTemplateBase<>),
};
return new TemplateService(config);
}
RazorEngine 3.1.0
Little bit modified example based on coxp answer without the injection:
private static bool _razorInitialized;
private static void InitializeRazor()
{
if (_razorInitialized) return;
_razorInitialized = true;
Razor.SetTemplateService(CreateTemplateService());
}
private static ITemplateService CreateTemplateService()
{
var config = new TemplateServiceConfiguration
{
BaseTemplateType = typeof (HtmlTemplateBase<>),
};
return new TemplateService(config);
}
public static string ParseTemplate(string name, object model)
{
InitializeRazor();
var appFileName = "~/EmailTemplates/" + name + ".cshtml";
var template = File.ReadAllText(HttpContext.Current.Server.MapPath(appFileName));
return RazorEngine.Razor.Parse(template, model);
}

Primefaces fileDownload non-english file names corrupt

I am using Primefaces 3.2. I've got problems with using primefaces fileDownload. I can upload the files and keep their non-english name on the server (in my case this is Russian). However, when I use p:fileDownload to download the uploaded files I cannot use Russian letters since they get corrupt. It seems that the DefaultStreamedContent class constructor accepts only Latin letters.
I am doing everything according to the showcase on the primefaces website as shown below.
public FileDownloadController() {
InputStream stream = ((ServletContext)FacesContext.getCurrentInstance().getExternalContext().getContext()).getResourceAsStream("/images/optimusprime.jpg");
file = new DefaultStreamedContent(stream, "image/jpg", "downloaded_optimus.jpg");
}
Any ideas how I can solve my problem?
Thanks, in advance.
This is fixed in the upcoming PrimeFaces 6.2, but for earlier versions the fix below needs to be applied. In a link in the comments below a reference to a PrimeFaces issue was posted which contains info that the fix below does work for Chrome, IE and Opera but not for FireFox (no version mentioned, nor is 'Edge' mentioned)
Workaround
Try to encode your file name in application/x-www-form-urlencoded MIME format (URLEncoder).
Example:
public StreamedContent getFileDown () {
// Get current position in file table
this.currentPosition();
attachments = getAttachments();
Attachment a = getAttachmentByPosition( pos, attachments );
FileNameMap fileNameMap = URLConnection.getFileNameMap();
// Detecting MIME type
String mimeType = fileNameMap.getContentTypeFor(a.getAttachmentName());
String escapedFilename = "Unrecognized!!!";
try {
// Encoding
escapedFilename = URLEncoder.encode(a.getAttachmentName(), "UTF-8").replaceAll(
"\\+", "%20");
} catch (UnsupportedEncodingException e1) {
e1.printStackTrace();
}
// Preparing streamed content
fileDown = new DefaultStreamedContent( new ByteArrayInputStream( a.getAttachment() ),
mimeType, escapedFilename);
return fileDown;
}