Thursday, June 12, 2008

Resharper Templates

I like and use Resharper because it is cheaper than CodeRush and I don't have to remember as many key commands most things are done with an alt + enter. It also works well with Unit Testing and for more yummy goodness with testing download JP's templates for Resharper.

livetemplates.xml (14.74 KB)

filetemplates.xml (3.79 KB)
#     Comments [0]  
kick it on DotNetKicks.com
 Friday, May 23, 2008

Configuration System Failed to Initialize

Problem: Your application contains User Scope Settings and you receive the exception,

“Configuration system failed to initialize” when attempting to retrieve these settings.

 

Solution: The settings file has been corrupted and is unreadable. Close or stop your application and delete the user.config file. The file is located at:

 

C:\Documents and Settings\[UserName]\Local Settings\Application Data\[AppCompany]\[AppName] \[AppVersion]\

 

If you are in Visual Studio you can easily find the exact file that is causing the problem by viewing the details and drilling down to the inner exception to find the file name.

#     Comments [1]  
kick it on DotNetKicks.com
 Monday, April 28, 2008

Interview Questions - Fibonacci

I found a interesting interview questions that is most likely a bit over done, but I still like it, it reminds me of my intro to programming classes from back in the day, which for me was only about 5 years ago. This one concerns the Fibonacci Numbers. The problem is write the Fibonacci Sequence without Recursion. With Recursion the fib sequence is relatively easy:

public static int GetFibValueRecursive(int place)
 {
     if (place <= 0) return 0;
     if (place == 1) return 1;
     return GetFibValueRecursive(place - 1) + GetFibValueRecursive(place - 2);
 }

First step to this problem I would write a test to make sure my code is correctly solving the problem.

[Test]
 public void GetFibValue_GivenPlace_ReturnCorrectValue()
 {
     Assert.AreEqual(0, Fibonacci.GetFibValue(-1));
     Assert.AreEqual(0, Fibonacci.GetFibValue(0));
     Assert.AreEqual(1, Fibonacci.GetFibValue(1));
     Assert.AreEqual(1, Fibonacci.GetFibValue(2));
     Assert.AreEqual(34, Fibonacci.GetFibValue(9));
     Assert.AreEqual(144, Fibonacci.GetFibValue(12));           
 }
Then I would write the code.
public static int GetFibValue(int place)
 {
     if (place <= 0) return 0;
     int previous = -1;
     int result = 1;
     for (int i = 0; i <= place; ++i)
     {
         int sum = result + previous;
         previous = result;
         result = sum;
     }
     return result;
 }

Bam! The Fibonacci Sequence without recursion of course if you wanted more than just a value for given place I would write it a little different perhaps return a list of values instead of a single value.

FibSequence.zip (71.66 KB)
#     Comments [0]  
kick it on DotNetKicks.com
 Thursday, April 10, 2008

General C# Questions

One of my career goals as a developer is to work for Microsoft, now that I have graduated school and have 2 years of development experience I am going to start actively perusing this goal. The word on the street is that the interview process for Microsoft positions is not easy. To prep for interviews I am trolling the web looking for possible interview questions and posting my answers. To start off I found these general questions on C#.

 

  1. What is metadata? What information is stored in Metadata?

Metadata describes every type and member defined in your code in a language-neutral manner. It stores the description of the assembly, description of types, and the attributes

 

  1. What are some of the Tables stored in metadata?

Each metadata table holds information about the elements of your program. For example, one metadata table describes the classes in your code, another table describes the fields, and so on. If you have ten classes in your code, the class table will have tens rows, one for each class. Metadata tables reference other tables and heaps. For example, the metadata table for classes references the table for methods.

 

  1. What are the two basic kinds of types in .net framework?

Two basic kinds of types are value types and reference types.

 

  1. What is boxing and unboxing?

Boxing a value type packages it inside an instance of the Object reference type, unboxing is the reverse.

 

  1. What class does all classes implicitly inherited from?

System.Object

 

  1. What is namespace, assembly?

Namespace declares a scope that lets you organize code and gives you a way to create globally unique types. An assembly is a collection of types and resources that are built to work together and form a logical unit of functionality.

 

  1. What is global assembly cache, what is the purpose?

The global assembly cache stores assemblies specifically designated to be shared by several applications on the computer.

 

  1. What are Primitive types?

Any data types directly supported by the compiler are called primitive types. Primitive types map directly to types that exist in the base class library.

 

  1. What is reflection?

Reflection allows the inspection of metadata in a PE file and late binding (run time) to types and their members.

           

  1. What is a delegate?

A delegate is a type that references a method with the same signature.

 

  1. Describe the accessibility modifier “protected internal”.

Access is limited to current project or types derived from the containing class.

 

  1. What does the term immutable mean?

It's simply a class that’s state does not change after it was initialized.

 

  1. What’s the difference between System.String and System.Text.StringBuilder classes?

StringBuilder class represents a mutable string of characters. System.String is immutable.

 

  1. What’s the advantage of using System.Text.StringBuilder over System.String?

A StringBuilder object is preferable for a concatenation operation if an arbitrary number of strings are concatenated; for example, if a loop concatenates a random number of strings of user input.

 

  1. Can you store multiple data types in System.Array?

No, array objects with the same array type share the same Type object.

 

  1. What’s the difference between the System.Array.CopyTo() and System.Array.Clone()?

CopyTo() is a deep copy that copies the values. Clone() is a shallow copy that copies only the elements of the Array.

 

  1. What’s the .NET collection class that allows an element to be accessed using a unique key?

System.Collections.Hashtable or System.Collections.Generic.Dictionary, I prefer the Generic Dictionary it is faster.

  1. Will the finally block get executed if an exception has not occurred?

Yes

 

  1. Can multiple catch blocks be executed for a single try statement?

No, the order of the catch clauses is important because the catch clauses are examined in order. Catch the more specific exceptions before the less specific ones.

#     Comments [0]  
kick it on DotNetKicks.com
 Monday, March 31, 2008

DotNetNuke Upgrade - My Rant

I have been using DotNetNuke for a year or more now mostly for personal fun projects but I have setup a site for a family business using DNN, nothing explosive and shinny but it has served its purpose. I manage 2 different DotNetNuke installations and I have to say upgrading DNN application (not the modules) is scary. I have yet to do it successfully on my first try. Here are my steps to failure:

1. Backup my SQL Server as well as my site files. This is the most important step because the fallowing steps are sure to fail.

2. Download the latest install or upgrade package for your DotNetNuke application. I have tried upgrading using both the upgrade and install packages with equal success err failure... successful failure?

3. Create an app_offline.htm with some generic text stating that you are doing maintenance on the site blah blah blah.

4. Rename your current web.config to web.config.old

5. Copy contents of the install/upgrade package to your DNN application folder.

6. Rename release.config to web.config.

7. Merge your old web.config with the new web.config. The areas to merge are: Connection Strings, MachineKey, and the codeSubDirectories. I also like to set AutoUpgrade key too false so nobody but me will trigger the installation.

8. Now I navigate to [Domain Name]/install/install.aspx

9. After I watch the list of Successful, or sometimes on Friday and the moon is full I will get a failure, I navigate to my home page of my DNN application to view the wonderful yellow screen. The error displayed is usually different every time or a different flavor of the same variety "Object Null Reference" being my favorite for its descriptiveness [insert sarcasm].

The good news and one of the reasons that I like DNN is it has a great community and I have fixed every problem with the help of people on the forums. Also once it is updated and running it is a solid application and very easy to extend and write custom modules for. I just wish for a one click update and BAM you are getting your "real" work completed. Anyway my SQL Server and root files are done restoring, time for try number two.

Note: Currently DotNetNuke was on version 4.8.2 when I wrote this.

Here are a few tutorials on upgrading your installation: 1 2

#     Comments [1]  
kick it on DotNetKicks.com
 Saturday, February 02, 2008

System.Data.EvaluateException

Problem: You are using Select Method to retrieve rows from a typed DataTable and you keep getting the fallowing exception:

 System.Data.EvaluateException: Cannot perform '=' operation on System.String and System.Int32.

This isn't the most helpful error message.

Solution: You are missing hyphens.

Example:

Wrong:

CustomerRow[] rows = Select(string.Format("LastName = {0}", LastName)) as CustomerRow[];

Right:

CustomerRow[] rows = Select(string.Format("LastName = '{0}'", LastName)) as CustomerRow[];

#     Comments [0]  
kick it on DotNetKicks.com
 Thursday, January 10, 2008

using Statement

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

#     Comments [0]  
kick it on DotNetKicks.com
 Friday, October 12, 2007

System.Diagnostics.Debugger

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

 
#     Comments [0]  
kick it on DotNetKicks.com
 Friday, September 21, 2007

Removing Non-Numeric Characters from a String

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());
 }

#     Comments [0]  
kick it on DotNetKicks.com
 Saturday, September 15, 2007

Sweet Sweet NUnit on VS2005 Action

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.

#     Comments [0]  
kick it on DotNetKicks.com
 Friday, September 14, 2007

Singleton Pattern

The singleton pattern in C# is very simple to implement and very useful. This pattern ensures that there is only one instance of its self providing a global point of access. There are different ways of doing this but I like to use the example below  because it is thread safe and clean.

public class User
{ private int _userId = 1; private static User _instance = new User(); static User() { } private User() { } public int UserId { get { return _userId ; } set { _userId = value; } } public static User Instance { get { return _instance; } }
}
Here is a quick test I wrote in NUnit that shows how it is used and comfirms there is only one instance.
[Test]
 public void TestSingleton()
 {
     User sngle1 = User.Instance;
     sngle1.UserId = 1;
     User sngle2 = User.Instance;
     sngle2.UserId = 2;
     Assert.AreEqual(sngle2.UserId, sngle1.UserId);
 }

More Info:

Everything you need to know about C# singleton.

More Patterns

#     Comments [3]  
kick it on DotNetKicks.com
 Thursday, September 13, 2007

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

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 .csproj file in note pad and edit the items 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. It might work if you just delete the code behind and then rebuild, but I didnt't try this.

 

#     Comments [0]  
kick it on DotNetKicks.com
 Wednesday, September 12, 2007

DataTable Select Method

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.
EmployeeDataSet.PeopleRow[] 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

#     Comments [0]  
kick it on DotNetKicks.com
 Thursday, August 23, 2007

Code Search Engine

Found a cool code search engine called Koders.com that crawls open source projects by language for code examples. It has a great syntax highlighting and plugs into your IDE.
 
#     Comments [0]  
kick it on DotNetKicks.com
 Tuesday, August 21, 2007

Measuring Time Elapsed in Code

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());


#     Comments [0]  
kick it on DotNetKicks.com
 Thursday, April 05, 2007

Switching to C# from VB.Net

    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.

#     Comments [0]  
kick it on DotNetKicks.com
 Wednesday, April 04, 2007

The Strategy Pattern

    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;
namespace MyUsefullPlugin
{
class MyUseFullPlugin : ICrazyBehavior
{
public void GoCrazy()
{
System.Windows.Forms.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();
}
}
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.

Dowload The Complete Code Below:

Patterns.zip (83.64 KB)
#     Comments [3]  
kick it on DotNetKicks.com
 Saturday, January 27, 2007

I' m Learning Design Patterns

I received a great book from my girl friend this Christmas called Head First Design Patterns. I have been reading this book and it is really getting me excited (about coding patterns in case you needed clarification). To better understand these patterns I am going to try and code examples of each one and post my experience as well as the code on my blog. I will list the patterns so I can keep track of them as well as giving my one or two readers a heads up on what to expect.

All of these patterns and definitions are described in Head First Design Patterns by Eric Freeman & Elisabeth Freeman with Kathy Sierra & Bert Bates from O'Reilly

Design patterns

  • The Strategy Pattern (p24) - Defines a family of algorithms, encapsulates each one, and makes them interchangeable. Strategy lets the algorithm vary independently from clients that use it.
  • The Observer Pattern (p51) - Defines a one-to-many dependency between objects so that when one object changes state, all its dependents are notified and updated automatically.
  • The Decorator Pattern (p91) - Attaches additional responsibilities to an object dynamically. Decorators provide a flexible alternative to subclassing for extending functionality.
  • The factory Method Pattern (p134) - Defines an interface for creating an object, but lets subclasses decide which class to instantiate. Factory Method lets a class defer instantiation to subclasses.
  • The Abstract Factory Pattern(p156) - Provides an interface for creating families of related of dependent objects without specifying their concrete classes.
  • The Singleton Pattern (p177) - Ensures a class has only one instance, and provides a global point of access to it.
  • The Command Pattern (p206) - Encapsulates a request as an object, thereby letting you parameterize other objects with different requests, queue or log requests, and support undoable operations.
  • The Adapter Pattern (p243) - Converts the interface of a class into another interface the clients expect. Adapter lets classes work together that couldn't otherwise because of incompatible interfaces.
  • The Template Method Pattern(p289) - Defines the skeleton of an algorithm in a method, deferring some steps to subclasses. Template Methods lets subclasses redefined certain steps of an algorithm without changing the algorithm's structure.
  • The Interator Pattern (p336) - Provides a way to access the elements of an aggregate object sequentially without exposing the underlying representation.
  • The Composite Pattern(p356) - Allows you to compose objects into tree structures to represent part-whole hierarchies. Composite lets clients treat individual objects and compositions of objects uniformly.
  • The State Pattern(p410) - Allows an object to alter its behavior when its internal state changes. The object will appear to change its class.
  • The proxy pattern(p460) -  Provides a surrogate or placeholder for another object to control access to it.

#     Comments [0]  
kick it on DotNetKicks.com