Showing posts with label PowerShell. Show all posts
Showing posts with label PowerShell. Show all posts

Monday, October 18, 2010

More AutoTesting - Powershell extensions and addins

There is a nice library called PS-Eventing that makes the event handling a whole lot cleaner and generally a nicer experience. This post with the plugin is not a smaller and doesnt really do any else other than the last post except cleanly deregister the event, but is much more user friendly.
I think i will also post my code on gisthub as I am not and have not been at my real machine for so long... i miss it... sorry.
Heres the link : http://gist.github.com/632749

Wednesday, October 13, 2010

Auto test - Thanks Powershell

Im doing some funky Nunit stuff* at the moment and sometimes the ReSharper or TD.Net runner wont pick up my inner fixtures, the console runner however runs them just fine. Here is a PS script to have auto test running on build:


$Script:initialdir = "C:\myroot\"

$fsw = new-object system.io.filesystemwatcher
$fsw.Path = "c:\mysln\myproj\Bin\"
$fsw.EnableRaisingEvents = $true

$action = {
$filter = "*Tests*.dll"
$file = $Event.SourceEventArgs.FullPath
if($file -like $filter)
{
$nunit = "C:\3rdParty\NUnit-2.5.2\nunit-console"
$currentdate = get-date -format g
write-Host "Running Tests on $file $currentdate" -ForegroundColor Yellow
&"$nunit" /xml:$_.Name-testresult.xml $file
if($LastExitCode -ne 0)
{
WRITE-HOST "Test have failed for $file"-ForegroundColor RED
}
else
{
WRITE-HOST "Test have passed for $file"-ForegroundColor GREEN
}
#$null = Remove-Event $_.EventIdentifier
}
}

Register-ObjectEvent -InputObject $fsw -EventName Changed "FileChanged" -Action $action
Register-ObjectEvent -InputObject $fsw -EventName Created "FileCreated" -Action $action


Note that you will either have to explicit unregister your event handlers or kill powershell to get rid of the handlers. Cancel the watcher by hitting ctrl+c and then Unregister by runnning these lines

unregister-event "FileCreated"
unregister-event "FileChanged"



*The stuff we are doing is to do with inheritance and inner test fixtures to give us a BDD experience without the drama of the BDD frameworks, that personally I still dont like. We are still a fair way off the TDD experience of the Ruby kids.

Wednesday, May 26, 2010

Powershell and the web

Lately I have been playing with PowerShell to see if it can help with some uptime/availability checks for our web sites and services at work; Yes i know what you are thinking but I'm not a sys-admin and I need to know if my stuff is working with out having access to the server... long story I'm sure you will appreciate.

In my reading I have seen lots of flaky posts about PowerShell and web services. I think people need to remember that web services still conform to the http protocol, there is no magic, you do not need to access any visual studio dll or do any weird crap like that, you just need to hit the url and receive a payload.

    $wc = new-object system.net.WebClient
    $webpage = $wc.DownloadData($url)     

That's it. No weird proxies no importing custom dll's.

Here's an example calling the Google Maps API (which is a nice API BTW) to get a latitude and longitude of an address, specifically Perth's craziest bar Devilles Pad (think Satan living in a trailer park that hangs out at a Go-Go club that used to be a James Bond-villians liar, yeah its that cool:

    $url = "http://maps.google.com/maps/api/geocode/xml?address=3+Aberdeen+St,+Perth,+WA+6000,+Australia&sensor=false"
    $wc = new-object system.net.WebClient
    $webpage = $wc.DownloadString($url)#Edit -Thanks Ken
    $xmldata = [xml]$webpage
    $lat = $xmldata.GeocodeResponse.result.geometry.location.lat
    $lng = $xmldata.GeocodeResponse.result.geometry.location.lng
    write-host "Latitude = $lat - Longitude = $lng" 

Like that? Go play: Google Maps API Doco

Thursday, May 14, 2009

PowerShell to set up MSMQ private queues for MassTransit

A pretty self explanatory title: I want to be able to create MSMQ private queues on the fly. I am currently playing with Mass Transit 0.6 and there are a couple of queues i needed to create and would like them to be done upfront. As far as i am aware there you have to go into the config of each project and get the names of each queue and manually create them. This script means i don't have to (I switch machines a lot):

CAVEAT: I am not a PS guru, in fact i am a complete n00b, combine that with my 101 knowledge of MSMQ and this is probably a disaster; you have been warned.

#Beginning of MassTransitSetup.ps1#
param(
[string] $nameofQ, [string]$username
)
[void][System.Reflection.Assembly]::LoadWithPartialName("System.Messaging")

function CreatePrivateMSMQQueue {
param ( [string]$queuename = $(throw "Please specify the queue name!"),
[string]$user)

if ([System.Messaging.MessageQueue]::Exists($queuename))
{
write-host "$queuename already exists"
}
else
{
$newQueue = [System.Messaging.MessageQueue]::Create($queuename)
if ([System.Messaging.MessageQueue]::Exists($queuename))
{
write-host "$queuename has been created"
$newQueue.Label = $queuename
#Default to everyone if no user is specified
if([string]::IsNullOrEmpty($user)){$user = "Everyone"}
write-host "Setting permissions for user : $user"
$newQueue.SetPermissions(
$user,
[System.Messaging.MessageQueueAccessRights] "ReceiveMessage, PeekMessage, GetQueueProperties, GetQueuePermissions")
}
else
{
write-host "$queuename could not be created!!!"
}
}
}

function CreateDefaultMassTransitQueues{
param ( [string]$user)

$deaultqueues = ".\private$\mt_client", ".\private$\mt_server", ".\private$\mt_server1", ".\private$\mt_subscriptions"
foreach($i in $deaultqueues)
{
CreatePrivateMSMQQueue $i $user
}
}

#Begining of script
if([string]::IsNullOrEmpty($nameofQ))
{
CreateDefaultMassTransitQueues $username
}
else
{
CreatePrivateMSMQQueue $nameofQ $username
}


For more info on MassTransit see the google code home page and be sure to check out the wiki on how to set up the starbucks sample. If you are running the starbucks sample set the queues in the scripts above to:

$deaultqueues = ".\private$\mt_client",
".\private$\mt_server",
".\private$\mt_server1",
".\private$\mt_subscriptions",
".\private$\mt_subscription_ui",
".\private$\mt_health",
".\private$\mt_timeout"

Tuesday, February 24, 2009

PowerShell to save the day!

I have been doing a fair bit of build script stuff over the last couple of months. I guess it started when we were having big problems dealing with the build process at my last contract. (I had been using Nant for about a year prior but it never really did anything other than clean rebuild and run my tests. That's cool, it's all it need to do.)
We really need to look at our build process as it took about 3 hours to do a deploy, which we were doing up to 2 times a week…. 6 hours a week of a London based .Net contractor: that is some serious haemorrhaging of cash. I started really looking in to build server and properly configuring build scripts. As most places I work at are very M$ friendly and not overly fond of OSS, so I tend to be stuck with MSBuild if it is a shared script. So goodbye Nant.
Fast forward to a few weeks ago and I have moved country and company and am working with a great team of developers that are incredibly pragmatic and receptive to new or different ideas. We set up a build server and installed Jet Brain TeamCity to point at VSS and a basic MSBuild script that was a basic port of my Nant script. It worked, it did what we need, which was take what was checked in, rebuild, test and send a zip of the output to a network folder and let us know if the whole process succeeded or not. Simple and sweet.
Enter ClickOnce. Ahhh. Ok, so ClickOnce is a great idea in that it manages your companies deployments of smart client software. No longer do you have to worry if the users are using the correct version of your software, the latest will always be on their machine. Personally I think this is a great idea and can see why mangers would love the idea. Its also really easy to deploy… if you are using Visual Studio… and if you only have one deployment environment. Unfortunately I don’t want to use VS (I want to do this from a build sever using a potentially automated process) and we deploy to Dev, Test, UAT and Prod. MSBuild really struggles when it comes to this… it basically just cant do it.
The biggest problem was I need to be able to change assembly names so the ClickOnce deployments don’t get mixed up (I want o be able to install Test and Prod on the same box). Changing the exe assembly name in MSBuild changes all the assembly names, which is not too good.
After struggling with MSBuild I realised I was hitting the limits of what MSBuild is supposed to do, it was either change my approach or enter hack town.
Initially I thought Boo, Python or Ruby would be my saviours… then quickly rethought. Although they would be good in MY mind, other people have to use this and those options are not real M$ friendly… yet. I don’t know why I didn’t think of it earlier but PowerShell was the obvious answer. I downloaded PowerShell and after playing with it for a couple of minutes I was super impressed. All the stuff I was struggling with in my bat files or my MSBuild scripts were trivial in PowerShell.
Variable assignment, Loops, switches etc are all trivial. It extend .Net so you can handle exceptions, interact with Web service Ado.Net Active Directory… the sky is the limit.

Anyway if you haven't played with PS go download it, get the manual and get the cheats sheets

Documents
http://www.microsoft.com/downloads/details.aspx?FamilyId=B4720B00-9A66-430F-BD56-EC48BFCA154F&displaylang=en

Cheat Sheets
http://blogs.msdn.com/powershell/attachment/1525634.ashx
http://refcardz.dzone.com/assets/download/refcard/5f78fd3b70e077cb9a5b3782356a8a14/rc005-010d-powershell.pdf

And Check out PSake from James on codeplex if you are keen on incorporating PS into your build cycle.

Rhys

NB: I hope to post my revised ClickOnce build strategy… as my last one was a bit of a failure, sorry if I lead anyone astray.

EDIT: Check out Powershell GUI if a nice free IDE