Archive for the ‘Visual Studio’ Category.

Changing the prop snippet for creating a Property in C#

Ok, so it is very common for the c# member variables to start with either an _ (underscore) or an m.  So when creating a property, you can save a lot of time by changing it to assume this as well.

For example, your class may look as follows:

namespace AgentConfigurationPlugin
{
    public class Class1
    {
        #region Member Variables
        String _MemberString;
        int _MemberInt;
        #endregion

        #region Constructors

        /*
		 * The default constructor
 		 */
        public Class1()
        {
        }

        #endregion

        #region Properties
        public String MemberString
        {
            get { return _MemberString; }
            set { _MemberString = value; }
        }

        public int Memberint
        {
            get { return _MemberInt; }
            set { _MemberInt = value; }
        }
        #endregion
    }
}

Note: I hate the _ character as it is hard to type (being up to the right of my pinky finger), so I use the letter “m”, which is easy to type (being just below my pointer finger) and it also stands for “member variable”.

        #region Member Variables
        String mMemberString;
        int mMemberInt;
        #endregion

Anyway, whether it is an “m” or “_” or any other character, it is common to prefix member variables. So it would be useful if the property snippet assumed that prefix character as well.

The default snippet for creating a Property is located here:

C:\Program Files (x86)\Microsoft Visual Studio 9.0\VC#\Snippets\1033\Visual C#\prop.snippet

The contents looks as follows.

<?xml version="1.0" encoding="utf-8" ?>
<codeSnippets  xmlns="http://schemas.microsoft.com/VisualStudio/2005/CodeSnippet">
	<codeSnippet Format="1.0.0">
		<header>
			<title>prop</title>
			<shortcut>prop</shortcut>
			<description>Code snippet for an automatically implemented property</description>
			<author>Microsoft Corporation</author>
			<snippetTypes>
				<snippetType>Expansion</snippetType>
			</snippetTypes>
		</header>
		<snippet>
			<declarations>
				<literal>
					<id>type</id>
					<toolTip>Property type</toolTip>
					<default>int</default>
				</literal>
				<literal>
					<id>property</id>
					<toolTip>Property name</toolTip>
					<default>MyProperty</default>
				</literal>
			</declarations>
			<code Language="csharp"><!&#91;CDATA&#91;public $type$ $property$ { get; set; }$end$&#93;&#93;>
			</code>
		</snippet>
	</codeSnippet>
</codeSnippets>

Change it to be like this:

<?xml version="1.0" encoding="utf-8" ?>
<codeSnippets  xmlns="http://schemas.microsoft.com/VisualStudio/2005/CodeSnippet">
	<codeSnippet Format="1.0.0">
		<header>
			<title>prop</title>
			<shortcut>prop</shortcut>
			<description>Code snippet for an automatically implemented property</description>
			<author>Microsoft Corporation</author>
			<snippetTypes>
				<snippetType>Expansion</snippetType>
			</snippetTypes>
		</header>
		<snippet>
			<declarations>
				<literal>
					<id>type</id>
					<toolTip>Property type</toolTip>
					<default>int</default>
				</literal>
				<literal>
					<id>property</id>
					<toolTip>Property name</toolTip>
					<default>MyProperty</default>
				</literal>
			</declarations>
			<code Language="csharp"><!&#91;CDATA&#91;public $type$ $property$
		{
    			get { return _$property$; }
    			set { _$property$ = value; }
		}
$end$&#93;&#93;>
			</code>
		</snippet>
	</codeSnippet>
</codeSnippets>

The key section that fixes this is:

			<code Language="csharp"><!&#91;CDATA&#91;public $type$ $property$
		{
    			get { return _$property$; }
    			set { _$property$ = value; }
		}
$end$&#93;&#93;>

Or if you use “m” instead of “_” as I do, of course you would replace the “_” with an “m”.

			<code Language="csharp"><!&#91;CDATA&#91;public $type$ $property$
		{
    			get { return m$property$; }
    			set { m$property$ = value; }
		}
$end$&#93;&#93;>

Now when you create a member variable and then a property that matches it exactly except for the prefix character, the works is done for you, making you a more efficient programmer.

You may want to change the propg snippet as well.


Copyright ® Rhyous.com – Linking to this page is allowed without permission and as many as ten lines of this page can be used along with this link. Any other use of this page is allowed only by permission of Rhyous.com.

A snippet for handling each native type in C# and Visual Studio…when generics won't work.

So sometimes you have to have a function that can do something to any native type.

Below are two snippets to speed up the coding for you.

Ok, so of course there are times when you can use Generics.

public class myclass<t>
{
	myclass(T inT)
	{
		// your class
	}
}

However, there are functions that don’t work with a generic type T.

public class myclass<t>
{
	myclass(T inT1, T inT2)
	{
		if (inT1 < inT2)
		{
			// do something
		}
	}
}
&#91;/sourcecode&#93;

This results in an error:   Error 1 Operator '<&#39; cannot be applied to operands of type &#39;T&#39; and &#39;T&#39;.

Maybe you need to handle all the native data types.  So it is annoying to type them in, so I created an iftype snippet.

Create a file called iftype.snippet in this directory: C:\Program Files (x86)\Microsoft Visual Studio 9.0\VC#\Snippets\1033\Visual C#\
Copy in this source and save the file.

&#91;sourcecode language="csharp"&#93;
<?xml version="1.0" encoding="utf-8" ?>
<codeSnippets  xmlns="http://schemas.microsoft.com/VisualStudio/2005/CodeSnippet">
	<codeSnippet Format="1.0.0">
		<header>
			<title>iftype</title>
			<shortcut>iftype</shortcut>
			<description>Code snippet for an automatically implemented an 'if' statement for each native type.</description>
			<author>Jared Barneck</author>
			<snippetTypes>
				<snippetType>Expansion</snippetType>
			</snippetTypes>
		</header>
		<snippet>
			<declarations>
				<literal>
					<id>varName</id>
					<toolTip>Variable name</toolTip>
					<default>t</default>
				</literal>
			</declarations>
			<code Language="csharp"><!&#91;CDATA&#91;
				if ($varName$.Equals(typeof(bool)))
                {
					throw new NotImplementedException();
                }
                else if ($varName$.Equals(typeof(Byte)))
                {
					throw new NotImplementedException();
                }
                else if ($varName$.Equals(typeof(Char)))
                {
					throw new NotImplementedException();
                }
                else if ($varName$.Equals(typeof(DateTime)))
                {
					throw new NotImplementedException();
                }
                else if ($varName$.Equals(typeof(Decimal)))
                {
					throw new NotImplementedException();
                }
                else if ($varName$.Equals(typeof(Double)))
                {
					throw new NotImplementedException();
                }
                else if ($varName$.Equals(typeof(Int16)))
                {
					throw new NotImplementedException();
                }
                else if ($varName$.Equals(typeof(Int32)))
                {
					throw new NotImplementedException();
                }
                else if ($varName$.Equals(typeof(Int64)))
                {
					throw new NotImplementedException();
                }
                else if ($varName$.Equals(typeof(SByte)))
                {
					throw new NotImplementedException();
                }
                else if ($varName$.Equals(typeof(Single)))
                {
					throw new NotImplementedException();
                }
                else if ($varName$.Equals(typeof(String)))
                {
					throw new NotImplementedException();
                }
                else if ($varName$.Equals(typeof(TimeSpan)))
                {
					throw new NotImplementedException();
                }
                else if ($varName$.Equals(typeof(UInt16)))
                {
					throw new NotImplementedException();
                }
                else if ($varName$.Equals(typeof(UInt32)))
                {
					throw new NotImplementedException();
                }
                else if ($varName$.Equals(typeof(UInt64)))
                {
					throw new NotImplementedException();
                }
$end$&#93;&#93;>
			</code>
		</snippet>
	</codeSnippet>
</codeSnippets>

However, you prefer a switch statement to an if statement. Here is the same thing using the switch statement.

Create a file called switchtype.snippet in this directory: C:\Program Files (x86)\Microsoft Visual Studio 9.0\VC#\Snippets\1033\Visual C#\
Copy in this source and save the file.

<?xml version="1.0" encoding="utf-8" ?>
<codeSnippets  xmlns="http://schemas.microsoft.com/VisualStudio/2005/CodeSnippet">
	<codeSnippet Format="1.0.0">
		<header>
			<title>switchtype</title>
			<shortcut>switchtype</shortcut>
			<description>Code snippet for an automatically implemented a switch statement for each native type.</description>
			<author>Jared Barneck</author>
			<snippetTypes>
				<snippetType>Expansion</snippetType>
			</snippetTypes>
		</header>
		<snippet>a
			<declarations>
				<literal>
					<id>varName</id>
					<toolTip>Variable name</toolTip>
					<default>varName</default>
				</literal>
			</declarations>
			<code Language="csharp"><!&#91;CDATA&#91;
			Type t = $varName$;
            switch (t.ToString())
            {
                case "System.Boolean":
                    throw new NotImplementedException();
                    break;
                case "System.Byte":
                    throw new NotImplementedException();
                    break;
                case "System.Char":
                    throw new NotImplementedException();
                    break;
                case "System.DateTime":
                    throw new NotImplementedException();
                    break;
                case "System.Decimal":
                    throw new NotImplementedException();
                    break;
                case "System.Double":
                    throw new NotImplementedException();
                    break;
                case "System.Int16":
                    throw new NotImplementedException();
                    break;
                case "System.Int32":
                    throw new NotImplementedException();
                    break;
                case "System.Int64":
                    throw new NotImplementedException();
                    break;
                case "System.SByte":
                    throw new NotImplementedException();
                    break;
                case "System.Single":
                    throw new NotImplementedException();
                    break;
                case "System.String":
                    throw new NotImplementedException();
                    break;
                case "System.TimeSpan":
                    throw new NotImplementedException();
                    break;
                case "System.UInt16":
                    throw new NotImplementedException();
                    break;
                case "System.UInt32":
                    throw new NotImplementedException();
                    break;
                case "System.UInt64":
                    throw new NotImplementedException();
                    break;
            }
$end$&#93;&#93;>
			</code>
		</snippet>
	</codeSnippet>
</codeSnippets>

How to process command line parameters or arguments in a WPF application?

UPDATE 10/25/2010:
Avoid using Environment.CommandLine. It appears much easier, but isn’t as robust. I learned a while ago that the command line arguments can be accessed using Environment.CommandLine. This is only different than the process below in that it is way easier and the first argument is the full path of the executable. So all this work is not exactly necessary, right? Wrong! I tried Environment.CommandLine for a while and it didn’t last. There are times when this executable is launched by another executable and the Environment.CommandLine is not set even though the other executable launched this executable with parameters. So I had to return to using the steps below anyway.


Ok, so I wanted to handle command line parameters, which is easy in every other language, however, the need for easy was overlooked in WPF. It is not obvious and you are not going to figure it out without being told how to do it.

Microsoft provides a sample here, you can look at.
http://msdn.microsoft.com/en-us/library/aa972153.aspx

I am going to walk you through creating a new WPF Project in Visual Studio 2008. Then I will walk you through handling command line parameters (arguments).

  1. Open Visual Studio 2008.
  2. Go to File | New | Project.
  3. Under Visual C#, choose WPF Application and give the project a name and then hit OK.
  4. Go to Project | ProjectName Properties (where ProjectName is the name of your project).
  5. In the Properties of you project, click on Debug.
  6. Enter three parameters intothe Command line arguments text field: Param1 Param2 Param3
  7. Close the properties window.
  8. Double-click on App.xaml to open it. It looks like this:
    <application x:Class="ParametersForWPF.App"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        StartupUri="Window1.xaml">
        <application.Resources>
    
        </application.Resources>
    </application>
    
  9. Add a carriage return after StartupUri=”Window1.xaml” and start type inside the bracket the word Startup=. As soon as you see an equals sign you will get a pop up with the words . Double-click on that. The name Application_Startup will automatically be added.
    <application x:Class="ParametersForWPF.App"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        StartupUri="Window1.xaml"
        Startup="Application_Startup">
        <application.Resources>
    
        </application.Resources>
    </application>
    

    Note: This will also automatcially update the App.xaml.cs file which originally looks as follows:

    using System.Windows;
    
    namespace ParametersForWPF
    {
        /// <summary>
        /// Interaction logic for App.xaml
        /// </summary>
        public partial class App : Application
        {
        }
    }
    

    But after adding the Startup=”Application_Startup” line, a function called Application_Startup is automatically added.

    using System;
    using System.Collections.Generic;
    using System.Configuration;
    using System.Data;
    using System.Linq;
    using System.Windows;
    
    namespace ParametersForWPF
    {
        /// <summary>
        /// Interaction logic for App.xaml
        /// </summary>
        public partial class App : Application
        {
    
            private void Application_Startup(object sender, StartupEventArgs e)
            {
    
            }
        }
    }
    
  10. Now we only want to work with arguments if there are some, so lets add an if statement inside the Application_Startup function as shown:
            private void Application_Startup(object sender, StartupEventArgs e)
            {
                if (e.Args.Length > 0)
                {
    
                }
            }
    
  11. Ok, so the next step is to create a public static string[] member variable to hold the arguments and assign the arguments array to it. I called my member variable mArgs. I use prefix it with m so I know it is a member variable.
    using System;
    using System.Collections.Generic;
    using System.Configuration;
    using System.Data;
    using System.Linq;
    using System.Windows;
    
    namespace ParametersForWPF
    {
        /// <summary>
        /// Interaction logic for App.xaml
        /// </summary>
        public partial class App : Application
        {
            public static String[] mArgs;
    
            private void Application_Startup(object sender, StartupEventArgs e)
            {
    
                if (e.Args.Length > 0)
                {
                    mArgs= e.Args;
                }
            }
        }
    }
    
  12. Now, in order to access the data in Windows1.xaml.cs, just call the App.mArgs array in the constructor as shown.
            public Window1()
            {
                InitializeComponent();
                String[] args = App.mArgs;
    
            }
    
  13. Put a break point on the line and start with debugging and sure enough you will see your arguments properly assigned to the String[] args variable. So you now have your parameters accessible in your WPF application.Hope this helps you.

    Copyright ® Rhyous.com – Linking to this article is allowed without permission and as many as ten lines of this article can be used along with this link. Any other use of this article is allowed only by permission of Rhyous.com.

How to modify the default new class template for C# in Visual Studio 2008 or 2010?

Updated: 5/17/2010 using information aquired from here: http://www.thecodinghumanist.com/Content/HowToEditVSTemplates.aspx

Ok, so I don’t like the way that the default new class template in Visual Studio 2008/2010 looks. I end up typing a lot of things over and over again.

Here is what it a new class looks like:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace MyNameSpace
{
	class MyClass
	{
	}
}

Here is what I want it to look like:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace MyNameSpace
{
	public class MyClass
	{
		#region Member Variables
		#endregion

		#region Constructors

		/// <summary>
		/// The default Constructor.
		/// </summary>
		public MyClass()
      		{
		}

		#endregion

		#region Properties
		#endregion

		#region Functions
		#endregion

		#region Enums
		#endregion
	}
}

So making this change is easy to do. All you have to do is edit a text file that is compressed.

Copy the zip file file located here to the desktop:
Visual Studio 2008

  • For 64 bit: C:\Program Files (x86)\Microsoft Visual Studio 9.0\Common7\IDE\ItemTemplates\CSharp\Code\1033\Class.zip
  • For 32 bit: C:\Program Files\Microsoft Visual Studio 9.0\Common7\IDE\ItemTemplates\CSharp\Code\1033\Class.zip

Visual Studio 2010

  • For 64 bit: C:\Program Files (x86)\Microsoft Visual Studio 10.0\Common7\IDE\ItemTemplates\CSharp\Code\1033\Class.zip
  • For 32 bit: C:\Program Files\Microsoft Visual Studio 10.0\Common7\IDE\ItemTemplates\CSharp\Code\1033\Class.zip

Extract the zip file.

Using a text editor, open the Class.cs file.

The file will have the following text:

using System;
using System.Collections.Generic;
$if$ ($targetframeworkversion$ >= 3.5)using System.Linq;
$endif$using System.Text;

namespace $rootnamespace$
{
	class $safeitemrootname$
	{
	}
}

Change it to have this text:

using System;
using System.Collections.Generic;
$if$ ($targetframeworkversion$ >= 3.5)using System.Linq;
$endif$using System.Text;

namespace $rootnamespace$
{
	public class $safeitemrootname$
	{
		#region Member Variables
		#endregion

		#region Constructors

		/// <summary>
		/// The default Constructor.
		/// </summary>
		public $safeitemrootname$()
		{
		}

		#endregion

		#region Properties
		#endregion

		#region Functions
		#endregion

		#region Enums
		#endregion
	}
}

Save the file.

Rebuild the zip file with the new Class.cs.  Be careful to build the zip file correctly.

Copy the new zip file back here and overwrite the existing one:
Visual Studio 2008

  • For 64 bit: C:\Program Files (x86)\Microsoft Visual Studio 9.0\Common7\IDE\ItemTemplates\CSharp\Code\1033\Class.zip
  • For 32 bit: C:\Program Files\Microsoft Visual Studio 9.0\Common7\IDE\ItemTemplates\CSharp\Code\1033\Class.zip

Visual Studio 2010

  • For 64 bit: C:\Program Files (x86)\Microsoft Visual Studio 9.0\Common7\IDE\ItemTemplates\CSharp\Code\1033\Class.zip
  • For 32 bit: C:\Program Files\Microsoft Visual Studio 9.0\Common7\IDE\ItemTemplates\CSharp\Code\1033\Class.zip

Now, you have to rebuild the template classes.  To do this:

  1. Open a command prompt as Administrator.
  2. Change to the appropriate directory:
    Visual Studio 2008
    64-bit

    cd C:\Program Files (x86)\Microsoft Visual Studio 9.0\Common7\IDE\

    32-bit

    cd C:\Program Files\Microsoft Visual Studio 9.0\Common7\IDE\

    Visual Studio 2010
    64-bit

    cd C:\Program Files (x86)\Microsoft Visual Studio 10.0\Common7\IDE\

    32-bit

    cd C:\Program Files\Microsoft Visual Studio 10.0\Common7\IDE\
  3. Run this command:
    devenv.exe /installvstemplates

Now any new class you create will have your new format.


Copyright ® Rhyous.com – Linking to this article is allowed without permission and as many as ten lines of this article can be used along with this link. Any other use of this article is allowed only by permission of Rhyous.com.