using Statement

01.10.08

The using Statement is simply syntax sugar for a try finally block. If you instantiate an object that implements IDisposable you can make your code look cleaner with the key word using.
Example:
StreamWriter sw = File.CreateText(filePath)
try
{
  sw.Write(someText);
}
finally
{
  sw.Dispose();
}
The above block works the same as:
using(StreamWriter sw = File.CreateText(filePath))
{
  sw.Write(someText);
}
More Info:
MSDN

System.Diagnostics.Debugger

10.11.07

Problem: You need functionality turned off or on when you are running your program in Debug mode.

Solution: System.Diagnostics.Debugger.IsAttached; it is a static property that returns true if there is a Debugger attached. I like to use this when debugging websevices, timing out while fixing a problem can be annoying.

if (Debugger.IsAttached)
     _webService.Timeout = -1;

More info:

MSDN

 

Removing Non-Numeric Characters from a String

09.21.07

Problem: I have an editable grid that needs to contain numeric integer values only.

My Solution: TryParse, this function accepts a string and an out value then returns a  bool True if it was successful, also it does not throw exceptions. I am a 100% sure there is someone with a better way of doing this but this is what I came up with. Feedback encouraged!

private string RemoveNonNumericValues(string p)
{
     int tempValue = 0;
     StringBuilder value = new StringBuilder(p.Length);
     foreach (char charValue in p.ToCharArray())
     {
         if (int.TryParse(charValue.ToString(), out tempValue))
             value.Append(tempValue.ToString());
     }
     return value.ToString();
}
private void dataGrid_CellEndEdit(object sender, DataGridViewCellEventArgs e)
{
    dataGridView[e.ColumnIndex, e.RowIndex].Value = RemoveNonNumericValues(dataGridView[e.ColumnIndex, e.RowIndex].Value.ToString());
}

Sweet Sweet NUnit on VS2005 Action

09.15.07

This is great! I dont know why I didnt do this earlier, but you can Debug your code and run NUnit at the same time. You just need to set the Debug>Start Action to start external aplication NUnit.exe. Then set your start project to be the same project as your test code and tada you now have debuging and break point goodness wile running nunit.

 

Unable to find the report in the manifest resources. please build the project, and try again.

09.13.07

I was reorganizing a project and I moved a crystal report after that I received this error at runtime "Unable to find the report in the manifest resources. please build the project, and try again." No amount of building could fix this problem. I eventually had to open up the project file in note pad and edit the entries in the xml/MSBUILD.

Here is what a Crystal Report should look like in your MSBUILD script.

<Compile Include="CrystalReport1.cs">
    <AutoGen>True</AutoGen>
    <DesignTime>True</DesignTime>
    <DependentUpon>CrystalReport1.rpt</DependentUpon>
    <SubType>Component</SubType>
</Compile>
<EmbeddedResource Include="CrystalReport1.rpt">
    <Generator>CrystalDecisions.VSDesigner.CodeGen.ReportCodeGenerator</Generator>
    <LastGenOutput>CrystalReport1.cs</LastGenOutput>
</EmbeddedResource>

After you correct the entry Rename the file Build then rename it again to the old name and build again.

DataTable Select Method

09.12.07

The Select method is really handy for filtering and sorting the rows you need from a strongly typed dataTable. It has 3 overloads Select() for returning all the rows as an array select(stringFilter) for returning the rows with out sorting and Select(stringFilter,stringSort) for returning rows with sorting. Here is quick way to fire everyone with the first name of bob in your employee management application.

var people = peopleDataTable.Select(
                                    "FirstName = bob AND Fired = 0",
                                    "LastName"
                                    ) as EmployeeDataSet.PeopleRow[];
foreach (EmployeeDataSet.PeopleRow person in people)
{
     person.Fired = true;
}


more Info:
MSDN
even better example

C#

Measuring Time Elapsed in Code

08.21.07

Some times you need to time an algorithm or method when trying to increase performance of an application. There is a quick and easy way to do this using the StopWatch class in System.Diagnostics.

System.Diagnostics.Stopwatch sw = new System.Diagnostics.Stopwatch();
sw.Start();
TestMethod();
sw.Stop();
Debug.WriteLine(sw.ElapsedMilliseconds.ToString());

C#

Switching to C# from VB.Net

04.05.07

My current job requires me to jump on the band wagon and start coding in the C# syntax for .Net. For the last year I have been coding in VB.Net and doing all my blog examples in VB.Net and I really started to enjoy that language. The My namespace allowed for quick access to a number of common functions, key words such as AndAlso and OrElse eliminated the need for extra if statements, the background compiler was great finding errors instantly, the VB.Net code is formatted automatically for you (in C# I find my self having to hit ctr+K+D a lot and some times still have to format braces my self), and the lack of {}.[], <>, and () makes the language easy to read.
    My switch to C# was relatively easy I can't quite code as fast as I am able to in VB.Net and I still try to write Dim, forget semicolons, and other little syntax issues like that. I like that C# seems to hide less from you than VB.Net one example is just having the namespace automatically at the top of the page. C# is also less wordy than VB.Net and I can see more of the code that is important to me at one time. Maybe its just because I am new to the language but C# seems to have less ambiguous ways of doing things as well, witch seems to make code from programmer to programmer more consistent. Example of this is casting int from a string in VB you can use Cint(str), Ctype(str,int), Integer.Parse(str), and Val(str). There are a lot of other instances of this in VB.Net I think it has a lot to do with helping the VB 6.0 coders with there transition to .Net.
    All and all it is a refreshing change and I like going back to “C” derived syntax I believe to progress as a programmer you really need to experience in multiple languages.

The Strategy Pattern

04.04.07

    The strategy pattern is intended to provide a means to define a family of algorithms, encapsulate each one as an object, and make them interchangeable. What does this mean?
    From my understanding of the strategy pattern, you are separating the behavior from an object with the use of an interface. The interface defines the family of algorithms and you encapsulate each behavior with a class that implements this interface. With this use of the interface contained in the class you have the ability to reference different behaviors at runtime.
    To better understand this I created a simple app that is a form with a button. When this button is clicked it uses Reflection to load a .dll that contains a class that defines the behavior of the button.



The first thing I did to implement the strategy pattern was to create my interface that defines my family of behaviors/Algorithms.
namespace Patterns.Strategy.PluginInterface
{
    public interface ICrazyBehavior
    {
        void GoCrazy();
    }
}

In order to assign a concrete behavior I created a class that implemented this interface.

using Patterns.Strategy.PluginInterface;
using System.Windows.Forms;
namespace MyUsefullPlugin
{
    class MyUseFullPlugin : ICrazyBehavior
    {
        public void GoCrazy()
        {
            MessageBox.Show("This Plug-in is out of controll");
        }
    }
}


Finally I wrote the class that contains the interface and all other content I needed.
using System;
using System.Collections.Generic;
using System.Windows.Forms;
using System.IO;
using System.Reflection;
using Patterns.Strategy.PluginInterface;
namespace Patterns.Strategy
{
    public partial class PlugableStrategy : Form
    {
        private List<ICrazyBehavior> _crazyBehavior = new List<ICrazyBehavior>();
        public PlugableStrategy()
        {
            InitializeComponent();
        }
        private void btnGoCrazy_Click(object sender, EventArgs e)
        {
            GetPlugins();
            foreach (ICrazyBehavior thisBehavior in _crazyBehavior)
            {
                thisBehavior.GoCrazy();
            }
        }
        // Messy Reflection stuff
        private void GetPlugins()
        {
            _crazyBehavior.Clear();
            string path = Application.StartupPath + "/Plugins";
            string[] files = Directory.GetFiles(path, "*.dll");
            foreach (string file in files)
            {
                try
                {
                    Assembly asm = Assembly.LoadFrom(file);
                    Type[] types = asm.GetTypes();
                    foreach (Type type in types)
                    {
                        Type[] interfaces = type.GetInterfaces();
                        foreach (Type currentInterface in interfaces)
                        {
                            if (currentInterface.Name == "ICrazyBehavior")
                            {
                                if (currentInterface.Namespace == "Patterns.Strategy.PluginInterface")
                                {
                                    object obj = asm.CreateInstance(type.Namespace + "." + type.Name);
                                    _crazyBehavior.Add((ICrazyBehavior)obj);
                                }
                            }
                        }//interface
                    }//type
                }
                catch (Exception) { }
            }//file
        }
    }
}

So, putting this all together I have my form/class that contains a button when some one clicks this button it calls GetPlugins(). The method GetPlugins() uses Reflection to find any .dlls in the plugins folder that contains the ICrazyBehavior interface with the name space of Patterns.Strategy.PluginInterface. If such thing exists in the folder it creates an instance of this object and adds it to my list of _crazyBehaviors once the list is filled the click event continues, it iterates through the list calling the method GoCrazy().

    Using the strategy pattern allowed me to decouple the context class and its behavior enabling me to implement a very "useful" pluggable application.

The Code:

Patterns.zip (83.64 KB)