A VS.NET Macro to Generate Machine Keys.
I needed to create a new machine key for an asp.net site. I found a couple of command line utils out on the web that would create a new key but I thought it would be easier to just have it avail in VS.NET. So, I threw together this little macro that will generate the machine key and insert it. Just run the macro while you have you web.config open in VS.NET. If you already have a machinekey it will find it and replace it. If not it will just add it right after the <system.web> node. It should do the proper indents and everything too.
1: Imports System
2: Imports EnvDTE
3: Imports EnvDTE80
4: Imports System.Diagnostics
5:
6: Public Module AspNetUtils
7:
8: #Region "Helper Code"
9:
10: Dim _rng As New System.Security.Cryptography.RNGCryptoServiceProvider()
11:
12: Private Function GetRandomData(ByVal size As Integer) As Byte()
13: Dim randomData(size) As Byte
14: _rng.GetBytes(randomData)
15: Return randomData
16: End Function
17:
18: Private Function ToHex(ByVal data() As Byte) As String
19: Dim sb As New System.Text.StringBuilder()
20: For i As Integer = 0 To data.Length - 1
21: sb.AppendFormat("{0:X2}", data(i))
22: Next
23: Return sb.ToString()
24: End Function
25:
26: Private Sub WriteNewMachineKey(ByVal sel As TextSelection)
27: sel.Insert("<machineKey")
28: sel.NewLine()
29: sel.Insert(String.Format("validationKey='{0}'", ToHex(GetRandomData(63))))
30: sel.NewLine()
31: sel.Insert(String.Format("decryptionKey='{0}'", ToHex(GetRandomData(23))))
32: sel.NewLine()
33: sel.Insert("decryption='SHA1'")
34: sel.NewLine()
35: sel.Insert("/>", vsInsertFlags.vsInsertFlagsContainNewText)
36: sel.Unindent()
37: sel.Collapse()
38: End Sub
39:
40: #End Region
41:
42: #Region "Macros"
43:
44: Public Sub GenerateMachineKey()
45: If Not DTE.ActiveDocument Is Nothing AndAlso DTE.ActiveDocument.Name.ToLower() = "web.config" Then
46: Dim sel As TextSelection = DTE.ActiveDocument.Selection
47:
48: If sel.FindPattern("\<machineKey((:b|\n)*:i=:q)*(:b|\n)*/\>", vsFindOptions.vsFindOptionsFromStart Or vsFindOptions.vsFindOptionsMatchInHiddenText Or vsFindOptions.vsFindOptionsRegularExpression) Then
49: ' Replace an existing <machineKey /> element
50: sel.Delete()
51: WriteNewMachineKey(sel)
52: ElseIf sel.FindText("<system.web>", vsFindOptions.vsFindOptionsFromStart Or vsFindOptions.vsFindOptionsMatchInHiddenText) Then
53: ' insert the new machineKey just after the <system.web> element
54: sel.Collapse()
55: sel.NewLine()
56: WriteNewMachineKey(sel)
57: Else
58: ' no <system.web> element found so just collapse the current selection and insert
59: ' the new key at the cursor location
60: sel.Collapse()
61: WriteNewMachineKey(sel)
62: End If
63: End If
64: End Sub
65:
66: #End Region
67:
68: End Module