Tag Archives: .Net - Page 2

VS2012 Express for Desktop

I’ve been waiting for this for a while so I was glad when they finally released this. Now for some initial feedback.

First off, the download was reasonable – size and speed wise. The installation was, lets just say ok – as I had to reboot since it had to update some libraries that were is ‘use’ at the time. Registration was also not too bad – since I have an old existing Hotmail/Live account where more of the details were already populated. Running it for the first time is where the shock comes in… it is as ugly as hell (reminds me death, all grey and boring). Unfortunately the same would apply to any of the other Express and even full versions of VS2012.

VS2012 Express For Desktop development

Functionality wise it provides just the very basics – not that you can expect anything more. Since I haven’t installed the ‘full’ express version I cannot comment on any other functionality that version might have. Anyway, The only templates worth mentioning is the Windows Forms, WPF and Console ones. Again, one cannot expect anything more of this release. Interestingly enough, when creating a new project the framework version cannot be changed on the ‘create project’ dialog screen. You can only change this ‘after’ the project has already been created.

One nice thing is that you can still create custom toolbars with ‘external’ commands – I use it to run a source backup tool I created some time ago. Another thing to remember is that this tool can be installed in Windows 7, unlike the full Express version that can ONLY be installed on Windows 8. The Web express version can also be installed on 7 (plus the TFS Express version).

If you excuse the way it looks (wearing shades to protect your eyes) then this tool is not that bad… Just wish they allowed old fashioned ‘themes’ to change the look and feel of the entire editor. Ah well, it is an ‘Express’ product… Fortunately you can import your VS 2010 color and font settings to get all your customizations back (even though it does moan about a whole bunch of settings that are not applicable to this edition which you can ignore)

In order to try it out you can follow this link.

Update:
If you like to change the overall theme and don’t like the built-in Light or Dark there are some more options if you look at this blog entry.

Windows Command Centre

A few years ago I created a quick utility to simply bring together all the various configuration tools that are included inside Windows itself. The problem is that there are actually all these built-in tools and utilities but finding them sometimes require you to search or discover them by accident. The tool I created simply provides an easy way to get to a lot of them. Even in Windows 7 not everything is located in one place – especially the more ‘advanced’, older or legacy tools – e.g. ODBC settings. Additionally I added something simple to simply ‘list’ the installed .Net versions as well.

A quick summary of what it contains:

System

Control panel
Manage computer
System config
Registry editor
Performance monitor
Scheduled tasks
Locale

Regional settings
Date and time

.Net

List versions
Disable Explorer GAC view

Hardware

Device manager
Install hardware
Remove hardware
Power options
Disk management
Removable storage
Settings

Keyboard
Mouse
Display
Sound
Printer

Software

Add & remove programs
Default programs
Windows components

Services

Services
IISAdmin
Component services
ODBC

Security

Security centre
Firewall settings
User accounts
Policy
Local security settings

Connections

Network connections
Create share
Shared folders
Map network drive
Disconnect network drive
Internet options

Looks

Taskbar properties
Fonts
Folder options
Display themes

I’ve now simple recompiled the utility and created a very simple installer for it (one for x86 and one for x64)

x86 – https://dl.dropbox.com/u/20983/WindowsCommandCentreSetup.msi

x64 – https://dl.dropbox.com/u/20983/WindowsCommandCentreSetupx64.msi

I’ve tested it on Windows 7 and it use to work on Vista/XP as well. Unfortunately I cannot guarantee that it will work properly on Windows 8 if at all. All it requires is the base .Net 2.0 framework to work.

HTMLWriter 1.7

Just a quick refresh on my HTMLWriter utility library. Some minor changes/additions:

1. Added support for the NOBR tag

2. Improved the special character functions including ignoring the ‘&’ sign when needed.

Latest version here.

Rumours of desktop development death greatly exaggerated

Ok, Microsoft has restored some faith from my side in them – after announcing that the new Visual Studio 11 (now called VS 2012) would NOT support any desktop development anymore.

They eventually changed their minds due to a lot of pressure and decided to release a desktop specific version as well – see this.

A quote from the article:

With this new Express edition, developers will be able to use C++, C#, or Visual Basic to create Windows desktop and console applications. Developers will also get access to new advances available across the Express family in Visual Studio 2012, such as the latest compilers and programming language tools, integrated unit testing, and the ability for small development teams to collaborate via Team Explorer and TFS Express.

Now, we just need to get MS to drop Metro and BioWare to fix Mass Effect 3’s ending… and the world could be a happy place again… hehe

Provide “Export to CSV” functionality on an ASP.Net page

I don’t do (or particularly like) ASP.Net development often but recently had to quickly add some ‘Export to CSV’ functionality of a displayed table to a page. Personally I would have just used ‘copy and paste’ to do it (the export) but since the user isn’t in the habit of thinking for themselves I had to create new functionality which turn out to be very nice – and even opens the door for some future more advanced functionality.

Anyway, to achieve this is really easy if you use the HttpContext.Current.Response class and add an attachment ‘header’ to your page. The header must be named ‘content-disposition‘ and ContentType ‘text/csv‘. See the following methods I created to simply take a DataSet and convert it to ‘CSV file’:

public class CSVExportUtils
{
    public void ExportDataSetToCSV(string title, DataSet ds, string columnNamesCSV = "")
    {
        string attachment = "attachment; filename=" + title.Replace(",", "").Replace(".", "") + ".csv";
        HttpContext.Current.Response.Clear();
        HttpContext.Current.Response.ClearHeaders();
        HttpContext.Current.Response.ClearContent();
        HttpContext.Current.Response.AddHeader("content-disposition", attachment);
        HttpContext.Current.Response.ContentType = "text/csv";
        HttpContext.Current.Response.AddHeader("Pragma", "public");
        if (columnNamesCSV.Length == 0)
        {
            WriteColumnName(ds);
            foreach (DataRow r in ds.Tables[0].Rows)
            {
                if (ds.Tables[0].Columns.Count > 0)
                {
                    string value = r[0].ToString();
                    if (value.Contains(","))
                        value = "\"" + value + "\"";
                    HttpContext.Current.Response.Write(value);
                    for (int i = 1; i < ds.Tables[0].Columns.Count; i++)
                    {
                        value = r[i].ToString();
                        if (value.Contains(","))
                            value = "\"" + value + "\"";
                        HttpContext.Current.Response.Write("," + value);
                    }
                }
                HttpContext.Current.Response.Write(Environment.NewLine);
            }
        }
        else
        {
            HttpContext.Current.Response.Write(columnNamesCSV);
            HttpContext.Current.Response.Write(Environment.NewLine);
            string[] columns = columnNamesCSV.Split(',');
            foreach (DataRow r in ds.Tables[0].Rows)
            {
                string value = r[columns[0]].ToString();
                if (value.Contains(","))
                    value = "\"" + value + "\"";
                HttpContext.Current.Response.Write(value);
                for (int i = 1; i < columns.Length; i++)
                {
                    value = r[columns[i]].ToString();
                    if (value.Contains(","))
                        value = "\"" + value + "\"";
                    HttpContext.Current.Response.Write("," + value);
                }
                HttpContext.Current.Response.Write(Environment.NewLine);
            }
        }

        HttpContext.Current.Response.End();
    }
    private static void WriteColumnName(DataSet ds)
    {
        StringBuilder sb = new StringBuilder();
        if (ds.Tables[0].Columns.Count > 0)
        {
            string value = ds.Tables[0].Columns[0].Caption;
            if (value.Contains(","))
                value = "\"" + value + "\"";
            HttpContext.Current.Response.Write(value);
            for (int i = 1; i < ds.Tables[0].Columns.Count; i++)
            {
                value = ds.Tables[0].Columns[i].Caption;
                if (value.Contains(","))
                    value = "\"" + value + "\"";
                HttpContext.Current.Response.Write("," + value);
            }
        }
        HttpContext.Current.Response.Write(Environment.NewLine);
    }
}

This method also allows you to specify the fields you want to export – or alternatively it just use the ones in the DataSet. For example, you can use it like this:

if (Request.QueryString["csvexport"] != null)
{
    CSVExportUtils csvExportUtils = new CSVExportUtils();
    csvExportUtils.ExportDataSetToCSV(fileName, dataSet, "Field1,Field2,...");
}

The calling page can then simply have a hyperlink like this:

SomePage.aspx?csvexport=Yes

Passing a ‘Method’ as parameter in C#

This is actually nothing new but sometimes you might still need a quick reference for to remember how to do this quickly… Say you have a generic class that does something like generating a report and display it somehow (or save or whatever the class do) and want all the ‘calling classes’ to just pass the ‘Method’ that it must ‘run’ in order to generate the report. Yes there are probably nice and fancy tools these days that could also do it if you have the mulla for it…

A solution is to use Anonymous methods that has been with C# (.Net) since version 3 of something.

Reporter r = new Reporter();
r.Report = delegate
{
string stuff = "example report yada yada yada";
return stuff;
}
r.Show();

The generic class that provides the ‘generic’ functionality can then look something like this using a defined delegate so it knows what output it will receive when ‘running’ the method.

public delegate string RefreshActionDelegate();
class Reporter
{
    public RefreshActionDelegate Report { get; set; }

    public Show()
    {
       if (Report != null)
       {
          string theContent = Report();
          DoSomethingWithContent(theContent);
       }
    }
}

This is just a quick example but it shows how you can use the main ‘generic’ class from multiple places each time just passing a different ‘Method’ with its own functionality.

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…