Chinh Do

Create a Temporary File in PowerShell

First time here? Check out my greatest hits or look around in the archives, and consider subscribing to the latest posts via RSS or email. I am also on Twitter and Google Plus. Thanks for visiting.
10th December 2009

Create a Temporary File in PowerShell

$tempFile = [IO.Path]::GetTempFileName()

An empty file created immediately when you call this method. Remember to clean it up when are you done!

image

posted in PowerShell, Programming | 0 Comments

12th November 2009

7-Zip Can Be Used to Open ISO Archives

Did you know that 7-Zip can open and extract ISO archives? I had to install OneNote today from the MSDN ISO and I didn’t have an virtual drive/ISO mounting tool installed on my work PC. So I tried to open the ISO in 7-Zip and it opened it just fine. All I then had to do was to extract the files to a temp folder and did the install from there.

image

posted in Software/tools, Technology, Tips | 0 Comments

16th June 2009

CircuitCity.com Comes Back from the Dead

I used to shop at Circuit City a lot and I kind of miss it now that it’s gone. I live in Richmond’s West End where there used to be two big Circuit City stores within a few miles of each others. Today I got an email from CircuitCity.com and it looks like the web site now has a new owner.

image

A few months ago when they were having the liquidation sale at one of their headquarter buildings, I came in, bought a few things, and took a few pictures. Having gone through a dotcom bust earlier in my career, the site actually looked eerily familiar.

Circuit City Headquarter

Circuit City Headquarter

Circuit City Headquarter 

20090226-IMG_1386

posted in Uncategorized | 0 Comments

2nd April 2009

Convert List<T>/IEnumerable to DataTable/DataView

Here’s a method to convert a generic List<T> to a DataTable. This can be used with ObjectDataSource so you get automatic sorting, etc.

/// <summary>
/// Convert a List{T} to a DataTable.
/// </summary>
private DataTable ToDataTable<T>(List<T> items)
{
    var tb = new DataTable(typeof (T).Name);

    PropertyInfo[] props = typeof (T).GetProperties(BindingFlags.Public | BindingFlags.Instance);

    foreach (PropertyInfo prop in props)
    {
        Type t = GetCoreType(prop.PropertyType);
        tb.Columns.Add(prop.Name, t);
    }


    foreach (T item in items)
    {
        var values = new object[props.Length];

        for (int i = 0; i < props.Length; i++)
        {
            values[i] = props[i].GetValue(item, null);
        }

        tb.Rows.Add(values);
    }22/

    return tb;
}

/// <summary>
/// Determine of specified type is nullable
/// </summary>
public static bool IsNullable(Type t)
{
    return !t.IsValueType || (t.IsGenericType && t.GetGenericTypeDefinition() == typeof(Nullable<>));
}

/// <summary>
/// Return underlying type if type is Nullable otherwise return the type
/// </summary>
public static Type GetCoreType(Type t)
{
    if (t != null && IsNullable(t))
    {
        if (!t.IsValueType)
        {
            return t;
        }
        else
        {
            return Nullable.GetUnderlyingType(t);
        }
    }
    else
    {
        return t;
    }
}
  • 1/22/2010 – Fix to support Nullable types.

posted in Dotnet/.NET - C#, Programming | 42 Comments

31st March 2009

Problem with jqModal/jQuery JavaScript Intellisense and Workaround

Is anyone else experiencing a problem with Visual Studio 2008 Intellisense with jQuery and jqModal?

It seems that jqModal (a jQuery plugin for modal dialogs) is breaking jQuery Intellisense on my Visual Studio 2008 setup. Without a reference to jqModal.js, jQuery Intellisense works fine:

image

As soon as I add the reference to jqModal.js, the Intellisense stops working with this error:

Warning    1    Error updating JScript IntelliSense: …\scripts\jquery-1.3.2-vsdoc.js: ‘jQuery.support.htmlSerialize’ is null or not an object @ 1430:4

Workaround

To work around the problem, generate the script include tag dynamically so that the JavaScript Intellisense engine doesn’t see the jqModal reference at design time.

<head runat="server">
    <title>My Web</title>
    <asp:Literal ID="LitJqModalScript" runat="server"></asp:Literal>
    <script src="../scripts/jquery-1.3.2.js" type="text/javascript"></script>
</head>

 

protected override void OnLoad(EventArgs e)
{
    base.OnLoad(e);
 
    LitJqModalScript.Text = @"<script src=""../scripts/jqModal.js"" type=""text/javascript""></script>";
}

posted in Dotnet/.NET - C#, Programming | 5 Comments

23rd February 2009

My Multiple-Monitor Programming Setup

In my opinion, the top three hardware items that help maximize programmer productivity are sufficient RAM, multiple monitors, and a fast multi-core CPU. For RAM, try to have at least 2GB for Visual Studio development, especially if you have additional applications such as Resharper, a local SQL Server instance, IIS, etc. Remember that on Windows XP or Vista 32-bit, the maximum usable RAM is limited to about 3.2 GB or so.

My current company-provided laptop, which I must perform most programming activities on, is a Core 2 Duo 2.4 Ghz. It is satisfactory for what I am doing. Given the choice however, I would go for a quad-core CPU desktop. Desktop usually has faster drives, better video cards, etc. And the additional cores allow for smooth multitasking and better performance when using virtual machines.

image

Plenty of RAM and multiple fast CPU cores will keep the waiting down to a minimum. Now you need to give yourself the ability to see all of those things that you have going on. Research has demonstrated that multiple monitors increase productivity. For most programmers, I would recommend two monitors. Adding that second monitor is a relatively inexpensive affair. Most laptops or desktop video cards has built-in support for a second monitor so all you have to do is getting that second LCD, which cost very little these days compared to three years ago. The third monitor and beyond is where things start to get complicated. You either have to install a second video card, or use a second PC/laptop in conjunction with a software application named MaxiVista. Unless you have spare monitors sitting around, I think the return on investment starts to diminish greatly beyond two monitors.

Another way to use that third or fourth monitor is to simply attach them to additional computers. Sure, you won’t be able to control all those monitors with the same mouse and keyboard but this setup is not without advantages:

  • When the first computer is rebooting or not responding, you still have a fully functioning computer.
  • The screens on the second computer are not using CPU/memory resources on the first computer.

My 5-Monitor Setup

I work from home most of the time and on my desk, there are five monitors, hooked up to three laptops. I know… it’s over the top but it’s not like I bought all of these laptops/monitors specifically for this setup. The second laptop is my personal laptop. The third one is another old personal laptop that would otherwise would be sitting around gathering dust. I might as well put them all to use. Here’s how the monitors are arranged:

image

The main laptop is hooked up to monitor #1, an ASUS 24″ running at 1920×1080 resolution and monitor #2, the main laptop’s built-in 15.4-inch LCD running at 1680×1050. I spend most of my time on these two monitors. The ASUS 24″ is great for programming/debugging and is where I normally park Visual Studio 2008 or Rational Software Architect. If you can get one with more vertical resolution (such as 1920×1200), that’s even better.

Visual Studio

The extra width on the main monitor allows me to permanently open supporting panes like Solution Explorer that I otherwise would configure to “auto hide”. Note where I have my Start menu: on the right edge of the main monitor. This gives me more vertical space so I can see more code without scrolling. The additional benefits are that more opened windows can fit on the task bar, and that I don’t have to move the mouse as much to access the start menu.

The built-in laptop monitor (#2) is where I have miscellaneous supporting windows such as rolling logs, instant messaging client, email client, documents, etc.

For taking notes, I use Microsoft OneNote and since it’s not installed on my company PC, I use my own laptop for it. This laptop is monitor #3, sitting to the left of the main monitor. Monitors #4 and #5 are used once in a while to display server logs, various server telnet and remote desktop connections, and anything I don’t need to control often.

Update 2/25/2008 – Synergy

Rohan kindly pointed out to me a free keyboard/mouse sharing utility called Synergy. You should give this a try if you have multiple computers on your desk. Synergy lets you use a single keyboard/mouse to control multiple computers, running multiple operating systems. Additional features include clipboard sharing, screen saver, and single password login. The configuration is not the most intuitive but once you have everything set up correctly, it works like a charm.

I now can control all three laptops and 5 monitors with one mouse/keyboard combo! Very nice.

Synergy animation

posted in Dotnet/.NET - C#, Java, Programming, Software/tools, Technology, Tips | 7 Comments

12th February 2009

Bag of Links #2

.NET/C# Programming

PowerShell

Apps and Tools

Other Stuff

posted in Dotnet/.NET - C#, Links, PowerShell, Programming, Silverlight, Software/tools, Technology | 0 Comments

6th February 2009

Learning Java from a .NET Developer’s Perspective

I feel like I am discovering a whole new world. For my latest project, I have to do a lot of stuff in Java (1.6). While I am familiar with Java the language, I am a total newbie when it comes to Java related technologies, frameworks, and tools. Some of the specific Java technologies and tools I am using are JAXB/JAX-WS web services, Spring Framework, WebSphere Application Server, Maven, Rational Software Architect/Eclipse IDE.

Java Learning Resources

Here are some of the resources I found very useful while learning Java and related technologies in the past several weeks:

Portals

  • Java.sun.com – From the creator of Java itself.
  • Dzone – It’s like DotNetKicks but has everything including Java stuff.
  • IBM Redbooks – Tons of reference materials and everything is free.
  • developerWorks: IBM’s version of MSDN. There is a busy community section with forums as well.
  • Safari Books Online offers on-demand digital access to reference books. It’s not free, but it’s a great resource if you can read lots of books in a short time. Subscribe to their unlimited account and read all the books you want for a month. Remember to cancel before the month is over. Also remember that IBM Redbooks are free on the Redbooks site. Don’t waste your Safari points on Redbooks. And even if you have an unlimited Safari account, IBM’s site is still better because it offers PDFs.

Java

Web Services

Spring Framework

Eclipse IDE, Rational Software Developer/Architect

Misc

C# Features I Wish Java Has

I am sure Microsoft was pretty much thinking about Java when they created C#. The Java language itself it very similar to C# in terms of syntax, keywords, and use of punctuations such as semicolons and braces. I have found that most language features in C# have equivalents in Java. However, there are a few notable exceptions which I particularly miss:

  • Code regions – I use code regions extensively in C#. Eclipse does support code outlining but it’s only for existing code structures (methods) and is not nearly as flexible as c# regions.
  • Properties – Java only has fields and methods. “Properties” are implemented as get* and set* methods. I really miss properties, especially after typing 10 getters and setters in a row.
  • var keyword – Another small but very nice feature in C# that helps make code more compact and reduce typing.
  • Verbatim (@) strings – Very handy for regular expressions and other string literals that contain lots of escape characters.

Java is still evolving. Here’s hoping that some of the above features will make it into the next version of the language.

posted in Dotnet/.NET - C#, Java, Programming | 9 Comments

5th February 2009

Wrap Your Unit Tests in Transactions

I have found that the key to writing good unit tests that interact with the database is making sure that the data is in a known state before and after the test. System.Transactions makes this very easy. All you have to do is wrap your unit test inside a TransactionScope and rollback at the end.

For example, in the test below, I am testing the update feature of my Customer data access class. To make sure I have a customer to update, I create it myself at the start of test, then I update it. At the end, scope.dispose() rolls back the whole thing. The database should look exactly like it was before my test.

[TestMethod]
public void CanUpdateCustomer()
{
    using (TransactionScope scope = new TransactionScope) {
        Customer customer = CreateTestCustomer();
        customerDac.saveCustomer(customer);
 
        customer.Phone1 = "804-555-1212";
        customerDac.updateCustomer(customer);
 
        // TODO: verify that update works
 
        scope.Dispose(); // roll back
    }
}

Here are a few more tips I have for unit tests that interact with the database:

  • Maintain scripts to create/rebuild a starting-point database. The starting-point database may contain some data such as lookup data, codes, etc. If your unit tests work correctly, the database will stay the same across tests. With the rebuild scripts, you can easily rebuild in the case of other mishaps or a bug in one of the unit tests causing corrupt data.
  • If you need to create a database record that doesn’t have an auto-generated key, use a random key to minimize the chance that your test will collide with another test running somewhere else. Seed your random generator with Environment.TickCount or a hash code of the machine name or user name.
  • With my Transactional File Manager, you can also restore the state of the file system in addition to the database. Transactional File Manager is great at automatically cleaning up any temporary files you create in your unit tests.
  • Don’t assume your code is the only thing that is touching the database. If the count of records in a table is x, it won’t necessarily be x + 1 after you add a new record to the table. Somebody else may have added to or deleted from the table while your test is running.

For Java programmers, try using Spring TestContext Framework. It’s a bit more complicated to use but it works just as well.

kick it on DotNetKicks.com

posted in Dotnet/.NET - C#, Java, Programming | 2 Comments

27th January 2009

My Silverlight 2.0 Hello World Application

This is an update to my original article that was based on Silverlight 1.0 alpha. The code for the old article no longer worked with the current Silverlight runtime.

Instead of the traditional and simple display of a string, this Hello World application uses animation in code to say “hello”.

Pre-requisites

You will need to have the following installed:

Create a New Silverlight Project

  • In Visual Studio 2008, choose File/New/Project and select Visual C#/Silverlight/Silverlight Application. The Silverlight project type is added when you install the Silverlight Tools.
  • Give your project a name and choose OK.

    New Silverlight Project

  • On the next dialog window, accept the default “Add a new ASP.NET Web project…” and choose OK.

Silverlight Project Files

Since we will be drawing objects, we need a Canvas control instead of the default Grid. Change your Page.xaml file to read like this:

<UserControl x:Class="SilverlightHelloWorld.Page"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Width="520" Height="140" Loaded="UserControl_Loaded">
    <Canvas x:Name="MyCanvas"/>
</UserControl>

Press F7 when you have Page.xaml opened to switch to the code-behind file Page.xaml.cs, and replace the code there with this code:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Windows.Threading;

namespace SilverlightHelloWorld
{
    public partial class Page : UserControl
    {
        // private Storyboard _timer = new Storyboard();
        private DispatcherTimer _timer;
        private List<Cell> cells = new List<Cell>(); // list of all cells
        private int _xSize = 26; // width of the grid, in number of cells
        private int _ySize = 7; // height of the grid
        private int _numCells; // total number of cells
        private int _cellIdx = 0;

        /// <summary>Represents a cell on the grid</summary>
        private class Cell
        {
            public double X; // x-coordinate of cell
            public double Y; // y-coordinate
            public bool On; // True if cell is "on"
            public double Order; // Display order
        }

        public Page()
        {
            InitializeComponent();
        }

        private void UserControl_Loaded(object sender, RoutedEventArgs e)
        {
            // Assign a random value to each cell 
            Random rnd = new Random(Environment.TickCount);
            _numCells = (int)(_xSize * _ySize);

            string template = "                          "
                + " x  x xxxx x    x     xx  "
                + " x  x x    x    x    x  x "
                + " xxxx xxxx x    x    x  x "
                + " x  x x    x    x    x  x "
                + " x  x xxxx xxxx xxxx  xx  "
                + "                          ";


            for (int y = 0; y < _ySize; y++)
            {
                for (int x = 0; x < _xSize; x++)
                {
                    Cell cell = new Cell();
                    cell.X = x * (this.Width / _xSize);
                    cell.Y = y * (this.Height / _ySize);
                    cell.Order = rnd.NextDouble();
                    cells.Add(cell);
                }
            }

            for (int i = 0; i < template.Length; i++)
            {
                cells[i].On = template[i] == 'x';
            }

            // Sort the cells by the random values
            cells.Sort(
                delegate(Cell c0, Cell c1)
                {
                    return c0.Order.CompareTo(c1.Order);
                }
            );

            _timer = new System.Windows.Threading.DispatcherTimer();
            _timer.Interval = TimeSpan.FromMilliseconds(1);
            _timer.Tick += new EventHandler(timer_Completed);
            _timer.Start();

        }

        void timer_Completed(object sender, EventArgs e)
        {
            if (_cellIdx < _numCells)
            {
                // Get the next cell
                Cell cell = cells[_cellIdx];

                // Draw the cell
                Rectangle r = new Rectangle();
                r.Stroke = new SolidColorBrush(Colors.DarkGray);
                if (cell.On)
                {
                    r.Fill = new SolidColorBrush(Colors.Red);
                }
                else
                {
                    r.Fill = new SolidColorBrush(Colors.LightGray);
                }

                r.Width = this.Width / _xSize;
                r.Height = this.Height / _ySize;
                r.SetValue(Canvas.LeftProperty, cell.X);
                r.SetValue(Canvas.TopProperty, cell.Y);
                MyCanvas.Children.Add(r);
                _cellIdx++;
            }
            else
            {
                _timer.Stop();
            }
        }
    }
}

Save the file. Right click on SilverlightHellowordTestPage.aspx and choose Set As Start Page, then run the app.

Hosting the Application

To host the application on your web site, just copy the following files:

  • Silverlight.js
  • SilverlightHelloWorldTestPage.html
  • ClientBin/SilverlightHelloWorld.xap

Click here to see the application in action.

posted in Dotnet/.NET - C#, Programming, Silverlight | 3 Comments