Tuple

Tuple is a new class in the .Net 4.0 framework which allows you to hold up to 8 components in a single class.  The alternative is creating a specific class with properties for each component.  This makes this class ideal for the following situations:

1.  Returning multiple values from a method without the use of out parameters

2.  Pass multiple values to a method using a single class.

3.  Collections of Tuples can be used to represent database information or array data.

4.  Easy access and manipulation of a data set.

Here’s an example using Tuple<T1, T2>

class Program
    {
        static void Main(string[] args)
        {
            int dividend, divisor;
            Tuple<int, int> result;

            dividend = 136945; divisor = 178;
            result = IntegerDivide(dividend, divisor);
            if (result != null)
                Console.WriteLine(@"{0} \ {1} = {2}, remainder {3}",
                                  dividend, divisor, result.Item1, result.Item2);
            else
                Console.WriteLine(@"{0} \ {1} = <Error>", dividend, divisor);

            dividend = Int32.MaxValue; divisor = -2073;
            result = IntegerDivide(dividend, divisor);
            if (result != null)
                Console.WriteLine(@"{0} \ {1} = {2}, remainder {3}",
                                  dividend, divisor, result.Item1, result.Item2);
            else
                Console.WriteLine(@"{0} \ {1} = <Error>", dividend, divisor);

            Console.ReadLine();

        }

        private static Tuple<int, int> IntegerDivide(int dividend, int divisor)
        {
            try
            {
                int remainder;
                int quotient = Math.DivRem(dividend, divisor, out remainder);
                return new Tuple<int, int>(quotient, remainder);
            }
            catch (DivideByZeroException)
            {
                return null;
            }
        }

    }
Advertisements

Happy 1/1/11 11:11!

 

Happy new years everyone!

How to Add Icons to Blogroll Links

I figured out a tricky way to show a websites icon next to the link in your blog roll.  I’m using Firefox to do this.

1.  Go to website’s homepage.

2.  Right click in an empty space and select “View Page Info”.  It should be directly below “View Page Source”

3.  You should see a popup for something like this:

4.  Next, click on the “Media” tab and look for the line that ends with “…favicon.ico”.

5.  Now go to your blog dashboard and go to “Links”.

6.  Select or create the link for the website you want and scroll down to the Advanced section and paste the address in the first field for “Image Address”.

A Few Good Resources

These are some recent books I’ve read related to software.

Clean Code:  A Handbook of Agile Software Craftsmanship

I highly recommend this book.  Go to the Amazon link above to read more about.

The Design of Design – Essays from a Computer Scientist

An interesting book that discusses the various design approaches.

The Art of Unit Testing

The definitive book on how to properly unit test.

Head First Design Patterns

A straightforward reference to many design patterns with easy to understand examples and excellent descriptions.

Design Patterns:  Elements of Reusable Object-Oriented Software

Another excellent reference for many design patterns used in software today.

Boxee: Watch Movies, TV, Shows from the Internet on your TV

So this is another gadget I’ve been debating on trying out.  I canceled my cable last summer since there’s really nothing on over the summer.  I bought an HD antenna so I could pick up local news stations which covered nearly all the shows we watch.  The biggest gap was sports events covered on ESPN, ESPN2, Fox Sports, etc.  I figured I could spend the summer looking for a better solution than paying $80/month  for cable just to get a few channels.

I soon discovered that nearly all games were broadcast over the Internet.  Most games were offered by several sources which is important since some broadcasts are streamed at a low resolution.  ESPN3.com is one of my favorites since it’s usually very good quality and covers a variety of games.  So now that I’ve found a way to watch everything I want, I’m looking for an easy way to display it on my TV.

I waited for the new Apple TV to come out to see what features it offered.  It connects to your home network so you can access media, but you’re limited to what content you can watch.  Obviously, you could rent or buy from iTunes, but that’s not something I do very often.  You aren’t able to display any videos from the Internet unless there’s an app specifically for the site.   It’s$99 which is a great deal, but I’d probably only use it for Netflix.

I’m thinking Boxee by D-Link might be the answer.  It’s a small little box that connects to your TV and home network (wireless or wired)  so it can connect to the Internet.  It comes with a small keyboard also, so you can easily surf.  It offers access to your media on you computers hard drive so you can streams, videos, movies, and music to you TV.  It also has hundreds of apps like Pandora and Netflix to stream even more content.  It’s currently $199 on Amazon.com at the top of my wish list 🙂

Here’s the product description from Amazon:

“The D-link DSM380 Boxee Box HD Media Player! watch, organize, share – you are now in full control of your TV for the first time. The freedom to watch what you want. It’s thousands of TV shows ready to watch, instantly. It’s tons of free movies, Hollywood blockbusters, and critically acclaimed films. It’s your videos, your Pandora and Facebook feeds somewhere they’ve never been before – your HDTV: organized, simplified and enjoyed from the comfort of your couch in 1080p. No keyboard or mouse required. Do what more than a million users have already done – download the D-link DSM380 Boxee Box HD Media Player’s software and try it for free on your computer first, we’ll automatically import your account when you’re ready to bring the Boxee Box experience to your HDTV. The D-link DSM380 Boxee Box HD Media Player delivers freedom of the Internet to your HDTV in stunning 1080p, Dolby Surround Sound, and a slick interface with a remote to simplify everything.”

 

On Demand TV
Thousands of shows available for free from your favorite networks, ready to watch any time
Huge Movie Library
Enjoy free movies from the web & watch new releases in stunning HD from premium movie services
Play Your Stuff Too
Access videos, songs, or pictures from your computer or home network
See What Your Friends are Watching
Follow what your Facebook and Twitter friends are watching, and share your favorites too
Give Your Wallet a Break
Get tons of free entertainment from the Internet with no monthly fee
The Holy Grail of Resolution
Experience the thrill of 1080p – that’s more than twice the resolution of 720p

Tailored to Your Couch

The Internet gives you the freedom to watch what you want, and the power to choose what you want to pay for. It’s awesome. What’s not awesome about the internet: no big screen, no HD, no home theater experience, no easy interface designed to sift through the mountains of TV shows, Movies, and content available online. And the real killer: no remote. If only there was a little box that brought the freedom of the Internet to your HDTV in stunning 1080p, Dolby Surround Sound, and had a slick interface to simplify everything and – wait for it, a remote to put it all at the tips of your fingers. Too bad nobody has thought of that yet. Oh wait, we did. Haha! Ahem – The Boxee Box, by D-Link, featuring our ingenious two-faced remote. Say goodbye to hunting and pecking for letters on screen, the Boxee Box remote comes with a full QWERTY keypad – as soon as you start typing Boxee Box’s autosearch function starts finding.

Setup? No Biggie!

Setting up your Boxee Box is a cinch. Plug your Boxee Box into the wall, connect it to your TV’s HDMI input and turn your Boxee Box on. Oh, please turn on your TV too, thanks. Make sure your TV is getting the signal from its HDMI input – if it is, you’ll see Boxee smiling at you :). Grab the remote and follow the on-screen instructions – that’s it! Boxee Box will automatically configure your internet connection, tune itself to your home entertainment system, and get you up and running in a flash. Already a Boxee user? Schweet!! Boxee Box will automatically start importing your account. See! It is a No Biggie!!

More of a visual person? Click here.

Product Specs

  • Dimensions (LxWxH): 4.5″ x 4.5″ x 4.6″
  • Language Support: English, French, German, Italian, Spanish
  • Network Protocol Support: IPV4, ARP, TCP, UDP, ICMP, DHCP Client, DNS Client, DDNS Client, HTTP Server, Samba Client, RTP/RTMP, VPN: PPTP, DLNA 1.5 (DMP)
  • Wireless: 802.11n/g/b
  • Ports: HDMI 1.3, 10/100 Fast Ethernet, 2x USB 2.0, Optical Audio (S/PDIF), Analog Audio (RCA L/R)
  • Memory Card Support: SD, SDHC up to 32GB, MMC
  • Audio Formats: MP3, WAV/PCM/LPCM, WMA, AIF/AIFF, AC3/AAC, OGG, FLAC, Dolby Digital/Dolby True HD
  • Video Formats: Adobe Flash 10.1, FLV/On2 VP6 (FLV/FV4/M4V), H.264 AVC (TS/AVI/MKV/MOV/M2TS/MP4), VC-1 (TS/AVI/MKV/WMV), MPEG-1 (DAT/MPG/MPEG), MPEG-2 (MPG/MPEG/VOB/TS/TP/ISO/IFO), MPEG-4 (MP4/AVI/MOV), DivX 3/4/5/6 (AVI/MKV), Xvid (AVI/MKV), WMV9 (WMV/ASF/DVR-MS)
  • Image Formats: JPEG, PNG, GIF, BMP, TIFF
  • Playlist Formats: M3U, PLS, WPL
  • Subtitle Formats: SRT, SUB, SSA, SMI, ASS
  • Supported Resolutions: H.264: 1080p at 30 fps, 1080i at 60 fps; WMV9/VC-1: 1080p at 30 fps, 1080i at 60 fps; MPEG4: 1080p at 30 fps, 1080i at 60 fps; MPEG2: 1080p at 30 fps, 1080i at 60 fps
  • Two-Sided RF Remote: with 4-way navigation and full QWERTY keypad

What’s In the Box

  • The Boxee Box by D-Link
  • 1x HDMI Cable
  • 1x AC Power Adapter
  • Remote Control with Full QWERTY keypad

ThreadPool

I discovered this class the other day.  It’s actually been around for a while as part of the .NET 2.0 framework.  You can use it to run a method in a different thread.  Here’s a description from the MSDN site.

A thread pool is a collection of threads that can be used to perform a number of tasks in the background. (See Using Threading for background information.) This leaves the primary thread free to perform other tasks asynchronously.

Thread pools are often employed in server applications. Each incoming request is assigned to a thread from the thread pool, so the request can be processed asynchronously, without tying up the primary thread or delaying the processing of subsequent requests.

Once a thread in the pool completes its task, it is returned to a queue of waiting threads, where it can be reused. This reuse enables applications to avoid the cost of creating a new thread for each task.

Thread pools typically have a maximum number of threads. If all the threads are busy, additional tasks are placed in queue until they can be serviced as threads become available.

Here’s a very simple example that illustrates how the main execution thread continues without waiting for the “DoSomething” thread to complete.  ≈

    class ThreadPoolExample
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Start");
            ThreadPool.QueueUserWorkItem(new WaitCallback(DoSomething), args);

            Console.WriteLine("Finish");

            Console.ReadLine();
        }

        private static void DoSomething(object args)
        {
            for (int i = 0; i < 10; i++)
            {
                Thread.Sleep(100);
                Console.WriteLine(i);
            }
        }
    }

Here’s the output:

 

 

 

 

 

 

If we needed to know when the work was finished from Threadpool, then a ManualResetEvent could be passed into a WaitHandle like the example described here.

A Few .NET String Functions (Split, Join, IsNullOrEmpty, IsNullOrWhiteSpace)

Here’s some of my favorite String functions in .NET.

    class StringFunctions
    {
        static void Main(string[] args)
        {
            // Check for Null or Empty
            const string emptyString = "";
            if (String.IsNullOrEmpty(emptyString))
                Console.WriteLine("String is Empty or Null");

            // Join an array of integers together
            Collection array = new Collection() { 1, 2, 3 };
            Console.WriteLine(String.Join(",", array));

            // Split a string into an array
            ICollection fullStringArray = "The cat in the hat".Split(' ');
            foreach (var element in fullStringArray)
                Console.WriteLine(element);

            // Split ignoring emtpy spaces
            const string numberList = "1,2,3,4,,6";
            ICollection trimmedStringArray = numberList.Split(new[] { ',' }, numberList.Length, StringSplitOptions.RemoveEmptyEntries);
            foreach (var element in trimmedStringArray)
                Console.WriteLine(element);

            Console.ReadLine();
        }
    }

Output:

 

 

 

 

 

 

Here’s a link to an article with more examples for Split.

IsNullOrWhiteSpace is new in .NET 4.0. It’s similar to IsNullOrEmpty, but it also will catch strings that contain only empty spaces. In prior versions, you would have to trim the string prior to calling IsNullOrEmpty if you wanted to treat strings with only empty spaces as empty strings.