views:

2978

answers:

25

What ReSharper 4.0 templates for C# do you use?

Let's share these in the following format:


[Title]

Optional description

Shortcut: shortcut
Available in: [AvailabilitySetting]

// Resharper template code snippet
// comes here

Macros properties (if present):

  • Macro1 - Value - EditableOccurence
  • Macro2 - Value - EditableOccurence


+5  A: 

Create new unit test fixture for some type

Shortcut: ntf
Available in: C# 2.0+ files where type member declaration or namespace declaration is allowed

[NUnit.Framework.TestFixtureAttribute]
public sealed class $TypeToTest$Tests
{
    [NUnit.Framework.TestAttribute]
    public void $Test$()
    {
     var t = new $TypeToTest$()
     $END$
    }
}

Macros:

  • TypeToTest - none - #2
  • Test - none - V
Rinat Abdullin
+4  A: 

Create new stand-alone unit test case

Shortcut: ntc
Available in: C# 2.0+ files where type member declaration is allowed

[NUnit.Framework.TestAttribute]
public void $Test$()
{
    $END$
}

Macros:

  • Test - none - V
Rinat Abdullin
+2  A: 

Shortcut: disposing

Available in: C# 2.0+ files where type member declaration is allowed

protected override void Dispose(bool disposing)
{
    try
    {
        if (disposing)
        {
            $END$
        }
    }
    finally
    {
        base.Dispose(disposing);
    }
}
Ed Ball
+2  A: 

Create test case stub for NUnit

This one could serve as a reminder (of functionality to implement or test) that shows up in the unit test runner (as any other ignored test),

Shortcut: nts
Available in: C# 2.0+ files where type member declaration is allowed

[Test, Ignore]
public void $TestName$()
{
    throw new NotImplementedException();
}
$END$
Rinat Abdullin
I do a variation on this, but with explicit Assert.Fail() in the body:http://aleriel.com/blog/2010/04/07/replace-paper-with-unit-tests/
Anna Lear
A: 

Create sanity check to ensure that an argument is never null

Shortcut: eann
Available in: C# 2.0+ files where type statement is allowed

Enforce.ArgumentNotNull($inner$, "$inner$");

Macros:

  • inner - Suggest parameter - #1

Remarks: Although this snippet targets open source .NET Lokad.Shared library, it could be easily adapted to any other type of argument check.

Rinat Abdullin
+1  A: 

Trace - Writeline, with format

Very simple template to add a trace with a formatted string (like Debug.WriteLine supports already).

Shortcut: twlf
Available in: C# 2.0+ files where statement is allowed

Trace.WriteLine(string.Format("$MASK$",$ARGUMENT$));

Macros properties:

  • Argument - value - EditableOccurence
  • Mask - "{0}" - EditableOccurence
Ray Hayes
+1  A: 

Assert.AreEqual

Simple template to add asserts to a unit test

Shortcut: ae
Available in: in C# 2.0+ files where statement is allowed

Assert.AreEqual($expected$, $actual$);$END$
Kjetil Klaussen
A: 

New COM Class

Shortcut: comclass

Available in: C# 2.0+ files where type member declaration or namespace declaration is allowed

[ComVisible(true)]
[ClassInterface(ClassInterfaceType.None)]
[Guid("$GUID$")]
public class $NAME$ : $INTERFACE$
{
    $END$
}

Macros

  • GUID - New GUID
  • NAME - Editable
  • INTERFACE - Editable
Ian G
Nice template, but this might be better suited to a file template rather than a live template.
Drew Noakes
A: 

Assert Invoke Not Required

Useful when developing WinForms applications where you want to be sure that code is executing on the correct thread for a given item. Note that Control implements ISynchronizeInvoke.

Shortcut: ani

Available in: C# 2.0+ files statement is allowed

Debug.Assert(!$SYNC_INVOKE$.InvokeRequired, "InvokeRequired");

Macros

  • SYNC_INVOKE - Suggest variable of System.ComponentModel.ISynchronizeInvoke
Drew Noakes
+1  A: 

Invoke if Required

Useful when developing WinForms applications where a method should be callable from non-UI threads, and that method should then marshall the call onto the UI thread.

Shortcut: inv

Available in: C# 3.0+ files statement is allowed

if (InvokeRequired)
{
    Invoke((System.Action)delegate { $METHOD_NAME$($END$); });
    return;
}

Macros

  • METHOD_NAME - Containing type member name


You would normally use this template as the first statement in a given method and the result resembles:

void DoSomething(Type1 arg1)
{
    if (InvokeRequired)
    {
        Invoke((Action)delegate { DoSomething(arg1); });
        return;
    }

    // Rest of method will only execute on the correct thread
    // ...
}
Drew Noakes
A: 

Test Method For Those Using MSTest

This is a bit lame but it's useful. Hopefully someone will get some utility out of it.

Shortcut: testMethod

Available in: C# 2.0

[TestMethod]
public void $TestName$()
{
    throw new NotImplementedException();

    //Arrange.

    //Act.

    //Assert.
}

$END$
Daver
+2  A: 

Quick ExpectedException Shortcut

Just a quick shortcut to add to my unit test attributes.

Shortcut: ee

Available in: Available in: C# 2.0+ files where type member declaration is allowed

[ExpectedException(typeof($TYPE$))]
womp
A: 

New GUID

Quick shortcut for new GUID.

Shortcut: gg

$GUID$
MicTech
there's a built it one: nguid
Muxa
+3  A: 

To add logging to some of my classes (using Log4net):

Macro: logger

private static readonly ILog _logger = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
Chris Brandsma
A: 

NUnit Setup method

Shortcut: setup
Available in: Available in: C# 2.0+ files where type member declaration is allowed

[SetUp]
public void SetUp()
{
    $END$
}
paraquat
Why use virtual?
Mike Two
Good point. I can think of some cases where you might want to subclass test fixtures (perhaps if you wanted to write "contract" tests where a set of assertions should apply to a number of objects), but I think in the much more common case, virtual is superfluous. I'll edit it out.
paraquat
A: 

NUnit Teardown method

Shortcut: teardown
Available in: Available in: C# 2.0+ files where type member declaration is allowed

[TearDown]
public void TearDown()
{
    $END$
}
paraquat
+2  A: 

Check if variable is null

Shortcut: ifn
Available in: C# 2.0+ files

if (null == $var$)
{
    $END$
}

Check if variable is not null

Shortcut: ifnn
Available in: C# 2.0+ files

if (null != $var$)
{
    $END$
}
Chris Doggett
How did that transition from C++ to C# treat you?
Ty
+1  A: 

New Typemock isolator fake

Shortcut: fake
Available in: [in c# 2.0 files where statement is allowed]

$TYPE$ $Name$Fake = Isolate.Fake.Instance();
Isolate.WhenCalled(() => $Name$Fake.)

Macros properties:
* $TYPE$ - Suggest type for a new variable
* $Name$ - Value of another variable (Type) with the first character in lower case

Karsten
A: 

Rhino Mocks Record-Playback Syntax

Shortcut: RhinoMocksRecordPlaybackSyntax *

Available in: C# 2.0+ files

Note: This code snippet is dependent on MockRepository (var mocks = new new MockRepository();) being already declared and initialized somewhere else.

using (mocks.Record())
{
    $END$
}

using (mocks.Playback())
{

}

*might seem a bit long for a shortcut name but with intellisense not an issue when typing. also have other code snippets for Rhino Mocks so fully qualifying the name makes it easier to group them together visually

Ray Vega
A: 

Rhino Mocks Expect Methods

Shortcut: RhinoMocksExpectMethod

Available in: C# 2.0+ files

Expect.Call($EXPECT_CODE$).Return($RETURN_VALUE$);

Shortcut: RhinoMocksExpectVoidMethod

Available in: C# 2.0+ files

Expect.Call(delegate { $EXPECT_CODE$; });
Ray Vega
A: 

Since I'm working with Unity right now, I've come up with a few to make my life a bit easier:


Type Alias

Shortcut: ta
Available in: *.xml; *.config

<typeAlias alias="$ALIAS$" type="$TYPE$,$ASSEMBLY$"/>

Type Declaration

This is a type with no name and no arguments

Shortcut: tp
Available in: *.xml; *.config

<type type="$TYPE$" mapTo="$MAPTYPE$"/>

Type Declaration (with name)

This is a type with name and no arguments

Shortcut: tn
Available in: *.xml; *.config

<type type="$TYPE$" mapTo="$MAPTYPE$" name="$NAME$"/>

Type Declaration With Constructor

This is a type with name and no arguments

Shortcut: tpc
Available in: *.xml; *.config

<type type="$TYPE$" mapTo="$MAPTYPE$">
  <typeConfig>
    <constructor>
        $PARAMS$
    </constructor>
  </typeConfig>
</type>

etc....

Bryce Fischer
A: 

Borrowing from Drew Noakes excellent idea, here is an implementation of invoke for Silverlight.

Shortcut: dca

Available in: C# 3.0 files

if (!Dispatcher.CheckAccess())
{
    Dispatcher.BeginInvoke((Action)delegate { $METHOD_NAME$(sender, e); });
    return;
}

$END$

Macros

  • $METHOD_NAME$ non-editable name of the current containing method.
JHappoldt
+1  A: 

MS Test Unit Test

New MS Test Unit test using AAA syntax and the naming convention found in the Art Of Unit Testing

Shortcut: testing (or tst, or whatever you want)
Available in: C# 2.0+ files where type member declaration is allowed

[TestMethod]
public void $MethodName$_$StateUnderTest$_$ExpectedBehavior$()
{
    // Arrange
    $END$

    // Act


    // Assert

}

Macros properties (if present):

  • MethodName - The name of the method under test
  • StateUnderTest - The state you are trying to test
  • ExpectedBehavior - What you expect to happen
Vaccano
A: 

log4net XML Configuration Block

You can import the template directly:

<TemplatesExport family="Live Templates">
  <Template uid="49c599bb-a1ec-4def-a2ad-01de05799843" shortcut="log4" description="inserts log4net XML configuration block" text="  &lt;configSections&gt;&#xD;&#xA;    &lt;section name=&quot;log4net&quot; type=&quot;log4net.Config.Log4NetConfigurationSectionHandler,log4net&quot; /&gt;&#xD;&#xA;  &lt;/configSections&gt;&#xD;&#xA;&#xD;&#xA;  &lt;log4net debug=&quot;false&quot;&gt;&#xD;&#xA;    &lt;appender name=&quot;LogFileAppender&quot; type=&quot;log4net.Appender.RollingFileAppender&quot;&gt;&#xD;&#xA;      &lt;param name=&quot;File&quot; value=&quot;logs\\$LogFileName$.log&quot; /&gt;&#xD;&#xA;      &lt;param name=&quot;AppendToFile&quot; value=&quot;false&quot; /&gt;&#xD;&#xA;      &lt;param name=&quot;RollingStyle&quot; value=&quot;Size&quot; /&gt;&#xD;&#xA;      &lt;param name=&quot;MaxSizeRollBackups&quot; value=&quot;5&quot; /&gt;&#xD;&#xA;      &lt;param name=&quot;MaximumFileSize&quot; value=&quot;5000KB&quot; /&gt;&#xD;&#xA;      &lt;param name=&quot;StaticLogFileName&quot; value=&quot;true&quot; /&gt;&#xD;&#xA;&#xD;&#xA;      &lt;layout type=&quot;log4net.Layout.PatternLayout&quot;&gt;&#xD;&#xA;        &lt;param name=&quot;ConversionPattern&quot; value=&quot;%date [%3thread] %-5level %-40logger{3} - %message%newline&quot; /&gt;&#xD;&#xA;      &lt;/layout&gt;&#xD;&#xA;    &lt;/appender&gt;&#xD;&#xA;&#xD;&#xA;    &lt;appender name=&quot;ConsoleAppender&quot; type=&quot;log4net.Appender.ConsoleAppender&quot;&gt;&#xD;&#xA;      &lt;layout type=&quot;log4net.Layout.PatternLayout&quot;&gt;&#xD;&#xA;        &lt;param name=&quot;ConversionPattern&quot; value=&quot;%message%newline&quot; /&gt;&#xD;&#xA;      &lt;/layout&gt;&#xD;&#xA;    &lt;/appender&gt;&#xD;&#xA;&#xD;&#xA;    &lt;root&gt;&#xD;&#xA;      &lt;priority value=&quot;DEBUG&quot; /&gt;&#xD;&#xA;      &lt;appender-ref ref=&quot;LogFileAppender&quot; /&gt;&#xD;&#xA;    &lt;/root&gt;&#xD;&#xA;  &lt;/log4net&gt;&#xD;&#xA;" reformat="False" shortenQualifiedReferences="False">
    <Context>
      <FileNameContext mask="*.config" />
    </Context>
    <Categories />
    <Variables>
      <Variable name="LogFileName" expression="getOutputName()" initialRange="0" />
    </Variables>
    <CustomProperties />
  </Template>
</TemplatesExport>
Igor Brejc
A: 

[New C# Guid]

Generates a new System.Guid instance initialized to a new generated guid value

Shortcut: csguid Available in: in C# 2.0+ files

new System.Guid("$GUID$")

Macros properties:

  • GUID - New GUID - False
codekaizen