Exec-Sql PowerShell Function

And the hits just keep on coming … here’s a simple little function which executes a query against a database and pipelines the results as PSObjects.

.SYNOPSIS
Executes SQL against the supplied connection string.
.DESCRIPTION
Executes SQL against the supplied connection string. The result set is then pipelined as a PSObject which can subsequently be formatted and filtered any way you choose.
.PARAMETER query
The query to execute
.PARAMETER connstring
The connection string to use
.EXAMPLE
PS C:\> Exec-Sql -q "select top 1 * from common.country" -conn ""
.EXAMPLE
PS C:\> Exec-Sql -q "select * from common.country (nolock)" -conn "" | where {$_.Code -eq "AX" } | select code, name
#>
function global:Exec-Sql
{
param ([Alias("q")]$query, [Alias("conn")]$connstring)

[system.reflection.assembly]::LoadWithPartialName("System.Data")
$connection = New-Object -TypeName System.Data.SqlClient.SqlConnection

$connection.ConnectionString = $connstring
$connection.Open()

$command = New-Object -TypeName System.Data.SqlClient.SqlCommand

$command.Connection = $connection
$command.CommandText = $query
$reader = $command.ExecuteReader()

$fieldcount = $reader.FieldCount

while ($reader.Read())
{
$o = new-object psobject

for ($i=0;$i -lt $fieldcount;$i++)
{
$o | add-member -membertype noteproperty $reader.GetName($i) $reader[$reader.GetName($i)].ToString()

}

write-output -inputobject $o
}

$connection.Close()

}

Comments

Minor PowerShell Prompt Customization

Having recently started using PowerShell a lot more, I wanted to share a minor customization I made to my powershell prompt.

function prompt
{
    $loc = $(get-location).ToString()
    $usr = ($env:userprofile).ToString()
    if ($loc.StartsWith($usr, $true,[System.Globalization.CultureInfo].CurrentCulture)) {
	$loc = "~"+$loc.SubString($usr.Length, $loc.Length - $usr.Length)
    }
    Write-Host ("PS " + $loc +">") -nonewline -foregroundcolor Yellow
    return " "
}

all it does is that when I’m in my user profile directory, it shortens the prompt to something like: PS ~>. Since you can use the ‘~’ character as a shortcut for your user directory, may as well shorten the path to give you more space. Also, it makes the prompt yellow so that it can be more easily distinguished from the rest of the output.

Comments

MS Tech-Ed 2011/Udder Chaos on XBLIG

What a whirlwind of a few weeks … first order of business, I can’t believe that I hadn’t even posted a link to this, but Udder Chaos was released on XBox Live Indie Games several weeks ago.

Udder Chaos

It’s received favorable reviews (or mildly tepid at worst), and was even featured on Kotaku’s favorites list for a bit. All in all, I had a great time helping the team get that game to market, and is a testament to FlatRedBall. Though we’re all working on other projects right now, a windows phone 7 version isn’t far away Smile

“Udder Chaos plays like one of the classic lightgun games of yesteryear, evoking nostalgic memories of the likes of Point Blank and Duck Hunt.” – Jonathan Lester of DealSpwn

But on to the fun, last week I had the pleasure of attending Tech-Ed 2011 … wow, what a blast that was. This is just a brief offload of my notes of a few of the cool things I saw. Definitely need to follow up on some of these

  • F# – interesting as always, did a hands on lab, but am still trying to find a compelling reason to really look at it in detail.
  • Task Parallel Library/Asynchrony
    • Async Actions – I had seen this on the feature lists before, but hadn’t had a chance to actually use them before. Very cool! if your app is IO bound (i.e. database access), you should absolutely be using this.
    • By far, one of the coolest pieces of tech, SingalR uses some of the async request infrastructure mentioned above to provide some really sweet push notification functionality in a scalable way.  This is one to watch
  • Windows Server AppFabric Cache – saw some cool sessions on this, glad to see that they’ve finally gone to market after seeing the first version back in PDC 2008.
    • My takeaway here is that you will want to do a lot of capacity planning to understand read/write frequency, and max # of projected objects. This will drive memory/server requirements.
    • Also, the primary use case is not specifically to increase response times, although that will often be a side-effect … but actually to lighten the load on the database (or other external data source). Because the db is often the bottleneck, this gives you an easily scalable layer between your application and the database.
  • Lots of cool HTML5 and client topics, in no particular order:
    • Modernizr is cool
    • jQuery Visualize plugin is cool
    • jQuery.Unobtrusive is cool
    • must look into KnockoutJS
  • And finally, NuGet represent! am really amped up for how easy NuGet makes dependency management and lib deployment.

Anyways, that was just a braindump of some of my notes … I still have a mountain of stuff to catch up and follow up on. Overall, very impressed with the conference, although one can make the argument that it was almost too big.

Comments

Udder Chaos in Peer Review

Udder Chaos for 360 has been published to peer review!

http://forums.create.msdn.com/forums/t/80247.aspx

If you’ve got an AppHub account, please take a moment and give us a review.

Comments

Lego/Snap-Circuits Mashup

My daughter Layla mentioned a few days ago that they are teaching her how to program simple Mindstorms robots at school. As a software developer, I was of course super excited when she started explaining the logic she was “writing” in the visual programming language to make her little mindstorms robot move around and turn. So then today my son Ashton goes upstairs and grabs all his legos, and the Snap Circuits I bought him a few years ago, and asked me to help him build a robot. The options were pretty limited because the snap circuits kit only had one motor, and the legos he has don’t have any gears or anything.

It was a blast helping the kids with it :-) The biggest challenge was figuring out how to transfer the power from the snap circuits motor to the lego pieces. We ended up cobbling together a rudimentary axle, and used a rubber band to transfer the torque from the motor to the axle.

And it totally works!

well, mostly … the motor was too weak to actually move the car without first getting a push … but as you can see above, they got it to actually turn the wheels :-) Of course it wasn’t done all on their own … I gave them help along the way, but I’m happy that they worked through the process of figuring out something like. And most importantly, it was because they wanted to … I can’t wait to see what this generation does with all the technology they are growing up with.

Comments

WebHelper for Desktop CLR

I recently posted a nice little helper class that I had been using on windows phone 7. This version works on the desktop CLR (there’s a minor difference in how you create a web request) … and also adds a new method that lets you get direct access to the response stream. So I figured I’d post it as it is a generally useful class.

public static class WebHelper
{
    public static WaitHandle Get(string url, Action<WebResponse> action)
    {
        return Get(new Uri(url), action);
    }

    public static WaitHandle Get(Uri uri, Action<WebResponse> action)
    {
        var request = WebRequest.CreateDefault(uri);
        ManualResetEvent handle = new ManualResetEvent(false);
        request.BeginGetResponse(i =>
        {
            var response = request.EndGetResponse(i);
            action(response);
            handle.Set();
        }, null);

        return handle;
    }

    public static WaitHandle Get(string url, Action<string> action)
    {
        return Get(new Uri(url), action);
    }

    public static WaitHandle Get(Uri uri, Action<string> action)
    {
        return Get(uri, response =>
        {
            var sreader = new StreamReader(response.GetResponseStream());
            var result = sreader.ReadToEnd();
            action(result);
        });
    }
}

For some example usage, you can easily proxy a download through an ASP.NET MVC web app:

        public ActionResult Get(string q)
        {
            Stream res = new MemoryStream();
            string contentType = "text/html";

            bool timedOut = !WebHelper
                .Get(q, html => 
                    {
                        res = html.GetResponseStream();
                        contentType = html.ContentType;
                    })
                .WaitOne(30000); // wait 30 seconds to get a response

            if (timedOut)
            {
                StreamWriter writer = new StreamWriter(res);
                writer.WriteLine("The request timed out, sorry!");
                res.Seek(0, SeekOrigin.Begin);
            }

            return File(res, contentType);
        }

Comments

Udder Chaos for XBox Live Indie Games in PlayTest

Big milestone for the FlatRedBall team, Udder Chaos has been submitted for play test on XBox Live Indie Games! :-)

AppHub members can download the game for play test here, and give us feedback on the game’s forum thread here.

I came onto this project rather recently, the game was mostly done.  So I’ve been working for the last few weeks on the leaderboards implementation and other polish tasks and bugs along with a great team: Vic, Dave, Pablo, and Taylor (not to mention the other guys on the credits that worked on the game before I got involved).

One interesting part of this project has been the cross platform development. It’s a topic that I’d like to go into more detail another day, but the game builds and runs simultaneously on windows, xbox, and windows phone. There are some definite challenges to this kind of development, especially when you have to consider different input mechanisms and screen/menu layouts on the different platforms. It’s been a great experience so far, and it’s fueling some thoughts about how to structure code to facilitate cross-platform dev.

We plan on getting the windows phone build out after the xbox version ships. Can’t wait to see the feedback we get in playtest, and hopefully we’ll ship it soon.

Comments

Lemonade Stand for WP7

Fresh on the Marketplace, Lemonade Stand for Windows Phone 7 now available for download! Please note: LMND.st is down until further notice, the app has been removed from the marketplace until that time.

Welcome to Lemonade Stand, a new and easy way to buy and sell locally. Lemonade Stand is a neighborly commerce platform that enables people to buy and sell goods within a community. Artists, craftspeople and entrepreneurs can share their wares with their neighbors while members of the community can find and buy close to home. An easy way to shop while supporting your local economy and the talent within it- what could be more wholesome?

This application had somewhat of an interesting birth. Right before this year’s SXSW began, I came across the StartupBus project. A group of entrepreneurs (or rather, busrepeneurs) would join forces on the bus to sxsw, and over the course of the road trip, produce and launch a startup.

One of the teams took an interesting approach by publishing a RESTful API as the first step to creating an Android and IPhone app for their startup. A WP7 app was regrettably not on the roadmap, so as I went to bed on Thursday night I wondered what it would take to gin up a version for wp7 based on their public API. When I woke up, I guess my subconscious was thinking about it all night, because I shot out of bed and saved a few pages of the lmnd.st site, including some of the art assets to my laptop. When I got on the train, I started by writing the rest calls and models, and experimenting with some of the different layouts. Of course I didn’t finish as my train ride (or at least the first train I take towards NYC) is only about 50 minutes. So I decided to hit up the closest Starbucks for lunch to leach off their WiFi. Now that I had network access, I started testing the rest calls and tweaking some of the layout/design to match the mockups they had put up on their site (of course with the Metro design language as inspiration).

Before my lunch hour was over, I had a working prototype. So I banged out a quick blog post and celebratory tweet before heading back to the office. Within a few hours, I got a twitter DM from one of the lmndst team members asking me to call them. Jon was super nice and thanked me for the effort. Then a bit later he called me back and asked if I could send him the app so they could show it off at sxsw. I asked him if he had a wp7 device and he said there may have been one on the startup bus from the sponsors, but sounded unsure. That’s when I remembered that a member of the wp7 team (Ben Lower) was in sxsw handing out phones in exchange for pitches. So I introduced them (and got some hash cred while I was at it ;) ) and they got a phone to show off the app. Then I went home and polished up the app a tiny bit before sending it off to the lmnd.st team and submitting it to the wp7 marketplace.

The rest of the weekend was pretty calm, I followed along on twitter as the team set up a real lemonade stand to cool down parched festival goers. Those guys put forth a pretty big effort as is evident by their many mentions in follow up articles to sxsw. I was even indirectly mentioned in one of the articles As an “unknown Supporter” :P

The team created the Android and iPhone applications, but they were greeted with an exceptional surprised when they woke up in Austin on Friday: A Window’s mobile version of their app.  A supporter unknown to any on the project team who had been following their progress on the New York Observer  blog took their API and created the Windows version.

Now that sxsw is over, the team says they will continue development of lmndst. I too plan on more iterations to at least reach feature parity with the iOS and Android apps.

One parting note, on the Saturday after I first published the app, I briefly skimmed over the premise of lemonade stand with my wife at dinner. I was surprised when, on Sunday as I was talking about needing a new laptop, my seven year old son said, “you can sell your old one on Lemonade Stand”. So maybe there is something to this idea ;)

Comments (1)

Khan Academy for WP7 Review

This was a nice little surprise :-) My (unofficial) Khan Academy app for windows phone 7 got reviewed on an episode of Hot Apps By Laura Foy – check the video below.

Only reason I noticed was because I checked the download stats and saw a sustained spike in traffic a few weeks ago. Thanks Laura!

Comments

Lmnd.st for wp7?

In honor of the NY Startupbus at SXSW … a wp7 app for lmnd.st :-)

Yes, it’s pointing to the live API … though only the display of the current listings is built right now. Total time spent thus far:

  • 50 minutes on the train this morning
  • 1 hour during lunch

Comments