views:

876

answers:

9

What are some macros that you have found useful in Visual Studio for code manipulation and automation? Since good code can be useful in all languages, this question is not language specific.

+3  A: 

I use this one alot:

Right Click -> Insert Code Snippet
Select -> Common Code Patterns
Select -> Conditionals And Loops
Select -> If .. End If Statement

What this allows you do, is only execute some code if something (a variable or expression or whatever) is true, or false, or greater than something. It's pretty handy.

Shawn Simon
I'm going to assume from the upvotes, this is a serious answer to the question? if so, I recommend the typing if and hitting tab twice instead of all the mousing.
Maslow
so thats hwy its there
Shawn Simon
+2  A: 

asnn as a snippet bound to Debug.Assert( [object] != null );

Anything else like that

Orion Edwards
+4  A: 

The best is the if snippet in C#

if -> Just hit tab twice and you get

if(true)
{

}

Also works with the while loop, for loop, foreach loop. There is a good property one.

Here is a snippet I wrote for ViewState properties.

<CodeSnippets xmlns="http://schemas.microsoft.com/VisualStudio/2005/CodeSnippet"&gt;

    <CodeSnippet Format="1.0.0">
     <Header>
      <Title>Generic Property - View State</Title>
      <Description>Inserts a Generic Property</Description>
      <Author>David Basarab</Author>
      <Shortcut>property_ViewState</Shortcut>
      <SnippetTypes>
       <SnippetType>Expansion</SnippetType>
      </SnippetTypes>
     </Header>
     <Snippet>
      <Declarations>
       <Literal Editable="true">
        <ID>PropertyName</ID>
        <Default>PropertyName</Default>
        <ToolTip>Replace this with the name of the Property.</ToolTip>
       </Literal>
        <Literal Editable="true">
          <ID>Type</ID>
          <Default>string</Default>
          <ToolTip>Replace this with the type of the Property.</ToolTip>
        </Literal>
        <Literal Editable="true">
          <ID>DefaultValue</ID>
          <Default>string.Empty</Default>
          <ToolTip>Replace this with the default value of the Property.</ToolTip>
        </Literal>
      </Declarations>
      <Code Language="CSharp">
        <![CDATA[#region $PropertyName$
            public $Type$ $PropertyName$
            {
                get
                {
                    if (this.ViewState["$PropertyName$"] == null)
                        return $DefaultValue$;

                    return ($Type$)this.ViewState["$PropertyName$"];
                }
                set { this.ViewState["$PropertyName$"] = value; }
            }
            #endregion]]>
      </Code>
    </Snippet>
  </CodeSnippet>

</CodeSnippets>
David Basarab
+1  A: 

Heh, i have the same kind of code snippet for the viewstate property, which i use while developping in vb.net

<?xml version="1.0"?>
<CodeSnippets xmlns="http://schemas.microsoft.com/VisualStudio/2005/CodeSnippet"&gt;
  <CodeSnippet Format="1.0.0">
    <Header>
      <Title>ViewState property</Title>
      <Author>SB</Author>
      <Description>Add data in the viewstate simply. </Description>
      <Shortcut>vprop</Shortcut>
    </Header>
    <Snippet>
      <Declarations>
        <Literal>
          <ID>PropertyType</ID>
          <ToolTip>Type of the object</ToolTip>
          <Default>Integer</Default>
        </Literal>
        <Literal>
          <ID>PropertyName</ID>
          <Type>String</Type>
          <ToolTip>Name of property</ToolTip>
          <Default>ViewStateProperty</Default>
        </Literal>
      </Declarations>
      <Code Language="VB"><![CDATA[Private $PropertyName$Default as $PropertyType$ '=
Public Property $PropertyName$() as $PropertyType$
    Get
     Dim obj as Object = ViewState("$PropertyName$")
     if (obj isnot Nothing)
      return DirectCast(obj, $PropertyType$)
     end if
     return $PropertyName$Default
    End Get
    Set(ByVal value As $PropertyType$)
     ViewState("$PropertyName$") = value
    End Set
End Property
]]></Code>
    </Snippet>
  </CodeSnippet>
</CodeSnippets>

I discovered these powerful tools only recently; for me, their use through shortcuts is really useful.

As a matter of fact, i think in future projects i will go as far as abstracting parts of the framework i'll be working with into snippets, assign them meaningful names and distribute them to the team; on the other hand, i could lead to code repetition, things that could be better handled by factoring the code...

samy
+5  A: 
ee
You can use ?? in the lazy `get` - makes for a cleaner definition.
Dmitri Nesteruk
A: 

I modify the existing class snippet to include sealed per default, because that is much more sensible to me. Types should be designed specifically for inheritance - if they are not, they should be sealed imo.

Brian Rasmussen
+1  A: 
ee
+1  A: 

Dispose pattern

///<summary>Releases unmanaged resources and performs other cleanup operations before the ClassName is reclaimed by garbage collection.</summary>
~ClassName() { Dispose(false); }
///<summary>Releases all resources used by the ClassName.</summary>
public void Dispose() { Dispose(true); GC.SuppressFinalize(this); }
///<summary>Releases the unmanaged resources used by the ClassName and optionally releases the managed resources.</summary>
///<param name="disposing">true to release both managed and unmanaged resources; false to release only unmanaged resources.</param>
protected virtual void Dispose(bool disposing) {
 if (disposing) {

 }
}


Event definition

Includes special versions for EventHandler and PropertyChangedEventHandler

///<summary>Occurs when ....</summary>
public event EventHandler<MyEventArgs> MyEvent;
///<summary>Raises the MyEvent event.</summary>
///<param name="e">A  MyEventArgs object that provides the event data.</param>
internal protected virtual void OnMyEvent(MyEventArgs e) {
 if (MyEvent != null)
  MyEvent(this, e);
}


Dispose Source

<?xml version="1.0" encoding="utf-8" ?>
<CodeSnippets  xmlns="http://schemas.microsoft.com/VisualStudio/2005/CodeSnippet"&gt;
 <CodeSnippet Format="1.0.0">
  <Header>
   <Title>Dispose pattern</Title>
   <Shortcut>dispose</Shortcut>
   <Description>Code snippet for virtual dispose pattern</Description>
   <Author>SLaks</Author>
   <SnippetTypes>
    <SnippetType>Expansion</SnippetType>
    <SnippetType>SurroundsWith</SnippetType>
   </SnippetTypes>
  </Header>
  <Snippet>
   <Declarations>
    <Literal Editable="false">
     <ID>classname</ID>
     <ToolTip>Class name</ToolTip>
     <Default>ClassNamePlaceholder</Default>
     <Function>ClassName()</Function>
    </Literal>
   </Declarations>
   <Code Language="csharp">
    <![CDATA[
  ///<summary>Releases unmanaged resources and performs other cleanup operations before the $classname$ is reclaimed by garbage collection.</summary>
  ~$classname$() { Dispose(false); }
  ///<summary>Releases all resources used by the $classname$.</summary>
  public void Dispose() { Dispose(true); GC.SuppressFinalize(this); }
  ///<summary>Releases the unmanaged resources used by the $classname$ and optionally releases the managed resources.</summary>
  ///<param name="disposing">true to release both managed and unmanaged resources; false to release only unmanaged resources.</param>
  protected virtual void Dispose(bool disposing) {
   if (disposing) {
    $end$$selected$
   }
  }]]>
   </Code>
  </Snippet>
 </CodeSnippet>
</CodeSnippets>


Event Source

<?xml version="1.0" encoding="utf-8" ?>
<CodeSnippets  xmlns="http://schemas.microsoft.com/VisualStudio/2005/CodeSnippet"&gt;
 <CodeSnippet Format="1.0.0">
  <Header>
   <Title>Typed Event</Title>
   <Shortcut>event</Shortcut>
   <Description>Code snippet for event and raiser with custom EventArgs type</Description>
   <Author>SLaks</Author>
   <SnippetTypes>
    <SnippetType>Expansion</SnippetType>
   </SnippetTypes>
  </Header>
  <Snippet>
   <Declarations>
    <Literal>
     <ID>type</ID>
     <ToolTip>EventArgs type</ToolTip>
     <Default>My</Default>
    </Literal>
    <Literal>
     <ID>event</ID>
     <ToolTip>Event name</ToolTip>
     <Default>MyEvent</Default>
    </Literal>
    <Literal>
     <ID>desc</ID>
     <ToolTip>Event description</ToolTip>
     <Default>...</Default>
    </Literal>
    <Literal>
     <ID>n</ID>
     <ToolTip>n</ToolTip>
     <Default></Default>
    </Literal>
   </Declarations>
   <Code Language="csharp"><![CDATA[///<summary>Occurs when $desc$.</summary>
  public event EventHandler<$type$EventArgs> $event$;
  ///<summary>Raises the $event$ event.</summary>
  ///<param name="e">A$n$ $type$EventArgs object that provides the event data.</param>
  internal protected virtual void On$event$($type$EventArgs e) {
   if ($event$ != null)
    $event$(this, e);
  }
  $end$]]></Code>
  </Snippet>
 </CodeSnippet>
 <CodeSnippet Format="1.0.0">
  <Header>
   <Title>Event</Title>
   <Shortcut>event</Shortcut>
   <Description>Code snippet for event and raiser</Description>
   <Author>SLaks</Author>
   <SnippetTypes>
    <SnippetType>Expansion</SnippetType>
   </SnippetTypes>
  </Header>
  <Snippet>
   <Declarations>
    <Literal>
     <ID>event</ID>
     <ToolTip>Event name</ToolTip>
     <Default>MyEvent</Default>
    </Literal>
    <Literal>
     <ID>desc</ID>
     <ToolTip>Event description</ToolTip>
     <Default>...</Default>
    </Literal>
   </Declarations>
   <Code Language="csharp"><![CDATA[///<summary>Occurs when $desc$.</summary>
  public event EventHandler $event$;
  ///<summary>Raises the $event$ event.</summary>
  internal protected virtual void On$event$() { On$event$(EventArgs.Empty); }
  ///<summary>Raises the $event$ event.</summary>
  ///<param name="e">An EventArgs object that provides the event data.</param>
  internal protected virtual void On$event$(EventArgs e) {
   if ($event$ != null)
    $event$(this, e);
  }
  $end$]]></Code>
  </Snippet>
 </CodeSnippet>
 <CodeSnippet Format="1.0.0">
  <Header>
   <Title>PropertyChanged Event</Title>
   <Shortcut>event</Shortcut>
   <Description>Code snippet for PropertyChanged event and raiser</Description>
   <Author>SLaks</Author>
   <SnippetTypes>
    <SnippetType>Expansion</SnippetType>
   </SnippetTypes>
  </Header>
  <Snippet>
   <Declarations>
    <Literal>
     <ID>event</ID>
     <ToolTip>Event name</ToolTip>
     <Default>MyEvent</Default>
    </Literal>
    <Literal>
     <ID>desc</ID>
     <ToolTip>Event description</ToolTip>
     <Default>...</Default>
    </Literal>
   </Declarations>
   <Code Language="csharp"><![CDATA[///<summary>Occurs when a property value is changed.</summary>
  public event PropertyChangedEventHandler PropertyChanged;
  ///<summary>Raises the PropertyChanged event.</summary>
  ///<param name="name">The name of the property that changed.</param>
  internal protected virtual void OnPropertyChanged(string name) { OnPropertyChanged(new PropertyChangedEventArgs(name)); }
  ///<summary>Raises the PropertyChanged event.</summary>
  ///<param name="e">An EventArgs object that provides the event data.</param>
  internal protected virtual void OnPropertyChanged(PropertyChangedEventArgs e) {
   if (PropertyChanged != null)
    PropertyChanged(this, e);
  }
  $end$]]></Code>
  </Snippet>
 </CodeSnippet>
</CodeSnippets>
SLaks
Sorry for the length
SLaks
A: 

The following is a snippet that I tend to use a lot in applications that use ODP.NET

<?xml version="1.0" encoding="UTF-8"?>
<CodeSnippets xmlns="http://schemas.microsoft.com/VisualStudio/2005/CodeSnippet"&gt;
  <CodeSnippet Format="1.0.0">
    <Header>
      <Title>ODP.NET Stub</Title>
      <Author>Rob (http://stackoverflow.com/users/1185/rob)&lt;/Author&gt;
      <Description>Inserts common Oracle code</Description>
      <Shortcut>csoraclestub</Shortcut>
      <HelpUrl></HelpUrl>
    </Header>
    <Snippet>
      <Imports>
        <Import>
          <Namespace>Oracle.DataAccess.Client</Namespace>
        </Import>
      </Imports>
      <Code Language="CSharp">
        <![CDATA[
        OracleConnection oraConnection = null;
        OracleCommand oraCommand = null;
        OracleDataReader oraData = null;

        try
        {
            // Connect to the database

            // Prepare and run the query

            oraCommand.BindByName = true;

        }
        catch (OracleException ex)
        {
            // TODO
        }
        catch (Exception ex)
        {
            // TODO
        }
        finally
        {
            // Perform a safe cleanup
            if (oraData != null) { oraData.Dispose(); }
            if (oraCommand != null) { oraCommand.Dispose(); }
            if (oraConnection != null) { oraConnection.Dispose(); }
        }   
        ]]>
      </Code>
    </Snippet>
  </CodeSnippet>
</CodeSnippets>
Rob