Tuesday, 9 March 2010

My small PowerShell presentation

This is my presentation from Intetics internal workshop:

Saturday, 6 March 2010

Using Push-Location and Pop-Location in PowerShell

All popular shell environments have a wonderful tool named directory stack. It allows you to jump there and here in different directions and be able to return to some saved points. This feature really rules when you have to intensively work with command line. It’s really nice that PowerShell designers have implemented it with Push-Location and Pop-Location cmdlets. These cmdlets have standard pushd and popd aliases that are familiar to all *n?x and CMD gurus.

pushd is similar to cd with the only difference that it saves your previous location before moving to a new one. popd is a pair for pushd because it pops the last saved directory and changes your current directory to it. This concept is really simple, isn’t it? :)

So how to ease learning these commands? As for me I’ve:

1. Added my custom aliases to these commands

Set-Alias pd pushd
Set-Alias ppd popd

This allows me to use pushd as easy as cd. popd is a bit more complicated (1.5 times!) but it’s a good point for not losing your context accidentally.

2. Modified my prompt to display current directory stack depth

  $_locationStackDepthString = New-Object string ([char] '+'), (Get-Location -Stack).Count

Now each time when I dive deeper into directory stack I get a ‘+’ sign in front of my prompt and when I pop out I return to previous prompt state:

PowerShell pushd popd

Enjoy!

Friday, 5 March 2010

My PowerShell prompt

Just wanted to share it :)

function prompt
{
  $_locationStackDepthString = New-Object string ([char] '+'), (Get-Location -Stack).Count


  $color = 'Yellow'

  Write-Host '>> ' -nonewline -ForegroundColor $color
  Write-Host $(Get-Date -Format T) -ForegroundColor 'Green' -NoNewLine
  Write-Host " " $PWD.Path -ForegroundColor 'Cyan'
  Write-Host ($_locationStackDepthString + '>') -nonewline -ForegroundColor $color


  return " "
}




It shows current time, folder, uses a separate line for commands and displays current depth of pushd/popd commands (I use them rather intensively).

Thursday, 18 February 2010

Using XmlPeek and XmlPoke in PowerShell

<xmlpeek /> and <xmlpoke /> commands in NAnt are really useful when it comes to changing configuration files during your automated build process. But do we do when we need that functionality in PowerShell? I did not find any native implementation but it's really easy to implement your own. Here it goes:

function xmlPeek($filePath, $xpath) {
    [xml] $fileXml = Get-Content $filePath
    return $fileXml.SelectSingleNode($xpath).Value
}

function xmlPoke($file, $xpath, $value) {
    $filePath = $file.FullName

    [xml] $fileXml = Get-Content $filePath
    $node = $fileXml.SelectSingleNode($xpath)
    if ($node) {
        $node.Value = $value

        $fileXml.Save($filePath) 
    }
}

It accepts FileInfos so it can be easily used together with Get-ChildItem:

Get-ChildItem P:\MyProject -Include *.config -Recurse | %{ xmlPoke($_, "/configuration/connectionStrings/add[@name='MainConnectionString']/@connectionString", "DataSource=MyDB") }

Enjoy! :)

Tuesday, 16 February 2010

What is Windows Phone 7 Series for developers?

Internet is buzzing all around about new Windows Mobile OS - Windows Phone 7 Series. Presentations are awesome, UI is nice and usable. At last Windows fans have something mobile to be proud of :)

But what is this event for us, developers? As an iPhone user and .NET developer I was rather anxious to people who could write programs for their phones and sell them at market. But looks like things have changed. We'll have a nice .NET environment at new phones - that's a fact. However, base technology still remains uncovered. According to Scott Guthrie:

re: Windows Phone 7 development: I can't say more right now other than we'll discuss it at MIX - and that it is very, very cool.

I'm not sure but I think Silverlight will be this technology. As I can judge from presentations it is already supported at WP7S devices. All needed is to allow Silverlight applications to run out of mobile browser and become an application that user can run just like Mail or Calendar. And that feature is already present in Silverlight 3 so guys have to work just a little bit more to make us very happy.

What will be next? I think I'm not the only one who wants to write mobile .NET applications so perhaps we'll see a mobile development boom in .NET community. More Silverlight developers, greater Windows Phone adoption, huge popularity raise for Expression Blend and Visual Studio - wonderful situation for Microsoft.

All these are just suggestions and we'll have official details only at MIX that will take place in March 15-17 in Las Vegas. Keeping in mind that we'll see Internet Explorer 9 there - it will be an Event.

Friday, 12 February 2010

What do I need from Internet Explorer 9?

That's a really interesting question. I did not use any Internet Explorer as my main browser before Internet Explorer 8. IE8 changed my mind a bit and I've been using it for about a month and a half. Why did I jump off:

  1. Tabs opened slowly
  2. Pages loaded slowly
  3. No nice CSS features like border-radius
  4. Misses some FireBug features (although see next p.1)
  5. Too large header bars (comparing to Chrome)

What I liked:

  1. Wonderful tool for developers, it's my favorite at the moment (better than FireBug!)
  2. Tab grouping
  3. Extensibility

After IE8 I've tried to return back to Firefox but I could not stand it's strange behaviors anymore so I've switched to Chrome. What do I like in Chrome:

  1. Damn it's fast
  2. It's fast
  3. Did I mention it's fast?
  4. It has neat interface

So, what do I want from IE9? That's what:

  1. Please fix what I disliked in IE8
  2. Please add what I like in Chrome

This is a simple recipe, isn't it? :)

Saturday, 6 February 2010

Mock or stub?

When I was just getting into unit testing the subject question was rather hard to me: it’s not actually obvious for a novice. The answer to it came from a unit testing book I think is very nice and useful - “The Art of Unit Testing” by Roy Osherove.
Mock or stub?

So what’s the core difference between mock and stub? The answer is: mocks can fail tests and stubs can not. You may think this minor point is not important but it is. Basically when you test something you have the following two components: code under test (CUT) and test itself. There are two different cases for testing:

1. You may run CUT and validate it results – it’s actually testing CUT internals

2. You may run CUT and validate how it communicated with some external service – it’s actually testing CUT externals

The first case usually accompanied by stubs – some stub objects that you use to pass initialization information to CUT. They just provide data and do nothing more.

The second case is usually accompanied by stubs and a mock. Let’s say you have some IExternalService your CUT communicates with. After running CUT you want to be sure that two IExternalService methods were called with some valid parameters. You can write some custom class that implements this interface but the simplest option is to use a mock. Mock allows you to specify what methods in what order with what parameters should be called. After CUT run you can validate mock and see whether it fits your expectations.

The rule of thumb here is to have one mock in your test at max. Why is that? The answer is simple: when you use two mocks and validate both of them in a single test it means that you test two different pieces of logic in one test. That may be a result of scattered logic (violation of Single Responsibility Principle) or just a bad test design – anyway it’s a bad practice. What though should be remembered is that you can use as many stubs in your test as you wish – they just provide initialization data and can’t fail your test.

Wednesday, 3 February 2010

The Law of Leaky Abstractions

The concept of leaky abstractions was introduced by Joel Spolsky in his blog 7 years ago, but it's not as widely known as it deserves. So here is the basic definition:

All non-trivial abstractions, to some degree, are leaky

This simply means that if you're trying to hide something beneath your abstraction layer - it will almost always show itself up. These errors are hard to detect and have severe consequences. There are many examples of leaky abstractions:

  1. Some SQL queries are thousand times slower than their logical equivalents - DB implementation leaks into SQL
  2. SQL, in its turn, has abstractions over itself like NHibernate or Linq to Sql - and rather often you have to deal with SQL directly losing many abstraction benefits
  3. When you program GWT and write your code in Java it is later on translated to JavaScript. And what can be more confusing than having a JS error from running your Java code? :)
  4. .NET is an abstraction over Win32 and it has leaks sometimes - rarely, but these rare cases make people mad
  5. Any component framework like ASP.NET or JSF hides HTML/CSS and JS beneath them - guess what problems you may have?

What can be a conclusion of all above? It's all in Joel's original post!

Never hire a developer for working with some abstraction if he doesn't know direct underneath layer of it

It may sound strange or may be offensive for some of us but it's rather obvious: you should not hire an ASP.NET developer if he is scared of JavaScript or hire a so-claimed NHibernate guru if he doesn't know what 'DISTINCT' is?

Sunday, 31 January 2010

Book Review: “The Passionate Programmer” by Chad Fowler

I’m a huge fan of books and from now on I’ll write a review on each technical (or may be not) book I read. The first book reviewed will be a wonderful book by Chad Fowler: "The Passionate Programmer”. Actually, it’s full name is “The Passionate Programmer: Creating a Remarkable Career in Software Development”. This is what this book is about – your career.

Chad Fowler is a great programmer, Ruby practitioner, musician and conference organizer. He recently lived and worked in India, setting up and leading an offshore software development center. He is co-founder of Ruby Central, Inc., a non-profit corporation responsible for the annual International Ruby Conference and The International Rails Conference, and is a leading contributor in the Ruby community.

As the author highlights, your career is the most important project in your life and you, as it’s result, is the most valuable product of it. That really makes sense if remember that your time is the most valuable resource: you can’t replenish it.

As Chad assumes you are a product, he splits his book into parts on how to promote this product:

  1. Choosing Your Market
    Here Chad describes what you should be and what niche you should take, what skills to develop and what technologies to specialize in.
  2. Investing in Your Product
    This part is about how to develop yourself, not what but how. How you should sharpen your skills, how you should choose a mentor.
  3. Executing
    Where to apply yourself, how much you are worth, how to behave in stress situations – you are a product and this part is about how to execute you and produce value.
  4. Marketing… Not Just for Suits
    Advertise yourself, make people believe you’re the one they need, be public – the marketing of product from all practical aspects.
  5. Maintaining Your Edge
    You’re at the top, you’re the king – but what next? Chad devotes this part to you-product maintenance: looking for future employments, planning your next career steps.

This book is good. Very good. My favorite statement from it is “Be the worse” – be the worse in your team meaning that all around are better than you. In this case you’ll grow up much faster than in any other case.

Thursday, 28 January 2010

Joining your social bits in one service

I'm using Twitter as my main way to express myself to other people. It's ultimately nice for sharing links and thoughts. However, I had also two other services that I could not synchronize with Twitter... since now.

Welcome, here come the TwitterFeed! Wonderful tool for joining all your services into one:
1. Google Reader - I share items time to time and now they are automatically reposted to Twitter. Step-by-step tutorial on how to configure TwitterFeed to get your Google Reader items - http://goo.gl/s0NK
2. Blog - my monthly posts rate is extremely low these days but I promise I'll speed up :) This post will be the first one automatically reposted to Twitter.

Also TwitterFeed plays nicely with OpenID so feel free to expose your Google or MSN account to it.

Sunday, 10 January 2010

Fixing Twitter for Chrome with User JS

I'm a rather conservative Twitter user and prefer web interface to all the others. The only thing in it that have been bugging me since I've started using it was impossibility of submitting tweet with Ctrl + Enter shortcut. And today I've fixed that (yeap, I'm damn proud of myself!) using User JS script for Chrome.

Yes, it only fixes Twitter in Chrome and may possibly fix it in Firefox with GreaseMonkey (I did not check it!).

So, first of all - make your Chrome accept User JS.

1. Switch to development channel of Chrome
2. Enable User JS in Chrome using "--enable-user-scripts" shortcut flag as it is described here
3. Restart Chrome
4. Copy this code and paste it to file named Twitter.user.js :

// ==UserScript==
// @name Twitter extensions script
// @description Short script that gives some features I really miss like Ctrl + Enter way to submit tweets.
// @version 0.1
// @include http://*twitter.com/*
// ==/UserScript==

console.log('Started Twitter script');

var txtStatus = document.getElementById('status');
if (txtStatus == null) {
return;
}
txtStatus.onkeypress = function (e) {
e = e || window.event;
var keyCode = e.keyCode || e.which;

var ctrlKeyPressed = e.ctrlKey;
var enterKeyPressed = keyCode == 13 || keyCode == 10;

if (ctrlKeyPressed && enterKeyPressed) {
console.log('trying to submit tweet...');
var submitTweetButton = document.getElementById('update-submit');
submitTweetButton.click();

return false;
}
}


5. Drag and drop this file to opened Chrome
6. Accept script installation
7. Enjoy Ctrl + Enter shortcut in Twitter web interface! :)

Friday, 18 December 2009

IronRuby LinkedIn Group

IronRuby is in RC state and soon we'll all get a possibility to use it in our production environments. I can't predict the exact amount, but I'm absolutely sure it will conquer many developer hearts and build a nice Ruby .NET community.

If you like IronRuby - JOIN LinkedIn community! Let's share our experience in using IronRuby!


Saturday, 21 November 2009

Diving into RIA architectures with Flex as an example

Now I have a need to dive into Flex architecture common structure and widely used patterns. Below goes the list of links I've found useful and interesting:

Introduction to RIA architectures

Flex Architecture Fundamentals in 4 parts

Martin Fowler UI patterns

Great benchmark for different ways of Flex to communicate with external services:
(Yes, and SOAP/XML is 4 times slower than Flash-native AMF format)

All of these are really interesting articles that are definitely worth reading even if you don't have same need as I do.

Friday, 20 November 2009

Fixing IronRuby error when installing Rake

I was trying to install Rake with IronRuby but was always getting the following error:

>igem install rake
ERROR: While executing gem ... (ArgumentError)

After some Googling I've found the following article:


It's not in English or in Russian so I had to ask Google Translate for help. The article stated that length of name is greater than 255 and that's the problem. I've checked mine:

C:/Program Files/IronRuby 0.9.2/

Obviously it's not longer than 255 characters, so the reason is possibly in spaces. I've reinstalled IronRuby to:

E:/bin/ironruby

And...

PS C:\Users\Ivan Suhinin> igem install rake
Successfully installed rake-0.8.7
1 gem installed
Installing ri documentation for rake-0.8.7...
Installing RDoc documentation for rake-0.8.7...

Yahoo! :) Hope this post will help someone with same problem.

Thursday, 19 November 2009

Running IronRuby 0.9.2 with RubyMine 2.0

Latest releases of IronRuby 0.9.2 and RubyMine 2.0 inspired me to make them play together. That's my first experience of running IronRuby in fully featured IDE so I was rather doubtful whether it will work or not.

Here goes step-by-step manual:

1. Download IronRuby 0.9.2 from here and install it.
2. Download RubyMine 2.0 from here and install it. You may need a licence - grab it here.
3. Run RubyMine
4. Click Project Settings or press Ctrl + Alt + S:


5. Navigate to 'Ruby SDK and Gems' left menu option:


6. Click 'Add SDK...' button:


7. Choose ir.exe in your IronRuby 0.9.2 installation folder:


8. That's it! We have IronRuby listed as Ruby SDK in RubyMine:


9. Let's try it in action! Close this window and create a new project:


10. Choose project location and 'Empty project' option - we don't need Rails at the moment:


11. Create a folder named 'src' and add a 'main.rb' file to it:


12. Write this code to editor (and feel the power of RubyMine's IntelliSense):


13. Click the arrow button and choose 'Edit Configurations' option:


14. Add new Ruby configuration:


15. Name configuration and select our 'main.rb' file as executable script:


16. It's damn important to clear 'Ruby Arguments' field. Change this:


to this:


otherwise you'll get the 'can't convert NilClass into String (TypeError)' error:


17. Press OK and run our first program:


18. Here we go, our first IronRuby program running in RubyMine:


Isn't it wonderful? :)

Wednesday, 18 November 2009

Use remote desktop connection faster with PowerShell

We have more than ten servers in our production network and all of them are accessible via RDC. The problem is that to connect via RDC you have to specify public IP and not local network nice name like "prod-01" or "prod-db-01". I had not bothered about it till I had a need of connecting some of them several times a day. To solve this problem I wrote a PowerShell script that takes nice name of server and launches RDC with its IP:

$prodServers =
@{
'prod-01' = '1.2.3.2';
'prod-02' = '1.2.3.3';
'prod-03' = '1.2.3.4';

'prod-db-01' = '1.2.3.6';
'prod-db-02' = '1.2.3.8';
}

Set-Alias rdcx 'c:/WINDOWS/system32/mstsc.exe'
function rdc([string]$serverName)
{
$param = ''

if ((![System.String]::IsNullOrEmpty($serverName)) -and ($prodServers.Contains($serverName)))
{
$param += '/v:' + $prodServers[$serverName]
}

rdcx $param
}

It's extremely useful if you have many servers, just believe me :)

Monday, 16 November 2009

Use PowerShell to determine MS SQL table used data space

Yet another issue to be solved: we have SQL Expression installed at our branch server and it allows only 4Gb per table. So - what's the solution? Of course, PowerShell!

Right click on database - "Start PowerShell". (Note: I do NOT know how to enter MS SQL mode from normal PowerShell). And now we can have some magic with our database! The following script shows databases that are too heavy and can be cleaned up after some consideration:

ls tables | sort -Property DataSpaceUsed -Descending | ? {$_.DataSpaceUsed -gt 1024} | % {$_.Name + " takes " + [math]::Round($_.DataSpaceUsed / 1024 ) + " Mb"}

Wasn't that just sexy? :) Here goes the step-by-step explanation:

ls tables

Listing all db tables.

sort -Property DataSpaceUsed -Descending

Sorting descending by DataSpaceUsed field - we need to see only the heaviest.


? {$_.DataSpaceUsed -gt 1024}

Taking only tables that take more than 1Mb in data space.

% {$_.Name + " takes " + [math]::Round($_.DataSpaceUsed / 1024 ) + " Mb"}

Making output look nice and actually showing table name.

Friday, 13 November 2009

Enlarge your Build System!

http://www.jameskovacs.com/blog/ReleasingPsakeV100PsakeV200.aspx

Rake? NAnt? NO!!!!!!!!!!!

PSake? YES!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!

What is it? Ha! Powershell-based build system. DSL for tasks, easily integrated with PS script blocks.

That's only 9th message!

Yeap. This message is only 9th message I have in this year. Compared to 158 messages from last year it seems a bit... small? :)

I should definitely write more.

Delete all MSMQ queues at some PC with PowerShell

We have a small issue at one of our production servers. Once something generated ~10K queues with Guid-like names. Since then they were not deleted as there was a problem: standard MSMQ manager doesn't allow deleting several queues at once.

What to do? Powershell, of course! :) Here goes the script:


[Reflection.Assembly]::LoadWithPartialName("System.Messaging")

[System.Messaging.MessageQueue]::GetPrivateQueuesByMachine("someserver") | % {".\" + $_.QueueName} | % {[System.Messaging.MessageQueue]::Delete($_); }


You may also filter them by name if you do not need to remove them all as I need:


[System.Messaging.MessageQueue]::GetPrivateQueuesByMachine("someserver") | % {".\" + $_.QueueName} | ? {$_ -match "SOME_REGEX_FILTER"} | % {[System.Messaging.MessageQueue]::Delete($_); }

And SOME_REGEX_FILTER is... Yeap, some regex filter :) The -match operator allow us using regular expressions in the Where-Object (alias "?") clause.

Have fun with PowerShell!