User Tools

Site Tools


start

Stephen's Wiki (Azure)

Welcome to Stephen's wiki. There is lots of really great content here - you just have to search for it.

Stephen's Blog (sort of)

This is a collection of random stuff I want to record for future reference. Probably not much use to anyone else.

Visual Studio can't open CSHTML files

Fix it thusly:

  1. Close Visual Studio.
  2. Delete everything in %LocalAppData%\Microsoft\VisualStudio\14.0\ComponentModelCache
  3. Open Visual Studio.

Append randomness to start of a filename

Get-ChildItem *.mp3 | ForEach-Object{Rename-Item $_ -NewName "$(Get-Random) $($_.Name).mp3"}

Why did Windows wake from sleep?

Run this and find out:

powercfg -lastwake

HTML Sanitation

Add the 'AntiXSS' (Microsoft) package from NuGet.

var input = "fjkdlsjf<script></script> <b>klds</b> <a href='fsdfsd.html'>Test</a> <a href='javascript:alert('bugger off')'>HubAdmin</a>"; 
 
var output =  Microsoft.Security.Application.Sanitizer.GetSafeHtmlFragment(input);
// fjkdlsjf <b>klds</b> <a href="fsdfsd.html">Test</a> <a href="">HubAdmin</a>

Setting up a Database User

  1. [SQL Server Management] Right click the server, Properties.
  2. [SQL Server Management, Server Properties] Security → Server Authentication → SQL Server and Windows Authentication mode
  3. [SQL Server Management, Server Properties] Ok
  4. [SQL Server Management] Right click (Server) → Security → Logins, New Login…
  5. [SQL Server Management, Login - New] General → Fill in details.
  6. [SQL Server Management, Login - New] Server Roles → public only.
  7. [SQL Server Management, Login - New] Ok
  8. [SQL Server Management] Right click (Server) → Databases → (Database) → Security → Users, New User…
  9. [SQL Server Management, Database User - New] General → Fill in details.
  10. [SQL Server Management, Database User - New] Membership → Fill in details.
  11. [SQL Server Management, Database User - New] Ok.

Reading Event Logs with PowerShell

# Logs that contain 'Sequence contains'.
Get-EventLog Application -Source M.pad -newest 20 -message "*Sequence contains*"  | Format-Table -autosize -wrap
 
# Logs that do not contain 'FromCommonAuditItem'.
Get-EventLog Application -Source M.pad -newest 2000 | Where { $_.Message -notmatch 'FromCommonAuditItem' } | Format-Table -autosize -wrap

Unit Testing Private Methods

Ignoring the argument as to whether a private method should be unit tested…

using Microsoft.VisualStudio.TestTools.UnitTesting;
 
public class Banana {
	private int _count;
	private static int Add(int n1, int n2) {
		return n1 + n2;
	}
 
	private int Inc() {
		_count = Add(_count, 2);
		return _count;
	}
}
 
class Program {
	static void Main(string[] args) {
		PrivateType bananaTest1 = new PrivateType(typeof(Banana));
		int result1 = (int)bananaTest1.InvokeStatic("Add", 12, 34);
 
		PrivateObject bananaTest2 = new PrivateObject(new Banana());
		int result2 = (int)bananaTest2.Invoke("Inc");
	}
}

Enable external web requests (Win8)

  1. Open 'Windows Firewall' (with Advanced Security)
  2. Add an Inbound Rule
  3. Local port 80 (and 443 if HTTPS is required).

When HTTPS requests always return 404s

  1. [IIS Manager] Select the Default Web Site.
  2. [IIS Manager] On the right, under Actions, Edit site, select Bindings…
  3. [IIS Manager, Site Bindings] There should be two entries, http & https. Select https, select Edit…
  4. [IIS Manager, Edit Site Binding] SSL certificate should be selected (e.g. PKS1684.corp.ps.co.nz).

Poor Man's Dependency Injection

Chris used an abstract base class. The following should be adapted for an interface, if possible.

/*
  <appSettings>
    <add key="definitionService" value="EA.ReportingPortal.Services.DbDefinitionService" />
  </appSettings>
*/ 
public abstract class DefinitionService
{
	public abstract List<CategoryTag> GetAllCategories();
	// ...
 
	public static DefinitionService Current
	{
		get
		{
			var activeServiceName = WebConfigurationManager.AppSettings["DefinitionService"];
			if (string.IsNullOrWhiteSpace(activeServiceName))
				throw new ConfigurationErrorsException("Definition Service type not specified or blank");
 
			var serviceType = typeof(DefinitionService).Assembly.GetType(activeServiceName);
			if (serviceType == null || !typeof(DefinitionService).IsAssignableFrom(serviceType))
				throw new ConfigurationErrorsException("Definition Service type does not exist or does not inherit from DefinitionService");
 
			var defaultConstructor = serviceType.GetConstructor(Type.EmptyTypes);
			if (defaultConstructor == null)
				throw new ConfigurationErrorsException("Definition Service type does not have an empty constructor");
 
			return (DefinitionService)defaultConstructor.Invoke(null);
		}
	}
}

How to view LINQ Generated SQL statements

((System.Data.Objects.ObjectQuery)myQuery).ToTraceString()

Or, if you want an extension method:

public static class IQueryableExtensions
{
    public static string ToTraceString<T>(this IQueryable<T> t)
    {
        ObjectQuery<T> oqt = t as ObjectQuery<T>;
 
        return oqt == null ? string.Empty : oqt.ToTraceString();
    }
}

Windows Azure Regional Response Times

Region Free Standard
Mean StdDev Mean StdDev
West US 160.03 23.97 155.72 12.17
East Asia 163.13 22.12 159.67 13.76
North Central US 205.12 11.56 207.13 15.07
East US 212.42 9.47 213.05 12.15
North Europe 293.83 16.72 287.96 14.76
West Europe 307.37 45.31 296.47 11.05

Azure Speed Test

Just use Australia East.

Unget Files from TFS

  1. [Visual Studio] Open Source Control Explorer.
  2. [Visual Studio - Source Control Explorer] Right click the branch or folder to be ungetted.
  3. [Visual Studio - Source Control Explorer] Select 'Get Specific Version…'
  4. [Visual Studio - Get dialogue] Type: Changeset.
  5. [Visual Studio - Get dialogue] Changeset: 1.
  6. [Visual Studio - Get dialogue] Click Get. Bye bye local files and the branch / folder is updated correctly in the Source Control Explorer.

Caches along a trail

  1. Open this page in a new browser window.
  2. Setup a list for the results.
  3. Create a new or reuse an existing route.
  4. Create a run-once pocket query based on the route.
  5. Sort the results by favourites and open each in separate browser tab.
  6. Send each one to c:geo.
  7. Bookmark the first one and add it to the list.
  8. Bookmark all the rest.
  9. Go back to the lists and create a pocket query based on it.
  10. Check lots of boxes and Use the “Uncheck the day of the week after the query runs” option.
  11. Go to pocket queries and delete it.
  12. Wait for email.
  13. Upload attached GPX file to phone.
  14. Import caches into Locus.
  15. Use uMap (Twitter log in).
  16. Create new map and upload GPX file.

To print:

  1. Open uMap page in Firefox.
  2. F11 to full screen.
  3. Ctrl + PrnScn (or whatever it is).
  4. Open Paint.NET, paste & print.
  5. Untick 'Fit picture to frame'.

How to enable Service Tracing

  1. [Visual Studio] Tools → WCF Service Configuration Editor
  2. [Microsoft Service Configuration Editor] File → Open → Config File…
  3. [Microsoft Service Configuration Editor] (Open the Web.config file)
  4. [Microsoft Service Configuration Editor] Diagnostics (not a subnode)
  5. [Microsoft Service Configuration Editor] Click Enable MessageLogging
  6. [Microsoft Service Configuration Editor] Click Enable Tracing
  7. [Microsoft Service Configuration Editor] File → Save
  8. [] Rerun app and reproduce error or whatever.
  9. [Windows Explorer] Open directory with Web.config in it.
  10. [Windows Explorer] Double click Web_messages.svclog and Web_tracelog.svclog.

MVC Date binding

[DataType(DataType.Date)]
[DisplayName("Start date")]
[DisplayFormat(DataFormatString = "{0:dd/MM/yyyy}", ApplyFormatInEditMode = true)]
[Date(ErrorMessage = "Please enter a start date")]
public DateTime StartDate { get; set; }

Get a connection string using a GUI

  1. Minimise all windows.
  2. On the desktop, create a new file and name it 'test.udl'.
  3. Double click it.
  4. Select Provider and connection settings and play with them until they work.
  5. Click ok.
  6. Open 'test.udl' in a text editor. There is your connection string.

Delete a TFS Workspace that does not exist

Visual Studio can sometimes get a bit confused about which TFS workspaces exist and which don't. Sort it out with the Visual Studio Command Prompt.

Figure out what workspaces really exist:

tf workspaces /collection:sourcecontrol.company.co.nz\DefaultCollection

Well and truly delete the motherfucker:

tf workspace /delete workspacename

If tf starts complaining about “Unable to determine the source control server”, try running the first command again (it seems to magically fix shit up or something):

tf workspaces /collection:sourcecontrol.company.co.nz\DefaultCollection

Rob Connery's JavaScript Inferno

Library Conceptual Density Googles/Hour Scaling Pain¹ Rob's Choice
Knockout Fairly Low 6 - 8 20, 25, 50, 90 80% of the time
Backbone High 25 - 30 50, 30, 20, 20
Angular Medium/ High 10 - 20 10, 20, 70, 90 Simple JS App
Ember Extreme 90, 25, 20, 10 Big JS App

¹ Simple, Moderate, Advanced, Enterprise
² Gave up googling, api changes often, lots of out-of-date info on web.

Conditional Attributes in Razor

<div @(item.Selected ? string.Empty : "style=display:none")></div>

Note that Razor is quite fussy about the format of the style=display:none bit. No spaces.

A less nice method that also works is:

<div class="notch" @(Html.Raw(item.Selected ? string.Empty : "style=\"display: none;\""))></div>

ASP.NET MVC Security Check List

Problem Steps Recorder

On Windows 7 and above:

  1. Start button.
  2. Type Steps or PSR.
  3. Click 'Record steps to reproduce a problem'.
  4. Be amazed.

Updating NuGet VS2010 WinXP

  1. Download NuGet.Tools.vsix (look for it at nuget.org)
  2. Uninstall NuGet from within Visual Studio.
  3. Close Visual Studio.
  4. Run the NuGet.Tools.vsix file to install the new version.

Log Parser Examples

Search the application event log on the local machine:

LogParser.exe -i:evt -rtp:-1 "SELECT TOP 100 * FROM Application WHERE SourceName like '%Reporting%'" > d:\Temp\Output.txt 

Search the standard three event logs on the local machine:

LogParser.exe -i:evt -rtp:-1 "SELECT TOP 100 * FROM System, Application, Security WHERE SourceName like '%Reporting%'" > d:\Temp\Output.txt 

Search the application event log on a remote machine (may take a while):

LogParser.exe -i:evt -rtp:-1  "SELECT TOP 100 * FROM \\MachineName\Application WHERE SourceName like '%Reporting%'" > d:\Temp\Output.txt 

The -rtp:-1 option suppresses the “Press a key…” prompt.

Batch Convert Image Format

In a Powershell console:

Get-Item *.jpg | ForEach-Object { convert $_ "$($_.basename).png" }

This also works:

Get-ChildItem 'C:\External Drives\Primary Media 2\My Pictures\Fractals\FA (Dual Monitor Wallpaper)' | Foreach { convert $_.FullName -resize 3840x1080! -quality 99 $_.Name }

For canvas prints through pixelpaint.co.nz, use 8E series images and convert to JPEG, < 15MB. Copy images from C:\External Drives\Primary Media 2\My Pictures\Fractals\8E (Printing) to a temp directory. Run this:

Get-ChildItem | Foreach { convert $_.FullName -quality 98 "$($_.basename).jpg" }

For any that are still bigger than 15MB, decrease quality and / or size (-resize 80%%).

Firefox Command Line Parameters

-ProfileManager Starts Firefox with the Firefox Profile Manager.
-P “Profile Name” Starts Firefox using the specified profile.
-safe-mode Starts Firefox in “Safe Mode” - useful when extensions go awry.
-no-remote Permits multiple instances of Firefox using separate profiles.

Enabling NTLM Authentication (Single Sign-On) in Firefox

  1. Open Firefox and type about:config in the address bar.
  2. In the Filter field enter network.automatic-ntlm-auth.trusted-uris.
  3. Set the value to a comma separated list of sites:
    http://intranet.company.com,http://email.company.lan

Binding a Drop Down to a Value That Might Not Exist

How do I fix the following error:

‘dropdownlist1′ has a SelectedValue which is invalid because it does not exist in the list of items
  1. Remove the SelectValue binding in the drop down:
    SelectedValue='<%# Bind("LocationId") %>'
  2. In the code behind, add the following to the PreRender of the FormView:
    Protected Sub EmployeeDetailsFormView_PreRender(ByVal sender As Object, ByVal e As System.EventArgs) Handles EmployeeDetailsFormView.PreRender
    	If EmployeeDetailsFormView.CurrentMode = FormViewMode.Edit Then
    		Dim Location_DropDownList As DropDownList = CType(EmployeeDetailsFormView.FindControl("Location_DropDownList"), DropDownList)
     
    		Dim rowView As DataRowView = CType(EmployeeDetailsFormView.DataItem, DataRowView)
    		If IsNothing(rowView) Then Return ' Or perhaps throw an exception.
    
    		Dim locationId As String = rowView("LocationId").ToString() 
     
    		If Not IsNothing(Location_DropDownList.Items.FindByValue(locationId)) Then
    			Location_DropDownList.SelectedValue = locationId
    		Else
    			' TODO: Set the value to whatever it should be if there is no match.
    			Location_DropDownList.SelectedValue = "0"
    		End If
    	End If
    End Sub
  3. Then add the following the ItemUpdating of the FormView:
    Protected Sub EmployeeDetailsFormView_ItemUpdating(ByVal sender As Object, ByVal e As FormViewUpdateEventArgs) Handles EmployeeDetailsFormView.ItemUpdating
    	Dim Location_DropDownList As DropDownList = CType(EmployeeDetailsFormView.FindControl("Location_DropDownList"), DropDownList)
     
    	e.NewValues("LocationId") = Location_DropDownList.SelectedValue
    End Sub

Breaking Excel VBA Project Passwords

  1. Open the Excel file in a Hex Editor (XVI32 will do nicely).
  2. Search for the text string “DPB=”.
  3. Change it to “DPx=”.
  4. Save and close.
  5. Open in Excel.
  6. Open VBA project (Alt + F11) - ignore errors.
  7. Right click the project and select Foo Properties…
  8. Change the password and save.

Running Unit Tests with Code Coverage

Create the Test Settings

  1. In Visual Studio, from the main menu, select TestEdit Test SettingsLocal (Local.testsettings).
  2. [Test Settings] Select the Save As button.
  3. [Save As] Enter 'CodeCoverage.testsettings' and select OK.
  4. [Test Settings] Select Data and Diagnostics.
  5. [Test Settings] Enable Code Coverage.
  6. [Test Settings] Double-click Code Coverage.
  7. [Code Coverage Detail] Select the assembly or assemblies that you wish to have code coverage for. Normally this would be the non-test assemblies.
  8. [Code Coverage Detail] Select OK.
  9. [Test Settings] Select Apply and then Close.
  10. [Save Dialog] Select Yes.
  11. Done. Test settings should be checked into source control.

Running Unit Test with Code Coverage

  1. In Visual Studio, from the main menu, select TestSelect Active Test SettingsLocal (CodeCoverage.testsettings).
  2. Change the build configuration to Debug.
    1. From the main menu, select BuildConfiguration Manager….
    2. [Configuration Manager] Set the Active Solution Configuration to Debug.
    3. [Configuration Manager] Select Close.
  3. If the target is signed, temporarily remove it.
    1. Open the project properties.
    2. Select the Signing tab.
    3. Uncheck the Sign the assembly check box.
    4. Save the project.
  4. Run the unit tests.
  5. Turn the Code Coverage Colouring on and off in the Code Coverage Results window.

Converting a Web Site Project to a Web Application Project

…and maintaining version history.

  1. [SubVersion] Export the trunk to a temp directory.
    • C:\Temp\SuperApp\trunk
  2. [Text Editor] In the temp solution, open the solution file.
    • C:\Temp\SuperApp\trunk\SuperApp.sln
  3. [Text Editor] Find the section that has Web Site Project. It will look something like:
    Project("{E24C65DC-7377-472B-9ABA-BC803B73C61A}") = "SuperApp.Web", "SuperApp.Web", "{C92B633A-C441-4FB6-904B-EEA604BAAF15}"
    	ProjectSection(WebsiteProperties) = preProject
    		...
    		ProjectReferences = "{0A231AD6-AF0C-45C1-B441-2AB97BC40975}|SuperApp.DataAccess.dll;{96DC8217-C24D-4851-B4C2-92FBE60727CC}|SuperApp.Business.dll;"
    		...
    	EndProjectSection
    EndProject
  4. [Text Editor] Note down any project references for later. In the example above, the Web Site Project references SuperApp.DataAccess.dll and SuperApp.Business.dll.
  5. [Text Editor] Delete the entire Web Site Project (from Project to EndProject inclusive) and save.
  6. [Windows Explorer] In the temp solution, delete the entire Web Site Project directory
    • C:\Temp\SuperApp\trunk\SuperApp.Web
  7. [Visual Studio] Open the temp solution.
  8. [Visual Studio] Create a new ASP.NET Empty Web Application in the old Web Site Project directory. Make sure it is the correct language (VB or C#)! The language of new ASP.NET Empty Web Application must match the existing Web Site Project.
    • C:\Temp\SuperApp\trunk\SuperApp.Web
  9. [Visual Studio] Save and close.
  10. [SubVersion] Copy and rename to a branch.
    • C:\Dev\SuperApp\trunkC:\Dev\SuperApp\branches\Converting to Web App
  11. [Text Editor] In the branch solution, open the solution file.
    • C:\Temp\SuperApp\branches\Converting to Web App\SuperApp.sln
  12. [Text Editor] Remove the Web Site Project and save.
  13. [Windows Explorer] Copy from the temp solution to the branch solution:
    • (C#) C:\Temp\SuperApp\trunk\SuperApp.Web\PropertiesC:\Temp\SuperApp\branches\Converting to Web App\SuperApp.Web
    • (VB) C:\Temp\SuperApp\trunk\SuperApp.Web\My ProjectC:\Temp\SuperApp\branches\Converting to Web App\SuperApp.Web
    • C:\Temp\SuperApp\trunk\SuperApp.Web\SuperApp.Web.csprojC:\Temp\SuperApp\branches\Converting to Web App\SuperApp.Web
    • C:\Temp\SuperApp\trunk\SuperApp.Web\Web.Debug.configC:\Temp\SuperApp\branches\Converting to Web App\SuperApp.Web
    • C:\Temp\SuperApp\trunk\SuperApp.Web\Web.Release.configC:\Temp\SuperApp\branches\Converting to Web App\SuperApp.Web
  14. [Text Editor] The Web.config in the branch solution probably does not need to be changed, but open both and check just in case.
    • C:\Dev\SuperApp\branches\Converting to Web App\SuperApp.Web\Web.config
    • C:\Temp\SuperApp\trunk\SuperApp.Web\Web.config
  15. [Visual Studio] Open the branch solution.
  16. [Visual Studio] In the Solution Explorer, turn on Show All files.
  17. [Visual Studio] In the Web App project, include all the file and directories except the Bin and Obj directories.
  18. [Visual Studio] Right click the Web App project and select Manage NuGet Packages.
  19. [Visual Studio, Manage NuGet Packages dialog] If there is a message about restoring NuGet packages, do it.
  20. [Visual Studio] Add the project references noted down in step 4.
  21. [Visual Studio] Right click each ASPX file and select Convert To Web Application.
  22. [Visual Studio] Set the Web App project as the start up project, and set the appropriate start page.
  23. [Visual Studio] Cross fingers and run it.

Click To Reveal Row

<script src="../Scripts/jquery-1.7.2.min.js" type="text/javascript"></script>
<script type="text/javascript">
	$(document).ready(function () {
		$(".CollapsibleTrigger").click(function (event) {
			$(this).next().toggle();
 
			if ($(this).next().is(':visible'))
				$(this).addClass('Expanded');
			else
				$(this).removeClass('Expanded');
		});
	});
</script>
<asp:ListView ID="Foo_ListView" runat="server" DataSourceID="Foo_Logic" DataKeyNames="FooID" >
	<LayoutTemplate>
		<table class="DataWebControlStyle" cellspacing="0" cellpadding="2" border="1">
			<tr class="GridHeader">
				<th>Blah</th>
				...
			</tr>
			<asp:PlaceHolder ID="itemPlaceholder" runat="server" />
		</table>
		<asp:DataPager runat="server" ID="ContactsDataPager" PageSize="50">
			<Fields>
			<asp:NextPreviousPagerField ShowFirstPageButton="true" ShowLastPageButton="true"
				FirstPageText="|&lt;&lt; " LastPageText=" &gt;&gt;|"
				NextPageText=" &gt; " PreviousPageText=" &lt; " />
			</Fields>
		</asp:DataPager>
	</LayoutTemplate>
	<ItemTemplate>
		<tr class='<%# String.Format("{0} CollapsibleTrigger", Me.AlternatingGridRowClass()) %>'>
			<td><asp:Label ID="Foo_Label" runat="server" Text='<%# Eval("Foo") %>' /></td>
			...
		</tr>
		<tr class="CollapsibleRegion" style="Display: none;">
			<td><asp:Label ID="Bar_Label" runat="server" Text='<%# Eval("Bar") %>' /></td>
			...
		</tr>
	</ItemTemplate>
</asp:ListView>
Private _alternateRow As Boolean
Protected ReadOnly Property AlternatingGridRowClass() As String
	Get
		_alternateRow = Not _alternateRow
		Return If(_alternateRow, "GridAlternatingRow", "GridRow")
	End Get
End Property

Debug Update Parameters

Protected Sub Foo_ObjectDataSource_Updating(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.ObjectDataSourceMethodEventArgs) _
	Handles Foo_ObjectDataSource.Updating
 
	Dim iod As IOrderedDictionary = e.InputParameters
	For Each de As DictionaryEntry In iod
		System.Diagnostics.debug.print(de.Key & "=" & de.Value)
	Next
End Sub

XhtmlConformance Breaks UpdatePanel

ASP.NET's UpdatePanel will not work if xhtmlConformance mode is set to Legacy in the Web.config file:

<xhtmlConformance mode="Legacy" />

Take it out of the Web.config file - it almost certainly does not need to be in there.

Set Up VLC Remote

With administrator privileges, edit the C:\Program Files (x86)\VideoLAN\VLC\lua\http\.hosts file, and set it to:

::/0
0.0.0.0/0

This will probably need to be done every time a new version of VLC is installed.

Netcetera Internal Server Error

Probably caused by the Web.config file. Remove the following, if they exist:

<section name="scriptResourceHandler" type="System.Web.Configuration.ScriptingScriptResourceHandlerSection, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" allowDefinition="MachineToApplication"/>
 
<section name="jsonSerialization" type="System.Web.Configuration.ScriptingJsonSerializationSection, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" allowDefinition="Everywhere" />
<section name="profileService" type="System.Web.Configuration.ScriptingProfileServiceSection, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" allowDefinition="MachineToApplication" />
<section name="authenticationService" type="System.Web.Configuration.ScriptingAuthenticationServiceSection, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" allowDefinition="MachineToApplication" />
<section name="roleService" type="System.Web.Configuration.ScriptingRoleServiceSection, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" allowDefinition="MachineToApplication" />

Removing these from the Web.config doesn't seem to matter, but if it does, try adding the relevant DLL files and see if that fixes the problem.

start.txt · Last modified: 2017/05/18 14:29 by stephen