Running random pictures in ASP.NET site - asp.net

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.

Related

Compile aspx page "on the fly"

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.

Generic Handler not getting called in asp.net

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...

Dynamically Size Silverlight Control on Webpage

Here is the issue...
I am adding some silverlight 3 controls to an ASP.Net Web Forms application. The silverlight application's height can change based on the amount of data in it. The application is part of a web page and not the whole page. My users would like to have only 1 set of scroll bars. Is there a way to dynamically size the div or object based on the suze of the silverlight application?
For example can I hook into the silverlight javascript to do this somehow?
There are two ways to do it: either by accessing the DOM element directly and changing its style (or css) attributes, or by calling a javascript function on the page which will do the same thing. Below i have the xaml, code behind, and the HTML for a simple example which when you drag a slider in the silverlight control, it resizes the div that contains the control. If you create a simple Silverlight Application with a complementary test website and page, and then copy and paste the following code in then you can have a play (note that i have snipped some of the generated styles/script from the aspx page for the sake of brevity).
The C# and javascript code is not particularly pretty or bullet proof, it is simply an example.
<UserControl x:Class="SilverlightApplication6.MainPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d" d:DesignWidth="200" d:DesignHeight="480">
<Grid x:Name="LayoutRoot">
<Slider x:Name="WidthSlider" Value="50" Maximum="200"></Slider>
</Grid>
</UserControl>
Code behind for the Silverlight application:
public partial class MainPage : UserControl
{
public MainPage()
{
InitializeComponent();
this.Loaded += new RoutedEventHandler(MainPage_Loaded);
}
private void MainPage_Loaded(object sender, RoutedEventArgs e)
{
WidthSlider.ValueChanged += new RoutedPropertyChangedEventHandler<double>(WidthSlider_ValueChanged);
}
private void WidthSlider_ValueChanged(object sender, RoutedPropertyChangedEventArgs<double> e)
{
//access and manipulate the DOM element directly:
HtmlElement container = HtmlPage.Document.GetElementById("silverlightControlHost");
if (container != null)
{
container.SetStyleAttribute("width", (50 + e.NewValue).ToString() + "px");
}
//pass a delta value to the js function, which will get added to the current width of the container:
HtmlPage.Window.Invoke("resizeContainer", (e.NewValue - e.OldValue).ToString());
}
}
and the aspx page:
<%# Page Language="C#" AutoEventWireup="true" %>
<!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>SilverlightApplication6</title>
<script type="text/javascript" src="Silverlight.js"></script>
<script type="text/javascript">
function resizeContainer(delta) {
var container = document.getElementById('silverlightControlHost');
if (container != null) {
//alert('starting width: ' + container.style.width);
container.style.width = (parseInt(container.style.width) + Number(delta) + 'px');
//alert('finishing width: ' + container.style.width);
}
}
</script>
</head>
<body>
<form id="form1" runat="server" style="height:100%">
<div id="silverlightControlHost" style="border: solid 1px red; width:200px; height: 400px;">
<object data="data:application/x-silverlight-2," type="application/x-silverlight-2" width="100%" height="100%">
<param name="source" value="ClientBin/SilverlightApplication6.xap"/>
<param name="onError" value="onSilverlightError" />
<param name="background" value="white" />
<param name="minRuntimeVersion" value="3.0.40624.0" />
<param name="autoUpgrade" value="true" />
<a href="http://go.microsoft.com/fwlink/?LinkID=149156&v=3.0.40624.0" style="text-decoration:none">
<img src="http://go.microsoft.com/fwlink/?LinkId=108181" alt="Get Microsoft Silverlight" style="border-style:none"/>
</a>
</object><iframe id="_sl_historyFrame" style="visibility:hidden;height:0px;width:0px;border:0px"></iframe></div>
</form>
</body>
</html>
Edit: Two days after i wrote this answer Charles Petzold wrote a blog post about resizing silverlight controls within the html page, you can find it here. The main difference is that he resizes the actual silverlight plugin control, while i was resizing the html element that the silverlight plugin resides within.
I do something similar with a silverlight control I have made. My problem was I have a control to show document scans in a silverlight control and I had the height hardcoded but some users run at a much higher resolution so they had a lot of wasted space they could use.
So I implemented a little client side javascript function that figures out the optimal size for the control. This code runs on page load.
At the bottom of your HTML page add the following code (using Jquery):
<script type="text/javascript" language="javascript">
function InitializeSilverlightControlHeight()
{
$(function()
{
var miniumimControlSize = 500;
var pagePadding = 150;
var screenheight = $(window).height() - pagePadding;
if (screenheight > miniumimControlSize)
{
$("#yourSilverLightControlName").height(screenheight);
}
});
}
InitializeSilverlightControlHeight();
</script>
What this does is it checks the browser window's viewable size and then minuses the padding amount (which in my case is 150px to account for the header's height). If this size is larger than the minimum size of the control it sets the control to this size.
Hope that helps or at least points you in a general direction to get you rolling.
Don't think this is quite what you're looking for but it might help...
In the ctor of your the first page your silverlight control creates you can add an event
App.Current.Host.Content.Resized += new EventHandler(Content_Resized);
Then in your event listener you can resize the control to fit the window better.
void Content_Resized(object sender, EventArgs e)
{
double height = App.Current.Host.Content.ActualHeight;
double width = App.Current.Host.Content.ActualWidth;
this.Height = height;
this.Width = width;
m_currentPage.Height = height;
m_currentPage.Width = width;
}
Hope that helps =D

ASP.NET 2.0 add styles dynamically to page in a control

I need to add to the page from within a custom control. I can't use a stylesheet (.css) because I'm using a url(...) and need to resolve the url.
Right now I'm doing:
Page.Header.Controls.Add(new LiteralControl("<style type='text/css'>.xyz { color: blue; }</style>"));
But I'm hoping for something a touch more elegant?
I guess it's not a bad solution for the problem. If you had an external stylesheet file, this piece of code will do the work:
HtmlLink cssRef = new HtmlLink();
cssRef.Href = "styles/main.css";
cssRef.Attributes["rel"] = "stylesheet";
cssRef.Attributes["type"] = "text/css";
Page.Header.Controls.Add(cssRef);
Another idea is to write your own ASP.NET ServerControl "HtmlInlineStyle", so you could call it this way (script tags would be done by your server control):
Page.Header.Controls.Add(
New HtmlInlineStyle(".xyz { width:300px;padding-left:10px }");
This blog entry and the comments show some alternatives (ScriptManager.RegisterClientScriptBlock). But in my opinion your solution is okay.
Here's another way... For example:
Parent ASPX portion:
<div id="div1" class="xyz" style="width: 40px; height: 40px;">
<span>abc</span>
</div>
Within the Control:
Dim xyzStyle As New Style()
xyzStyle.CssClass = "xyz"
xyzStyle.BackColor = Drawing.Color.LightBlue
Page.Header.StyleSheet.CreateStyleRule(xyzStyle, Nothing, ".xyz")
Note that this assumes that the parent ASPX page has the class attribute set for the target control. If not, then you will need to merge the style with the control using the MergeStyle method. (This requires that the control be runat="server").
This code renders the following output: (Showing entire source for your convenience)
<html>
<head>
<title>Untitled Page </title>
<style type="text/css">
.xyz { background-color:LightBlue; }
</style>
</head>
<body>
<form name="form1" method="post" action="MyPage.aspx" id="form1">
<div id="div1" class="xyz" style="width: 40px; height: 40px;">
<span>abc</span>
</div>
</form>
</body>
</html>
I create my own class and inherit Style, with my own dictionary for attributes that the default Style class does not include. Here is a brief example...
protected override void FillStyleAttributes(CssStyleCollection attributes, IUrlResolutionService urlResolver)
{
Dictionary<String, String> _styles = new Dictionary<string, string>();
_styles.Add("display", "inline-block");
foreach (String s in _styles.Keys)
{
attributes[s] = (String)_styles[s];
}
base.FillStyleAttributes(attributes, urlResolver);
}

ASP.NET :Show background process status to User

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.

Resources