Tag Archives: Development - Page 3

Formatting C# code in WordPress post

If you are like me working with C# a lot and trying to post articles on your WordPress site you might like this: Alex Gorbatchev’s SyntaxHighlighter

Example source code listing

[ sourcecode language=”csharp” ]
void Stuff
{

int moreStuff = 0;

}
[ /sourcecode ]

Would look like this:

void Stuff
{
    int moreStuff = 0;
}

I haven’t tested it with all possible language features but at least it is a start!

Linq – group by multiple fields

Seems this is an issue that multiple people have asked around at several occasions.

The question is how to use a Linq query where you want to group on more than one ‘field’

Turns out it is really not that hard. Thanks to ‘Anonymous’ methods that was also introduced ‘yay back’ it is as simple as the following example. Lets say you have a list of values like these:

Person 1: Age = 25, Gender = M, HighScore = 123
Person 2: Age = 21, Gender = F, HighScore = 99
Person 3: Age = 27, Gender = M, HighScore = 140
Person 4: Age = 19, Gender = M, HighScore = 131
Person 5: Age = 25, Gender = M, HighScore = 119
Person 6: Age = 22, Gender = M, HighScore = 108
Person 7: Age = 27, Gender = M, HighScore = 152
Person 8: Age = 21, Gender = M, HighScore = 98
Person 9: Age = 22, Gender = M, HighScore = 101
Person 10: Age = 25, Gender = M, HighScore = 167
Person 11: Age = 22, Gender = F, HighScore = 105
… etc

To get a simple report on average high score by Age and Gender you’ll have to use a query like this:

foreach(var entry in (from p in Persons
group p by new {  Age = p.Age, Gender = p.Gender } into g
orderby g.Key.Age, g.Key.Gender
select new
{
Age = g.Key.Age,
Gender = g.Key.Gender,
Avg = g.Average(pavg=>p.HighScore)
} ))

{

Console.WriteLine(“Age: {0}, Gender: {1}, Avg: {2}”, entry.Age, entry.Gender, entry.Avg);

}

Perhaps it might have simpler if you could simply have stated : “group p by p.Age, p.Gender” but unfortunately this is not supported. Then again this allows you to be more creative in defining the anonymous type so you can manipulate the data even more. Perhaps in the next version of Linq… if there is ever one…

 

Loading custom resources

The idea to use ‘custom’ resources in a .Net app might not make sense for all – and there may be times when it does not make sense at all since .Net apps (using VS.Net) have a built-in editor to manage embedded resources for an app. But… {here it comes} there could be some more flexibility to do it yourself like the ‘resource files’ does not have to be all located in the same directory (from a source point of view) and you can choose whether you want to include the files separately from the main executable when distributing the app.

First off, to you have to add a file (the resource) to the project – either by using the ‘Add new Item’  or ‘Add Existing Item’ context menus. Then under ‘Properties’ of the file ‘Build Action’ to ‘Embedded Resource’. Optionally you can set the ‘Copy to Output Directory’ but for this blog entry it won’t be used. Take note of the relative directory name (to the project’s root) since that will become part of the name of the resource – including the exact ‘case’ of the letters. For example, adding a text file named ‘CreateTables.sql‘ under a project directory ‘SQL‘ would result in a resource name ‘<Default namespace>.SQL.CreateTables.sql‘. Yes that is correct, the default namespace of the project is prepended to the full resource name.

Now to use the resource file (actually only the content since the file name has no use inside the project) you can use the following code:

public static string GetResourceByName(string name)
{

Stream s = System.Reflection.Assembly.GetExecutingAssembly().GetManifestResourceStream(name);
System.IO.StreamReader sr = new StreamReader(s);

return sr.ReadToEnd();

}

…

string sql = GetResourceByName(‘myNamespace.SQL.CreateTables.sql‘);

One small note: this example code does no error checking.

You can make the resource name a constant inside the project or create an enum using something like a string value attribute to match the enum entries to a string or something. Also, this example assumes the content is a text file but you can use the same principle of any type of content (like images, audio, video or whatever).

Revisited – XML File as database

I’ve again relooked at the idea of using a plain XML file as a source of a ‘small’ database. The previous attempt resulted in me going down the path of using datasets (typed and non-typed).

This time I started with a set of very simple classes (.Net/C# classes) that when you serialize them to XML it looks very much like a small data store/structure I also happened to use for another import/export genealogical database app I created.

Effectively through the use of ‘Generics’ I am able to create a simple ‘base’ class with which any such small in-memory database can be created/used/persisted to and from disk again. At the ‘lowest’ level I have a class that only does 3 things: Create the data store, load from disk/file and then save to disk/file. It makes use of a small utility class that handles serialization to (xml) files.

public interface ISmallDataStore
{

void CreateNewDataStore();
void LoadDataStore(string source);
void SaveDataStore(string destination);

}

public abstract class SDSXMLFileBase<T> : ISmallDataStore where T: class
{

private string sourceFilePath;
internal T DataContainer;

#region ISDS Members
abstract public void CreateNewDataStore();
abstract internal void SetRelationObjects();
abstract internal void RefreshCacheObjects();

public void LoadDataStore(string source)
{

sourceFilePath = source;
DataContainer = SerializationUtils.DeserializeXMLFile<T>(source);
SetRelationObjects();
RefreshCacheObjects();

}
public void SaveDataStore(string destination)
{

sourceFilePath = destination;
SerializationUtils.SerializeXMLToFile<T>(destination, DataContainer);

}
#endregion

}

Two abstract methods are added to facilitate functionality that will be explained later (SetRelationObjects and RefreshCacheObjects). They are optional and but I needed them for specific reasons.

The next ‘layer’ is a class that implements ‘DataContainer’ with data structures you want to use as the data store. These data structures are what is going to be saved/serialized. The following is small example of what it looks:

public class SampleSDSImplementation : SDSXMLFileBase<SampleTDataContainer>
{

public override void CreateNewDataStore()
{

DataContainer = new SampleTDataContainer();

}
…

}

Through the use of serialization attributes you can define the way the resulted xml would look that is stored. In my example the class SampleTDataContainer is effectively the data store and its fields are decorated with the attributes like XmlElement, XmlAttribute etc.

The following is a small excerpt from a sample class:

[Serializable(), XmlType(“data”)]
public class SampleTDataContainer
{

[XmlElement(“p”)]
public List<Person> Persons = new List<Person>();
[XmlElement(“m”)]
public List<Marriage> Marriages = new List<Marriage>();

}

[Serializable(), XmlType(“p”)]
public class Person
{

[XmlAttribute(“id”)]
public int Id { get; set; }
[XmlAttribute(“fn”)]
public string FirstName { get; set; }
[XmlAttribute(“sn”)]
public string Surname { get; set; }

…

}

A basic output of the (xml) file will look something like this:

<?xml version=”1.0″ encoding=”utf-16″?>
<data>

<p id=”1″ fn=”Anakin” sn=”Skywalker” … />
<p id=”2″ fn=”Padmé” sn=”Amidala” … />

<m id=”1″ mno=”1″ hid=”1″ wid=”2″ … />

…

</data>

Now that is all good and well for very basic stuff but what about a few more advanced requirements, like auto generating the ‘id’s, having ‘references’ between the objects (the Marriage class will have two references to Person (husband and wife), Person will have two (father and mother) and even reverse referencing (Person having a list of Marriage objects..).

Setting up those references in code is easy but once it has been serialized and then deserialized you get all kind of funnies. For example, An instance of a Person class might have a reference to a marriage and that Marriage instance has a reference to the same Person instance (the first time when you set it up in the code). Next time when the data is loaded from file (deserialized) the Marriage instance reference will not pont to the same instance as the Person instance (and vice versa). Ok this is a generic explanation of the issue but hopefully you get the drift…  Well, this is where one of those 2 methods I mentioned in the original base class comes in – SetRelationObjects. To ensure all referencing objects (at run-time) are actually referencing the correct objects you can do something like this:

internal override void SetRelationObjects()
{

foreach (Marriage m in DataContainer.Marriages)
{

if (m.HusbandId > 0 && m.Husband == null)

m.Husband = DataContainer.Persons.FirstOrDefault(h => h.Id == m.HusbandId);

if (m.WifeId > 0 && m.Wife == null)

m.Wife = DataContainer.Persons.FirstOrDefault(w => w.Id == m.WifeId);

}
foreach (Person p in DataContainer.Persons)
{

if (p.FatherId > 0 && p.Father == null)

p.Father = DataContainer.Persons.FirstOrDefault(f => f.Id == p.FatherId);

if (p.MotherId > 0 && p.Mother == null)

p.Mother = DataContainer.Persons.FirstOrDefault(f => f.Id == p.MotherId);

//Reassign union objects since deserialization created new/separated instances.
for (int i = 0; i < p.Marriages.Count; i++)
{

Marriage m = p.Marriages[i];
p.Marriages[i] = DataContainer.Marriages.FirstOrDefault(u => u.Id == m.Id);

}

}

}

The fields for things like (Person) Father and (Person) Mother was not shown in the class listing but you can probably guess what they should look like. These fields are ‘NOT’ serialized per se but rather handled by adding a (int) FatherId and (int) MotherId set of fields that ‘ARE’ serialized. It both makes it easier to read and smaller to store in the xml file. When deserializing only the ‘id’ fields are restored letting the SetRelationObjects method correct the referencing just after load. There may be other ways to do these kind of things but I choose this one as it suits me at the moment.

When designing classes for serialization it helps to know a couple of things about Xml serialization attributes and hidden methods. Lets say you want to have a public field in your class (like the Father/Mother ones) that you do not want exposed by serialization you can use a public bool ShouldSerialize<FieldName>() method inside the class. e.g.

public bool ShouldSerializeFatherId()
{

return FatherId > 0;

}
public bool ShouldSerializeMotherId()
{

return MotherId > 0;

}

[XmlAttribute(“fid”)]
public int FatherId { get; set; }

[XmlAttribute(“mid”)]
public int MotherId { get; set; }

private Person father = null;
[XmlIgnore]
public Person Father
{

get { return father; }
set
{

if (value != null)
{

father = value;
FatherId = father.Id;

}
else

FatherId = 0;

}

}
private Person mother = null;
[XmlIgnore]
public Person Mother
{

get { return mother; }
set
{

if (value != null)
{

mother = value;
MotherId = mother.Id;

}
else

MotherId = 0;

}

}

Helper methods for interacting with the data

It is possible that you can use the data container as is and directly call methods on the Person objects but that means you could be duplicating a lot of code or functionality each time you use it. To help with this I added a few simple helper methods in the class that implements the base class (SampleSDSImplementation). For example:

public Person AddPerson(string firstName, string surname)
{

int nextPersonId = 1;
if (DataContainer.Persons.Count > 0)

nextPersonId = (from p in DataContainer.Persons select p.Id).Max() + 1;

Person newPerson = new Person() { FirstName = firstName, Surname = surname };
newPerson.Id = nextPersonId;
DataContainer.Persons.Add(newPerson);
return newPerson;

}

public Person FindSinglePersonById(int id)
{

return DataContainer.Persons.FirstOrDefault(p => p.Id == id);

}

As an example of how to use it look at the following:

string dataStoreLocation = System.IO.Path.Combine(System.Environment.GetFolderPath(Environment.SpecialFolder.Desktop), “TestSDS.xml”);
SampleSDSImplementation sdsSample = new SampleSDSImplementation();
sdsSample.CreateNewDataStore();

Person vader = sdsSample.AddPerson(“Anakin”, “Skywalker”);
vader.IsMale = true;
vader.History = “The baddy of the story”;
vader.NickName = “Darth Vader”;
vader.PlaceOfBirth = “Tatooine”;
vader.PlaceOfDeath = “Death star 2”;

Person padme = sdsSample.AddPerson(“Padmé”, “Amidala”);
padme.DateOfDeath.Year = 2005;
padme.PlaceOfDeath = “Polis Massa”;
sdsSample.AddMarriage(vader, padme, 1, null, “Naboo”, null, “Mustafar”);

Person luke = sdsSample.AddPerson(“Luke”, “Skywalker”);
luke.IsMale = true;
luke.ChildNo = 1;
luke.NickName = “Master Luke”;
luke.PlaceOfBirth = “Polis Massa”;
luke.Father = vader;
luke.Mother = padme;

sdsSample.SaveDataStore(dataStoreLocation);

Conclusion

This is a simple way to build a little database (don’t fool yourself that you can easily build huge databases with this hehe) with which you can run a simple system that requires small database that can fit into memory.

See example project here: SDSTest

 

QPerfmon 1.8.2

I made a small change to my Quick Perfmon tool so that the performance counter definition set files (qpmset files) can also save the location of the application window’s size and location. This is useful if you want it to always load up to the same position on the screen – say when you have multiple sets and you want to position a couple of these windows with a specific layout.

Go grab it here…

Create SQLCE database in code

This is not exactly something new or breaking any new boundaries but it could be a useful tip for anyone that wants to make use of SQLCE databases from a small .Net application. There are some great tools and utilities to create a new SQL compact edition database using some UI but what if you want to automate the process or allow a client app to create a new database ‘on the fly’ or when needed?

It turns out it is not really that hard at all. All you need is a reference to the System.Data.SqlServerCe assembly – which is installed when you run the Sql server compact installer. Then you simply need to use the following code (example):

string connStr = string.Format(“Data Source={0};File Mode=Shared Read;Persist Security Info=False”, sdfFilePath);
using (System.Data.SqlServerCe.SqlCeEngine SQLCEDB = new System.Data.SqlServerCe.SqlCeEngine(connStr))
{

SQLCEDB.CreateDatabase();

}

That will create a new ‘blank’ database. What if you want to also create tables inside it? That is also very simple. I created a simple library to do that – it simply takes an input script and runs each command one by one. Each statement must be separated by a ‘GO’ statement that is on its own line.

e.g.

CREATE TABLE [TableA] (
[SomeID] int NOT NULL IDENTITY (1,1)
, [Desc] nvarchar(100) NOT NULL
);
GO
CREATE TABLE [TableB] (
[OtherID] int NOT NULL IDENTITY (1,1)
, [Desc] nvarchar(100) NOT NULL
);
GO
…

The class that handles it looks like this:

public delegate void CreateCmndResponseMsgDelegate(string createCMND, string message);
public class CreateSQLCEDB : BaseSQLCEDAL
{

private List<string> createCMDs = new List<string>();
public int ErrorCount { get; set; }
public event CreateCmndResponseMsgDelegate CreateCmndResponseMsg;
private void RaiseCreateCmndResponseMsg(string createCMND, string message)
{

if (CreateCmndResponseMsg != null)
{

CreateCmndResponseMsg(createCMND, message);

}

}
public void CreateCommandsFromScript(string script)
{

string[] createCmds = script.Split(new string[] { “\r\nGO\r\n” }, StringSplitOptions.RemoveEmptyEntries);
createCMDs.AddRange(createCmds);

}
public bool RunCommands()
{

ErrorCount = 0;
base.OpenConnection();
foreach (string cmndStr in createCMDs)
{

try
{

base.ExecuteNonQuery(cmndStr);

}
catch (Exception ex)
{

ErrorCount++;
RaiseCreateCmndResponseMsg(cmndStr, ex.Message);

}

}
base.CloseConnection();
return ErrorCount == 0;

}

}

Note that the base class ‘BaseSQLCEDAL’ is simply a wrapper class to handle all interactions with SqlCeConnection, SqlCeCommand etc.

See CreateSQLCEDB for full example code.

HTMLWriter 1.5

I’ve updated this little utility library by simplifying some method overloads plus added a static method for getting escaped html special characters.

To make the code more maintainable for the special characters (like adding new ones in the future) I’ve added an enum that use some .Net ‘attributes’ so you can see, use and reference everything about these ‘things’ in one place. To do that I had to add a special helper class so the enum can carry some additional properties (like the actual strings for the special character and the escaped string). To do this I created a custom attribute class called ‘StringValueAttribute’ like this:

public class StringValueAttribute : Attribute
{

public string StringExpandedValue;
public string StringValue;

public StringValueAttribute(string value, string stringExpandedValue)
{

this.StringValue = value;
this.StringExpandedValue = stringExpandedValue;

}

}

To retrieve the associated values from an enum another static helper class is needed: StringValueAttributeUtil

internal static class StringValueAttributeUtil
{

public static string GetStringValue(Enum value)
{

// Get the type
Type type = value.GetType();

// Get fieldinfo for this type
System.Reflection.FieldInfo fieldInfo = type.GetField(value.ToString());
// Get the stringvalue attributes
StringValueAttribute[] attribs = fieldInfo.GetCustomAttributes(
typeof(StringValueAttribute), false) as StringValueAttribute[];
// Return the first if there was a match.
return attribs.Length > 0 ? attribs[0].StringValue : null;

}
public static string GetStringExpandedValue(Enum value)
{

// Get the type
Type type = value.GetType();

// Get fieldinfo for this type
System.Reflection.FieldInfo fieldInfo = type.GetField(value.ToString());
// Get the stringvalue attributes
StringValueAttribute[] attribs = fieldInfo.GetCustomAttributes(
typeof(StringValueAttribute), false) as StringValueAttribute[];
// Return the first if there was a match.
return attribs.Length > 0 ? attribs[0].StringExpandedValue : null;

}

}

 

Then to actually make use of this helper class you decorate the enum like this: (showing only part of it…)

public enum HTMLSpecialCharacter
{

[StringValue(“<“, “&amp;lt;”)]
LessThanSign,
[StringValue(“>”, “&amp;gt;”)]
GreaterThanSign,
[StringValue(“\””, “&amp;quot;”)]
DoubleQuote,
[StringValue(“‘”, “&amp;#39;”)]
SingleQuote,

…

}

Happy HTML’ing 🙂

Update: Version 1.6 has now been released since…

VS11 Beta – Initial impressions

Ok, I’ve just installed the VS11 Beta. I know this might sound ‘weird’ to some (like the new, leading and bleeding edge guys) but I’m glad the ‘old’ stuff are still in there – aka Windows and Console type of applications. There are the obviously new project types that allow you to create all the new Metro interface apps but also a few other changes. For one, the built in Visual Studio Installer seems to be no more – the only option is the ‘Enable Installshield Limited Edition’.

Interestingly under ‘Other languages’ (since I choose C# as primary language) JavaScript now has its whole own section. These are all Metro project types. There are of course also VB.Net, C++, SQL Server and F#. Then LightSwitch also has its own options.

But since I mostly (ok only these days) use C# lets look at that. If you look at the screenshot the first thing you notice is the lack of colours. Yes, everything is now ‘Metro’ (or Retro like I call it). 

For my purposes there are the Windows Forms, Windows Services, Console and Class library projects. Also the standard ASP.Net types are still there. Most of the new ones are Metro related. Then as far as .Net frameworks are concerned you can choose anything from 2.0 to 4.5 (like 3.0, 3.5, 4.0). Interestingly, 4.5 does not have a ‘Client Profile’ option like 4.0 and 3.5. I have to wonder if they somehow made the complete 4.5 smaller so it could be compared to 4.0 client profile again??

Looks like there are a whole lot more performance analysis features included but I’ll have to ‘play around’ with it to see how it works before I make any judgement (on whether I like it or not).

As a first test I created a plain old Windows Forms project:

As you can see other than the boring colour scheme nothing else changed much. At least that is a good thing. The toolbox seems to have all the old controls in it. I might be mistaken but it looks like the team explorer stuff might be built in (this is the Pro Beta).

Well, those are my initial impressions and I’m not disappointed (yet). Best is you can try it out yourself!

Mail Aggregator Service on CodePlex

I’ve created a new project on CodePlex for ‘Mail Aggregator Service‘ so others can share and contribute if they want to.

There is no dedicated installer yet but installing the service is quite easy as the service exe supports my command line installation options like my other services (i.e. -install command line option).

It can be used with or without QuickMon.

I even have a new project icon/image for the project… mail gator 😉

QuickMon 2.6 released

Another quick note – QuickMon 2.6 has been released. The biggest change is the introduction of some parallel threading when calling collectors – using the .Net 4.0 parallel extensions. No new collectors or notifiers added yet.