I am trying to display an image from my database. I have an generic handler to display the image. But my problem is that it doesn't get called. My code for calling the handler is
Image1.ImageUrl = "~/ShowImage.ashx?id=" + id;
where id is a number and ShowImage.ashx is the handler. The breakpoints in .ashx file doesn't get hit either. I am new to asp.net. So any help would be highly appreciated.
In this cases the steps that you need to follow is to see how the html is rendered.
So, right click on the html page, and "view page source".
There locate the point that the ShowImage.ashx is called, and see if the full rendered path is correct.
From there you simple correct the path.
Additional you can use the browser tools to see what browser looks for, and if he finds it or not. On google chrome for example you make right click, then inspect elements and then click on the network. There you can see with red, what files your page can not find, and you need to fix the path.
Check this sample Example code this might help you.
ASPX Code :
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<h1>
HTTP Handler class Impliment in Img tag
</h1>
<h1>Id : 1</h1>
<img src="ImageHandler.ashx?id=1" alt="Dynamic Image" />
<h1>Id : 2</h1>
<img src="ImageHandler.ashx?id=2" alt="Dynamic Image" />
</div>
</form>
</body>
</html>
C# Examples (ImageHandler.ashx File) :
<%# WebHandler Language="C#" Class="ImageHandler" %>
using System;
using System.Web;
public class ImageHandler : IHttpHandler {
public void ProcessRequest (HttpContext context) {
//context.Response.ContentType = "text/plain";
//context.Response.Write("Hello World");
context.Response.ContentType = "image/jpeg";
if (context.Request.QueryString["id"] == "1")
{
context.Response.WriteFile("bamboo.jpg");
}
else
{
context.Response.WriteFile("palmtree.jpg");
}
}
public bool IsReusable {
get {
return false;
}
}
}
Here is live downloadable C# Examples and VB.Net Examples of this. Click Here...
Related
I am trying to build an aspx page at runtime (by another aspx page which finally redirects to the new one). As far as I understand, aspx pages MUST be precompiled before a user can view them. In other words, the aspx page must be compiled to the DLL in the /bin folder.
Is there a away to tell IIS, or to order it by VB.NET code, to compile a page before I am redirecting my user to the page?
Any help would be greatly appriciated.
You can use the VirtualPathProvider class to load pages from a database.
Basicallly what you need is to render content of the page dynamically. You can create page content dynamically on server side by adding controls (HTML or Server Ones) to controls collection for example to place holder server element.
For example you can create page with the following markup:
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="TestPage.aspx.cs" Inherits="StackOverflowWebApp.TestPage" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<asp:ScriptManager ID="ScriptManager1" runat="server" EnablePartialRendering="true" />
<asp:PlaceHolder runat="server" ID="ContentPlaceHolder"></asp:PlaceHolder>
</form>
</body>
</html>
And then in code behind class we can add controls to render which is necessary dynamically be reading information from database.
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
namespace StackOverflowWebApp
{
public partial class TestPage : Page
{
#region Methods
protected override void CreateChildControls()
{
base.CreateChildControls();
// HERE get configuration from database.
// HERE create content of the page dynamically.
// Add reference to css file.
HtmlLink link = new HtmlLink { Href = "~/Styles/styles.css" };
link.Attributes.Add("type", "text/css");
link.Attributes.Add("rel", "stylesheet");
this.Page.Header.Controls.Add(link);
// Add inline styles.
HtmlGenericControl inlineStyle = new HtmlGenericControl("style");
inlineStyle.InnerText = "hr {color:sienna;} p {margin-left:20px;}";
this.Page.Header.Controls.Add(inlineStyle);
// Add div with css class and styles.
HtmlGenericControl div = new HtmlGenericControl("div");
this.ContentPlaceHolder.Controls.Add(div);
div.Attributes.Add("class", "SomeCssClassName");
div.Attributes.CssStyle.Add(HtmlTextWriterStyle.ZIndex, "1000");
TextBox textBox = new TextBox { ID = "TestTextBox" };
div.Controls.Add(textBox);
// and etc
}
#endregion
}
}
Note: this example can be a start point to create dynamic pages which content depend on values specified in database or configuration.
I'm building a web application and I have a question.
I want to display to the user running Random pictures in the Web Page.
how can I do this if it is possible.
thanks.
If you want to use a built-in control, you should look at the AdRotator. It will allow you to setup a XML file that lists all of your images that will be random displayed when the control renders on the page.
Control Usage:
<asp:AdRotator id="AdRotator1" runat="server" Target="_self"
AdvertisementFile="~/App_Data/Ads.xml"/>
Example XML File ( Ads.xml ):
<Ad>
<ImageUrl>~/Images/image1.jpg</ImageUrl>
<height>60</height>
<width>190</width>
<NavigateUrl>http://www.microsoft.com</NavigateUrl>
<AlternateText>Microsoft Main Site</AlternateText>
<Impressions>80</Impressions>
<Keyword>Topic1</Keyword>
</Ad>
<Ad>
<ImageUrl>~/Images/image2.jpg</ImageUrl>
<height>90</height>
<width>90</width>
<NavigateUrl>http://www.wingtiptoys.com</NavigateUrl>
<AlternateText>Wingtip Toys</AlternateText>
<Impressions>80</Impressions>
<Keyword>Topic2</Keyword>
</Ad>
</Advertisements>
If your looking for something that can change the images client side (via JavaScript), there are a ton of solutions available. Here is an example of using the jQuery.Cycle plugin.
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="jQueryRotateImages.aspx.cs" Inherits="DevOne.jQueryRotateImages" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>jQuery Rotate Images - Cycle Plugin</title>
<style type="text/css">
.slideshow { height: 232px; width: 232px; margin: auto; }
.slideshow img { padding: 15px; border: 1px solid #ccc; background-color: #eee; }
</style>
<!-- include jQuery library -->
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.5/jquery.min.js"></script>
<!-- include Cycle plugin -->
<script type="text/javascript" src="http://cloud.github.com/downloads/malsup/cycle/jquery.cycle.all.latest.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$('.slideshow').cycle({
fx: 'fade' // choose your transition type, ex: fade, scrollUp, shuffle, etc...
});
});
</script>
</head>
<body>
<form id="form1" runat="server">
<div id="slideshow" class="slideshow" runat="server">
</div>
</form>
</body>
</html>
And here is how you can add your images dynamically in your code behind.
using System;
using System.Web.UI.HtmlControls;
namespace DevOne
{
public partial class jQueryRotateImages : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
slideshow.Controls.Add(new HtmlImage() { Src = "http://cloud.github.com/downloads/malsup/cycle/beach1.jpg", Width = 200, Height = 200});
slideshow.Controls.Add(new HtmlImage() { Src = "http://cloud.github.com/downloads/malsup/cycle/beach2.jpg", Width = 200, Height = 200 });
slideshow.Controls.Add(new HtmlImage() { Src = "http://cloud.github.com/downloads/malsup/cycle/beach3.jpg", Width = 200, Height = 200 });
}
}
}
pseudocode:
//On Page Load do this:
//create list of images from whatever your image source is
//generate a random number between 0 and `ImageList.Length - 1`
//assign the url from the image at the random index to the ImageUrl property of your Image control
If you simply want to pull a random image from a folder on the website, you could do something like the following:
string[] files = Directory.GetFiles(Server.MapPath(#"/images/"));
Random r = new Random();
string imageName = files[r.Next(files.Length);
// ... Code to display image.
However, you've really given sparse information of what you're trying to accomplish, such as where the images are coming from. This would be a very generic solution.
The following blog of msdn explains all the basics about the Random()
MSDN Microsoft Developer Network: Random()
The basic about it is that the Random class selects a random number from an array. It depends on the ticks time. MSDN DateTime Ticks
The ticks are used basically to generate a random. Random can be used as: Suppose I am extracting data from database. It will be
var db = Database.Open("databasename")
var image = db.Query("SELECT * FROM Images").ToList();
var randomImage = image[new Random().Next(image.Count)]
And display the data of it.
Hi,
I have implemented this plugin by Steve Sanders from 2008. In my solution I have 3 buttons for 3 uploads and this works just fine. But ist not a perfect fit and the question is if thera is a better solution for me?
What I need is :
Be able to upload multiple files
When the Control Action is triggered It should be possible to work with the files
The enduser should be able to cancel a uploaded file(this is not possible with Steves plugin as far as I know)
Easy to use with ASP.NET MVC
If a post is done to the Control Action and a validation error is thrown back the uploads may not disappear.
Pleas Advice
How about using Uploadify? I have used it before, and it works great. But do notice that it also needs a Flash front-end in order to work...
Take a look at this StackOverflow question - there you'll find more info of how to use it with ASP.NET MVC.
Under the hood the Steve Sanders' plugin uses swfUpload which can support everything you need. His plugin however does not seem to expose all of the features of swfUpload such as canceling uploads.
I use swfUpload to it's full extent on my sites supporting multiple files, canceling uploads, validation without canceling other uploads, etc.
Here's a demo of swfUpload in action where you can cancel uploads
Another option is SlickUpload.
It's not free but definitely worth it in my opinion. I used it in an MVC project recently and was extremely happy with it. Best upload plugin I've ever used + it comes with all sorts of validation helpers.
It's fully customizable too.
Download the trial and have a look for yourself :)
It's not possible with pure ASP.NET.
You need to take JQuery uploadify.
It's the best you can find, trust me, I tried for an entire day.
<%# Page Language="vb" AutoEventWireup="false" CodeBehind="MassUpload.aspx.vb" Inherits="Raumplaner_New.MassUpload" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
<title>Mass Upload</title>
<link href="../upload/css/uploadify.css" rel="stylesheet" type="text/css" />
<script type="text/javascript" src="../scripts/jquery-1.3.2.min.js"></script>
<script type="text/javascript" src="../scripts/swfobject.js"></script>
<script type="text/javascript" src="../scripts/jquery.uploadify.v2.1.0.min.js"></script>
<script type = "text/javascript">
$(document).ready( function()
{
$("#<%=FileUpload1.ClientID%>").uploadify({
'uploader' : '../upload/scripts/uploadify.swf',
'script' : '../cgi-bin/Upload.ashx',
'cancelImg' : '../upload/images/cancel.png',
'folder' : '../upload/temp',
'buttonImg' : '../upload/images/uploadbutton.png',
'width' : '97',
'height' : '22',
'wmode' : 'transparent',
'displayData' : 'speed',
'multi' : true,
'auto' : true,
'simUploadLimit' : 20,
'fileDesc' : 'DWG und SWF - Dateien',
'fileExt' : '*.dwg;*.swf',
'onSelect' : function(event, queueID, fileObj){ EnableObject('FileUpload1');},
'onCancel' : function(event, queueID, fileObj, data){DisableObject('FileUpload1');},
'onComplete' : function(event,queueID,fileObj,response,data){alert(fileObj.name);}
});
$("#startUploadLink").click( function()
{
$('#<%=FileUpload1.ClientID%>').uploadifyUpload();
return false;
});
$("#clearQueueLink").click( function()
{
$("#<%=FileUpload1.ClientID%>").uploadifyClearQueue();
return false;
});
});
</script>
</head>
<body style='background:black;'>
<div id='main'>
<form id="form1" runat="server">
<br/>
<div class="demo">
<asp:FileUpload ID="FileUpload1" runat="server" />
<br />
Start Upload |
Clear
</div>
</form>
</div>
</body>
</html>
And here's upload.ashx
<%# WebHandler Language="VB" Class="Upload" %>
Imports System
Imports System.Web
Public Class Upload : Implements IHttpHandler
Public Sub ProcessRequest(ByVal context As HttpContext) Implements IHttpHandler.ProcessRequest
Dim postedFile As HttpPostedFile = context.Request.Files("Filedata")
Dim savepath As String = ""
Dim tempPath As String = ""
tempPath = context.Request("folder")
'If you prefer to use web.config for folder path, uncomment below:
'tempPath = System.Configuration.ConfigurationManager.AppSettings("FolderPath")
savepath = context.Server.MapPath(tempPath)
Dim filename As String = postedFile.FileName
If Not System.IO.Directory.Exists(savepath) Then
System.IO.Directory.CreateDirectory(savepath)
End If
postedFile.SaveAs((savepath & "\") + filename)
context.Response.Write((tempPath & "/") + filename)
context.Response.StatusCode = 200
End Sub
Public ReadOnly Property IsReusable() As Boolean Implements IHttpHandler.IsReusable
Get
Return False
End Get
End Property
End Class
Is there a quick and dirty way of using a query passed as follows:
domain.com/mypage.aspx/product/toycar/
I've done it before in PHP, but this needs to be done in page (in this instance).
--
I only have access to the aspx page and code behind, and have to work in asp.net 2 (i wish i was using 3.5)
quick and dirty:
public class ModuleRewriter : IHttpModule
{
public void Init(HttpApplication application)
{
application.BeginRequest += (new EventHandler(this.Application_BeginRequest));
}
private void Application_BeginRequest(Object source, EventArgs e)
{
// The url will look like: http://domain.com/mypage.aspx/product/toycar/
// The module will rewrite it to: http://domain.com/mypage.aspx?product=toycar
HttpApplication application = source as HttpApplication;
string[] urlInfo = application.Request.RawUrl.ToString().Split('/');
if (urlInfo.Length > 2)
{
string page = urlInfo[urlInfo.Length - 3];
string action = urlInfo[urlInfo.Length - 2];
string id = urlInfo[urlInfo.Length - 1];
if (string.IsNullOrEmpty(page))
{
page = "default.aspx";
}
application.Server.Transfer(string.Format(
"~/{0}?{1}={2}", page, action, id));
}
}
public void Dispose()
{
}
}
web.config:
<httpModules>
<add name="ModuleRewriter" type="ModuleRewriter, MyWebApplication"/>
</httpModules>
and a test page:
<%# Page Language="C#" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<%= Request["product"] %>
</div>
</form>
</body>
</html>
You might want to look into the ASP.NET System.Web.Routing namespace, which was added in .NET 3.5 SP1 I believe:
http://blogs.msdn.com/mikeormond/archive/2008/05/14/using-asp-net-routing-independent-of-mvc.aspx
http://msdn.microsoft.com/en-us/library/system.web.routing.aspx
You'd be able to get rid of the .aspx extension too.
This would involve making a custom HTTP Handler.
Check this
You've got a few options, but all of them require access to the web.config and a change to IIS to map all file extensions to the dotNet ISAPI dll:
Use MVC (like stackoverflow does,
notice the urls)
Use asp.net routing (new in 3.5)
Write your own http handler Massive guide from Microsoft here
Use the excellent urlrewriting.net which does just about everything perfectly including getting round some awkward authentication and image path problems.
Personally I used urlrewriting.net with good results.
Since you mention you don't have access to anything but the code behind and the page, the only thing I can think of is actually creating those dirs (if you have access to do that) and using a server.transfer page passing the value to your actual page in the folder above. Messy, but if you can't access the other stuff, your choices are limited.
In case you just want to read the path from within your .aspx:
Request.ServerVariables["PATH_INFO"]
To clarify:
he has only access to the aspx (+ codebehind) itself, so he must know how the query is, but it is not in the Request.QueryString because of the format. So the only way then is Request.ServerVariables["PATH_INFO"] (Request.RawUrl)
I have a web page where it will input an excel/CSV file from the user and read the data from it and import to DB.While inserting each record.I just want to show the details about the record being inserted to the user.(Ex : Client Details of A is adding...)
Try this... Set the output to unbuffered (Response.BufferOutput), and include some javascript in your page that updates the UI as you see appropriate. For example, it might update a SPAN with a percentage complete or the details of the record you are processing. Then in your server code, output <script> tags that call the Javascript function from the Render override. Make sure you call Flush() at the appropriate times, and also Flush the base code after it Renders... The JS function calls should get sent down at the appropriate times and executed on the client, resulting in an updating page.
For example... Your HTML page might look like this:
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="WebApplication1._Default" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title></title>
<script type="text/javascript">
function UpdateScreen(t) {
document.getElementById('output').innerHTML = t;
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<div id='output'></div>
</div>
</form>
</body>
</html>
<script type="text/javascript">
UpdateScreen('hello');
</script>
and your codebehind will look like this:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Threading;
namespace WebApplication1
{
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected override void Render(HtmlTextWriter writer)
{
Response.BufferOutput = false;
base.Render(writer);
Response.Flush();
for (int i = 0; i < 10; i++)
{
Thread.Sleep(1000);
Response.Write(string.Format("<script type='text/javascript'>UpdateScreen('{0}');</script>", i * 10));
Response.Flush();
}
}
}
}
I know this is an old question, and the owner of it may have moved on a long time ago. Anyway:
The proposed solution will not work on ASP.NET MVC. And if you ask me, which you don't, I'll say this is not the cleanest solution to the problem:
Here's a jQuery one,
And here's an IFrame one.