Archive

Posts Tagged ‘C#’

Scope Identity with SqlCe

October 6th, 2009 robber.baron No comments

Normally I write my data access layer using an ORM like nHibernate as I thoroughly enjoy the speed, flexibility and power that comes from using such tools. Recently at work, however, I have been doing a lot of Windows Mobile development and I although there are compact framework ORMs I didn’t have the experience enough to want to use one in a very important project.

As a result the following code is something I had to look up and was actually an annoying thing to find. I wanted to return the identity of a newly inserted object. Normally nHibernate would set this for me but as I’m not using nHibernate I have to do this myself.

using (connection = new SqlCeConnection(CONNECTION_STRING))
{
     connection.Open();
 
     var command = new SqlCeCommand(@"INSERT INTO photos (path, format) VALUE (?, ?) SELECT SCOPE_IDENTITY();");
     command.Parameters.Add(New SqlCeParameter());
     command.Parameters.Add(New SqlCeParameter());
     command.Parameters(0).Value = path;
     command.Parameters(1).Value = format;
 
     var id = command.ExecuteScalar();
 
     Debug.WriteLine(String.Format("New Identifier = {0}", id));
}

This is insert the photo into the database and return the new id for the photo rather than the number of rows effected. The key is the ExecuteScalar function.

How cool is it that log4net works for Compact Framework apps. Has been a huge lifesaver.

Dictionary Iteration

October 2nd, 2009 robber.baron No comments

In a project I’m working on I am storing results in a dictionary.  While I could just be storing them in a list I thought the speed and ease of use was better for a dictionary.  [In fact it turned out to be a great choice because due to collisions in the results I discovered that the data was actually bad and needed to be cleaned up.]

Once I had the results through I needed loop through them to export them to a better file format.  At first I wasn’t exactly sure how to do this.  I new a dictionary implemented the IEnumerable interface I just didn’t know how to access it.

Here is how:

var dictionary as new Dictionary();
 
dictionary.Add(obj1.GetHashCode(), obj1);
dictionary.Add(obj2.GetHashCode(), obj2);
dictionary.Add(obj3.GetHashCode(), obj3);
 
foreach (KeyValuePair result in dictionary)
{
     Console.WriteLine(String.Format("Key = {0} - Value = {1}", result.Key, result.Value.ToString());
}

Conversion Operator Methods

August 11th, 2009 robber.baron No comments

While the .Net Framework provides a plethora of classes for you to use when building applications it is not all inclusive. Part of being a programmer is adding functionality to a specific system that might not be useful to all people.

Within this application’s domain, certainly custom data types might become as important as .Net’s base types. In this case you might want to have the compiler treat your objects as such; using implicit and explicit operators.

public sealed class Currency
{
     // Constructs a Currency from a Double
     public Currency(Double amt) { ... }
 
     // Constructs a Currency from a String
     public Currency(String amt) { ... }
 
     // Convert a Currency to a Double
     public Double ToDouble() { ... }
 
     // Convert a Currency to a String
     public override ToString() { ... }
}

This works well but requires explicit calls to these functions to work. This creates a new type in your code but it isn’t as privileged as framework types. You cannot have the follow code compile, let alone run.

Currency amt1 = 5.25;     // Implicit cast
Currency amt2 = "$3.13";
 
Double x = (Double) amt1;     // Explicit cast
String y = (String) amt2;

Now if Currency was a base type like, for example, Int32 then you could implicitly and explicitly cast it from type to type. The Currency class, written as is, above, cannot. In order to do so you must use the operator keyword in your class.

The Currency class needs to be rewritten as follows.

public sealed class Currency
{
     // Constructs a Currency from a Double
     public Currency(Double amt) { ... }
 
     // Constructs a Currency from a String
     public Currency(String amt) { ... }
 
     // Convert a Currency to a Double
     public Double ToDouble() { ... }
 
     // Convert a Currency to a String
     public override ToString() { ... }
 
     // Allows implicitly casting to Currency from Double
     public static implicit operator Currency(Double amt)
     {     return new Currency(amt);     }
 
     // Allows implicitly casting to Currency from String
     public static implicit operator Currency(String amt)
     {     return new Currency(amt);     }
 
     // Allows explicitly casting to Double from a Currency
     public static explicit operator Double(Currency c)
     {     return c.ToDouble();     }
 
     // Allows explicitly casting to String from a Currency
     public static explicit operator String(Currency c)
     {     return c.ToString();     }
}

Conversion operators require that the overload methods be both public and static. The implicit keyword indicates to the compiler that an explicit case does not have to appear in code to call the conversion method. The explicit keyword indicates to the compiler that an explicit cast must to present to call the conversion method.

This allows your custom types to feel more natural within your programming environment, making them seem as though they are a part of the core .Net framework. This is especially useful within core libraries that you use repeatedly.

Categories: C#, Programming, Uncategorized Tags: ,

BitFlags in C#

July 31st, 2009 robber.baron 4 comments

Awhile back I had a discussion about user permissions with a client. Specifically how to store the permissions in the database. As a software developer I wanted my object model to have explicit control over the security model. If you wanted to alter a person’s security you’d need to do so via a utility program or perhaps an administrative panel within the software.

The client wanted to be able to alter a field within a table in the database to change permissions. He thought it was much more efficient to have a DBA hop into the database and change a field. He further thought have a bunch of fields Boolean fields like “Read”, “Write”, “Publish”, “Edit”, and “Delete” were too cumbersome. He wanted to have a bit string where each bit represented a yes/no relationship with a type of permission.

This is something that can be represented beautiful with a special type of enum. Adding the [Flags] attribute to an enum turns it into a bit string just like above. It is implemented as follows.

1
2
3
4
5
6
7
8
9
[Flags]
public enum Permissions {
     None = 0
     Read = 0x0001,
     Write = 0x0002,
     ReadWrite = Permissions.Read | Permissions.Write,
     Execute = 0x0004,
     Delete = 0x0005
}

As you can see it looks as though it is a simple enum but isn’t quite that. You are allowed to combine enum values to create other values.

What is especially great is that

1
2
3
4
Permissions permissions = Permissions.Read | Permissions.Execute;
User user = new User("robber.baron", permissions);
 
Console.Writeline(user.permissions.ToString());

The output of the final line is very user friendly. The output is:

Read, Execute

This is a native part of the common language runtime and is part of the .Net base library. This is a fantastic and simple language feature that provides a simple and intuitive way of dealing with the concept of bit strings without custom code.

I’ll never worry about having to implement a bit string again. In fact I might start using them more often.

Categories: C#, Programming Tags: , ,

Hiding System.Object default methods from IntelliSense

July 31st, 2009 robber.baron No comments

Every object in Microsoft’s .Net common language runtime (CLR) implements the System.Object interface.  This means that every object in .Net has the following methods; Equals(), HashCode(), GetType(), and ToString().  While this is extremely helpful when you want to override ToString() (for use with DataGridView) or Equals().

It becomes annoying when using Microsoft’s IntelliSense.  Every class will always expose these methods to IntelliSense.  Since everyone but the most novice of programmers knows these classes exist there is little sense for IntelliSense to expose them. They add unnecessary clutter.

Thankfully there is a way to turn them off using the System.ComponentModel.EditorBrowsableAttribute namespace, which controls what members are visible in IntelliSense.

While you can choose for each and every class I prefer to use a single interface and just have my classes inherit from that interface.

namespace BlorkSamples.IntelliSense
{
     [EditorBrowsable(EditorBrowsableState.Never)]
     public interface IInvisibleSystemObjectMethods
     {
          [EditorBrowsable(EditorBrowsableState.Never)]
          bool Equals();
 
          [EditorBrowsable(EditorBrowsableState.Never)]
          int GetHashCode();
 
          [EditorBrowsable(EditorBrowsableState.Never)]
          Type GetType();
 
          [EditorBrowsable(EditorBrowsableState.Never)]
          string ToString();
     }
}

This hides the System.Object methods from IntelliSense and whenever writing your own interfaces or classes just inherit from this interface to hide its common methods.  Extremely handy with large and confusing APIs.

Static Keyword

June 23rd, 2009 robber.baron No comments

I wanted to start information for beginner programmers to improve their programming skills. One of my chief complaints about the programmer culture is that currently there is a lot of very basic information online and a lot of very advanced information online, but not a lot of information to help a novice become advanced.

Over the last few years I have run into the same sort of questions over and over without a solid reply. I figured that I could at least chronicle some of the more useful information to help an inexperienced programmer increase his skills.

The first entry is on the static keyword and its utility for programmers.

Static classes and class members are used to create data and functions that can be accessed without creating an instance of the class. Static class members can be used to separate data and behavior that is independent of any object identity: the data and functions do not change regardless of what happens to the object. Static classes can be used when there is no data or behavior in the class that depends on object identity.

- microsoft developer network

This means that you don’t need to use the new keyword to access static members or static methods of a class.

Let us re-implement a subset of the Math class in the .Net Framework.

public class Math
{
     public const double PI = 3.14159;
 
     public double Max(double d1, double d2)
     {
          return d1 < d2 ? d2 : d1;
     }
 
     public double Min(double d1, double d2)
     {
          return d1 < d2 ? d1 : d2;
     }
}

This is a perfectly legitimate implementation of the Math class but isn’t exactly perfect.  If you wanted to use the Min method currently, you would have to instantiate a new Math class before using it.

var math = new Math();
 
var max = math.Max(2.4, math.PI);

Read more...

Categories: C#, Programming Tags: , , ,

Creating Custom Performance Counters

June 17th, 2009 robber.baron No comments

Windows has a handy tool called Performance Monitor.  You can access it on any (modern) Windows computer by typing perfmon at the command line or into run.  I had always wondered how to create my own monitors for use with my own software.  It seemed like a very easy way to keep track of the internals of a complex piece of software without a lot of overhead.

This is a rather contrived example but it basically creates a … well .. counter counter.  A counter that counts the number of something.  For a system that handles large quantities of input and output it might be nice to know what your buffers, queues, and lists are doing and a simple monitor like this would work perfectly.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
using System.Diagnostics;
 
namespace CodeMonkey.Sample.Counters
{
     public class ItemCounter
     {
          private const string CATEGORY_NAME = "CodeMonkey";
          private PerformanceCounter _counter;
 
          public ItemCounter()
          {
                var collection = new CounterCreationDataCollection();
                var data = new CounterCreationData("Number of Items", "", PerformanceCounterType.NumberOfItems32);
 
                if (!PerformanceCounterCategory.Exists(CATEGORY_NAME))
                {
                     PerformanceCounterCategory.Create(CATEGORY_NAME, "",
                                                    PerformanceCounterCategoryType.MultiInstance,
                                                    collection);
                }
                _counter = new PerformanceCounter(CATEGORY_NAME, "Number of Items", "Sample", false);
          }
 
          public void IncrementBy(int value)
          {
               _counter.IncrementBy(value);
          }
 
          public void DecrementBy(int value)
          {
               _counter.DecrementBy(value);
          }
     }
}

One of the most common mistakes with creating custom counters is keeping your naming straight.  I first declare a constant to keep the category name straight.  When adding a counter to perfmon this is the descriptor for the Performance object drop down list.  It is a container for all the different counters you might want for a system.

Since I only wanted to show a simple example of this I’ve left it as a simple class with only the counter object as publicly accessible.  Ideally you would be adding multiple counters to a single CounterCreationDataCollection for all your programs needs.

In the constructor I create the CounterCreationDataCollection to hold my counters.  Then I create the CounterCreationData object to add to the collection.  I give it a name (Number of Items), empty help string, and the counter type.  There are a plethora of counter types.  Since all I care about is counting a simple integer I went with NumberOfItems32.

Then I test to see if the Category has been previously registered with the operating system.  If not then I register it.  After I’m sure all the grunt work is out of the way I create a new counter in that category with a name.

Then I expose the Increment and Decrement methods.  This allows you to change the system.  Within the software I would create a new counter for say shopping cart items and every time an item was added or remove increment or decrement the counter.

This way while the system is running you can add your counters to perfmon and watch what is going on from there.  You can monitor your software will very little up front costs.  Genius.

Categories: C#, Programming Tags: ,

Advanced C# Operators

June 12th, 2009 robber.baron No comments

I often find use for the C# ? operator but don’t use it often enough to have it memorized. While it isn’t the most readable operator, it certainly shrinks two lines of code into a very concise single line. Worth the lack of readability.

Then I discovered the ?? operator which is another great way to short hand.

if (variable == null)
     return null;
else
     return variable;

It is a very convenient way to collapse that if-else statement into a single line. I thought I’d share as well as note them here for posterity’s sake.

a ? b : c if a is true, returns the value of b, otherwise c
a ?? b if a is null, returns b, otherwise returns a
Categories: C# Tags: , ,