Generating GUIDs in Visual Studio IDE

An easy way to generate GUIDs in the Visual Studio IDE is to create you own macros and do it through the Windows clipboard. The clipboard is accessed through System.Windows.Forms.Clipboard, easy enough, but the rub is that Visual Studio macros run in the context of an MTA apartment. You need to access the Clipboard .NET class in an STA thread. To do this, we create a new thread in a Visual Studio macro and make it an MTA thread.

I You can use the class below in a Visual Studio 2010 macro project. The same class should work in other Visual Studio versions, you may just have to tweak the Import statements a bit.

Imports System
Imports EnvDTE
Imports EnvDTE80
Imports EnvDTE90
Imports EnvDTE90a
Imports EnvDTE100
Imports System.Diagnostics
Imports System.Windows.Forms

''
'' Class for setting and getting values from Windows clipboard in Visual Studio macros.
''
'' Remarks: The call to System.Windows.Forms.Clipboard need to be make in an STA, Visual
'' Studio runs in an MTA.
Public Class VSClip

    Private _data As Object = Nothing
    Private _fmt As String = Nothing

    Public Sub SetData(ByVal Data As Object)
        _data = Data
        Dim t As New System.Threading.Thread(AddressOf Me._runSet)

        ' create STA thread to set clipboard data
        t.SetApartmentState(Threading.ApartmentState.STA)
        t.Start()
        t.Join() ' wait for thread to finish
    End Sub

    Private Sub _runSet()
        System.Windows.Forms.Clipboard.SetDataObject(_data, True)
    End Sub

    Public Function GetData(ByVal fmt As String) As Object
        _fmt = fmt
        Dim t As New System.Threading.Thread(AddressOf Me._runGet)

        ' create STA thread to get clipboard data
        t.SetApartmentState(Threading.ApartmentState.STA)
        t.Start()
        t.Join() ' wait for thread to finish
        Return _data
    End Function

    Private Sub _runGet()
        _data = Nothing
        Dim oData As IDataObject = System.Windows.Forms.Clipboard.GetDataObject()
        If Not oData Is Nothing Then
            If oData.GetDataPresent(_fmt, True) Then
                _data = oData.GetData(_fmt, True)
            End If
        End If
    End Sub

End Class

Now, for the task of adding a new GUID to the clipboard, we create a macros such as the one below:

Imports System
Imports EnvDTE
Imports EnvDTE80
Imports EnvDTE90
Imports EnvDTE90a
Imports EnvDTE100
Imports System.Diagnostics

Public Module ClipboardExchange

    Public Sub NewGuid()
        Dim cp As New VSClip
        cp.SetData(Guid.NewGuid().ToString())
    End Sub

End Module

I included all of the Import ... stuff at the top of each snippet so you can easily copy and paste into a Visual Studio macro project.

This macro was written for Visual Studio 2010, but I have been doing this back since the days of Visual Studio 2003. You may have to tweak a little for different versions, maybe the Import statements, but the code stays pretty much the same.

Posted in Visual Studio Macros | Tagged | 1 Comment

Refresh Windows 7 Icon Cache

When Modified Icons Don’t Change Appearance

This is a real pain in the butt when you are testing installs with new application icons or are designing icons and they don’t show up differently on the desktop.

taskkill /IM explorer.exe /F
cd %USERPROFILE%\AppData\Local
del /a IconCache.db
start explorer

Your icons will now be smiling back at you with their fresh new faces.

Posted in Uncategorized | Leave a comment

Override a Widget’s Default In a web2py View

I have been trying to learn web2py over the last few months. I have found it hard to do something like update a form widget in a view, especially that of a password field. I learned that you could do it when creating the Field object and setting default='blahblah', but what if you wanted to change it later, like in a view? Well, here is:

form.element(_name='myfield').update(_value='myvalue')

I spent some time digging around for this. Now, if this is a registration form, this might not work.

Posted in web2py | Tagged | Leave a comment

Cygwin Snippets and Resources

With Cygwin, sometimes you need all the help you can get. Here are some usefull snippets.

Bash

Find command for file, exclude Windows directories

This searches or .png files among the Cygwin files. The -path ‘/BlahBlah’ -prune prevents the recursion from going into specific directories, and the -o strings the options together. You need to knock out /cygdrive, /dev, and /proc to prevent the native Windows directories, registry, etc. from being searched. Without eliminating those, your search takes a long time.

find / -path '/cygdrive' -prune -o -path '/dev'-prune -o -path '/proc' -prune -o -name '*.png' -print

Delete A File If Present, Delete Parent Directory If Now Empty

#!/bin/sh
function RemoveFile()
{
	if [ -f "$1" ]; then
		chmod u+w "$1"
		rm -f "$1"
	fi
}

function RemoveFileAndEmptyParent()
{
	RemoveFile "$1"
	scdir=$(dirname "$1")
	if [ -d "${scdir}" ]; then
		if [ ! "$(ls -A "${scdir}")" ]; then
			chmod u+w "${scdir}"
			rm -r "${scdir}"
		fi
	fi
}

DeskTopDir=$(cygpath -A -D)

RemoveFile "${DeskTopDir}/My Shortcut.lnk"

SMDIR="$(cygpath -P -A)"/My\ Application

RemoveFileAndEmptyParent "${SMDIR}/My Shortcut.lnk"

Extract Contents From tar.bz2 File
tar -xjvf some-file.tar.bz2

Extract Contents From tar.z File
tar -zxvf some-file.tar.gz

Recursively Grep, Excluding Directories
grep -r --exlcude-dir=".svn" MySearchTerm .

When Things Get Weird

Rebasing Cygwin DLLs

Nothing seems to work? Xterm in a bad mood and won’t load? Rebasing the DLL’s in Cygwin seems to do the trick often. So try this:

From a CMD prompt:

cd c:\cygwin
ash
./rebaseall -v
exit

Posted in Cygwin, Snippets | Tagged | Leave a comment

VIM Snippets and Resources

Sometimes you have to get yourself to use VIM. It is a good tool, but when you are starting out, it can be frustrating. Come here for some links to resources and useful snippets; it’s cheaper than a therapist. I need these for myself also.

Snippets

Clear Last Search Pattern

:let @/=”"

or

:noh

Repeat Character N Times

:norm 79i=

Stop Recording
Sometimes I don’t know how I got here but I gotta get out!!!

q

Useful Links

Nothing like going to the source itself: www.vim.org

Cheat Sheets

Nice and clean, not a lot of cryptic graphics: tnerual.eriogerg.free.fr/vimqrc.html
Some good notes: http://www.brezeale.com/technical_notes/vim_notes.shtml
vim and Tabs

https://www.linux.com/learn/tutorials/442422-vim-tips-using-tabs

Useful .vimrc settings

set backupdir = ~/tmp # annoying ~ files in ~/tmp
set noswapfile #no swap files
#set nobackup #uncomment out for no backups, period
#set nowritebackup #no backup files while editing

Posted in Snippets | Tagged | Leave a comment

T4 Text Transformation Snippets

Getting Started
First you need to download the following:

Visual Studio SP1 SDK
http://www.microsoft.com/download/en/details.aspx?id=21835

Visual Studio Modelling SDK

Microsoft Visual Studio 2010 Visualization & Modeling SDK

If you need the Visual Studio SP1, here it is:
Microsoft Visual Studio 2010 Service Pack 1 (Installer)

Emit Project Namespace In Included File

System.Runtime.Remoting.Messaging.CallContext.LogicalGetData("NamespaceHint")

Posted in Uncategorized | Leave a comment

PowerShell v2 Snippets

Here is a new, hopefully ever expanding library of PowerShell snippets.

Set PowerShell Current Working Directory
To set current working directory to current directory currently navigated to use

[IO.Directory]::SetCurrentDirectory((Convert-Path (Get-Location -PSProvider FileSystem)))
or
[Environment]::CurrentDirectory=(Get-Location -PSProvider FileSystem).ProviderPath

These snippets are from: http://huddledmasses.org/powershell-power-user-tips-current-directory/

Execute WMI Query
Get-WmiObject -Query "Select * from Win32_Process WHERE Caption=""Notepad.exe"""

Checkout WMI Query Language (WQL) – An introduction at http://www.ravichaganti.com/blog/?p=1509 for some great resources on PowerShell querying examples.

Posted in PowerShell, Snippets | Tagged | Leave a comment

Smash the Learning Curve – MVVM Light

I like learning cool new stuff but I hate steep learning curves. Some messages in AZGroups inspired me to do this post. I am long overdue for a blog post anyway. I want to kick off a post getting people started off with lightweight MVVM frameworks, especially ones for Silverlight. The goal is to have a post referencing some good MVVM “light” frameworks, links to good examples and tutorials on these frameworks, MVVM in general, and some good ideas to get people rapidly productive using these tools and concepts. It took me long enough to learn this, so let’s get some stuff up that other people can use to compress their learning curves. I’ll post some of my ideas, you can post responses, and I’ll try to organize things as time goes by. This is a post that’s intended to be updated a lot.

MVVM Light
First of all, let’s start with Laurent Bugnion’s MVVM Light. This is something that got me on the right track to learning MVVM for Silverlight. Works great for WPF also. Download the toolkit at . Laurent Bugnion’s site is at , There you can find lots of resources for his framwork and MVVM in general.

MVVM Light Survival Guide – Good point to get down and focus on for flatten the learning curve.

  1. Code Behind – this is all the spaghetti we used to have in our VB6, MFC, VB/C# .NET Winform, etc projects. Think about those 1500+ lines of slop in the code behind file for a form VB .NET project. You might have not even written it, but it’s in you lap and you need to fix, enhance, and understand it. This is the stuff that makes a project hard to maintain and impossible to test. This the stuff that needs to go. Think of code-behind, a carton of cigarettes, and kicking the habit.
  2. Behaviors – a good understanding of behaviors is necessary for proficiency at MVVM. I will update this post with examples for behaviors using the Blend SDK. We can use the Blend SDK without having to install Blend. Blend is nice and is your friend, albeit not free. You can write behaviors without using the Blend SDK however. In many respects, a behavior is a conduit for handling one or more events in a Silverlight/WPF control in a code module. They are applied in the XAML in a declarative manner.
  3. Design Time &ndash MVVM is great designing. Can’t do this with code-behind. A master-detain view showing up in Cider or Blend with design time data will get team members excited about kicking any lingering code behind habits.
Posted in MVVM, Silverlight 4, Uncategorized, WPF | Tagged , , | Leave a comment

Code Banquet Started

Here is a new place for those code snippets and quick examples to copy-and-paste and massage into your own work.

A lot of this is for my own benefit. I won’t take the time to throw all of this in my own personal compiled library and I have gotten tired of rewriting the same similar pieces of code.

http://www.level533.com/code-banquet/

Posted in Uncategorized | Leave a comment

Class For Parsing Windows Command Line

This is more of a snippet for myself. This is useful for parsing command lines for Windows Console applications and I have written code like this many times over. This class parses command lines of the form:

someprogram.exe /<switch0>:<switch0 value> /<switch1> /<switch2>:<switch2 value enclosed in quotes>

An example would be:

foo.exe /source:"C:\temp\path with spaces" /source:C:\temp\foo /dest:C:\DestFolder /c /o

Note the duplicate entry for /source. This class supports the same switch appearing multiple times.

using System;
using System.Collections.Generic;
using System.Text.RegularExpressions;

namespace ConParse
{
    /// <summary>
    /// This class will parse a Windows console application command line.
    /// <remarks>
    /// Switches are entered in the form
    /// Example: YourProgram.exe /switchname:&quot;switch value with spaces in quotes&quot; /f /sec:90  /src:C:\temp /src:"C:\temp\foo dir"
    /// Switches start with / followed by a single character or string token for the switch.  Switches with values are followed by a colon :.
    /// Values with spaces in them are enclosed in quotes.  A particulare switch may be entered more than once.
    /// </remarks>
    /// </summary>
    public class CArgs : Dictionary<string, List<string>>
    {
        /* Without excaped quotes, the Regex looks like the following below.
(?<=/) (?<sw>\w+)
(?<co>:)?   (?(co) (?<qu>")?
                (?(qu) (?<arg> [^"]+)" | (?<arg> \S+)  )
            )
         */

        // pattern to parse the command line
        private const string _PATTERN = @"(?<=/) (?<sw>\w+)
(?<co>:)?   (?(co) (?<qu>"")?
                (?(qu) (?<arg> [^""]+)"" | (?<arg> \S+)  )
            )  ";

        /// <summary>
        /// Constructor, parses the command line and populates the dictionary.
        /// </summary>
        public CArgs()
        {

            // get complete command line
            string sCmdLine = Environment.CommandLine;

            // sanity check, should never be true
            if (string.IsNullOrEmpty(sCmdLine))
                return;

            // we get the name of the program at the beginning of the command line.  This we want to strip out
            string[] args = Environment.GetCommandLineArgs();

            // sanity check, these should never be true
            if (null == args)
                return;

            // other sanity check, should not be true
            if (args.Length < 1)
                return;

            // first arg is the path to the program
            string arg0 = args[0];
            if (!string.IsNullOrEmpty(arg0))
            {
                int startAt = arg0.Length;

                // the command line may being with a quote for an exe in a path with spaces, args[0] will no have the quotes
                if (sCmdLine.StartsWith("\""))
                    startAt += 2;

                // strip out the exe part
                sCmdLine = sCmdLine.Substring(startAt);
            }

            // parse the command line switches
            Match mt = Regex.Match(sCmdLine, _PATTERN, RegexOptions.IgnorePatternWhitespace | RegexOptions.Singleline);
            string sw = null;
            string sarg = null;
            List<string> vals = null;
            while (mt.Success)
            {
                sw = mt.Groups["sw"].Value;
                sarg = mt.Groups["arg"].Value;

                if (this.ContainsKey(sw))
                {
                    vals = this[sw];
                }
                else
                {
                    vals = new List<string>();
                    this[sw] = vals;
                }

                //switches without values will have empty string values.
                vals.Add(sarg ?? string.Empty);

                mt = mt.NextMatch();
            }
        }
    }
}
Posted in C#, Code Samples | Tagged | Leave a comment