by Wojciech Sura

Custom code snippets in Visual Studio

Visual Studio’s editor provides quite useful feature: code snippets. Code snippets are pieces of frequently used code with – optionally – a few blank fields to fill in.

It turns out, that one may create his own code snippets and import them into Visual Studio. I’ll show you, how can you do it.

First of all, create a new file and name it, for instance, SerializedClass.snippet . Then open it in your favorite text editor and let’s start writing.

[xml]<?xml version="1.0" encoding="utf-8"?>
<CodeSnippets xmlns="http://schemas.microsoft.com/VisualStudio/2005/CodeSnippet">
<CodeSnippet Format="1.0.0">
<Header>
<Title>XML serializable class</Title>
<Author>Spook</Author>
<Description>Creates an XML serializable class with constructor.</Description>
<Shortcut>xclass</Shortcut>
</Header>[/xml]

So far, everything should be self-explanatory. Now, before entering snippet’s source code, we may define some literals, which will be later replaced by values entered by user.

[xml] <Snippet>
<Declarations>
<Literal>
<ID>ClassName</ID>
<ToolTip>Name of the class</ToolTip>
<Default>MyClass</Default>
</Literal>
</Declarations>[/xml]

ID specifies name, which will be used in snippet’s code. To inform, that piece of snippet is a literal, you have to surround it with dolar-signs: $ClassName$.

[xml] <Code Language="CSharp">
<![CDATA[ [XmlRoot("$ClassName$")]
public class $ClassName$
{
public $ClassName$()
{

}
}]]>
</Code>
</Snippet>
</CodeSnippet>
</CodeSnippets>[/xml]

Ok, now we have to import the snippet to Visual Studio. Start the IDE and choose Tools | Code Snippets Manager…. Then use the Import button to import new snippet to the IDE. The snippet will be copied to %USERPROFILE%\Documents\Visual Studio 2013\Code Snippets\Visual C#\My Code Snippets (assuming, that you use Visual Studio 2013, of course).

TooltipManager

When the snippet is imported, it immediately is available. Simply write “xclass”:

snippet_code

And then press Tab key twice. Voila!

snippet_inserted

Read more about custom code snippets in the MSDN library.

by Njål

Windows Azure SQL – Entity Framework 6 Retry Logic

 

One of the biggest drawbacks of using Azure SQL is that the connection towards the database is a lot more fragile and unstable than when you’re using a database server on your LAN. Also – your Azure database is running on servers with several hundred other databases – so the database server might disconnect you at any given time to ensure fairness of service etc.

These are transient errors – meaning that a retry of the query most often will succeed and fix the error.

Microsoft has released several code blocks and guidelines to help developers use this retry logic – http://code.msdn.microsoft.com/windowsazure/SQL-Azure-Retry-Logic-2d0a8401

And luckily – the EntityFramework team has added support for this in version 6 as well.

Here’s how you can get started with EF6 (beta 1) – using the built in SqlAzureExecutionStrategy

 

1. Install EF6 beta by opening the NUGET console in Visual Studio and typing
     PM> Install-Package EntityFramework –Pre

2. Install the EF6 Template generator – http://visualstudiogallery.msdn.microsoft.com/18a7db90-6705-4d19-9dd1-0a6c23d0751f. This will create the C# code for you – which will handle the communication towards the database

3. Restart Visual Studio

4. Add New Item  -> EDMX file. Connect to Database and/or specify your datamodel. Just like older versions of Entity Framework.

5. Right click in the EDMX editor – and select Add Code Generation Item. Select EF 6.x DbContext Generator.

6.
Compile. You should now have EF6 up and running. Only one crucial part missing – the Azure Retry Logic.

7. Add a class inside your Project with the following code. It will get picked up upon Application Start – and make sure that all the EF Database queries will be retried if they fail.

 

using System;
using System.Data.Entity.Config;
using System.Data.Entity.Infrastructure;
using System.Data.Entity.SqlServer;

namespace Www.Business.Database
{
    public class SqlAzureDbConfiguration : DbConfiguration
    {
        public SqlAzureDbConfiguration()
        {
            AddExecutionStrategy(() => new SqlAzureExecutionStrategy(), null);
        }

        protected void AddExecutionStrategy(Func<IExecutionStrategy> getExecutionStrategy, string serverName)
        {
            AddDependencyResolver(new ExecutionStrategyResolver<IExecutionStrategy>("SqlAzureExecutionStrategy", serverName, getExecutionStrategy));
        }
    }
}

(The example provided here: http://entityframework.codeplex.com/wikipage?title=Connection%20Resiliency%20Spec does not work/compile)

by Andreas

Define a #Region in javascript files (Visual Studio 2010 / 2012)

In these times of super responsive client side processing mega javascript extravaganza web applications  you’re more than likely to end up with fairly large .js files in your projects. The standard code file in Visual Studio allows you to define collapsible sections by wrapping them with the #region / #endregion blocks. In javascript files however, you are restricted to collapsible functions only (“#region” is not recognized as anything valid):

image

Well, I just found out that that’s not entirely true. By marking a section of code (regardless of any logical blocks) and hitting CTRL + M + H you’ll define the selection as a region which is collapsible and expandable

image

by Andreas

Visual Studio 2008/2010/2012 error: “The following module was built…”

I just encountered DAE #6 (Daily Annoying Error) when debugging an application:

The following module was built either with optimizations enabled or without debug information

image

This was in a solution with a couple of (signed) Sharepoint webparts, and even though I was attempting to debug a standalone command line app, the assembly in question was one of the webparts. Visual Studio seemed to believe that this code wasn’t “my code” (copyright infringement, anyone?), so by going to Tools –> Options –> Debugging –> General you can disable the “Enable Just My Code” option to fix the problem:

image

You might also want to look at other options, but at least this one worked for me this time.

by Andreas

KnockoutJS – how to get started

imageKnockoutJS is a Javascript framework implementing the Model-View-ViewModel (MVVM) pattern. It’s purpose is to provide a way for developers “to create rich, responsive display and editor user interfaces with a clean underlying data model.” (Wikipedia). This is achieved by offering declarative bindings, dependency tracking and an automatic refresh of the UI upon changes to the data model.

Recently we have been using KnockoutJS in a fairly large web based document management system. We were replacing an existing desktop application and it was important to keep the system responsive and “non-web like”. We achieved this through substantial use of javascript based frameworks like jQuery and KnockoutJS. This blog post will help you get started with the setup and a very basic example, and hopefully you’ll see the potential of this great technology. Later I will add more blog posts about the advanced (and sometimes quirky) ways to use KnockoutJS.

First of all, fire up Visual Studio 2010 / 2012. Open or create your web project and install the KnockoutJS NuGet package.

image

Add a reference to knockoutjs (at the time of writing v. 2.1.0), define a simple data model containing an observable variable for name and occupation and some input and label fields. Take note of the declarative bindings (“data-bind”):

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title>Simple KnockoutJS test</title>
    <script src="Scripts/knockout-2.1.0.js"></script>
</head>
<body>
    <!-- input fields -->
    <p>First name: <input data-bind="value: firstName" /></p>
    <p>Occupation: <input data-bind="value: occupation" /></p>

    <!-- auto updated labels -->
    <p><label data-bind="text: firstName"></label> is a <label data-bind="text: occupation"></label></p>

    <script>
        function myViewModel() {
            self = this;
            self.firstName = ko.observable("Andreas"); // set default value
            self.occupation = ko.observable("Software Developer");
        }

        // initialize
        ko.applyBindings(new myViewModel());
    </script>
</body>
</html>

(Note: creating a self object in the data model is not necessary, but it has become a habit of mine to ensure a clear separation from the regular this reference).

imageThe above code will generate a page with two input fields and a text. The observable variables (firstName, occupation) in the data model are bound to the input fields and labels through the “data-bind” parameter. To test the binding run the project and see how changes to the input fields trigger the labels to be updated (when the cursor leaves the input field). This simple example shows the KnockoutJS declarative bindings and automatic UI refresh in action.

Now that you have a working example running on your computer I recommend going through the tutorials at the official Learn KnockoutJS site. Through their jsfiddle type GUI you can complete the basic steps as well as some more advanced examples, and then steal some code and ideas and transfer it into your own test project. This is the best way to prepare you before implementing the framework in your real world projects.

by Njål

Visual Studio 2012 Fakes – ShimNotSupportedException when debugging tests

 

image

When testing VS2012 Ultimate I tried to use the new Microsoft Fakes framework to mock a simple static method. Running the test went fine, but I kept getting a ShimNotSupportedException when debugging the test. 

After goggling and trying all kinds of stuff I finally managed to debug the test by following these steps:

  1. Deleted the local.testsettings file (both in VS and on disk)

  2. Deleted the <solution>.vsmdi file (both in VS and on disk)
  3. Made sure IntelliTrace had these settings (not sure if this mattered):

    image

  4. Restarted VS2012
  5. Made sure that no .testsettings file were selected here

    image

Debugging of tests now works fine!
(Running/debugging the tests from Resharper still does not work – but I can live with this.)

I tried to add a new .testsettings file (with CodeAnalysis and everything else disabled) – but this makes the ShimNotSupportedException reappear again.

Similar Fakes/ShimNotSupportedException/Debug issues have been reported to MS, so I hope they get this resolved soon.

———————————————————————————————————–

Another sad fact is that the Fakes framework is only available in the Ultimate edition of Visual Studio 2012 – which retails at over USD 13,000. This makes absolutely no sense at all. ALL developers should use unit testing as part of their tool belt – and isolating tests using a mocking framework plays a key role. Microsoft Moles could be used for free in the previous VS 2010 version – and it worked great. This is very disappointing.

Please vote for this issue here: http://visualstudio.uservoice.com/forums/121579-visual-studio/suggestions/2919309-provide-microsoft-fakes-with-all-visual-studio-edi

by Stian

TFS: Discard changes in merge

imagesWhen merging between two branches in TFS, you get a list containing specific changesets that have been checked into the source branch but not merged into the target branch. Sometimes these are changesets that you never want to merge into your target branch and they are just messing up for you (because at some point you are going to hurry through this wizard and accidentally  select “Merge all changesets”).

Well, no need to kill yourself yet: you can always discard these changesets and forget all about them. There is no way to do this in Visual Studio GUI, so you will need to fire up the Visual Studio Command Prompt.

Make sure you are in your workspace directory and write a command like:

tf merge $/project/branch $/project/trunk /discard /recursive /version:C666~C688


Version is FROM changeset ~ TO changeset. If you are only discarding one changeset, you would repeat the changeset like this /version:C666~C666.

It should also be mentioned that you are still required to check in the changes, even though there is essentially no change in the file content.

by Stian

Moles not compiling

Have you ever experienced that you get a long list of compilation errors after adding Moles Assembly on a reference? The other day I was stucked with several compile errors like:

The command ""C:Program FilesMicrosoft Molesbinmoles.exe" @"D:…objDebugMolesmoles.args"" exited with code –1007
‘System.Net.Moles.SFileWebResponse.Dispose(bool)’: no suitable method found to override [D:…objDebugMolessm.g.csproj]
Cannot call an abstract base member: ‘System.Xml.XmlReader.Close()’ [D:…objDebugMolessxm.g.csproj]
The command ""C:Program FilesMicrosoft Molesbinmoles.exe" @"D:…objDebugMolesmoles.args"" exited with code –1002

I tried to clean, rebuild, restart, re-add, redo and all the other tricks you do when you see a very unreasonable compile error in Visual Studio. The solution seem to be way more unlogical, but it works – so no questions asked at this time.

<Moles xmlns="http://schemas.microsoft.com/moles/2010/">
  <Assembly Name="System.Xml" ReflectionOnly="true"/>
</Moles>


moleThe secret seems to be to add the ReflectionOnly attribute and set it to true.

I should mention that while searching for a good explanation for this, I found little information, but it seemed that everybody affected by this was using Visual Studio 2010 SP1. Still, using this version on many other computers, this was the only time I ran into this issue. And I did so with adding Moles assembly for System.Xml 

by Andreas

Sharepoint debugging – process terminated by IIS

”The web server process that was being debugged has been terminated by IIS”

When debugging Sharepoint components you’re likely to come across this error message. It is easily fixed by turning off the ping IIS is sending the worker process at regular intervals to keep it alive.

Go to IIS Manager, select the Application Pool used by your Sharepoint app, choose advanced settings and turn the “Ping Enabled” setting under “Process Model” to FALSE:

image

by Joakim

Delete ReSharper Test Results on “Clean Solution”

On my local dev machine, I can see no reason for keeping old test results (on a build server it’s another matter completely though). You usually run your tests quite often when developing, and thus you get a lot of “test result”-folders cluttering up your hard drive. Some test runners have options for configuring how many old test results you would like to keep, but this is not the case for ReSharper’s test runner (afaik).

To remedy this I’ve created a new target in the project file for my test project, that will delete the test result folder when I right-click the solution Visual Studio’s solution explorer and select “Clean Solution” (or on a project and select “Clean”). By default ReSharper creates the test results in “<ProjectFolder>/bin/<Configuration>/TestResults”, you can however change this (and therefore need to modify the config below accordingly).

<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
  .
  .
  .
  <PropertyGroup>
    <TestResultsFolderPath>bin$(Configuration)TestResults</TestResultsFolderPath>
  </PropertyGroup>
  <Target Name="AfterClean">
    <RemoveDir Directories="$(TestResultsFolderPath)" Condition="Exists('$(TestResultsFolderPath)')" />
  </Target>
</Project>

This target will check if there is a test results folder, and if there is, it will delete it (and it will only run when you clean the solution/project).

If you have more than one test project (i.e. one for unit tests and one for integration tests, etc.) you need to add it the project file for each project. Also beware that adding this target will affect everyone working on the project, not just you!

This solution should work for other test runners as well, just modify the “TestResultsFolderPathabove to reflect where the test results are created.

As I said in the beginning, some test runners allow you to configure how many old test results should be kept at any time, making this a non-issue. E.g. if you’re using the test runner found in Visual Studio out of the box, you could go to “Tools –> Options –> Test Tools –> Test Execution” and specify a number for the “Limit number of old Test Results to”-setting.