Intrepid Studios, Inc. Blog - Minneapolis, MN - .NET, XHTML, CSS, Adobe, web, graphic, media, and software design services

Learn more:

Overview

Intrepid Studios, Inc. is a software and web studio located in Minneapolis, MN that provides professional services for the web and desktop. We offer web design and development, graphic design, application design and development, and a host of other solutions.

Our Network

Previous Posts

Archives

 Subscribe in a reader

Powered by Blogger

Blog

Friday, August 8, 2008

How To: Integrate Google Picasa Onto Your Own Website Using PHP

I mentioned when I posted about finishing a website that I had made some custom scripts, and this was one of them.

This assumes you have all the Google PHP scripts ready on your site, comments have been made at appropriate areas. The HTML included is meant to be styled and is just the structure I used to make it. You can see the implementation right over yonder.

Features:

It’s tested and working, make sure you configure it properly. As always, feel free to add on as you please.

This was a quick script so I’d add some more error checking if I were you. It doesn’t use classes or anything, it’s just down and dirty.

Download Source Code (.zip)

gallery.php

<?php
/************************************************************
****    Picasa and PHP Integration Script
****    Created by: Kamran Ayub (c)2008 Intrepid Studios, Inc.
****    http://www.intrepidstudios.com/
****    This is just a very barebones implementation! No fancy
****    classes and whatnot. Feel free to improve it.
****
**************************************************************/    
//set_include_path("/local/home/"); // set if Zend folder isn't in the same directory as gallery.php, e.g. it's below it
 
// Vars
$user = "YOUR_GOOGLE_USERNAME";
$pass = "YOUR_PASSWORD";
$albumId = $_REQUEST['albumId'];
$albumName = $_REQUEST['albumName']; // This is just lazy, because when you are using the newAlbumQuery method, the name of the album can be gotten anyway.
$page = $_REQUEST['page'];
$maxResults = 15; // Max Results per page
$maxImageSize = 800; // don't go over 800 otherwise you won't be able to embed the larger photos
$zend_dir = "Zend/Loader.php"; // should point to your Zend directory
 
// Functions
function Paginate($numPages,$currentPage,$albumName,$albumId) {
    // Create page links
    
    $s = "<ul class='page-nav'>\n";
    for($i=1;$i<=$numPages;$i++) {
        $class = "";
        
        // Current page?
        if($i == $currentPage) {
            $class = " class='selected'";
        }
        $s .= "<li".$class.">";
        $s .= "<a href='?albumId=".$albumId."&amp;albumName=".$albumName."&amp;page=".$i."'>".$i."</a></li>\n";
    }
    $s .= "</ul>\n";
    
    return $s;
}
 
// Picasa Web Albums
require_once($zend_dir);
Zend_Loader::loadClass('Zend_Gdata_Photos');
Zend_Loader::loadClass('Zend_Gdata_ClientLogin');
Zend_Loader::loadClass('Zend_Gdata_AuthSub');
 
// Authenticate
$serviceName = Zend_Gdata_Photos::AUTH_SERVICE_NAME;
 
$client = Zend_Gdata_ClientLogin::getHttpClient($user, $pass, $serviceName);
 
// update the second argument to be CompanyName-ProductName-Version
$gp = new Zend_Gdata_Photos($client, "Google-DevelopersGuide-1.0");
 
 
// Default page
if(!isset($page)) {
    $page=1;
}
 
if(isset($albumName)) {
    $albumName = urldecode($albumName);
}
?>
<html>
<head>
    <title>Integrate Picasa and PHP Demo</title>
    <link rel="stylesheet" type="text/css" href="base.css" media="all" />
    <link rel="stylesheet" type="text/css" href="gallery.css" media="all" />
    <link rel="stylesheet" type="text/css" href="awesomebox.css" media="all" />
    
    <!-- YUI, older -->
    <script type="text/javascript" src="http://yui.yahooapis.com/2.2.0/build/yahoo-dom-event/yahoo-dom-event.js"></script>
    <script type="text/javascript" src="http://yui.yahooapis.com/2.2.0/build/animation/animation-min.js"></script>
    
    <script src="awesomebox.js" type="text/javascript"></script>
</head>
<body>
    <h1>Photo Gallery</h1>
    
    <div class="albums">
    <h3>Albums</h3>
                
        <?php
        try {
            $userFeed = $gp->getUserFeed("default");
            echo "<ul>\n";
            foreach ($userFeed as $userEntry) {
                echo "<li><a href='gallery.php?albumId=". $userEntry->gphotoId->text . "&amp;albumName=". urlencode($userEntry->title->text) ."'>". $userEntry->title->text . "</a></li>\n";
            }
            echo "</ul>\n";
            //print_r($userFeed); // Debug
        } catch (Zend_Gdata_App_HttpException $e) {
            echo "Error: " . $e->getMessage() . "<br />\n";
            if ($e->getResponse() != null) {
                echo "Body: <br />\n" . $e->getResponse()->getBody() . 
                     "<br />\n"; 
            }
            // In new versions of Zend Framework, you also have the option
            // to print out the request that was made.  As the request
            // includes Auth credentials, it's not advised to print out
            // this data unless doing debugging
            // echo "Request: <br />\n" . $e->getRequest() . "<br />\n";
        } catch (Zend_Gdata_App_Exception $e) {
            echo "Error: " . $e->getMessage() . "<br />\n"; 
        }
        ?>
     </div>       
    <?php
    // List photos from album
    
    if(!isset($albumId)) {
    ?>
        <div class="grid">
        <p>Choose a photo album to view.</p>        
        </div>            
    <?php
    } else {
        $query = $gp->newAlbumQuery();
    
        $query->setUser("default");
        $query->setAlbumId($albumId);
        $query->setImgMax($maxImageSize); 
        $query->setMaxResults($maxResults);
        
        if(isset($page)) {
            $query->setStartIndex((($page-1) * $maxResults)+1);
        }
    ?>
        <h3>Photos from <?= $albumName ?></h3>
        <div class="grid">
        <?php    
        try {    
            $albumFeed = $gp->getAlbumFeed($query);
            
            // Number of results
            $numResults = $albumFeed->gphotoNumPhotos->text;
            
            // You should probably check if $numResults is a number...
            
            // If there are more than $maxResults, we need to paginate this...
            $numPages = ceil($numResults / $maxResults);
            
            if($numPages > 1) {                            
                echo Paginate($numPages,$page,$albumName,$albumId);
            }
            foreach ($albumFeed as $photoEntry) {
                $contentUrl = "";
                $thumbnailUrl = "";
                
                if ($photoEntry->getMediaGroup()->getContent() != null) {
                  $mediaContentArray = $photoEntry->getMediaGroup()->getContent();
                  $contentUrl = $mediaContentArray[0]->getUrl();
                }
        
                if ($photoEntry->getMediaGroup()->getThumbnail() != null) {
                  $mediaThumbnailArray = $photoEntry->getMediaGroup()->getThumbnail();
                  $thumbnailUrl = $mediaThumbnailArray[1]->getUrl();
                }
        
                echo "<div class='photo'><a rel='gallery' href='".$contentUrl."'><img src='" . $thumbnailUrl . "' alt='" . $photoEntry->title->text ."' title='" . $albumName ."' /></a></div>\n"; 
            }
            //print_r($albumFeed);
            echo "<div style='clear:both;margin-bottom:6px;'>&nbsp;</div>";
            if($numPages > 1) {                            
                echo Paginate($numPages,$page,$albumName,$albumId);
            }
        } catch (Zend_Gdata_App_HttpException $e) {
            echo "Error: " . $e->getMessage() . "<br />\n";
            if ($e->getResponse() != null) {
                echo "Body: <br />\n" . $e->getResponse()->getBody() . 
                     "<br />\n"; 
            }
            // In new versions of Zend Framework, you also have the option
            // to print out the request that was made.  As the request
            // includes Auth credentials, it's not advised to print out
            // this data unless doing debugging
            // echo "Request: <br />\n" . $e->getRequest() . "<br />\n";
        } catch (Zend_Gdata_App_Exception $e) {
            echo "Error: " . $e->getMessage() . "<br />\n"; 
        }
        ?>
        </div>
    <?php
    }
    ?>
</body>
</html>

Labels: , ,

» Read more...

Monday, August 4, 2008

How To: Use PHP to Grab Event Date from Google Calendar RSS [Tips & Tricks]

Recently I finished a site that required me to use Google Calendar to manage events. I thought that it would be nice to show what events are up and coming, so I used SimplePie to grab and show their calendar feed.

However, the RSS date was the date the event was added, not the date that the event happens. This makes sense but makes it a bit harder to be useful in the website.

I used some simple RegEx to get the event date… it’s rough but it works and I’ve tested it with events spanning multiple dates, all day, and specific times.

<dl>
    <?php
    // Feed: http://www.google.com/calendar/feeds/[google account]/public/basic?max-results=5
    foreach ($feed->get_items() as $item):
        
        // Grab When: date.
        $content = $item->get_content();
        $content = strip_tags($content);
        
        if(preg_match("/When: (.*!?)/", $content, $matches)) {
            $content = $matches[1];
        } else {
            $content = "No Date Found";
        }
    ?>
        <dt>Event:</dt>
        <dd><a href="<?php echo $item->get_permalink(); ?>"><?php echo $item->get_title(); ?></a></dd>
        <dt>Event Date:</dt>
        <dd><?php echo $content; ?></dd>
    <?php endforeach; ?>
</dl>

This assumes you have a SimplePie feed… you can just use the RegEx in any other implementation instead…

Labels: , ,

» Read more...

Wednesday, March 19, 2008

Customize ASP.NET Wizard SideBar Template [Snippet]

If you have used the ASP.NET Wizard Control and have tried to use the default Sidebar template, you know that it does not allow you to get rid of the LinkButton controls. Some of us, however, don't want users to skip all around our wizard, so we need a way to show the users where they are but prevent them from screwing it all up.

Here's a quick hack that will do just that. Basically, the theory is that the DataList control in the Sidebar template has to be there along with a LinkButton. But you don't have to show it to the user, do you? All we do is attach a PreRender event handler on the DataList to grab all the wizard steps and duplicate them as labels in a separate label control.

Page with Wizard Control
<SideBarTemplate> <asp:Label ID="SideBarInfo" OnPreRender="InitSideBarLbl" runat="server" /> <asp:DataList ID="SideBarList" OnPreRender="LoadSideBar" RepeatLayout="Flow" Style="display:none;" runat="server"> <ItemTemplate> <asp:LinkButton ID="SideBarButton" Visible="false" runat="server"></asp:LinkButton> </ItemTemplate> <SelectedItemStyle Font-Bold="True" CssClass="Wizard-Sidebar-Selected" /> </asp:DataList> </SideBarTemplate>
Then, in your Code-Behind:
Label SideBarInfo; // Hide all LinkButton controls and duplicate into labels! protected void LoadSideBar(object s, EventArgs e) { DataList me = (DataList)s; // Reset label (postbacks) SideBarInfo.Text = ""; // Loop through datalistitems foreach (DataListItem item in me.Items) { // Each list item LinkButton btn = (LinkButton)item.FindControl("SideBarButton"); if (btn != null) { Label newLabel = new Label(); newLabel.Text = btn.Text; // Current step? if (me.SelectedItem == item) { newLabel.CssClass = me.SelectedItemStyle.CssClass; } // Styled divs SideBarInfo.Text += "<div class='" + newLabel.CssClass + "'>" + newLabel.Text + "</div>"; } } } protected void InitSideBarLbl(object s, EventArgs e) { SideBarInfo = (Label)s; }

See? Easy as pie. Feel free to improve it! And if you do, let me know how in the comments.

Labels: , , ,

» Read more...

Tuesday, February 19, 2008

Using Localization in ASP.NET

If you've designed, developed or worked on websites recently, you have probably come across the topic of localization. In this article, I'll show you how to implement localization in your Visual Studio .NET projects. Most of us blanch at the idea of tailoring our pages to localize in multiple languages. The hard part of localization is, of course, the localizing. However, translating static labels and site content can be as easy as asking your user base to help. Good news though, once you've got that covered, the implementing is the easy part! In this article, I'm going to focus on two ways of implementing localization in your .NET projects (and how to let your users choose). The first way is the "easy" way but might prove daunting in the long-term for large-scale websites. The second way is by grouping and scaling-down the amount of files to tend to. No way is best and I'll leave it up to you to decide which is better for your project.

Method 1: Using Generated Resource Files

Visual Studio .NET makes it easy to use localization by using its designer and tools. Let's see how it's done. First, create a new website project. I am using Visual Studio .NET 2008, but it will be similar no matter what version you're using. Then, design a fairly simple webpage with a few label controls and a button control. One label will be a localized text label and the other will show what culture we're currently set to. The button will let us switch to a predefined culture. Now, go to Tools and click 'Generate Local Resource.' This will create a corresponding Default.aspx.resx resource file for your webpage in the App_LocalResources folder. If you add more controls to the page, you must generate a local resource again. Note: Controls removed from the page will still show up in the resource file. Make sure to clean the resource file if you have deleted controls. If you noticed, in the Source of your Default.aspx file, the attribute meta:resourcekey was added to your controls. The attribute value corresponds to the resource file control names (e.g. meta:resourcekey="Label1Resource1" corresponds to "Label1Resource1" and all its properties in the Default.aspx.resx file). Now that we've generated a resource file, we can proceed to create a localized resource file. For a list of accepted cultures, check out this list. You can localize your project on a page-by-page basis or a global basis. For more information, see MSDN's How To: Set the Culture and UI Culture for ASP.NET Web Page Globalization. We're going to localize on the page basis. In the Page directive, change the following attributes (from the default 'auto'): UICulture="es" culture="es-MX". Espanol will be our test culture. Your page directive should look something like this:
<%@ Page Language="VB" AutoEventWireup="false" CodeFile="Default.aspx.vb" Inherits="_Default" culture="es-MX" meta:resourcekey="PageResource1" uiculture="es" %>
Now, let's localize! Right-click Default.aspx.resx and copy it. Paste it in the same folder and rename it to Default.aspx.es.resx. Change Label1Resource1.Text to 'A localized string in Espanol'. Let's see what happens. Right-click Default.aspx and click View in Browser. Voila! We can see that the label's text has changed to the Spanish localized text. Remember that you can use the Web.Config or Page method to also set the culture based on a browser's settings. But also realize that most people don't set it or might not have the correct setting. That's why we need to have a method for the user to choose a set language. Let's create a button that will change the culture back to US English programatically and display it. Double-click the page background on the designer to create a Page_OnLoad event. In the event method, type in this code:
Dim c As CultureInfo = CultureInfo.CurrentCulture lblCulture.Text = c.NativeName
This code is to display the current culture for the page. I named my label lblCulture but you may have left it at Label2. Change the name to whatever you named your label control to display the current culture. Now, create a new method to override the InitializeCulture method. This method comes before any of the controls are generated so we have to go old-school and use the Request.Form method to check if we've submitted the form. In a real project, you could put code in this method to check your user's profile object for a language specification.
Protected Overrides Sub InitializeCulture() If Request.Form("Button1") IsNot Nothing Then Dim selectedLanguage As String = "en-US" UICulture = selectedLanguage Culture = selectedLanguage Thread.CurrentThread.CurrentCulture = _ CultureInfo.CreateSpecificCulture(selectedLanguage) Thread.CurrentThread.CurrentUICulture = New _ CultureInfo(selectedLanguage) End If MyBase.InitializeCulture() End Sub
Make sure to import System.Globalization and System.Threading. Let's see what happens now. Run your project again and you'll see that the label shows "Español (México)." Now click Change Culture. You'll see it says "English (United States)." Note: I changed my label to read "English label" via the resource file. Congratulations! You've just learned how to use VS.NET's built-in Generate Local Resource tool to create a localized website. Now let's take a look at a slightly different approach.

Method 2: Using A Global Resource File

If you're like me, the less files to manage the better. That's why I dug a little deeper and discovered how to use just one resource file to localize my websites. It requires a bit more work in the short-run but less work in the long run. Let's get started. Create a new page in our project called GlobalExample.aspx. Set it up so it looks like our previous page. Now, right-click your project and go to "Add ASP.NET Folder" then App_GlobalResources. Create a new file called Lang.resx. We've created a new resource file that will store all of our language strings. Let's add some. How about: LBL_LOCALIZED_TXT with a value of "A global localized English string" Now go back to GlobalExample.aspx and view the Source Code. For Label1's Text property, type in <%$ Resources: Lang, LBL_LOCALIZED_TXT %>. It should look like this:
<asp:label id="Label1" runat="server" text="<%$ Resources: Lang, LBL_LOCALIZED_TXT %>" />
Here you see I've used a super-secret awesome shorthand for referencing our Lang resource file. If you to do the equivalent programatically, type this in the Code view:
Label1.Text = Resources.Lang.LBL_LOCALIZED_TXT
Kind of nice, huh? Strongly typed resource files makes it real easy to programatically add text to your controls. In theory, you could create an array with all your control IDs and their corresponding resource string names and assign them their values that way (e.g. a label named "lblTextInfo" and a resource string entry "lblTextInfo"):
Label1.Text = Resources.Lang.ResourceManager.GetString(Label1.ID)
If you view GlobalExample.aspx in a web browser, you'll see it works perfectly. Now, let's localize! Create a duplicate of Lang.resx like we did before and rename it to Lang.es.resx. Type in something else for our label string. Go back to GlobalExample.aspx and add the two Page directives, UICulture="es" and Culture="es-MX". View the page in a browser. Voila! We've used one independent resource file as our container for localized strings. Now, let's see how we switch it up a bit like our last example. Here's the best part. Copy and paste both the Page_Load and InitializeCulture routines from Default.aspx.vb into GlobalExample.aspx.vb (remember to import System.Globalization and System.Threading) and run the project!
Protected Overrides Sub InitializeCulture() If Request.Form("Button1") IsNot Nothing Then Dim selectedLanguage As String = "en-US" UICulture = selectedLanguage Culture = selectedLanguage Thread.CurrentThread.CurrentCulture = _ CultureInfo.CreateSpecificCulture(selectedLanguage) Thread.CurrentThread.CurrentUICulture = New _ CultureInfo(selectedLanguage) End If MyBase.InitializeCulture() End Sub Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load Dim c As CultureInfo = CultureInfo.CurrentCulture lblCulture.Text = c.NativeName End Sub
You'll see that everything works just like it did in the last example. The only difference for this method is that we can have one resource file to hold all of our text strings. Maybe you want to organize it and create resource files for different kinds of text like "Links" and "Labels"; the possibilities are endless.

Final Thoughts

What have we learned? We learned about:
  • Using resource files
  • Changing a webpage or website's Culture
  • Programatically accessing a resource file
  • Programatically changing the current Culture
So which method is better? On one of my websites, I use Method 2. My dad uses Method 1 in his project at work and is very happy with the results. I don't advocate one method over the other, it's totally up to you. Maybe you have a small project so quickly generating resource files works just fine. Happy coding and if you have suggestions or opinions, don't hesitate to comment!

Labels: , ,

» Read more...

Thursday, February 14, 2008

ASP.NET Customizable Tag/Search Cloud

I use a keyword cloud for my BitTorrent website and I thought that it might be helpful for people to just have a customizable component to plop into their site, so they don't have to deal with the headache of all the calculations. So, welcome SearchCloud, a VB.NET Server Control for generating a tag or search cloud (or any cloud, for that matter). It's free and you can edit the source all you want. Just make sure you leave the credits, so that it gets back to here. This page will serve as the informational and support page for the component. Please let me know if there are any major bugs or major features you'd like me to add to the release. Features
  • Free Source Code or Component-Only
  • Generated by Dataset (use with XML, Databases, Programmatically Created, etc.)
  • Optional 2-Color Gradient Cloud
  • Various Font Size Units (em, px, pt, %)
  • Max and Min Font Sizes (in Hex format)
  • Sort by a field name, ascending or descending
  • Customizable URL w/ variables
  • Customizable Link Title Format w/ variables
  • Assignable CSS Class
  • Ability to add custom HTML attributes to links (w/ variables)
  • XHTML Valid and CSS Friendly
Download Last Updated: 2-14-08 Demo and Installation View Demo Here

To use this component, you need to copy the SearchCloud.dll DLL file to your bin directory. Once it is copied, open up the page you plan to implement the Cloud in and add this to the top:

<%@ Register assembly="SearchCloud" namespace="IntrepidStudios.SearchCloud" tagprefix="IS" %>

Then, implement the cloud by using this tag:

<is:cloud id="cloud1" runat="server" />
Before using it, you need to assign it a DataSource and some field names. To do so, open the code-behind of your page and use this code to activate the control:

Dim ds As New DataSet

Cloud1.DataIDField = "keyword_id" Cloud1.DataKeywordField = "keyword_value" Cloud1.DataCountField = "keyword_count" Cloud1.DataURLField = "keyword_url" Cloud1.DataSource = ds

You have to have a DataSet with keyword data to be able to use the control. This can come from a Database, XML file, or anything that can be translated into a DataSet. How to Customize

There are many different ways to customize the SearchCloud control. Let's break it down.

Required Attributes
  • DataSource
  • DataIDField
  • DataKeywordField
  • DataCountField
Optional Attributes
  • DataURLField
  • SortBy
  • MaxFontSize
  • MinFontSize
  • FontUnit
  • MaxColor
  • MinColor
  • KeywordTitleFormat
  • KeywordURLFormat
  • CssClass
  • Debug
Methods
  • AddAttribute
Required Attributes Datasource The dataset containing the keywords. For proper display, make sure integer value columns have the proper column type. DataIDField The column name corresponding to your keyword/tag ID DataKeywordField The column name corresponding to your keyword/tag title value DataCountField The column name corresponding to your keyword count value Optional Attributes DataURLField The column name corresponding to your keyword URL, if any. Default: None SortBy The DataView expression to use as a sort. Example: SortBy="keyword_count DESC" MaxFontSize The maximum font size (in value only) to render for the largest tag. Default: 22 MinFontSize The minimum font size (in value only) to render for the smallest tag. Default: 10 FontUnit The font CSS unit. Accepted values: pt, px, em, and %. Default: px. MaxColor The color to use for the largest tag. Must be in Hex format with leading #. Can be 3 or 6 digit. Default: #00f. Example: MaxColor="#fff" or MaxColor="#f93cd0" MinColor The color to use for the smallest tag. Must be in Hex format with leading #. Can be 3 or 6 digit. Default: #000. Example: MinColor="#fff" or MinColor="#f93cd0" KeywordTitleFormat The format to display the link's title attribute in. Accepts 4 variables.
  • %i = ID
  • %k = Keyword Value
  • %c = Keyword Count
  • %u = Keyword URL (if any)
Example: KeywordTitleFormat="%k appears %c times" KeywordURLFormat The format to display the link's href attribute in. Accepts 4 variables.
  • %i = ID
  • %k = Keyword Value
  • %c = Keyword Count
  • %u = Keyword URL (if any)
Example: KeywordURLFormat="/search/%k" CssClass Built-in ASP.NET attribute. Applies to the containing <div> element. Example: CssClass="cloud" will output:
<div class="cloud">cloud HTML</div>
Debug In Debug mode, the control will throw an actual ASP.NET exception instead of displaying a friendly error message. Unhandled errors will also throw a ASP.NET exception even if not in Debug Mode and if that happens, please report it below. Default: false. Example: Debug="true" Methods AddAttribute(attribute, value) This method allows you to add an HTML attribute to a keyword anchor tag. It must be called in the code. It accepts 4 variables.
  • %i = ID
  • %k = Keyword Value
  • %c = Keyword Count
  • %u = Keyword URL (if any)
Example: AddAttribute("onclick", "javascript:alert('You clicked: %k')") will generate:
<a href="link" title="title" onclick="javascript:alert('You clicked: keyword')">keyword</a>
Demo Code The code below is the source for default.aspx. It shows an example of using a default control and a customized control.
<%@ Page Language="VB" AutoEventWireup="false" CodeFile="default.aspx.vb" Inherits="projects_SearchCloud_default" %> <%@ Register assembly="SearchCloud" namespace="IntrepidStudios.SearchCloud" tagprefix="IS" %> <!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>ASP.NET Tag/Search Cloud Demo - SearchCloud Component - Intrepid Studios</title> <link rel="Stylesheet" href="/lib/css/base.css" /> <style type="text/css"> div.cloud { border:1px dotted #666; padding:20px; width:350px; font-family:Trebuchet MS, Arial, Verdana, Sans-Serif; } div.cloud a { text-decoration:none; } </style> </head> <body> <form id="form1" runat="server"> <h1>ASP.NET Tag/Search Cloud Server Control Demo</h1> <h2>Default Example</h2> <p>This is an example of a default tag/search cloud, with no customization.</p> <IS:Cloud ID="Cloud1" runat="server" /> <p></p> <h2>Customized Example</h2> <p>This is an example of a customized tag/search cloud.</p> <IS:Cloud ID="Cloud2" MaxColor="#339966" MinColor="#333399" MaxFontSize="250" MinFontSize="100" FontUnit="%" KeywordTitleFormat="%k appeared %c times" KeywordURLFormat="default.aspx?id=%i" SortBy="keyword_id DESC" CssClass="cloud" runat="server" /> </form> </body> </html>
The code below is for the default.aspx.vb or code-behind file. It demonstrates how to create a test DataSet and how to use the AddAttribute method.
Imports System.Data Partial Class projects_SearchCloud_default Inherits System.Web.UI.Page Sub Page_Load(ByVal s As Object, ByVal e As Object) Handles Me.Load ' Create Demo DataSet Dim ds As New dataset Dim dt As New DataTable Dim dr As DataRow Dim ki As String = "keyword_id" Dim kv As String = "keyword_value" Dim kc As String = "keyword_count" Dim ku As String = "keyword_url" dt.Columns.Add(ki, GetType(Integer)) dt.Columns.Add(kv) dt.Columns.Add(kc, GetType(Integer)) dt.Columns.Add(ku) ' Make Rows dr = dt.NewRow dr(ki) = 0 dr(kv) = "Pan's Labryinth" dr(kc) = 17 dr(ku) = "www.google.com" dt.Rows.Add(dr) dr = dt.NewRow dr(ki) = 1 dr(kv) = "Linkin Park" dr(kc) = 56 dr(ku) = "www.google.com" dt.Rows.Add(dr) dr = dt.NewRow dr(ki) = 2 dr(kv) = "Sony PSP" dr(kc) = 65 dr(ku) = "www.google.com" dt.Rows.Add(dr) dr = dt.NewRow dr(ki) = 3 dr(kv) = """Quotes""" dr(kc) = 50 dr(ku) = "www.google.com" dt.Rows.Add(dr) dr = dt.NewRow dr(ki) = 4 dr(kv) = "Unfathomably Long Name for a Product No One Knows About" dr(kc) = 12 dr(ku) = "www.google.com" dt.Rows.Add(dr) dr = dt.NewRow dr(ki) = 5 dr(kv) = "Generic Search Term" dr(kc) = 34 dr(ku) = "www.google.com" dt.Rows.Add(dr) dr = dt.NewRow dr(ki) = 6 dr(kv) = "/""'\\?:-0228" dr(kc) = 65 dr(ku) = "www.google.com" dt.Rows.Add(dr) dr = dt.NewRow dr(ki) = 7 dr(kv) = "Movies" dr(kc) = 16 dr(ku) = "www.google.com" dt.Rows.Add(dr) dr = dt.NewRow dr(ki) = 8 dr(kv) = "Music" dr(kc) = 29 dr(ku) = "www.google.com" dt.Rows.Add(dr) dr = dt.NewRow dr(ki) = 9 dr(kv) = "Fish" dr(kc) = 23 dr(ku) = "www.google.com" dt.Rows.Add(dr) ds.Tables.Add(dt) Cloud1.DataIDField = ki Cloud1.DataKeywordField = kv Cloud1.DataCountField = kc Cloud1.DataURLField = ku Cloud1.DataSource = ds Cloud2.DataIDField = ki Cloud2.DataKeywordField = kv Cloud2.DataCountField = kc 'Cloud2.DataURLField = ku Cloud2.DataSource = ds Cloud2.AddAttribute("onclick", "javascript:alert('Hello world. %i, %k, %u, %c');") Cloud2.AddAttribute("class", "tag") End Sub End Class
You can view the output of all this code on the demo page. If you need help or additional information, please leave a comment and I can create a FAQ.

Labels: , ,

» Read more...

Return to Navigation