CodeVerge.Net Beta


   Explore    Item Entry   Register  Login  
Microsoft News
Asp.Net Forums
IBM Software
Borland Forums
Adobe Forums
Novell Forums

MS SQL 2008 on ASP.NET Hosting



Zone: > NEWSGROUP > Asp.Net Forum > starter_kits_and_source_projects.club_web_site_starter_kit Tags:
Item Type: NewsGroup Date Entered: 4/17/2006 4:38:06 PM Date Modified: Subscribers: 0 Subscribe Alert
Rate It:
(NR, 0)
XPoints: N/A Replies: 4 Views: 26 Favorited: 0 Favorite
Can Reply:  No Members Can Edit: No Online: Yes
5 Items, 1 Pages 1 |< << Go >> >|
cheeso
Asp.Net User
Extension: Random Image control4/17/2006 4:38:06 PM

0/0

I wanted to add a control that would randomly select an image from the library, and display it in a leftblock on any particular ASPX page in the site. So I created a new custom control. When it loads, it selects a random image. It then generates an image tag in the HTML, with the appropriate image data. The control then wraps a hyperlink around the image; when clicked the link opens up the album that contains the image in question, using the existing PhotoAlbum_Contents.aspx.

This is the new control, put it into a new file called ImageRandom.ascx:

<%@ Control Language="C#" ClassName="ImageRandom" %>
<script runat="server">
    public int MaxWidth
    {
        get
        {
            object o = ViewState["MaxWidth"];
            return (o != null) ? Convert.ToInt32(o.ToString()) : 0;
        }
        set
        {
            ViewState["MaxWidth"] = value;
        }
    }

    private int imageId = 0;

    protected void Page_PreRender(object sender, System.EventArgs e)
    {
        int[] x= ImageUtils.SelectRandomPhoto();
        Image1.ImageUrl = "ImageFetch.ashx?Size=" + MaxWidth.ToString() + "&ImageID=" + x[0].ToString();
        Hyperlink1.NavigateUrl = "PhotoAlbum_Contents.aspx?AlbumId=" + x[1].ToString() + "&ImageID=" + x[0].ToString();
    }
</script>


<asp:HyperLink ID="Hyperlink1" runat="server">
	<asp:Image ID="Image1" runat="server" CssClass="picture" BorderWidth="1" />
</asp:HyperLink> 


To use the control, stuff something like this into an ASPX page:

<%@ Register TagPrefix="Club" TagName="ImageRandom" Src="ImageRandom.ascx" %>
....
<asp:Content ID="Content1" ContentPlaceHolderID="ContentPlaceHolder1" runat="Server">
    <div id="body">
        <!--Start of left column-->
        <div id="columnleft">
        ...
            <div class="leftblock">
                <h3>
                    Photo pick:</h3>
                <Club:ImageRandom ID="ImageRandom" runat="server" MaxWidth="180" />
            </div>
        ...
        </div>
     ...


The control references a new static method in the ImageUtils class - so add this to App_Code\ImageHandling.cs :

    public static int[] SelectRandomPhoto()
    {
        SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["ClubSiteDB"].ConnectionString);
        
        // randomly select an image
        SqlCommand command = new SqlCommand("select MAX(id) from images", connection);
        connection.Open();
        int maxId = (int)command.ExecuteScalar();

        // now, select an imageID randomly, and verify that it is attached to an album (any album)
        System.Random rnd = new System.Random();
        command = new SqlCommand("select album from images where id=@id", connection);
        SqlParameter p0 = new SqlParameter("@id", SqlDbType.Int);
        command.Parameters.Add(p0);
        int ImageID=0, albumId = 0;
        do
        {
            ImageID = rnd.Next(1, maxId+1);
            p0.Value = ImageID;
            albumId = (int)command.ExecuteScalar();
        } while (albumId == 0);
        connection.Close();

        return new int[] {ImageID, albumId};
    }

Finally, the PhotoAlbum_Contents.aspx page - if you want to open an album to a particular image, you need to add an OnIteBound event handler to the DataList2, like so:

                <asp:DataList ID="DataList2" runat="server" DataSourceID="SqlDataSource2" DataKeyField="id"
                    RepeatColumns="2" CellSpacing="2" 
                    OnItemDataBound="ItemBound"
                    ...

And then this is the ItemBound method, which should also go into that page (Photoalbum_Contents.aspx). What it does is sets the particular photo to "selected" in the list, when that is the "requested" image in the querystring.

    private int _requestedImageId=-455;
    private int RequestedImageId
    {
        get
        {
            if (_requestedImageId == -455)
            {
                object o = Request.QueryString["ImageID"];
                if (o != null)
                    _requestedImageId = System.Convert.ToInt32(o);
                
            }
            return _requestedImageId;
        }
    }

   protected void ItemBound(Object sender, DataListItemEventArgs e)
    {
        if (e.Item.GetType().Name == "DataListItem")
        {
            DataListItem item = (DataListItem)e.Item;
            System.Data.DataRowView drv = (System.Data.DataRowView)item.DataItem;
            if ((int)drv[0] == RequestedImageId)
            {
                DataList2.SelectedIndex = item.ItemIndex;
                item.ControlStyle.CssClass = "selected";
                Trace.Write(String.Format("item {0} selected, ID={1}", item.ItemIndex, RequestedImageId));
                DataList2_SelectedIndexChanged(null, null);
            }
            else
            {
                Trace.Write(String.Format("item {0} NOT selected, ID={1}", item.ItemIndex, RequestedImageId));
            }
        }
    }

MrLunch
Asp.Net User
Re: Extension: Random Image control4/18/2006 7:47:47 PM

0/0

Very cool cheeso!

Your SelectRandomPhoto() hits the DB at least twice and maybe more if you have deleted images. May I suggest you let the DB do the work of picking a random row? You can do this with NEWID():

    public static int[] SelectRandomPhoto()
    {
        SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["ClubSiteDB"].ConnectionString);
       
        // randomly select an image
        SqlCommand command = new SqlCommand("SELECT TOP 1 id, album FROM images ORDER BY NEWID()", connection);
        connection.Open();
        SqlDataReader myReader = command.ExecuteReader();
        int ImageID = myReader.GetInt32(0);
        int albumId = myReader.GetInt32(1);
        myReader.Close();
        connection.Close();

        return new int[] {ImageID, albumId};
    }

Or something like that.

Cheers,


Mark Bracewell
Forums Starter Kit
cheeso
Asp.Net User
Re: Extension: Random Image control4/18/2006 9:41:36 PM

0/0

Hey MrLunch,

nice, I like optimizations.  I knew my implementation was a lazy way to do it, but I am no T-SQLer.  What does NEWID() do, and what does the query do?  (can you translate in english?)

-Cheeso  

 

cheeso
Asp.Net User
Re: Extension: Random Image control4/18/2006 10:21:25 PM

0/0

MrLunch, after reading up on it a bit, now I understand newid().  Great suggestion, thanks!   It does exactly what I want, but more efficiently.  I added in a myReader.Read() and a WHERE clause.  Here's the actual code I used: 

    public static int[] SelectRandomPhoto()

    {

        SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["ClubSiteDB"].ConnectionString);

 

        // randomly select an image (it must be associated to an album)

        SqlCommand command = new SqlCommand("SELECT TOP 1 id, album FROM images WHERE album<>0 ORDER BY NEWID()", connection);

        connection.Open();

        SqlDataReader myReader = command.ExecuteReader();

        myReader.Read();

        int ImageID = myReader.GetInt32(0);

        int albumId = myReader.GetInt32(1);

        myReader.Close();

        connection.Close();

 

        return new int[] { ImageID, albumId };

    }

 

MrLunch
Asp.Net User
Re: Extension: Random Image control4/18/2006 11:20:27 PM

0/0

Oops! Yeah, gotta do .Read() to get anywhere :)

> I knew my implementation was a lazy way to do it

Nah, lazy is where you write *less* code ;-)

Cool controls man, keep it up!

Cheers


Mark Bracewell
Forums Starter Kit
5 Items, 1 Pages 1 |< << Go >> >|


Free Download:

Books:
Processing: A Programming Handbook for Visual Designers and Artists Authors: Casey Reas, Ben Fry, Pages: 710, Published: 2007
Digital Image Processing Authors: Rama Chellappa, Pages: 801, Published: 1992
A Game of Two Halves: Football, Television, and Globalisation Authors: Cornel Sandvoss, Pages: 212, Published: 2003

Web:
Extensions Download custom extensions for BlogEngine.NET. ... Random Image Control - Displays a random image from a given directory; Gallery User Control ...
tumelty dot com - Definitive List of BlogEngine.Net Extensions Net Extensions. Total Number of Extensions: 60 - Last Updated 25th February 2008 ... Random Image Control - Displays a random image from a given directory ...
Dreamweaver Extension List - Kaosweaver The ICRA provides a way for people to rate their web sites to control ... Random Rollover Dreamweaver extension icon Makes the rollover image a random one! ...
Dreamweaver Extensions - XML Flash Slideshow v3 - Instantly Create ... With the random autoplay option, the slideshow will start with a random image ... Apply links to each image. Or, for greater control, use the Custom Link ...
Joomla! Extensions Directory - Reviews by Harrison After using random image modules for other galleries I was expecting a ... you have no control to change this other than directly editing the module code. ...
Joomla! Extensions Directory - Simple Image Rotator - Rotate ... Front Page Image Rotator (22 Euros) - This extension allows you to insert ... I was satisfied with the included random image module but it is lacking in the ...
Include subfolders in random image script - Dynamic Drive Forums isset( $extList[ strtolower( $file_info['extension'] ) ] ) ) { $items[] = $file; } } sort($items); // get the random image ...
Simple Random Header Images for Your Blog — Pearsonified Not if you use my incredibly simple random header image solution! ... you’re using .gif files, then make sure that each header image has the .gif extension. ...
Out of Control™ It is a simple little extension that will automatically resize any imaged ... that resolvers should use random source source ports when sending queries. ...
Adobe Dreamweaver Tutorial | Add Features | Extension Manager ... You’ll find a wide range of extensions on the Dreamweaver Exchange site and ... live Web server (this is true for the random image extensions, for example. ...

Videos:
H.A.F. - Mirage 2000 ####Reuploaded#### DOWNLOAD LINK http://www.patricksaviation.com/in/6426?i=INx The Mirage 2000 is a French-built multirole fighter jet manufactured b...
Developing JavaScript with Chickenfoot Google TechTalks July 25, 2006 Rob Miller Michael Bolin ABSTRACT Chickenfoot is a Firefox extension that embeds a JavaScript programming environmen...




Search This Site:










how do i add a 3rd column into the css file for all pages?

where are the codebehindfiles

club starter kit security

can't get news_edit to insert rows via stored procedure

eventcalendar interface and description?

aspspider.net help !!!

club.vsi install

event calendar control

problem installing club starter kit

server error in '/clubwebsite1' application

need help identifying error in deployed site

adding news - layout corrupt ?

hit counter

aspnetdb.mdf not created!!!!

location of images

'http://schemas.microsoft.com/.netconfiguration/v2.0:configuration'

club site login script

focus on username of logincontrol (part ii)

javascript, fckeditor and the events page

using this on a server with tight security?

deleting users breaks website

show and share your csk 2.0 sites here.

who is online module

whitepaper (extending the club site) issue

dbnull to type integer is not valid error message

news articles - how do u sort most recent first

image upload errors when file is nothing

security problems

foruns

multi user upload photo

  Privacy | Contact Us
All Times Are GMT