Display an ashx image using jQuery? - asp.net

I've been trying to use the jQuery plugin Colorbox to display images I have in my DB through an ashx file. Unfortunately it just spits a bunch of gibberish at the top of the page and no image. Can this be done? Here is what I have so far:
$(document).ready
(
function ()
{
$("a[rel='cbImg']").colorbox();
}
);
...
<a rel="cbImg" href="HuntImage.ashx?id=15">Click to see image</a>
UPDATE:
My ashx file is writing the binary out:
context.Response.ContentType = "image/bmp";
context.Response.BinaryWrite(ba);

Colorbox has an option 'photo'. If you set this to true in your constructor then it will force it to render the photo.
$(target).colorbox({photo: true});

You should be setting the src attribute in the client side.
<img src="HuntImage.ashx?id=15" ..../>
The handler
public class ImageRequestHandler: IHttpHandler, IRequiresSessionState
{
public void ProcessRequest(HttpContext context)
{
context.Response.Clear();
if(context.Request.QueryString.Count != 0)
{
//Get the stored image and write in the response.
var storedImage = context.Session[_Default.STORED_IMAGE] as byte[];
if (storedImage != null)
{
Image image = GetImage(storedImage);
if (image != null)
{
context.Response.ContentType = "image/jpeg";
image.Save(context.Response.OutputStream, ImageFormat.Jpeg);
}
}
}
}
private Image GetImage(byte[] storedImage)
{
var stream = new MemoryStream(storedImage);
return Image.FromStream(stream);
}
public bool IsReusable
{
get { return false; }
}
}

It appears that I can't do what I am trying using colorbox with an ashx image. If anyone finds a way please post it here.
I considered deleting the question but I will leave it up incase someone else runs into the same issue.

Find this function around line 124 (colorbox 1.3.15)
// Checks an href to see if it is a photo.
// There is a force photo option (photo: true) for hrefs that cannot be matched by this regex.
function isImage(url) {
return settings.photo || /\.(gif|png|jpg|jpeg|bmp)(?:\?([^#]*))?(?:#(\.*))?$/i.test(url);
}
On line 127, add |ashx after bmp in (gif|png|jpg|jpeg|bmp) so it reads like this:
// Checks an href to see if it is a photo.
// There is a force photo option (photo: true) for hrefs that cannot be matched by this regex.
function isImage(url) {
return settings.photo || /\.(gif|png|jpg|jpeg|bmp|ashx)(?:\?([^#]*))?(?:#(\.*))?$/i.test(url);
}
This is working just fine for me in Sitecore 6.2 :)

Related

flutter with firebase - detect the url string whether it is image(jpg) or video(avi)

I'm beginner with these Google's products and got 'serious' problem.
I uploaded photos and videos to firebase storage and urls of the photos and videos in the firebase storage is generated and stored automatically in firebase database. In my flutter lib, I could call those urls by my own code and display the url's image on the avd screen.
Image.network(url) is the code to display image url from firebase. But I also wanna display video url's asset simultaneously with single code. That is, videos and photos should be in single screen! In this case, Image.network(url) doesn't work anymore..
If I change that image.network code for video format according to video_player plug-in, I cannot display image asset anymore and if I stay same with that Image.network(url) code, I cannot display video url from firebase. So here is the question:
How can I detect whether the firebase's url string is image or video with my flutter code, and display that asset on the 'single screen' whatever the file format is(at least video and photo) with integrated flutter code?
url example
It's not much of a deal since type of the media is in the URL. You can parse it as a
Uri object then extract the type.
import 'dart:core';
enum UrlType { IMAGE, VIDEO, UNKNOWN }
void main() async {
var imageUrl =
'https://firebasestorage.googleapis.com/v0/b/myAppCodeNameForFirebase.appspot.com/o/Posts%20Pictures%2Fiufri095620200814.jpg?alt=media&token=89b6c22f-b8dd-4cff-9395-f53fc0808824';
var videoUrl =
'https://firebasestorage.googleapis.com/v0/b/myAppCodeNameForFirebase.appspot.com/o/Posts%20Pictures%2Fiufri095620200814.mp4?alt=media&token=89b6c22f-b8dd-4cff-9395-f53fc0808824';
print(getUrlType(imageUrl));
print(getUrlType(videoUrl));
}
UrlType getUrlType(String url) {
Uri uri = Uri.parse(url);
String typeString = uri.path.substring(uri.path.length - 3).toLowerCase();
if (typeString == "jpg") {
return UrlType.IMAGE;
}
if (typeString == "mp4") {
return UrlType.VIDEO;
} else {
return UrlType.UNKNOWN;
}
}
Let me give you an idea.
Consider implementing this scenario.
var url = 'domain.com/file.jpg?querySegment';
In your widget area,
child: url.contains('.mp4?') ? VideoWidget() : ImageWidget()
also, even with multiple conditions,
child: (url.contains('.jpg?') || url.contains('.png?')) ? ImageWidget() : VideoWidget()
May this suits your case.
Improving upon the accepted answer, here is what I have in my code. I needed a way to identify many types of videos and images from the passed url.
Using path package to idetify the extension
Have a list of video and image extension
import 'package:path/path.dart' as p;
enum UrlType { IMAGE, VIDEO, UNKNOWN }
class UrlTypeHelper {
static List<String> _image_types = [
'jpg',
'jpeg',
'jfif',
'pjpeg',
'pjp',
'png',
'svg',
'gif',
'apng',
'webp',
'avif'
];
static List<String> _video_types = [
"3g2",
"3gp",
"aaf",
"asf",
"avchd",
"avi",
"drc",
"flv",
"m2v",
"m3u8",
"m4p",
"m4v",
"mkv",
"mng",
"mov",
"mp2",
"mp4",
"mpe",
"mpeg",
"mpg",
"mpv",
"mxf",
"nsv",
"ogg",
"ogv",
"qt",
"rm",
"rmvb",
"roq",
"svi",
"vob",
"webm",
"wmv",
"yuv"
];
static UrlType getType(url) {
try {
Uri uri = Uri.parse(url);
String extension = p.extension(uri.path).toLowerCase();
if (extension.isEmpty) {
return UrlType.UNKNOWN;
}
extension = extension.split('.').last;
if (_image_types.contains(extension)) {
return UrlType.IMAGE;
} else if (_video_types.contains(extension)) {
return UrlType.VIDEO;
}
} catch (e) {
return UrlType.UNKNOWN;
}
return UrlType.UNKNOWN;
}
}
/// Usage
if(UrlTypeHelper.getType(message) == UrlType.IMAGE) {
/// handle image
}
else if(UrlTypeHelper.getType(message) == UrlType.VIDEO) {
/// handle video
}

Sitecore: Show input option after using menu context item

I've added a menu context item to the TreelistEx. This menu item sends a messages that I later catch in a HandleMessage method.
In this method i create a new item ( template type and parent item are given in the source of the treelist field ).
All i need now is a way to ask the user for a name. But i haven't been able to find a simple way to do this.
class MyTreeListEx : TreelistEx, IMessageHandler
{
void IMessageHandler.HandleMessage(Message message)
{
if (message == null)
{ return; }
if (message["id"] == null)
{ return; }
if (!message["id"].Equals(ID))
{ return; }
switch (message.Name)
{
case "treelist:edit":
// call default treelist code
case "mytreelistex:add":
// my own code to create a new item
}
}
}
Does anyone have any suggestions on how to achieve this ?
Edit: added image & code + i'm using Sitecore 8 Update 1
I don't know which version of Sitecore you use but what you can try is SheerResponse.Input method.
You can use it like this:
using Sitecore.Configuration;
using Sitecore.Globalization;
using Sitecore.Shell.Applications.ContentEditor.FieldTypes;
using Sitecore.Web.UI.Sheer;
void IMessageHandler.HandleMessage(Message message)
{
...
case "mytreelistex:add":
Sitecore.Context.ClientPage.Start(this, "AddItem");
break;
}
protected static void AddItem(ClientPipelineArgs args)
{
if (args.IsPostBack)
{
if (!args.HasResult)
return;
string newItemName = args.Result;
// create new item here
// if you need refresh the page:
//SheerResponse.Eval("scForm.browser.getParentWindow(scForm.browser.getFrameElement(window).ownerDocument).location.reload(true)");
}
else
{
SheerResponse.Input("Enter the name of the new item:", "New Item Default Name", Settings.ItemNameValidation,
Translate.Text("'$Input' is not a valid name."), Settings.MaxItemNameLength);
args.WaitForPostBack();
}
}
This code will even validate your new item name for incorrect characters and length.

How can I run custom tool or save a file programmatically using EnvDTE?

I want to save/run custom tools on a handful of .tt files from my extension. I don't want to loop over all the files in the solution/project, rather I want to be able to use a relative (or full) path of the file to execute a save/run custom tool.
Is there a way to get a ProjectItem object given a path of the file ($(SolutionDir)/MyProject/MyFile.tt) so I can execute methods on it?
You can use the FindProjectItem method of the EnvDTE.Solution type to find a file within the current solution by its name. The ExecuteCommand method is dependent on the current UI context; so the item must be selected, otherwise, the call fails.
private bool TryExecuteTextTemplate(string filename)
{
var dte = (DTE2)this.GetService(typeof(SDTE));
Solution solution = dte.Solution;
if ((solution != null) && solution.IsOpen)
{
VSProjectItem projectItem;
ProjectItem item = solution.FindProjectItem(filename);
if (item != null && ((projectItem = item.Object as VSProjectItem) != null))
{
// TODO: track the item in the Solution Explorer
try
{
projectItem.RunCustomTool();
return true;
}
catch (COMException)
{
}
}
}
return false;
}

Flex navigateToURL from iframe POST

Let me explain my current issue right now:
I have a webapp located at domain A. Let's call it A-App. I open an iframe from A-App that points to a Flex app on domain B. We'll call it B-FlexApp. B-FlexApp wants to post some data to another app located on the same domain, we'll call it B-App. The problem is that in IE the communication breaks somewhere between B-FlexApp and B-App while B-FlexApp is opened in the iframe. This only happens in IE.
However when opening B-FlexApp in a new window, posting the data to B-App works just fine. How to overcome this? Dropping the iframe is not possible.
ThereĀ“s a issue with AS3 navigateToURL and IE. You can try calling javascript to navigate: I have a little utility class to handle this:
//class URLUtil
package com
{
import flash.external.*;
import flash.net.*;
public class URLUtil extends Object
{
protected static const WINDOW_OPEN_FUNCTION:String="window.open";
public function URLUtil()
{
super();
return;
}
public static function openWindow(arg1:String = "", arg2:String="_blank", arg3:String=""):void
{
var browserName:String = getBrowserName();
switch (browserName)
{
case "Firefox":
{
flash.external.ExternalInterface.call(WINDOW_OPEN_FUNCTION, arg1, arg2, arg3);
break;
}
case "IE":
{
flash.external.ExternalInterface.call("function setWMWindow() {window.open(\'" + arg1 + "\');}");
break;
}
case "Safari":
case "Opera":
{
flash.net.navigateToURL(new URLRequest(arg1), arg2);
break;
}
default:
{
flash.net.navigateToURL(new URLRequest(arg1), arg2);
break;
}
}
return;
}
private static function getBrowserName():String
{
var str:String="";
var browserName:String = ExternalInterface.call("function getBrowser(){return navigator.userAgent;}");
if (!(browserName == null) && browserName.indexOf("Firefox") >= 0)
{
str = "Firefox";
}
else
{
if (!(browserName == null) && browserName.indexOf("Safari") >= 0)
{
str = "Safari";
}
else
{
if (!(browserName == null) && browserName.indexOf("MSIE") >= 0)
{
str = "IE";
}
else
{
if (!(browserName == null) && browserName.indexOf("Opera") >= 0)
{
str = "Opera";
}
else
{
str = "Undefined";
}
}
}
}
trace("Browser: \t" + str);
return str;
}
}
}
and you call it like:
btn.addEventListener(MouseEvent.CLICK, onBTNClick);
function onBTNClick(evt:MouseEvent):void
{
URLUtil.openWindow(YOUR_URL_STRING);
}
Hope it helps!
It is better to let the browser actually does the "navigate to URL" function instead of Flex.
For example, in the page that contains the Flex app, the page would contain a Javascript function call handleNavigationRequest(pageName, target). In the Flex application, you may utilize ExternalInterface, and call the handleNavigationRequest.
By using this paradigm, the Flex application would not have to figure the details as to how the external implementations such as frame setup, etc, and you end up having a cleaner and less-coupled design.
I've found out that i can use swfObject to embed the flash object thus the iframe implementation is completely useless. Embedding the flash component in the overlay, instead of opening it in an iframe, makes IE behave properly.
I had the same problem and I solved it simply passing the second argument (browser window) to the function:
navigateToUrl(url,"_blank"); , in my case I use "_blank".
It works with IE8 and IE9.
Davide

How do I convert a .docx to html using asp.net?

Word 2007 saves its documents in .docx format which is really a zip file with a bunch of stuff in it including an xml file with the document.
I want to be able to take a .docx file and drop it into a folder in my asp.net web app and have the code open the .docx file and render the (xml part of the) document as a web page.
I've been searching the web for more information on this but so far haven't found much. My questions are:
Would you (a) use XSLT to transform the XML to HTML, or (b) use xml manipulation libraries in .net (such as XDocument and XElement in 3.5) to convert to HTML or (c) other?
Do you know of any open source libraries/projects that have done this that I could use as a starting point?
Thanks!
Try this post? I don't know but might be what you are looking for.
I wrote mammoth.js, which is a JavaScript library that converts docx files to HTML. If you want to do the rendering server-side in .NET, there is also a .NET version of Mammoth available on NuGet.
Mammoth tries to produce clean HTML by looking at semantic information -- for instance, mapping paragraph styles in Word (such as Heading 1) to appropriate tags and style in HTML/CSS (such as <h1>). If you want something that produces an exact visual copy, then Mammoth probably isn't for you. If you have something that's already well-structured and want to convert that to tidy HTML, Mammoth might do the trick.
Word 2007 has an API that you can use to convert to HTML. Here's a post that talks about it http://msdn.microsoft.com/en-us/magazine/cc163526.aspx. You can find documentation around the API, but I remember that there is a convert to HTML function in the API.
This code will helps to convert .docx file to text
function read_file_docx($filename){
$striped_content = '';
$content = '';
if(!$filename || !file_exists($filename)) { echo "sucess";}else{ echo "not sucess";}
$zip = zip_open($filename);
if (!$zip || is_numeric($zip)) return false;
while ($zip_entry = zip_read($zip)) {
if (zip_entry_open($zip, $zip_entry) == FALSE) continue;
if (zip_entry_name($zip_entry) != "word/document.xml") continue;
$content .= zip_entry_read($zip_entry, zip_entry_filesize($zip_entry));
zip_entry_close($zip_entry);
}// end while
zip_close($zip);
//echo $content;
//echo "<hr>";
//file_put_contents('1.xml', $content);
$content = str_replace('</w:r></w:p></w:tc><w:tc>', " ", $content);
$content = str_replace('</w:r></w:p>', "\r\n", $content);
//header("Content-Type: plain/text");
$striped_content = strip_tags($content);
$striped_content = preg_replace("/[^a-zA-Z0-9\s\,\.\-\n\r\t#\/\_\(\)]/","",$striped_content);
echo nl2br($striped_content);
}
I'm using Interop. It is somewhat problamatic but works fine in most of the case.
using System.Runtime.InteropServices;
using Microsoft.Office.Interop.Word;
This one returns the list of html converted documents' path
public List<string> GetHelpDocuments()
{
List<string> lstHtmlDocuments = new List<string>();
foreach (string _sourceFilePath in Directory.GetFiles(""))
{
string[] validextentions = { ".doc", ".docx" };
if (validextentions.Contains(System.IO.Path.GetExtension(_sourceFilePath)))
{
sourceFilePath = _sourceFilePath;
destinationFilePath = _sourceFilePath.Replace(System.IO.Path.GetExtension(_sourceFilePath), ".html");
if (System.IO.File.Exists(sourceFilePath))
{
//checking if the HTML format of the file already exists. if it does then is it the latest one?
if (System.IO.File.Exists(destinationFilePath))
{
if (System.IO.File.GetCreationTime(destinationFilePath) != System.IO.File.GetCreationTime(sourceFilePath))
{
System.IO.File.Delete(destinationFilePath);
ConvertToHTML();
}
}
else
{
ConvertToHTML();
}
lstHtmlDocuments.Add(destinationFilePath);
}
}
}
return lstHtmlDocuments;
}
And this one to convert doc to html.
private void ConvertToHtml()
{
IsError = false;
if (System.IO.File.Exists(sourceFilePath))
{
Microsoft.Office.Interop.Word.Application docApp = null;
string strExtension = System.IO.Path.GetExtension(sourceFilePath);
try
{
docApp = new Microsoft.Office.Interop.Word.Application();
docApp.Visible = true;
docApp.DisplayAlerts = WdAlertLevel.wdAlertsNone;
object fileFormat = WdSaveFormat.wdFormatHTML;
docApp.Application.Visible = true;
var doc = docApp.Documents.Open(sourceFilePath);
doc.SaveAs2(destinationFilePath, fileFormat);
}
catch
{
IsError = true;
}
finally
{
try
{
docApp.Quit(SaveChanges: false);
}
catch { }
finally
{
Process[] wProcess = Process.GetProcessesByName("WINWORD");
foreach (Process p in wProcess)
{
p.Kill();
}
}
Marshal.ReleaseComObject(docApp);
docApp = null;
GC.Collect();
}
}
}
The killing of the word is not fun, but can't let it hanging there and block others, right?
In the web/html i render html to a iframe.
There is a dropdown which contains the list of help documents. Value is the path to the html version of it and text is name of the document.
private void BindHelpContents()
{
List<string> lstHelpDocuments = new List<string>();
HelpDocuments hDoc = new HelpDocuments(Server.MapPath("~/HelpDocx/docx/"));
lstHelpDocuments = hDoc.GetHelpDocuments();
int index = 1;
ddlHelpDocuments.Items.Insert(0, new ListItem { Value = "0", Text = "---Select Document---", Selected = true });
foreach (string strHelpDocument in lstHelpDocuments)
{
ddlHelpDocuments.Items.Insert(index, new ListItem { Value = strHelpDocument, Text = strHelpDocument.Split('\\')[strHelpDocument.Split('\\').Length - 1].Replace(".html", "") });
index++;
}
FetchDocuments();
}
on selected index changed, it is renedred to frame
protected void RenderHelpContents(object sender, EventArgs e)
{
try
{
if (ddlHelpDocuments.SelectedValue == "0") return;
string strHtml = ddlHelpDocuments.SelectedValue;
string newaspxpage = strHtml.Replace(Server.MapPath("~/"), "~/");
string pageVirtualPath = VirtualPathUtility.ToAbsolute(newaspxpage);//
documentholder.Attributes["src"] = pageVirtualPath;
}
catch
{
lblGError.Text = "Selected document doesn't exist, please refresh the page and try again. If that doesn't help, please contact Support";
}
}

Resources