views:

365

answers:

2

I'm trying to write a vs code snippet that will take the selected and surround it with an if null check, i.e.

accgrp.CREATEDATE = DateTime.Now;

will become:

if (accgrp.CREATEDATE == null)
        {
            accgrp.CREATEDATE = DateTime.Now;
        }

I've got as far as the below. $selected$ only seems to work the last time it is used, if used more than once, the other instances where you would expected to see the selected code are blank. I understand the code below wouldn't do exactly what I want, as I wont get the right hand side of the assignment, btu it would be good enough.

      <Declarations>
   <Literal>
    <ID>expression</ID>
    <ToolTip>Expression to evaluate</ToolTip>
    <Default>o</Default>
   </Literal>
  </Declarations>
  <Code Language="csharp"><![CDATA[if ($selected$ == null)
{
 $selected$ = $expression$$end$  
}]]>
  </Code>

Can anyone help?

+1  A: 

Assuming CREATEDATE is a property, why don't you move this logic over there?

DateTime? CREATEDATE
{
    set { _createdate = value ?? DateTime.Now; }
}

or use the same ?? operator outside setter:

accgrp.CREATEDATE = accgrp.CREATEDATE ?? DateTime.Now;
Anton Gogolev
nice approach, i'd forgotten about the ?? operator. however i can't move the logic to the setter as accgrp is an entity in the entity framework. for every property on the entity i need to set a default where the user has entered no value. i understand that there's a defaultvalue property in the ef designer, but it can't take functions. your second suggestion is cool, but still suffers from not being able to use $selected$ twice in a snippet
burnside
+1  A: 

Here is macro for you, that will provide you identical functionality.

Sub NullCheck()
    Dim selected As String
    Dim var As String
    Dim res As String
    Dim sel As TextSelection


    sel = DTE.ActiveDocument.Selection
    selected = sel.Text        
    var = selected.Substring(0, selected.IndexOf("=") - 1).Trim()
    res = String.Format("if ({0} == null) {1} ", var, selected)

    sel.Delete()
    sel.Insert(res, vsInsertFlags.vsInsertFlagsContainNewText)
    sel.SmartFormat()

End Sub

The alternative (after reading your comment) may be to use PostSharp in order to intercept field/property setter.

majkinetor
burnside