Setting PowerShell console color when running elevated May 31, 2008
Posted by reddogaw in PowerShell, Tips.Tags: PowerShell, Profile.ps1, Run as administrator, Vista
add a comment
Recently I’ve just started delving into Powershell and I’m really growing fond of it!
One tiny feature I missed about classic console (dare I say I miss it!) was how the console foreground color changed to yellow when you are running in elevated mode (through Run As Administrator).
Then I stumbled onto the creation of a personal profile.ps1 file inside your <Profile Documents>\WindowsPowerShell\profile.ps1. First things first, be sure that you’ve run Set-ExecutionPolicy to either RemoteSigned or Unrestricted (ironically, in Vista be sure that you’re elevated with Run as Administrator). Next up create the WindowsPowerShell folder in your user profile’s My Documents (or Documents in Vista) and create a new text file in there called profile.ps1.
Using code borrowed and ever so slightly changed from Nivot Ink you can add the following to your profile file:
- # Returns a boolean indicating whether the passed windows identity is an administrator.
- # Argument defaults to current user.
- function Test-Elevated {
- param(
- $identity = [security.principal.windowsidentity]::Getcurrent()
- )
- $principal = new-object security.principal.windowsprincipal $identity;
- $adminsRole = [system.security.principal.securityidentifier]“S-1-5-32-544″;
- $principal.IsInRole($adminsRole);
- }
- # Usage:
- #
- # If-Elevated { .. admin code .. } { “sorry, need admin” }
- #
- function If-Elevated {
- param(
- [scriptblock]$AsAdmin = $(Throw “Missing ‘as admin’ script”),
- [scriptblock]$AsUser= $(Throw “Missing ‘as user’ script”)
- )
- if (Test-Elevated) {
- & $AsAdmin
- } else {
- & $AsUser
- }
- }
- # Change the foreground color to yellow if admin
- If-Elevated { [System.Console]::ForegroundColor = [System.ConsoleColor]::Yellow; } { }
Remember PowerShell has all of .NET at it’s disposal so that’s exactly what we’re using in the Test-Elevated function. Similarly we change the console colour in the same way we would in a normal console application and while there we’ll also keep the current working directory consistent to the $HOME variable (in elevated mode it defaults to the Windows\System32 directory).
Love,
Reddog.
When does a requirement need to quit being a requirement? May 22, 2008
Posted by reddogaw in Developer Life, Project Management, Uncategorized.add a comment
In recent times I’ve done the unmentionable, the disgusting, the horrifying, the unheard of: I said “we’ll just have to change their requirement then” and “stuff the requirement, they just didn’t know what they wanted”.
When you make this sort of statement it almost becomes like the old western movies when the odd looking but well intentioned guy walks into the bar – the crowd falls silent, the tumbleweeds roll past outside, there’s just a faint noise of horses or insects outside and dead silence inside… Then the tough guy who’s been drinking at this bar for some time (and is quite possibly drunk on dirty whiskey) gets up from high seat at the bar and says “them’s mighty strong words, runt!”
Like many, in recent times I’ve been working in a environment following a waterfall-esque development methodology where upon developers are completely shielded from the end user (or perhaps its the other way around) through numerous layers of indirection and obfuscation (aka analysts, management, and expensive “requirements” documents). So what’s a developer meant to do when the gut says “something smells fishy here”? What do we do when we stumble onto that magical requirement that flies in the face of the rest of them or just won’t fit with the architecture that’s been built up around all the other requirements?
Initially when the feeling of inferiority (and a touch of rage) for having such impure thoughts had subsided I felt compelled to write about the fact that not all of our so called “requirements” are to be treated as gospel and to try to explain how certain situations called for developers to take drastic action by simply chucking them out or re-engineering until they were unrecognisable. Finally, it occurred to me that I too was falling into the old waterfall habits of blaming the “other guy”; in this case the analyst who wrote the spec. In reality, software development is about an evolution as a team and business toward the end product. It’s not just about building something to a plan, it’s about creating something, it’s about a delicate balance of art and logic. All this means is that if you don’t have the courage to communicate your problems then the whole team loses.
Some validation for your courage
When it comes to trusting the quality of a requirement Chad Myers makes the point beautifully in his “I don’t trust me” development methodology ideal (which is suspiciously agile and TDD) such that when it comes to requirements he says:
I don’t trust the customer or the target consumer for the software we’re building. I don’t trust them to know thoroughly what their problem is. I don’t trust them to be able to communicate effectively to me what picture of a solution they have in their mind. I don’t trust them to be able to know, beforehand, everything that they would need to have their problem solved to complete satisfaction. They will change their mind, remember things they missed mid-way through the project, remember that what they asked for earlier on was wrong and needs corrected, etc.
With these (rather cynical) realities in mind, it becomes quite clear that not everything in the precious requirements documents is to be considered gospel. It’s up to the developer – who has the most intimate working knowledge of the system to be proactive by seeking a solution that best delivers true value to the project.
Thinking and talking win-win
Realising that everyone involved in the team has different viewpoints (some perhaps flawed, invalidated by time, or less intricate than others) it’s time for you, the courageous one, to communicate your problem and reasoning. If a requirement can’t be done affordably, doesn’t fit your current architecture, is contradictory, is futile, or any other reasons then it’s up to you the developer to be proactive and start the conversation rolling. There are many project management solutions that all offer continuous and potentially cheap alternatives that won’t suck the soul from the developer who would have otherwise felt like going into battle in an David versus Goliath grudge match that would have resulted in re-estimations, benefit analysis, requirements revisions, or anything else that limits developers from actually being creative. My personal preference are informal communication channels such as a chat over your desk or during a daily stand-up meeting (where you can’t forget to occasionally invite those chickens). However, probably best avoid written media (email, MSN) except as an affirmation of your plan of attack.
Love,
Reddog.
How else do we earn l33t respect? May 12, 2008
Posted by reddogaw in Developer Life, Uncategorized.add a comment
I want to preface this post with a statement: I don’t think I’m l33t (meaning an elite programmer for the less nerdy of us). Having previously worked at a Sydney software consultancy where I can assure you the standard of the young consultants was very high such that I felt constantly in the shadow of an incredible 16 year old prodigy, an organised “old-timer” who just knew how to get things done (and fast!), or the respected industry speaker and rule maker… So the question beckons, how do developer’s talents get recognised?
I think it’s fair to say that not all programmers are equal so what does it take to be considered one of those hyper-productive folks that we nerds might call l33t?
In any software development team with more than a few people, you’re almost guaranteed that your manager is no longer technical… They used to be, but by the very definition of management they’ve shifted focus onto broader topics such as staffing, team morale, project delivery, process management, financial risk mitigation, and project funding. So are they a good judge of your development skills? The way I see it is that they are looking to see if you can do some of the following:
- Have the ability to d3-l33t1fy your conversations (talk non-technical)
- Are seen as a teacher or mentor
- Are social with your management team
- Can communicate with the big picture in mind
- Can understand that development costs money, lots of it
- Follow change management, timesheeting, task tracking procedures
- Contribute to collaboration and knowledge sharing
- Estimate well
- Gain industry certifications
- (Cynically) Can spin when things go wrong (which we know will happen a lot!)
But how does this correlate with what makes a good developer from another developer’s point of view? Or even a software quality point of view?
Almost certainly developer’s opinions of other developers are influenced by the personal, creative, social and technical sides of software development. Perhaps including some of the following:
- Are social with your coworkers and make them feel happy at work – you enjoy a good laugh, are fun to be around, you don’t smell, and you can go to lunch or drinks together
- Can put time aside to help when you should
- We’ve all been super focused on our task at hand to find someone whom is trying to debug your code asking you a million questions which feel unreasonable, but really they’re not. You should help them… Don’t let them deplete their life-force.
- Document your code where necessary
- Incidentally, I would typically go for a minimalist approach where code should be self-documenting
- This mostly includes code organisation and following coding standards
- Write simple code that uses chosen frameworks to their best intentions
- They know when to fix vs. when to extend vs. when to roll your own
- They use inheritance and polymorphism well
- Truly understands all code that they produce and “write“
- Gets things done with a gist for how to do things better in the future
- Did you ever notice a good coder will often leave many TODO’s in their code?
- Has a broad knowledge of system components, technologies and frameworks
- Somewhat similar to a good architect in that regard
- Continually improving old code with fresh ideas
- Isn’t afraid to throw things out
- They have a good “code smell” for dud code and don’t mind re-engineering if need be
- Develops a quick familiarity with new technology rather than a deep understanding
The reason I bring these points up is that I recently was chatting with Dr Neil about MS certifications as a resume filler and then stumbled onto thoughts about whom is your best referee when going for a job… The answer is almost certainly the 360° profile including a manager (for the business smarts), coworkers or peers (for the developer smarts), and possibly system users or peers (for the common sense/usability smarts).
The other question we should ask ourselves once we’ve settled into a job is whether the way we see ourselves in our own careers is similar to that of our managers and coworkers… (Remember, you must consider it from their view point rather than your own). Is that a problem? Does that highlight some goals you could set yourself for the next year?
What do you respect in other’s programmer skills?
Love,
Reddog.
Which lobe are you? May 8, 2008
Posted by reddogaw in Fun, Uncategorized.add a comment
Unexpectedly, I see it clockwise… Though more worrying was that it took me 30 seconds to remember which way is clockwise!
Using SiteMap for external links and additional attributes May 8, 2008
Posted by reddogaw in ASP.NET, WCSF.Tags: not a valid virtual path, SiteMap
1 comment so far
In a website we are currently developing we are using the WCSF (from the Patterns and Practices group) and we wanted to inject in some links to a few external websites. The WCSF uses a custom SiteMapProvider that is part of its framework. A coworker highlighted how he solved the problem by simply overriding the URL as part of the TreeView (our menu) databound event handler within a master page.
I wasn’t especially happy with this solution since it separated the URL information from the code that created the information in the first place.
Since the problem originated a “not in virtual path” when the sitemap node has a URL that’s external to the application, I decided to route the external links through a redirect page (Redirect.aspx). The other important thing is to use HttpUtility.UrlEncode and HttpUtility.UrlDecode to take care of making the URL suitable for a querystring value.
(Note: don’t use escaped characters in the input string – e.g. +, %2f, etc. since this makes HttpUtility.UrlEncode assume the string is already encoded).
The redirect page is simply this:
if (!String.IsNullOrEmpty(Request.QueryString["url"])) { string url = HttpUtility.UrlDecode(Request.QueryString["url"]); Response.Redirect(url); } else { Response.Redirect("~/Default.aspx"); }
Then when inserting the SiteMapNodeInfo nodes into the collection I instead formatted the URL with:
string url = String.Format("~/Redirect.aspx?url={0}", HttpUtility.UrlEncode("http://www.myexternallink.com"));
The rest is specific to WCSF SiteMapNodeInfo nodes, but additionally, I wanted the external link to pop-out into a new browser window (target=”_blank”) so we need to pass in NameValueCollection with key/values for all the attributes you want converted in the final SiteMapNode instance (in our case we simply need Target):
NameValueCollection attrs = new NameValueCollection(1); attrs.Add("Target", "_blank"); SiteMapNodeInfo externalLinkNode = new SiteMapNodeInfo("ExternalLink1", url, "My External Site", "Check out the external site", null, attrs, null, null);
Then as was pointed out earlier, in order to take advantage of those additional attributes within your Menu or TreeView we will have to do so within our master page (or page).
protected void MainMenu_TreeNodeDataBound(object sender, TreeNodeEventArgs e) { Debug.Assert(e.Node.DataItem != null); Debug.Assert(e.Node.DataItem is SiteMapNode); e.Node.Target = (e.Node.DataItem as SiteMapNode)["Target"]; }
You could use the same method using additional attributes on the SiteMapNode used to include little images or icon’s (e.g. ImageUrl) next to the menu node.
Hope this helps some lost soul…
Love,
Reddog.
Tiny Tip: Use Consolas font pack for Visual Studio May 4, 2008
Posted by reddogaw in .NET General, Tips, Visual Studio.add a comment
This one has been often blogged but a good tip came around on email to use Consolas mono-spaced, clear type font inside Visual Studio. I’ve been using it for a little while and think it looks great. You can download it from MSDN. A good visual comparison between Consolas and the standard Courier is here.
One thing to add is that it’s optimised as a clear-type font. In Vista all fonts are enabled in clear type by default, but at least on my XP machine they weren’t. To enable this you need to go to the display properties dialogue (right click -> Properties on the desktop). Then on the Appearance tab, hit the Effects button to find this dialogue to enable it.

In Vista you can find this dialogue under Control Panel\Appearance and Personalization\Personalization on the Window Color and Appearance item. Use the link to open the classic properties box.
Archive: ASP.NET impersonation and SQL Server May 3, 2008
Posted by reddogaw in .NET General, Archive, SQL Server.Tags: ASP.NET Authentication, Impersonation, SQL Server
add a comment
From: http://blogs.ssw.com.au/andrewweaver/archive/2005/03/11/3968.aspx
Its a frequent situation where you want your ASP.NET application to connect to the SQL Server using the integrated security account. For example, you have all of your roles setup on the SQL Server and want your web application (secured via IIS integrated authentication) to get data specific to your role on the server.
In a windows application this is easily achieved by just making your SQL connection string use the integrated account (whichever windows account is running the app). But in a web application, the account that your SQL Server will open the connection under is the \ASPNET [or \Network Service in IIS6] not the account that is used for IIS authentication. To make it use the authenticating account you could turn on impersonation within your web.config file with the following:
<authentication mode="Windows" /> <identity impersonate="true" />
When I ran it with impersonation = true it just seemed to work perfectly (you can run a SQL trace to spot who the connection is coming in as). But be warned it doesn’t work for all server configurations apparently. I’ve just formatted and have a fresh install of SQL (running under the local system account) so I would think that I’ve got a “default” install…
An MSDN article sheds some light on why it won’t always work:
Why can’t I enable impersonation for the Web application, so that I can secure the resources accessed by my Web application using ACLs configured against the original caller?
If you enable impersonation, the impersonated security context will not have network credentials (assuming delegation is not enabled and you are using Integrated Windows authentication). Therefore, the remote call to SQL Server will use a NULL session, which will result in a failed call. With impersonation disabled, the remote request will use the ASP.NET process identity.
You will notice that it says that “assuming delegation is not enabled” (which it isn’t by default) these problems will occur. So obviously we might want to work out how to get this enabled… Keith Brown wrote an article detailing what you need to do to get this enabled – which should in theory get things working seamlessly.
A key problem with using impersonation is that you might now have security considerations that you weren’t thinking about, e.g. access to file resources, etc… Remember that all of your code is now executing as that user – not the ASPNET account…
Archive: Windows Impersonation in C# – Handy when debugging with ExOLE DB May 3, 2008
Posted by reddogaw in .NET General, Archive.Tags: DllImport, Externs, Impersonation, LogonUser
add a comment
From: http://blogs.ssw.com.au/andrewweaver/articles/186.aspx
While working on our new product SSW Exchange Reporter, the need to impersonate users (mostly for debugging purposes) arose. The reason being that unlike most of the other OLE providers you can’t provide login details with the connection string when trying to connect to Exchange with the ExOLEDB provider. For example an SQL connection string you can have “user=sa; password=xxx; ….” but you can’t for an ExOLE connection string. Therefore the ExOLE provider will not do any impersonation for you, it will always run under who ever is executing your application code. That is, whoever your service runs under or whoever is logged on and runs your .exe or whoever you run the .exe as using the ‘Run As…’ context menu item. Additionally the user we run under needed read permissions to all mailboxes.
Use some of the following code to do some impersonation.
Firstly make use of the windows LogonUser() function in advapi32.dll. Note that username and passwords are passed as plain text…
public const int LOGON32_LOGON_INTERACTIVE = 2;
public const int LOGON32_LOGON_SERVICE = 3;
public const int LOGON32_PROVIDER_DEFAULT = 0;
[DllImport("advapi32.dll", CharSet = CharSet.Auto)]
public static extern bool LogonUser(String lpszUserName, String lpszDomain, String lpszPassword, int dwLogonType, int dwLogonProvider, ref IntPtr phToken);
Then you can call this method to get the handle (the last parameter) for the user and use this to create a WindowsIdentity (in the System.Security.Principle namespace) and then begin impersonation with this handle.
IntPtr userHandle = new IntPtr(0); bool returnValue = LogonUser(name, machine, password, LOGON32_LOGON_INTERACTIVE, LOGON32_PROVIDER_DEFAULT, ref userHandle); if (! returnValue) throw new Exception("Invalid Username"); WindowsIdentity newId = new WindowsIdentity(userHandle); WindowsImpersonationContext impersonatedUser = newId.Impersonate();
You would probably wrap all this code, along with some additional verification code into a function called “BeginImpersonate“ or similar that would return both the user handle (so that you can free it later) and the impersonatedUser object so that you can end impersonation later via and “EndImpersonate“ function… End impersonation with the following code.
impersonatedUser.Undo();
Free the userHandle with a call to another windows function.
[DllImport("kernel32.dll", CharSet = CharSet.Auto)] public extern static bool CloseHandle(IntPtr handle);
Better examples can be found on the MS .NET documentation on WindowsIdentity.Impersonate method, but I hope this helped a little… In this document they actually duplicate user handles that they use for impersonation, though I don’t exactly understand why… You duplicate your handles via:
[DllImport("advapi32.dll", CharSet = CharSet.Auto, SetLastError = true)] public extern static bool DuplicateToken(IntPtr ExistingTokenHandle, int SECURITY_IMPERSONATION_LEVEL, ref IntPtr DuplicateTokenHandle);
Archive: Getting the Date portion of a DateTime type in SQL (T-SQL) – Use Floats and Floor! May 3, 2008
Posted by reddogaw in Archive, SQL Server.Tags: Convert, DateTime, SQL Server
2 comments
Update – 2 May 2008 – Watch out for SQL Server 2008′s new Date and Time data types!
From: http://blogs.ssw.com.au/andrewweaver/archive/2006/06/19/8262.aspx
Something that comes up quite frequently when dealing with reporting and DateTime fields on a data table is grouping by the Date portion only of the field or filtering for a full day of data.
If you were to filter DateTime values where the actual time portion is used then doing: SELECT * FROM Sales WHERE Sales.TransactionTime = '19 Jun 06'
Then you will only be getting the sales that were created at midnight!
Often you will see people wanting to only get the date portion by using a string conversion or a convoluted mix of SQL DateTime functions. For example: SELECT * FROM Sales WHERE CONVERT(varchar(10), Sales.TransactionTime, 101) = '2006-06-19'
But this is somewhat slower and more memory intensive than a way in which two co-workers (Mehmet and Mark) have suggested (I don’t think it was ever posted by them, but I’m sure its on the net somewhere). They say that you should convert the DateTime field to a float and floor it in order to get the date portion. This is will work as when the DateTime is converted to a float the date portion can be found as the whole number representation of the float, the time is the fractional portion.
For example:
-
Convert date to a float: SELECT CONVERT( Float, GETDATE())
-
Floor (take only whole number value) the float value to get only the date portion: SELECT FLOOR( CONVERT( Float, GETDATE()))
-
Convert back to date time (if needed) for display purposes: SELECT CONVERT(DateTime, FLOOR( CONVERT( Float, GETDATE())))
There are tonnes of posts regarding this, so checkout a few of them.
Archive: TIP: Shrinking / Saving / Compressing your big digital images May 3, 2008
Posted by reddogaw in Archive, Tips, Uncategorized.Tags: Compress, Images, IrfanView, Shrink
add a comment
Update – 3 May 2008 – IrfanView now has a batch save/edit mode that you can use to achieve a similar result…
From: http://blogs.ssw.com.au/andrewweaver/archive/2004/06/02/234.aspx
In order to share (via email or web page etc) your digital photos, you really should compress them (and shrink them a bit too) first.
One of the easiest ways is to use a freeware application called IrfanView. It’s great to use for viewing slideshows, and doing basic image editing (such as cropping, resizing, saving to different formats etc). It’s only like 800 KB so it’s small as well…
You can then use it’s command line options to make a simple bat file, that will take all files in a directory, shrink them a bit, knock down the compression quality and re-save them into a sub directory. I use the following bat file (which you can simply place in any directory that you want to shrink the files in).
@echo off set IViewDir=C:\Program Files\IrfanView set CurDir=%cd% set OutDir=%CurDir%\web "%IViewDir%\i_view32" "%CurDir%\*.jpg" /resize=(0, 600) /aspectratio /jpgq=75 /convert="%OutDir%\*.jpg" @echo on
This will put save all jpeg’s in a directory into a subdirectory called “web” (same filenames), change the jpeg quality to 75%, and resize the image to 600 pixels high (and width will scale according to the original aspect ratio).