Blog

Blogging on programming and life in general.

  • I recently needed to dynamically display a list of YouTube video’s from a specific YouTube account. If you plan to output the list of video’s straight from the YouTube’s RSS feed into your .NET application don’t bother. The RSS feed is not structured in a nice enough format to output all the information you may need with ease. For example, video ratings, time, etc are all in the same XML block.

    As you can see from the screenshot below, the ASP.NET page I created outputs all the information that you will probably want to show (if it doesn’t then it should give you a good starting point).

    YouTubeReaderScreenshot

    Before creating your own custom YouTube .NET application you will need to carry out two things:

    1. Go to the YouTube API Toolswebsite and download the “Google Data API SDK”. Once you have installed this on your computer. You will need to copy three dll’s from one of the sample projects:

      • Google.GData.Client.dll
      • Google.GData.Extensions.dll
      • Google.GData.YouTube.dll

      These dll's can be copied to your new project.

    2. Register a Developer Key. This is important! Without the developer key, your custom YouTube application will not work.

    To create the page (above), copy the following code:

    ASPX.CS Page

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    using System.Web.UI;
    using System.Web.UI.WebControls;
    using System.Xml;
    using System.Net;
    using System.IO;
    using System.Text.RegularExpressions;
    using Google.GData.Client;
    using Google.GData.Extensions;
    using Google.GData.Extensions.MediaRss;
    using Google.YouTube;
    using Google.GData.YouTube;
    using System.Text;
    using System.Data;
    
    public partial class _Default : System.Web.UI.Page
    {
        private string YouTubeChampionshipChannel;
        private string YouTubeClientID;
        private string YouTubeDeveloperKey;
        public string YouTubeMovieID;
        public DataTable dtVideoData = new DataTable();
    
        protected void Page_Load(object sender, EventArgs e)
        {
            //Pass User Name to the YouTube link
            YouTubeChampionshipChannel = "MotoGP";
    
            //Add the YouTube Developer keys.
            //Register a Developer Key at: http://code.google.com/apis/youtube/dashboard
            YouTubeClientID = "test";
            YouTubeDeveloperKey = "testabc123";
    
            CreateVideoFeed();
    
            //Assign the first video details on page load.
            if (String.IsNullOrEmpty(YouTubeMovieID))
            {
                YouTubeMovieID = dtVideoData.Rows[0]["VideoID"].ToString();
                lblDescription.Text = dtVideoData.Rows[0]["Description"].ToString();
            }
    
        }
    
        private void CreateVideoFeed()
        {
            YouTubeRequestSettings settings = new YouTubeRequestSettings("MotoGP Channel", YouTubeClientID, YouTubeDeveloperKey);
            YouTubeRequest request = new YouTubeRequest(settings);
    
            //Link to the feed we wish to read from
            string feedUrl = String.Format("http://gdata.youtube.com/feeds/api/users/{0}/uploads?orderby=published", YouTubeChampionshipChannel); ;
                    
            dtVideoData.Columns.Add("Title");
            dtVideoData.Columns.Add("Description");
            dtVideoData.Columns.Add("DateUploaded");
            dtVideoData.Columns.Add("Ratings");
            dtVideoData.Columns.Add("NoOfComments");
            dtVideoData.Columns.Add("VideoID");
            dtVideoData.Columns.Add("Duration");
    
            DataRow drVideoData;
    
            Feed<Video> videoFeed = request.Get<Video>(new Uri(feedUrl));
    
            //Iterate through each video entry and store details in DataTable
            foreach (Video videoEntry in videoFeed.Entries)
            {
                drVideoData = dtVideoData.NewRow();
    
                drVideoData["Title"] = videoEntry.Title;
                drVideoData["Description"] = videoEntry.Description;
                drVideoData["DateUploaded"] = videoEntry.Updated.ToShortDateString();
                drVideoData["Ratings"] = videoEntry.YouTubeEntry.Rating.Average.ToString();
                drVideoData["NoOfComments"] = videoEntry.CommmentCount.ToString();
                drVideoData["VideoID"] = videoEntry.YouTubeEntry.VideoId;
                drVideoData["Duration"] = videoEntry.YouTubeEntry.Duration.Seconds.ToString();
    
                dtVideoData.Rows.Add(drVideoData);            
            }
    
            repVideoList.DataSource = dtVideoData;
            repVideoList.DataBind();
        }
    
        protected void repVideoList_ItemDataBound(object sender, RepeaterItemEventArgs e)
        {
            if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
            {
                DataRowView drVideo = (DataRowView)e.Item.DataItem;
    
                LinkButton showVideo = (LinkButton)e.Item.FindControl("btnShowVideo");
                Literal title = (Literal)e.Item.FindControl("Title");
                Literal description = (Literal)e.Item.FindControl("Description");
                Literal ratings = (Literal)e.Item.FindControl("Ratings");
                Literal noOfComments = (Literal)e.Item.FindControl("NoOfComments");
                Literal duration = (Literal)e.Item.FindControl("Duration");
    
                showVideo.CommandArgument = drVideo["VideoID"].ToString();
                title.Text = drVideo["Title"].ToString();
                description.Text = drVideo["Description"].ToString();
                ratings.Text = drVideo["Ratings"].ToString();
                noOfComments.Text = drVideo["NoOfComments"].ToString();
                duration.Text = drVideo["Duration"].ToString();
    
            }
        }
        protected void repVideoList_ItemCommand(object source, RepeaterCommandEventArgs e)
        {
            // Pass the YouTube movie ID to flash
            YouTubeMovieID = e.CommandArgument.ToString();
    
            if (YouTubeMovieID == e.CommandArgument.ToString())
            {
                lblDescription.Text = ((Literal)e.Item.FindControl("Description")).Text;
            }
    
        }
    }
    

    ASPX Page

    <%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_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>
    </head>
    <body>
        <form id="form1" runat="server">
        <div style="margin: 10px;">
            <div style="float: left; width: 300px; height: 400px; overflow: scroll;">
                <asp:Repeater ID="repVideoList" runat="server" OnItemDataBound="repVideoList_ItemDataBound"
                    OnItemCommand="repVideoList_ItemCommand">
                    <HeaderTemplate>
                        <table>
                    </HeaderTemplate>
                    <ItemTemplate>
                        <tr>
                            <td>
                                <asp:LinkButton ID="btnShowVideo" runat="server">Show Video</asp:LinkButton>
                                <br>
                                <strong>
                                    <asp:Literal ID="Title" runat="server"></asp:Literal></strong>
                                <br />
                                <asp:Literal ID="Description" runat="server"></asp:Literal>
                                <br />
                                Rating: <asp:Literal ID="Ratings" runat="server"></asp:Literal>
                                <br />
                                Comments: <asp:Literal ID="NoOfComments" runat="server"></asp:Literal>
                                <br />
                                Duration: <asp:Literal ID="Duration" runat="server"></asp:Literal>
                                <br />
                                <br />
                            </td>
                        </tr>
                    </ItemTemplate>
                    <FooterTemplate>
                        </table>
                    </FooterTemplate>
                </asp:Repeater>
            </div>
            <div style="float: left; margin-left: 15px;width:600px;2">
                <object width="480" height="385" style="float: left; clear: both; margin-bottom: 10px;">
                    <param name="movie" value="http://www.youtube.com/v/<%=YouTubeMovieID %>&hl=en&fs=1&rel=0">
                    </param>
                    <param name="allowFullScreen" value="true"></param>
                    <param name="allowscriptaccess" value="always"></param>
                    <embed src="http://www.youtube.com/v/<%=YouTubeMovieID %>&hl=en&fs=1&rel=0" type="application/x-shockwave-flash"
                        allowscriptaccess="always" allowfullscreen="true" width="480" height="385"></embed>
                </object>
                <div style="float: left;">
                    <asp:Label ID="lblDescription" runat="server"></asp:Label>
                </div>
            </div>
        </div>
        </form>
    </body>
    </html>
    

    This is just the beginning on what the YouTube API has to offer. For more information, visit the YouTube API website (http://code.google.com/apis/youtube/2.0/developers_guide_dotnet.html).

    * Post Updated 18/06/2009 – You can output YouTube video’s via RSS feed *

  • In Windows XP you had the option to analyse a disk drive you wished to defragment without carrying out a full disk defragmentation. Looking at the Windows Vista Disk Defragmenter GUI at face value I thought this feature was left out. After some research, I found that this  this feature has been included but you will be forgiven for not knowing where it is. Fortunately, using the command line tool does allow you to analyse a drive. It is as simple as typing the following:

    1. Open up Command Line tool.

    2. Type the following: defrag –a <disk drive letter>

    3. Press enter and you will see the following:

    Microsoft Windows [Version 6.0.6000]
    Copyright (c) 2006 Microsoft Corporation.  All rights reserved.
    
    C:\Users\Surinder>defrag -a c:
    Windows Disk Defragmenter
    Copyright (c) 2006 Microsoft Corp.
    
    Analysis report for volume C:
    
        Volume size                         = 298 GB
        Free space                          = 236 GB
        Largest free space extent           = 136 GB
        Percent file fragmentation          = 1 %
    
        Note: On NTFS volumes, file fragments larger than 64MB are not included in the fragmentation statistics
    
        You do not need to defragment this volume.
    

    Neato!!

  • I needed a flash movie to displayed at 100% in my web page. I thought this will be a simple job. Just set the height and width attributes within my object tag to “100%”. This method worked fine for Internet Explorer but failed in Firefox. Firefox seemed to ignore my size settings that contained a percentage. After a lot of time wasting, I confirmed that Firefox does not like its height and width attributes measured in percentages and only likes measurements in pixels.

    In order to fix this problem I needed to do the following:

    1. Write some JavaScript just for Firefox so that it will get the users screen resolution in pixels and add this into my object tag that contained my Flash movie.
    <script type="text/javascript" language="javascript">
            if (window.innerWidth)
            {
                // Get screen width and height minus scroll bars
                var width = window.innerWidth - 24;
                var height = window.innerHeight - 24;           
                    
                //Find Flash movie
                var FlashMovie = document.getElementById('FlashMovie');           
    
                //Only assign width and height if browswer is not Internet Explorer
                if (navigator.appName.indexOf('Internet Explorer') == -1)
                {
                    FlashMovie.height = height;
                    FlashMovie.width = width;        
                }
            }       
    </script>
    
    1. Keep the height=”100%” width=”100%” object attributes. This will be needed for Internet Explorer.
    <object id="FlashMovie" type="application/x-shockwave-flash" height="100%" width="100%" data="myflash.swf">
        <param name="movie" value="myflash.swf" />
        <param name="wmode" value="transparent" />
        <p>
            No flash message
        </p>
    </object>
    

    If anyone has any better idea on how to solve this problem. Please comment. Thanks!

  • I currently have a SharePoint 2007 demonstration setup on a development environment. The SharePoint 2007 installation was originally setup for a specific client. So the host headers, computer name and farm credentials contained the client name. This all had to be changed. Carrying out another installation of SharePoint was something I did not want to do since I wanted to retain all the dummy data and sites.

    You might be thinking: Why don’t I just change the host headers with the new client name? Well that’s because I am a bit OCD and I like everything to be consistent. Tongue out

    To rename, carry out the following. But remember to carry out these steps exactly because you might come across the problem I did where I couldn’t get to Central Admin or view my Intranet:

    1. Go to Central Admin > Operations > Alternate Access Mappings.
    2. Change the host headers as required.
    3. If you changed the name of the server carry out the following command:
    stsadm -o renameserver -oldservername <oldname> -newservername <newname>
    
    1. Rename the server to a new server name by going to My Computer > Properties > Computer Name and restart.
    2. After restart you will need to update the farm login credentials since the computer name has been changed from Steps 3 and 4. If you do not update the farm credentials, you will get the dreaded “Cannot connect to database” message when trying to view your Intranet.
    stsadm -o updatefarmcredentials -userlogin <domain\user> -password <password>
    
    1. Change the site names in IIS. This site names will need to reflect the changes you made in Step 1.
    2. Change the host headers in the host file (C:\Windows\System32\drivers\etc\hosts).
  • ASP.NET Membership Provider makes implementing secure authenticating membership forms more straightforward. The ASP.NET Membership Provider contains so many useful methods. But I could not find a method within the Membership class to check whether there was an existing email address in the database even though you can state in the web.config (requiresUniqueEmail) file:

    <membership>
      <providers>
        <add
          name="SqlMembershipProvider"
          type="System.Web.Security.SqlMembershipProvider, ..."
          connectionStringName="LocalSqlServer"
          enablePasswordRetrieval="false"
          enablePasswordReset="true"
          requiresQuestionAndAnswer="true"
          applicationName="/"
          requiresUniqueEmail="true"
          passwordFormat="Hashed"
          maxInvalidPasswordAttempts="5"
          minRequiredPasswordLength="7"
          minRequiredNonalphanumericCharacters="1"
          passwordAttemptWindow="10"
          passwordStrengthRegularExpression=""
        />
      </providers>
    </membership>
    

    I created the following CustomValidator with a ServerValidate event to carry out the duplicate email check:

    protected void DuplicateEmailCheck_ServerValidate(object source, ServerValidateEventArgs args)
        {
            //Create MembershipUserCollection to collate a list of duplicate email addresses
            MembershipUserCollection memCollection = Membership.GetUserNameByEmail(args.Value.ToString());
    
            //If duplicate email addresses are found then error
            if (memCollection.Count > 0)
            {
                args.IsValid = false;
            }
            else
            {
                args.IsValid = true;
            }
        }
    
  • I came across a problem today when trying to find an effective way to validate the length of a password field within a registration form I was creating. ASP.NET already has a bunch of useful validation controls. Most of which I have already have in use within my registration form, such as the RequiredFieldValidator, CompareValidator and RangeValidator.

    Now you might be thinking. What’s your problem dude? Its not hard to validate the length of a field. Yeah, you are right. But all the validation controls I am using (above) do not create post backs. I could have easily created a CustomValidator control to solve my problem, but this only fires once a post back has occurred.

    I guess my only solution is to use a RegularExpressionVaildator which meant I had to do some research into RegEx. To use RegEx to validate the length of a string between 0 and y (some number), use the following expression:

    .{0,y}
    

    To validate the exact length, use the following expression:

    .{y}
    

    Both example’s above will accept any type of characters entered in the field.

  • Published on
    -
    1 min read

    I Feel It's Going Down 10 Feet Below The Ground

    microsoft_vista-logo Since the middle of 2008 we have seen that quite a few business have been hard hit by the recession we are currently experiencing. Things are set to get worse in 2009. Who would have thought that out of all the businesses in the world that the Microsoft monopoly would somehow be effected. I was quite surprised to read speculation across the web that for the first time ever in Microsoft's 33 year history,  15,000 of its employees across US and overseas divisions could be laid off and 3,000 UK employees face an uncertain future.

    Well I suppose this was bound to happen sooner or later since retail spending has been reduced and consumers are opting for open source operating systems such as Linux. You cannot beat getting something for free! Microsoft operating system, corporate and office licences could also suffer a hit due to businesses scaling down costs. Maybe if Microsoft stopped releasing crap bug filled software (like Windows Vista) they could have reduced their costs.

    Many companies are not even touching Windows Vista with a barge pole, due to the performance hungry features and poor reception. Generally, companies normally delay upgrading their operating systems, since they need to justify the impact on the business and of course costing's. There have been reports that Vista is installed on considerably fewer enterprise PCs than originally projected. Oop's, I went off on a bit of a tangent. Window's Vista really annoys me!!!

    Anyway, if Microsoft do go ahead with the redundancies, internetnews.com states that under performing areas, such as Entertainment and Devices Division and the Online Business Division will face the most brutal cuts.

  • Published on
    -
    1 min read

    Free McAfee Internet Security 2009

    McAfee-Internet-Security-2009-Free-3-Months-Trial What a way to start the new year with some free software (and I am talking the legal way). I found that my current PC Internet Security was soon to expire. Instead of renewing my existing Bullguard licence, I decided it was time for a change after being a loyal three year customer mainly because the yearly fee was starting to get a bit too expensive compared to other packages on the market.

    As usual I always look at the customer reviews on the Amazon web site, which is always useful. But this time I found one the reviews someone written more useful than others. It contained a coupon code for a free copy of McAfee Internet Security from the US McAfee website.

    All you need to do in order to get your free copy of McAfee Internet Security 2009 is to carry out the following:

    1. Go to http://us.mcafee.com/root/campaign.asp?cid=53347.
    2. Enter coupon code: VSPPROMOCF. You will magically see the Grand Total is now $0.00.
    3. Ensure that there is only one copy of Internet Security in your basket for one user.
    4. Click on the "Checkout" button and register your new account. This account will just contain details of when your year subscription will expire.

    Awesome!

    I am not too sure how long it is valid for. But give it a try. It worked for me!

  • If any of you have come across a problem in SharePoint 2003 whereby some users are not able to see a link to an area within the main portal page, the solution couldn't be even easier. Ensure all users required to access the area are setup with access rights for that area. I always thought that even if a user does not have access to an area the link will always be shown in the navigation within the main portal site. Obviously I was wrong. Silly me!

  • I always used NULL and DBNULL interchangeably in my coding around my database results without ever considering what were the differences. Fortunately, I stumbled upon a great blog written by Bilal Haidar, "Difference between NULL and DBNull"

    If I understand correctly, you use DBNULL to check if a certain field in a database is null and you would use NULL to check if a whole record is not found in the database.