12 Jan 2012 @ 3:11 PM 

In some of my recent posts, I’ve covered the topic of accessing and parsing an INI file for configuration data in a C# Application.

Some may wonder why. After all; the “norm” for C# and .NET applications is to use XML files for configuration information, isn’t it? Well, yes. But to be honest, XML files are a fucking pain in the ass. They aren’t human readable to your average person the same way an INI file is, and getting/setting values is tedious. Primarily, the reason I use INI files is that they are:

  1. Human Readable: Anybody can understand the basic structure of the sections and Name=Value syntax.
  2. Accessible: You don’t need a special editor
  3. Portable: since the entire thing is interpreted using Managed code, it will act the same on any platform (Mono or the MS CLR).

Mostly, I feel that XML, and in many ways other configuration options, are more or less driven by fad. Another option for configuration settings on Windows is the Registry, which is in fact often the recommended method; but this is anything but accessible to the user. Would you rather guide a user to edit a INI file or to fiddle with registry settings?

With that said, INI Files do have their own issues. For example, their data is typically typeless; or, more precisely, the Values are all strings. Whereas using a .NET XML Serializer, for example, you could easily(relatively speaking) serialize and deserialize a special configuration class to and from an XML file and preserve it’s format, with my INI file class there will typically be some work to parse the values.

It was with the idea of turning my string-only INIFile configuration settings into something that can be used for nearly any type that I created the INItemValueExtensions class, which is nothing more than a static class that provides some extension methods for the INIDataItem class. I covered this in my previous post.

The prototypes for the two static functions are:

  1.  
  2. public static T GetValue<T>(this INIDataItem dataitem, T DefaultValue);
  3.  
  4. //and
  5.  
  6. public static void SetValue<T>(this INIDataItem dataitem, T newvalue);
  7.  
  8.  

How would one use these extension methods? Well, here’s an Example:

  1.  
  2. public static void main(String[] args)
  3. {
  4.     INIFile loadini = new INIFile("D:\\testini.ini");
  5.     loadini["Dates"]["TestDate"].SetValue(DateTime.Now);
  6.     DateTime readvalue = loadini["Dates"]["TestDate"].GetValue<datetime>();
  7.    
  8. }
  9. </datetime>

Woah, hold the phone! What’s going on here? We’re loading DateTime values directly from the INI File? How does that work?

All the “magic” happens in the getValue generic extension method. The first thing the routine does is check to see if the Type Parameter has a static TryParse() method; if it implements ISerializable and have a TryParse method, than the routine will read the string from the INI file, decode it via Base64, and throw it in a MemoryStream, and then try to deserialize the Object Graph for a Type T using that stream.

If it does implement a TryParse() routine, (like, for example, DateTime) it doesn’t try quite as hard. It takes the string from the INI file and hands it to the Type’s TryParse() routine, and then returns what that gives back. Naturally, the inverse function (setValue) does something somewhat opposite; it checks the Base64 logic, and if so it sets the value of the item to the Base64 encoded value of the serialized object. Otherwise, it just uses toString().

This typically works, particularly with DateTime, because usually ToString() is the inverse of TryParse(). In the case of DateTime, this has a few edge cases with regards to locale, but usually it works quite well. And more importantly, the introduction of allowing any object that implements ISerializable to simply be thrown as an INI value via a Base64 encoded string is useful too, although with large objects it’s probably not a good idea for obvious reasons.

But… I still want to access other settings!

Of Course, an INIFile is only one of any number of ways to store/retrieve configuration settings. And while they don’t typically lend themselves to the same syntax provided by the INIFile class, it would be useful to have some sort of common denominator that can handle it all. That was the original intent of the relatively unassuming ISettingsStorage interface:

  1.  
  2.    public interface ISettingsStorage
  3.     {
  4.         void Save();
  5.         void Load();
  6.         void AddValue(String Category, String ValueName, String Value);
  7.         String GetValue(String Category, String ValueName);
  8.     }
  9.  

This uses a concept known as a “category” which is pretty much the same idea as an INI File section. What makes it different is that, for implementors that use other storage mechanisms, it could have additional meaning; for example, a fictitious XML implementation of ISettingsStorage could use the “Category” string as an XPath to an element; and the Value could be stored/retrieved as a Attribute. a Registry implementation might use it as a Registry path, and so on.

The problem is, even though the INIFile class implements this interface, it’s too basic, and doesn’t provide nearly the syntactic cleanliness that just using the INIFile does. Stemming from that, and because I wanted to try to get a way to store settings directly in a DB, I introduced two events to the INIFile class; one that fires when a Value is retrieved, and one when a value is saved. This way, the event could be hooked and the value saved elsewhere, If desired. Now, to be fair, this is mostly a shortcoming of my interface definition; as you can see above, there is no way to, for example, inspect category or Value names. I toyed with the idea of adding a “psuedo” category/value combination that would return a delimited string of category names, but that felt extremely silly. The creation of a generic interface- or abstract class- that provides all the conveniences I currently enjoy using my INIFile class but allowing me to also use XML, Registry, or nearly any other persistent storage for settings will be a long term goal. For now, I’m content with accessing INI files and having a unclean event to hack in my own behaviour.

My first test of the above feature- whereby it allows values to be TryParse’d and ToString’d back and forth from a given type on the fly- was the creation of a FormPositionSaver class.

The proper way to save and restore a window’s position on Windows is using the GetWindowPlacement() and SetWindowPlacement() API Functions. These use a structure, named, quite aptly, “WINDOWPLACEMENT” to retrieve and set the window position and various attributes. Therefore, our first task is to create the proper P/Invoke’s for these functions:

  1.  
  2.  [DllImport("user32.dll")]
  3.         private static extern int OffsetRect(ref RECT lpRect, int x, int y);
  4.  
  5. [DllImport("user32.dll")]
  6.         private static extern int GetWindowPlacement(IntPtr hwnd, ref WINDOWPLACEMENT lpwndpl);
  7.  
  8. [DllImport("user32.dll")]
  9.         private static extern int SetWindowPlacement(IntPtr hwnd, ref WINDOWPLACEMENT lpwndpl);
  10.  

I also include OffsetRect(), but I’ll get to that in a bit. Now the “big one” is the definition of the WINDOWPLACEMENT structure and it’s various aggregate structures. Why? well, in the interest of leveraging the INIFile’s static extensions, Why not define a static TryParse() and a toString() method on the structure that can set and retrieve the member values:

  1.  
  2.  
  3.         [StructLayout(LayoutKind.Sequential)]
  4.         private struct POINTAPI
  5.         {
  6.             internal int x;
  7.             internal int y;
  8.  
  9.  
  10.             public POINTAPI(int px, int py)
  11.             {
  12.                 x = px;
  13.                 y = py;
  14.             }
  15.  
  16.             public static void TryParse(String parseit, out POINTAPI result)
  17.             {
  18.                 //format: (X,Y)
  19.                 //strip out parens.
  20.                 String[] parsed = parseit.Replace("(", "").Replace(")", "").Split(new char[] {‘,’});
  21.                 int kx = int.Parse(parsed[0]);
  22.                 int ky = int.Parse(parsed[1]);
  23.  
  24.  
  25.                 result = new POINTAPI(kx, ky);
  26.             }
  27.  
  28.             public override string ToString()
  29.             {
  30.                 return "(" + x + "," + y + ")";
  31.             }
  32.         }
  33.  
  34.         [StructLayout(LayoutKind.Sequential)]
  35.         private struct RECT
  36.         {
  37.             internal int Left;
  38.             internal int Top;
  39.             internal int Right;
  40.             internal int Bottom;
  41.  
  42.             public override string ToString()
  43.             {
  44.                 return "{" + new POINTAPI(Left, Top).ToString() + "-" + new POINTAPI(Right, Bottom).ToString() + "}";
  45.             }
  46.  
  47.             public RECT(int pLeft, int pTop, int pRight, int pBottom)
  48.             {
  49.                 Left = pLeft;
  50.                 Top = pTop;
  51.                 Right = pRight;
  52.                 Bottom = pBottom;
  53.             }
  54.  
  55.             public static void TryParse(String parsestr, out RECT result)
  56.             {
  57.                 //strip out braces…
  58.                 parsestr = parsestr.Replace("{", "").Replace("}", "");
  59.                 //split at ")-("…
  60.                 String[] Pointstrings = parsestr.Split(new string[] {")-("}, StringSplitOptions.RemoveEmptyEntries);
  61.                 POINTAPI firstpoint, secondpoint;
  62.                 //parse the resulting values. re-add the parens that were removed by the split.
  63.                 POINTAPI.TryParse(Pointstrings[0] + ")", out firstpoint);
  64.                 POINTAPI.TryParse("(" + Pointstrings[1], out secondpoint);
  65.  
  66.  
  67.                 result = new RECT(firstpoint.y, firstpoint.y, secondpoint.x, secondpoint.y);
  68.             }
  69.         }
  70.  
  71.  
  72.  [StructLayout(LayoutKind.Sequential)]
  73.         private struct WINDOWPLACEMENT
  74.         {
  75.             internal int Length;
  76.             internal int flags;
  77.             internal int showCmd;
  78.             internal POINTAPI ptMinPosition;
  79.             internal POINTAPI ptMaxPosition;
  80.             internal RECT rcNormalPosition;
  81.  
  82.             public override string ToString()
  83.             {
  84.                 return String.Join(",", new string[]
  85.                                             {
  86.                                                 flags.ToString(), showCmd.ToString(),
  87.                                                 ptMinPosition.x.ToString(), ptMinPosition.y.ToString(),
  88.                                                 ptMaxPosition.x.ToString(), ptMaxPosition.y.ToString(),
  89.                                                 rcNormalPosition.Left.ToString(), rcNormalPosition.Top.ToString(),
  90.                                                 rcNormalPosition.Right.ToString(), rcNormalPosition.Bottom.ToString()
  91.                                             });
  92.             }
  93.  
  94.             //parsed a string into a WINDOWPLACEMENT structure.
  95.             public static bool TryParse(String parseme, out WINDOWPLACEMENT result)
  96.             {
  97.                 try
  98.                 {
  99.                     String[] splitvalues = parseme.Split(‘,’);
  100.                     int[] parsedvalues = new int[splitvalues.Length];
  101.  
  102.  
  103.                     for (int i = 0; i < parsedvalues.Length; i++)
  104.                     {
  105.                         int.TryParse(splitvalues[i], out parsedvalues[i]);
  106.                     }
  107.  
  108.                     result = new WINDOWPLACEMENT
  109.                                  {
  110.                                      flags = parsedvalues[0],
  111.                                      showCmd = parsedvalues[1],
  112.                                      ptMinPosition = new POINTAPI(parsedvalues[2], parsedvalues[3]),
  113.                                      ptMaxPosition = new POINTAPI(parsedvalues[4], parsedvalues[5]),
  114.                                      rcNormalPosition =
  115.                                          new RECT(parsedvalues[6], parsedvalues[7], parsedvalues[8], parsedvalues[9])
  116.                                  };
  117.  
  118.                     return true;
  119.                 }
  120.                 catch
  121.                 {
  122.                     result = new WINDOWPLACEMENT();
  123.                     return false;
  124.                 }
  125.             }
  126.         }
  127.  
  128.  

WHEW! that’s quite a bit of code for a structure definition, but we’ll make up for it with the brevity of the actual FormPositionSaver class itself. First, my design goal with this class was to make it basically do all the heavy lifting; it hooks both the Load and Unload event, and saves to and from a given INIFile Object in those events. Since the application I was working on at the time didn’t actually get a Valid INI object until during it’s main form’s Load event, and since there is no way to say “Invoke this event first no matter what” I also added a way for it to be told that hooking the load event would be pointless since it already occured, at which point it will not hook the event and instead set the form position immediately. Values are stored

  1.  
  2. public class FormPositionSaver
  3. {
  4.  
  5.   private Form FormObject = null;
  6.         private INIFile Configuration = null;
  7.         private static readonly String usesectionName = "WindowPositions";
  8.  
  9.  
  10.         /// <summary>
  11.         /// Create the FormPositionSaver
  12.         /// </summary>
  13.         /// <param name="FormObj">Form to deal with</param>
  14.         /// <param name="configfile">INIFile to load and save</param>
  15.         /// <param name="alreadyloaded">whether the Load event has fired. If true, will try to set the form position immediately. otherwise, it hooks the Load event and waits.</param>
  16.         public FormPositionSaver(Form FormObj, INIFile configfile, bool alreadyloaded)
  17.         {
  18.             Configuration = configfile;
  19.             FormObject = FormObj;
  20.  
  21.             FormObject.FormClosed += new FormClosedEventHandler(FormObject_FormClosed);
  22.  
  23.  
  24.             if (!alreadyloaded)
  25.                 FormObject.Load += new EventHandler(FormObject_Load);
  26.             else
  27.             {
  28.                 FormObject_Load(FormObject, new EventArgs());
  29.             }
  30.         }
  31.  
  32.         //save the placement...
  33.         private void FormObject_FormClosed(object sender, FormClosedEventArgs e)
  34.         {
  35.             //save placement.
  36.             //all the "tough work" is handled above, and by the INIDataItem Extension methods. Here we
  37.             //can simply use SetValue<> and set the value. Nice and clean.
  38.             WINDOWPLACEMENT grabplacement = new WINDOWPLACEMENT();
  39.             GetWindowPlacement(FormObject.Handle, ref grabplacement);
  40.             Configuration[usesectionName][FormObject.Name].SetValue(grabplacement);
  41.         }
  42.  
  43.         //Load event: load the form placement, if present, from the INI file we were given in our constructor.
  44.         private void FormObject_Load(object sender, EventArgs e)
  45.         {
  46.             WINDOWPLACEMENT currplacement = new WINDOWPLACEMENT();
  47.             GetWindowPlacement(FormObject.Handle, ref currplacement);
  48.                 //default is wherever it is now if there is a parse problem.
  49.  
  50.             WINDOWPLACEMENT getplacement =
  51.                 Configuration[usesectionName][FormObject.Name].GetValue(currplacement);
  52.  
  53.             //check for previous instances, and offset if there are.
  54.             String thisproc = Process.GetCurrentProcess().ProcessName;
  55.             Process[] existing = Process.GetProcessesByName(thisproc);
  56.             if (existing.Length > 1)
  57.             {
  58.                 //more than one, so offset...
  59.                 OffsetRect(ref getplacement.rcNormalPosition, 16*existing.Length, 16*existing.Length);
  60.             }
  61.  
  62.  
  63.             SetWindowPlacement(FormObject.Handle, ref getplacement);
  64.  
  65.             //load placement...
  66.         }
  67.     }
  68.  

Alright, so maybe I lied a bit. It's not super short. Although a lot of it is comments. Some might note that I only sporadically add doc comments, even though I ought to be adding them everywhere. Well, sue me. I just add them when I feel like it. When I'm concentrating on function, I'm not one to give creedence to form.

This is where I explain OffsetRect(). Basically, if your application is run twice, and you load the form position twice, the second form will open over the first one, and the screen will look pretty much the same. So we detect previous instances and offset by an amount to make it's position different from any previous instances as necessary. That's pretty much the only purpose of OffsetRect.

I have packaged the current versions of cINIFile.cs and the new FormPositionSaver.cs in a zip file, it can be downloaded from here.

Posted By: BC_Programming
Last Edit: 12 Jan 2012 @ 03:11 PM

EmailPermalinkComments (0)
Tags
 01 Jan 2012 @ 5:20 PM 

HAHA! How’s that for a clever title?

Oh… well… ahem… nevermind.

As a avid user of my own INIFile class, which I first write about- at least it’s C# implementation- in my parsing INI files posting, I am always looking for ways to improve it’s usage make it more “accessible”.

Recently, I have been tasked (by way of my new title of “freelance consultant”) with creating several LOB (Line of Business) Type applications. Applications, naturally, have a tendency to lend their implementations to the creation and reading of settings. Being something of a fan of the simplicity of INI Files, I chose to use my INIFile class in the application. It works well, however, I have noticed that I have a lot of duplicate code. More specifically, I typically have to implement a “wrapper” class, which manages configuration information and reads/writes values to and from the INIFile as its own properties are accessed. For example:

  1. public bool PopulateUserOrderDropdown
  2. {
  3.    get {
  4.     bool tparse;
  5.     if(bool.TryParse(OurINI["Admin.Settings"]["PopulateUserOrderDropDown","false"].Value,out tparse)
  6.         return tparse;
  7.     return false;
  8.    }
  9.    set { OurINI["Admin.Settings"]["PopulateUserOrderDropDown"].Value;}
  10. }

Nothing too dreadful, but imagine having nearly the exact same thing repeated a number of times! The code is repeated and as Larry Wall says, one of the traits of a good programmer is sloth. I don’t like having to write this same code over and over again! The INIFile is supposed to make it easy!

The trouble here stems from the fact that the INIFile values are only strings; and typically, many settings are represented in the application itself as integers and booleans, dates, and so forth. My first attempt to mitigate the clutter was a static method, which I called xParse:

  1. public static class boolEx
  2. {
  3.     public static bool xParse(String Value, bool Default)
  4.     {
  5.         bool parseresult;
  6.         if(bool.TryParse(Value,out parseresult))
  7.             return parseresult;
  8.         else
  9.             return Default;
  10.  
  11.     }
  12. }

relatively straightforward- basically it’s a shell of what I had repeated over and over again. This mitigated the issue somewhat, so my properties in the wrapper looked like this:

  1. public bool PopulateUserOrderDropdown
  2. {
  3.    get { return boolEx.xParse(OurINI["Admin.Settings"]["PopulateUserOrderDropDown", "false"].Value); }
  4.    set { OurINI["Admin.Settings"]["PopulateUserOrderDropDown"].Value;}
  5. }

much more managable, but still, could we not make this more concise? My first thought, was that perhaps I could eliminate the necessity of having the wrapper at all; I recalled two interfaces from my old COM programming days, specifically, IDispatch and IDispatchEx. Surely, I could do something similar?

Unfortunately, the interfaces are for COM, and C# doesn’t have dynamics until Version 4.

So, I fired up Visual Studio 2010 express to see if I couldn’t add the dynamic language constructs to the INIFile class; additionally, since I still need to work with .NET 3.5, I’ll add the new code as a conditional compilation.

The first step was deciding exactly what I wanted to happen. Imagine code like this:

  1. INIFile useINI = new INIFile("settings.ini");
  2. String ConnectionString = (String)useINI.General.ConnectionString;

The holy grail of the INIFile simplicity! Naturally, the .NET framework does provide the facility with which to add this functionality, as part of the System.Dynamic namespace.

The first step was deciding on the method by which to conditional compile. Since projects copy the source of a file to your project folder when you add them, it seemed reasonable to simply add it as a #define right inside the INIFile class itself.

#define CS4

And now, I just need to enclose all my new happy stuff in a conditional directive, and I’ll get the best of both worlds- C# 4.0 consumers who keep the #define will be able to use the suave new feature, and older consumers will still be able to work without ripping apart the classes. The code to add this was surprisingly simple; as it stands now the longest method (An implementation of TryDeleteMember, which is never called from C#/VB.NET consumers, so is excessive for my usage). First, obviously we enclose the import statement in the conditional compile; the class headers are conditionally compiled as well, only deriving from DynamicObject with CS4 set.

The core of the new functionality is in the overrides to the Dynamic Object’s TryGetMember.

For the INISection:

  1. public override bool TryGetMember(GetMemberBinder binder,out object result)
  2. {
  3.     result = this[binder.Name];
  4.     return true;
  5. }

And for the INIFile…

  1. public override bool TryGetMember(GetMemberBinder binder,out object result)
  2. {
  3.     result = this[binder.Name];
  4.     return true;
  5. }

Exactly the same, in fact. This works because of the indexer I added; the indexer will add the item if it doesn’t exist and return the new value, so even if the member name doesn’t exist, the INIFile will simply have that section added.

That’s for the retrieval of erements; to allow the assignment to them in the same fashion, we need to override TrySetMember(). In my case, this was a bit more involved, for flexibility purposes.

For example, code like INIFile.MainSection=”hello” should work, and change the name of the section. And why allow things like assignments from a Dictionary<String, String>, or maybe even a list (assigning a numbered id to set values)? And of course allow setting the Value directly, which will likely use the indexer much as I did for the TryGet… Implementations.

  1.        public override bool TrySetMember(SetMemberBinder binder, object value)
  2.         {
  3.  
  4.             //if it is a dataitem, set it directly.
  5.             if (value is INIDataItem)
  6.             {
  7.                 this[binder.Name] = (INIDataItem)value;
  8.                 return true;
  9.             }
  10.             else if (value is Tuple<, Object>)
  11.             {
  12.                 Tuple<, Object> theTuple = (Tuple<, Object>)value;
  13.                 INIDataItem getitem = this[binder.Name];
  14.                 getitem.Name = theTuple.Item1;
  15.                 getitem.Value = theTuple.Item2.ToString();
  16.                 return true;
  17.  
  18.             }
  19.             else if (value is Tuple<, String>)
  20.             {
  21.                 Tuple<, Object> theTuple = (Tuple<, Object>)value;
  22.                 INIDataItem getitem = this[binder.Name];
  23.                 getitem.Name = theTuple.Item1;
  24.                 getitem.Value = theTuple.Item2.ToString();
  25.                 return true;
  26.             }
  27.  
  28.             else if (value is KeyValuePair<, Object>)
  29.             {
  30.  
  31.                 //Allow a KeyValuePair<,Object> to be passed to set Name and Value.
  32.                 KeyValuePair<, Object> castedval = (KeyValuePair<, Object>)value;
  33.                 INIDataItem getitem = this[binder.Name];
  34.                 getitem.Name = castedval.Key;
  35.                 getitem.Value = castedval.Value.ToString();
  36.  
  37.                 return true;
  38.             }
  39.             else if (value is KeyValuePair<, String>)
  40.             {
  41.                 //Allow a KeyValuePair<,String> to be passed to set Name and Value.
  42.                 KeyValuePair<, String> castedval = (KeyValuePair<, String>)value;
  43.                 INIDataItem getitem = this[binder.Name];
  44.                 getitem.Name = castedval.Key;
  45.                 getitem.Value = castedval.Value;
  46.  
  47.                 return true;
  48.  
  49.             }
  50.  
  51.             else
  52.             {
  53.                 this[binder.Name].Value = value.ToString();
  54.                 return true;
  55.             }
  56.         }

setting the Value should be equally flexible; since we can, why not?
for example, why not make the following “legal”?

  1. INIFile.Section.Value="newvalue";
  2. INIFile.Section.Value=DateTime.Now;
  3. INIFile.Section.Value=Tuple.Create("NewName","Chicken");
  4. INIFile.Section.Value=Tuple.Create("NewName",DateTime.Now);

The first example sets the Value to a string, the second sets it to a DateTime that is silently casted to a String (using toString(), and the last two use the new C# 4.0 tuples, to set both the name of the value and the value simultaneously.

A more elegant solution would be to add this code to the Indexer, and merely call the indexer with the name and the value and return true if no exception occurs and false otherwise. However, I’m reluctant to go that route since some of the types are C# 4 types (Tuples).

  1.        public override bool TrySetMember(SetMemberBinder binder, object value)
  2.         {
  3.  
  4.             if (value is String)
  5.             {
  6.                 this[binder.Name].Name = (String)value;
  7.                 return true;
  8.  
  9.             }
  10.             else if (value is List<INIItem>)
  11.             {
  12.                 INISection getsection = this[binder.Name];
  13.                 getsection.INIItems = (List<INIItem>)value;
  14.                 return true;
  15.  
  16.             }
  17.             else
  18.             {
  19.                 return false;
  20.  
  21.             }
  22.  
  23.         }

So Now, I’ve got an INI File implementation that supports Dynamic invocation. Well, that’s great… except that the application I first found it clumsy in is using .NET 3.5, so I can’t use the dynamic features. Back at square one.

In C# 2008/3, we might not be able to leverage the power of dynamics, but we do have generics and Extension methods at our disposal. a feasible alternative could be to add a extension method to the INIDataItem class that has a generic type parameter that it will attempt to convert it’s string Value into. First, using ChangeType, second, it can try to invoke a static TryParse on the given Type to parse the “value” string. And if none of that works, it can return a passed in default. This is still more verbose than the dynamic solution, but it has two distinct advantages- first, it’s type-safe, so you get all the intellisense goodness, and second, it’s still shorter than the alternative.

Here is the code, which can be found in the cINIFile.cs file attached to this posting as well.

  1.    public static class INItemValueExtensions
  2.     {
  3.         //extensions for INIDataItem
  4.  
  5.         //normally, INIDataItem is a Name/Value Pair; More Specifically, because of the way INI files are, they are
  6.         //naturally typeless. However, most configuration options are mapped to a different type by the application.
  7.         //and I’ve found it to be a gigantic pain to have to write the same TryParse() handling code over and over.
  8.         //so I added these handy extensions to the INIDataItem class, which provide some functions for setting.
  9.         //I keep them out of the main code simply because that way it doesn’t clutter it up. It’s already cluttered enough as-is.
  10.  
  11.         /// <summary>
  12.         /// Attempts to use Convert.ChangeType() to change the Value of this INIDataItem to the specified type parameter.
  13.         /// If this fails, it will attempt to call a static "TryParse(String, out T)" method on the generic type parameter.
  14.         /// If THAT fails, it will return the passed in DefaultValue parameter.
  15.         /// </summary>
  16.         /// <typeparam name="T">Parameter Type to retrieve and act on in Static context.</typeparam>
  17.         /// <param name="dataitem">INIDataItem instance whose value is to be parsed to the given type.</param>
  18.         /// <param name="DefaultValue">Default value to return</param>
  19.         /// <returns>Result of the parse/Conversion, or the passed in DefaultValue</returns>
  20.         public static T GetValue<T>(this INIDataItem dataitem, T DefaultValue)
  21.         {
  22.  
  23.             //Generic method, attempts to call a static "TryParse" argument on the given class type, passing in the dataitem’s value.
  24.             try
  25.             {
  26.                 return (T)Convert.ChangeType(dataitem.Value, typeof(T));
  27.             }
  28.             catch (InvalidCastException ece)
  29.             {
  30.                 //attempt to call TryParse. on the static class type.
  31.                 //TryParse(String, out T)
  32.  
  33.                 Type usetype = typeof(T);
  34.                 T result = default(T);
  35.                 Object[] passparams = new object[] { dataitem.Value, result };
  36.                 try
  37.                 {
  38.                     bool tpresult = (bool)usetype.InvokeMember("TryParse", BindingFlags.Static, null, null, passparams);
  39.                     if (tpresult)
  40.                     {
  41.                         //tryparse succeeded!
  42.                         return (T)passparams[1]; //second index was out parameter…
  43.                     }
  44.                 }
  45.                 catch (Exception xx)
  46.                 {
  47.                     //curses…
  48.                     return DefaultValue;
  49.  
  50.                 }
  51.  
  52.             }
  53.             return DefaultValue;
  54.  
  55.         }
  56.         /// <summary>
  57.         /// Logical inverse of the getValue routine… a bit faster to implement…
  58.         /// </summary>
  59.         /// <typeparam name="T"></typeparam>
  60.         /// <param name="dataitem"></param>
  61.         /// <param name="newvalue"></param>
  62.  
  63.         public static void setValue<T>(this INIDataItem dataitem, T newvalue)
  64.         {
  65.             dataitem.Value = newvalue.ToString();
  66.  
  67.         }
  68.  
  69.         private static void GetTypeDefault<T>(out T result)
  70.         {
  71.             Type tt = typeof(T);
  72.  
  73.             //basic idea: call default, empty constructor using reflection.
  74.             ConstructorInfo defaultconstructor = tt.GetConstructor(new Type[] { });
  75.  
  76.             result = (T)defaultconstructor.Invoke(null);
  77.  
  78.         }
  79.  
  80.     }
  81.  
  82.  
  83.  

And there you have it, a bunch of awesome additions. INI files are often thought of as deprecated, but that’s only the INIFile functions. This class was designed because working with the registry makes it difficult to test properly, and because JSON,YAML, and many other formats are excessively complicated. when you just need a few basic settings, all you need is the clean, simple format of a INI file. And now, with these additions, code for reading from those INI files is clean and simple as well!

The Source- cINIFile.cs

Posted By: BC_Programming
Last Edit: 01 Jan 2012 @ 05:27 PM

EmailPermalinkComments (0)
Tags
 25 Dec 2011 @ 2:05 PM 

As I posted previously here, Sorting a Listview can be something of a pain in the ass.

In that article, I covered some basics on providing a class that would essentially give you sorting capabilities for free, without all the messy code that would normally be required. A lot of the code required for sorting is mostly boilerplate with a few modifications for sorting various types. As a result, the generic implementation works rather well.

However, as with any class, adding features never hurts. In this case, I got to thinking- why not have right-clicking the ColumnHeaders show a menu for sorting against that Column? Seems simple enough. I quickly learned that apparent simplicity often is misattributed.

I faced several issues. The first thought was that I could hook a Mouse event for Right-Clicking a column header. Unfortunately, I soon discovered two facts about the .NET ListView control. First, was that there was no event for right-clicking a header control. Second, no even was fired at all by the ListView control when you right-clicked a header.

This left me stymied. How the heck do I implement this feature? I discovered something of a “hack” however, in that when the ListView’s ContextMenuStrip property is set, that ContextMenu Strip will be shown regardless of the location the ListView is clicked. This at least gave me something to work with. Since a ContextMenuStrip’s “Opening” event can be easily hooked, we can use that as an entry point and perform needed calculations to determine if we are indeed on a columnheader.

Which brings me to the next problem, which is determining when a columnheader was in fact the item that was clicked. This requires determining the rectangle the Header control occupies, first. The Header Control is a child control of the ListView; as such, a platform Invoke using the EnumChildWindows() API was required, something like this:

private Rectangle _HeaderRect;
private delegate bool EnumWindowsCallBack(IntPtr hwnd,IntPtr lparam);
[DllImport("user32.dll")]
private static extern int EnumChildWindows(IntPtr hwndParent,EnumWindowCallBack callbackFunction,IntPtr lParam);
[DllImport("user32.dll"]
private static extern bool GetWindowRect(IntPtr hWnd,out RECT lpRect);

[StructLayout(LayoutKind.Sequential)]
private struct RECT
{
    public int Left;
    public int Top;
    public int Right;
    public int Bottom;

}

private bool EnumWindowCallback(IntPtr hwnd, IntPtr lParam)
{
    RECT rct;
    if(!GetWindowRect(hwnd,out rct))
    {
    //first child of the listview should be the header control
    _HeaderRect=Rectangle.Empty; //likely the listview is not in Details mode, so there is no header control.
    }
    else
    {
        _HeaderRect = new Rectangle(rct.Left,rct.Top,rct.Right-rct.Left,rct.Bottom-rct.Top);
    }
    return false; //cancel enumeration.
}
private static ColumnHeader[] GetOrderedHeaders(ListView lvw)
{
    ColumnHeader[] returnarray = new ColumnHeader[lvw.Columns.Count];
    foreach(ColumnHeader loopheader in lvw.Columns)
    {
        returnarray[loopheader.DisplayIndex] = loopheader;

    }
    return returnarray;
}

Quite a bit of boilerplate to add in. Basically, the idea is that we will hook the contextMenu Opening event of the Listview, (and we add a context menu to hook if the listview in fact doesn’t have one) in our constructor; and then when we receive the event we need to determine if the click occured within the area of the header control of the listview, if so, we cancel the event (which stops the default context menu from appearing) and show our own menu for the columnheader, which we can acquire using a bit of math and the static “GetOrderedHeaders” function, which retrieves the array of columnheaders of a ListView in order of appearance Left to Right (since the user could rearrange the Columns).

So First, we need to add code to the GenericListViewSorter’s Constructor. We also have a few private variables that are added; in this case, we need a ContextMenuStrip variable called “_ghostStrip” which we will use if we need to create a context menu for the control, since we don’t want that to appear in the default case. Of course we create our own ContextMenuStrip which we will show in the event instead of the default when appropriate. so we add this beneath the existing code in the constructor:

    if(handleListView.ContextMenuStrip==null)
    {
        handleListView.ContextMenuStrip = new ContextMenuStrip();
        handleListView.ContextMenuStrip.Items.Add("GHOST"); //add a ghost item so we get the Opening Event
        _ghoststrip = handleListView.ContextMenuStrip;
}

//create OUR context menu
_headerContextMenuStrip = new ContextMenuStrip();
//add a ghost item to make sure Opening will fire.
_HeaderContextMenuStrip.Items.Add("ghost");
handleListView.ContextMenuStrip.Opening += ContextMenuStrip_Opening;
handleListView.ContextMenuStripChanged += handleListView_ContextMenuStripChanged;

Of course we need to add the two referenced event handlers, too. The ContextMenuStripChanged being a rather simple implementation designed to keep changes in the contextmenu of the listview from causing us to balls up and stop showing ours (since we are now hooking a orphaned context menu not being shown by the listview).

void handleListView_ContextMenuStripChanged(object sender,EventArgs e)
{
    OurListView.ContextMenuStrip.Opening+=ContextMenuStrip_Opening;
}

Now the meat of the code is in the ContextMenuStrip_Opening() routine. This will need to determine wether its applicable to show the Column menu, or the already present menu (which it doesn’t show either if it happens to be the _ghoststrip). This is accomplished by use of the GetCursorPos() API routine paired with the already present GetWindowRect() implementation, which we update by calling EnumWindows.

void ContextMenuStrip_Opening(object sender,System.ComponentModel.CancelEventArgs e)
{
    //first, get screen coordinates of Cursor.
    POINTAPI gapi;
    GetCursorPos(out gapi);

    Point gotposition = new Point(gapi.X,gapi.Y);

    //acquire the HeaderRect of the control...
    EnumChildWindows(OurListView.Handle,new EnumWindowCallBack(EnumWindowCallback),IntPtr.Zero);
    //if the mouse position is within the retrieved rectangle, cancel the display of the normal menu and create and show ours.
    if(_HeaderRect.Contains(gotposition))
    {
        e.Cancel=true;
        int xoffset = gotposition.X - _HeaderRect.Left;
        ColumnHeader clickedheader = HeaderAtOffset(OurListView,xoffset);

        if(clickedheader != null)
        {
        //create the context menu as needed.
        _HeaderContextMenuStrip = new ContextMenuStrip();
        _HeaderContextMenuStrip.Tag = clickedheader;
        //two items, one for ascending order, one for descending order.
        ToolStripMenuItem AscendingHeaderItem = new ToolStripMenuItem(String.Format("Sort Column \"{0}\" Ascending",clickedheader.Text));
        ToolStripMenuItem DescendingHeaderItem = new ToolStripMenuItem(String.Format("Sort Column \"{1}\" Descending",clickedheader.Text));

        //if the current sort column is the header, check it off and disable it.

        if(CurrentSortColumn == clickedheader)
        {
            if(OurListView.Sorting ==SortOrder.Ascending)
            {
                AscendingHeaderItem.Checked=true;
                AscendingHeaderItem.Enabled=false;
            }
            else if (OurListView.Sorting==SortOrder.Descending)
            {
              DescendingHeaderItem.Checked=true;
              DescendingHeaderItem.Enabled=false;
            }   

        }
        AscendingHeaderItem.Tag = ClickedHeader;
        DescendingHeaderItem.Tag = ClickedHeader;
        //set event handlers for the two items.
        AscendingHeaderItem.Click+= AscendingHeaderItem_Click;
        DescendingHeaderItem.Click+= DescendingHeaderItem_Click;
        //add them to the context menu strip.
        _HeaderContextMenuStrip.Items.Add(AscendingHeaderItem);
        _HeaderContextMenuStrip.Items.Add(DescendingHeaderItem);
        //display the menu.
        _HeaderContextMenuStrip.Show(gotposition);
        }
   }
   else
   {
       //show the default menu, but only if it isn't the ghoststrip.
       if(OurListView.ContextMenuStrip == _ghoststrip)
           e.Cancel=true;

   }   

}

The events for the two buttons basically sort based on the columnheader in their tag, nothing particularly special there. the actual details can be seen in the source file itself, really.

It actually works quite well, I’m using it in a production application, and it’s working quite well.

Some obvious enhancements, of course, include making it possible to customize the shown menu, to present other options; perhaps a delegate or event that can be hooked that is given the Strip and the clicked column, and any number of other parameters? This would essentially give the equivalent of a ColumnHeaderRightClicked type event, too.

Posted By: BC_Programming
Last Edit: 25 Dec 2011 @ 02:05 PM

EmailPermalinkComments (0)
Tags
 21 Dec 2011 @ 8:24 PM 

Anybody who has used windows is probably familiar with the ListView control. It is used in Windows Explorer; it is even used for the desktop. Heck, the ListView control even has implementations on Linux and Mac, and in the latter case it was there first.

The ListView itself can display in several modes. Normally, it shows things as Icons. But it can also be set to show Small Icons, a List, in some Operating Systems, there is a ‘Tile’ option, or even options like Large,Medium, and other sizes of Icons. My Personal favourite is the details mode.

HA! Bet you didn't expect me to use an image from Windows 95! Expect the unexpected, chaps.

Because I mostly see and use Listviews in Details mode, I also force people who use my software to deal with Details mode. Mostly because the reason I am displaying a ListView is to show some data in a somewhat tabular format and not just give them a few icons to drag around with minimal actual information, but I digress. Anyway, I think a good question at this point might be to look at what different parts this particular ListView has. First, the gray “buttons” at the top, which serve to title each column, are referred to affectionately as ColumnHeaders. Under each ColumnHeader there is data for a given “subitem” of each item. For example, the “Size” entry here is a Subitem for each drive. An interesting feature of columnheaders that is nearly universal is that you can click on one, and it will sort by that column.

Another interesting thing, is that in many programming environments, the ListView control doesn’t actually provide this feature for you, and you have to code it yourself. It is rather frustrating. In particular, Visual Basic 6 allows you to sort, but you can’t really customize what you sort by; it always treats it as text. In one of my VB6 applications, BCSearch (which is available for download from my Downloadspage) I managed to use a Custom control, available from VBAccelerator.com, which exposes additional functionality of the ListView Control on top of that provided in either of the MS provided libraries for use within Visual Basic. One of these features is that it has better support for sorting. I still had to add my own “arrow” to show the sort direction, though.

BCSearch showing results sorted by Size

The VBAccelerator control exposes a number of events and properties for controlling sorting, which I use to properly sort the various subitems, so that various entries like date or size aren’t sorted as text.

Curiously, the .NET Windows Forms ListView control, while having more functionality, still leaves a lot of effort to the programmer for what ideally ought to be a free feature supported by the OS. In fact it IS a free feature supported by the OS. Thankfully, the .NET control does in fact provide a feature for customizing sort functionality, And all you need is a class to implement IComparer. the IComparer will be used to compare the listitems as the Listview sorts. But if you have, say, Date and Time fields and size fields or other fields that can’t just be sorted as text, you are going to need to implement your own special comparer for each. This amounts to quite a bit of glue code; on top of that, you will need to handle the ColumnClick events on the ColumnHeader, change the sort mode, and sort it, and so forth.

To combat this bloating code, I wrote a relatively small class designed to encapsulate sorting. The idea being that you create a instance of this class for each listview, pass in the ListView to it’s constructor, and the class handles all the details. It worked quite well. There was a minor issue that amounted to a gigantic pain in the ass but at the same time made the result a lot better.

  1.  
  2. using System;
  3.  
  4. using System.Collections;
  5.  
  6. using System.Collections.Generic;
  7.  
  8. using System.Diagnostics;
  9.  
  10. using System.Drawing;
  11.  
  12. using System.Linq;
  13.  
  14. using System.Runtime.InteropServices;
  15.  
  16. using System.Text;
  17.  
  18. using System.Windows.Forms;
  19.  
  20.  
  21.  
  22. namespace JobClockAdmin
  23.  
  24. {
  25.  
  26.    
  27.  
  28.     public static class ListViewExtensions
  29.  
  30.     {
  31.  
  32.         [System.Runtime.InteropServices.StructLayout(LayoutKind.Sequential)]
  33.  
  34.         public struct HDITEM
  35.  
  36.         {
  37.  
  38.             public int mask;
  39.  
  40.             public int cxy;
  41.  
  42.             [System.Runtime.InteropServices.MarshalAs(UnmanagedType.LPTStr)]
  43.  
  44.             public string pszText;
  45.  
  46.             public IntPtr hbm;
  47.  
  48.             public int cchTextMax;
  49.  
  50.             public int fmt;
  51.  
  52.             public IntPtr lParam;
  53.  
  54.             // _WIN32_IE >= 0×0300
  55.  
  56.             public int iImage;
  57.  
  58.             public int iOrder;
  59.  
  60.             // _WIN32_IE >= 0×0500
  61.  
  62.             public uint type;
  63.  
  64.             public IntPtr pvFilter;
  65.  
  66.             // _WIN32_WINNT >= 0×0600
  67.  
  68.             public uint state;
  69.  
  70.  
  71.  
  72.             [Flags]
  73.  
  74.             public enum Mask
  75.  
  76.             {
  77.  
  78.                 Format = 0×4,  // HDI_FORMAT
  79.  
  80.             };
  81.  
  82.  
  83.  
  84.             [Flags]
  85.  
  86.             public enum Format
  87.  
  88.             {
  89.  
  90.                 SortDown = 0×200,   // HDF_SORTDOWN
  91.  
  92.                 SortUp = 0×400,     // HDF_SORTUP
  93.  
  94.             };
  95.  
  96.         };
  97.  
  98.         private const int HDM_FIRST = 0×1200;
  99.  
  100.         private const int LVM_FIRST = 0×1000;
  101.  
  102.         private const int HDM_GETITEMCOUNT = (HDM_FIRST + 0);
  103.  
  104.         private const int HDM_SETITEM = (HDM_FIRST + 4);
  105.  
  106.  
  107.  
  108.         private const int LVM_GETHEADER = (LVM_FIRST + 31);
  109.  
  110.         private const int HDM_GETITEM = (HDM_FIRST + 3);
  111.  
  112.         [DllImport("user32.dll", EntryPoint = "SendMessageA")]
  113.  
  114.         private static extern IntPtr SendMessage(IntPtr hwnd, int wMsg, IntPtr wParam, IntPtr lParam);
  115.  
  116.  
  117.  
  118.  
  119.  
  120.         [System.Runtime.InteropServices.DllImport("user32.dll", EntryPoint = "SendMessage")]
  121.  
  122.         public static extern IntPtr SendMessageHDITEM(IntPtr hWnd, uint Msg, IntPtr wParam, ref HDITEM hdItem);
  123.  
  124.  
  125.  
  126.  
  127.  
  128.         public static void SetSortIcon(this System.Windows.Forms.ListView ListViewControl, int ColumnIndex, System.Windows.Forms.SortOrder Order)
  129.  
  130.         {
  131.  
  132.             IntPtr ColumnHeader = SendMessage(ListViewControl.Handle, LVM_GETHEADER, IntPtr.Zero, IntPtr.Zero);
  133.  
  134.  
  135.  
  136.             for (int ColumnNumber = 0; ColumnNumber < = ListViewControl.Columns.Count1; ColumnNumber++)
  137.  
  138.             {
  139.  
  140.                 IntPtr ColumnPtr = new IntPtr(ColumnNumber);
  141.  
  142.                 HDITEM item = new HDITEM();
  143.  
  144.                 item.mask = (int)HDITEM.Mask.Format;
  145.  
  146.                 SendMessageHDITEM(ColumnHeader, HDM_GETITEM, ColumnPtr, ref item);
  147.  
  148.  
  149.  
  150.                 if (!(Order == System.Windows.Forms.SortOrder.None) && ColumnNumber == ColumnIndex)
  151.  
  152.                 {
  153.  
  154.                     switch (Order)
  155.  
  156.                     {
  157.  
  158.                         case System.Windows.Forms.SortOrder.Ascending:
  159.  
  160.                             item.fmt &= ~(int)HDITEM.Format.SortDown;
  161.  
  162.                             item.fmt |= (int)HDITEM.Format.SortUp;
  163.  
  164.                             break;
  165.  
  166.                         case System.Windows.Forms.SortOrder.Descending:
  167.  
  168.                             item.fmt &= ~(int)HDITEM.Format.SortUp;
  169.  
  170.                             item.fmt |= (int)HDITEM.Format.SortDown;
  171.  
  172.                             break;
  173.  
  174.                     }
  175.  
  176.                 }
  177.  
  178.                 else
  179.  
  180.                 {
  181.  
  182.                     item.fmt &= ~(int)HDITEM.Format.SortDown & ~(int)HDITEM.Format.SortUp;
  183.  
  184.                 }
  185.  
  186.  
  187.  
  188.                 SendMessageHDITEM(ColumnHeader, HDM_SETITEM, ColumnPtr, ref item);
  189.  
  190.             }
  191.  
  192.         }
  193.  
  194.     }
  195.  
  196.  
  197.  
  198.  
  199.  
  200.  
  201.  
  202.  
  203.  
  204.     class GenericListViewSorter : IComparer
  205.  
  206.     {
  207.  
  208.         private System.Windows.Forms.ListView OurListView;
  209.  
  210.  
  211.  
  212.  
  213.  
  214.         //GetCompareValue: given a columnname and a ListViewItem, should return any more specific type.
  215.  
  216.         //For example, if Column represents a date value, it would return a DateTime.
  217.  
  218.         public delegate Object GetCompareValue(GenericListViewSorter Sorter, String ColumnName, ListViewItem Item);
  219.  
  220.  
  221.  
  222.         private GetCompareValue CompareValueFunc;
  223.  
  224.         private ColumnHeader CurrentSortColumn = null;
  225.  
  226.         private SortOrder[] SortOrders = new SortOrder[] { SortOrder.None,SortOrder.Ascending, SortOrder.Descending };
  227.  
  228.         private String[] SortOrderImageKey = new string[] {"CLEAR","ASCENDING","DESCENDING" };
  229.  
  230.         private int CurrSortIndex = 0;
  231.  
  232.  
  233.  
  234.        
  235.  
  236.  
  237.  
  238.  
  239.  
  240.         private Object GetCompareValue_Default(GenericListViewSorter Sorter, String ColumnName, ListViewItem Item)
  241.  
  242.         {
  243.  
  244.             //default just returns the String, for now. Later, add special conditions that detect when something is a valid date. Or something…
  245.  
  246.             int indexuse = Sorter.OurListView.Columns[ColumnName].Index;
  247.  
  248.             return Item.SubItems[indexuse].Text;
  249.  
  250.            
  251.  
  252.  
  253.  
  254.         }
  255.  
  256.  
  257.  
  258.         public GenericListViewSorter(ListView handleListView,GetCompareValue GetCompareRoutine)
  259.  
  260.         {
  261.  
  262.             OurListView = handleListView;
  263.  
  264.            
  265.  
  266.             if (GetCompareRoutine != null)
  267.  
  268.                 CompareValueFunc = GetCompareRoutine;
  269.  
  270.             else
  271.  
  272.                 CompareValueFunc = GetCompareValue_Default;
  273.  
  274.  
  275.  
  276.             handleListView.ColumnClick += new ColumnClickEventHandler(handleListView_ColumnClick);
  277.  
  278.            
  279.  
  280.                
  281.  
  282.              
  283.  
  284.         }
  285.  
  286.  
  287.  
  288.         void handleListView_ColumnClick(object sender, ColumnClickEventArgs e)
  289.  
  290.         {
  291.  
  292.             //throw new NotImplementedException();
  293.  
  294.             //First thing is first: is this the same column that was clicked before?
  295.  
  296.             ColumnHeader clickedcolumn = OurListView.Columns[e.Column];
  297.  
  298.             if (CurrentSortColumn == null)
  299.  
  300.             {
  301.  
  302.                 CurrentSortColumn = clickedcolumn;
  303.  
  304.  
  305.  
  306.             }
  307.  
  308.             if (CurrentSortColumn != clickedcolumn)
  309.  
  310.             {
  311.  
  312.                 //if not, set the current sort Index to 0…
  313.  
  314.                
  315.  
  316.                // CurrentSortColumn.ImageKey = "CLEAR"; //don’t want it to keep the image…
  317.  
  318.                
  319.  
  320.                 CurrentSortColumn = clickedcolumn;
  321.  
  322.  
  323.  
  324.             }
  325.  
  326.             else
  327.  
  328.             {
  329.  
  330.                 //if it is the same, increment it and take the modulus…
  331.  
  332.  
  333.  
  334.                 CurrSortIndex = (CurrSortIndex + 1) % (SortOrders.Length);
  335.  
  336.                 Debug.Print("CurrSortIndex:" + CurrSortIndex);
  337.  
  338.  
  339.  
  340.             }
  341.  
  342.            
  343.  
  344.             //CurrentSortColumn.ImageKey = SortOrderImageKey[CurrSortIndex];
  345.  
  346.            
  347.  
  348.             OurListView.Sorting = SortOrders[CurrSortIndex];
  349.  
  350.             OurListView.SetSortIcon(CurrentSortColumn.Index, OurListView.Sorting);
  351.  
  352.             if (CurrSortIndex == 0)
  353.  
  354.             {
  355.  
  356.                 OurListView.ListViewItemSorter = null;
  357.  
  358.             }
  359.  
  360.             else
  361.  
  362.             {
  363.  
  364.                 OurListView.ListViewItemSorter = this;
  365.  
  366.             }
  367.  
  368.             OurListView.Sort();
  369.  
  370.         }
  371.  
  372.  
  373.  
  374.         #region IComparer Members
  375.  
  376.  
  377.  
  378.         public int Compare(object x, object y)
  379.  
  380.         {
  381.  
  382.             ListViewItem a = (ListViewItem)x;
  383.  
  384.             ListViewItem b = (ListViewItem)y;
  385.  
  386.             String columnnameuse = CurrentSortColumn.Name;
  387.  
  388.  
  389.  
  390.  
  391.  
  392.             Object checkA = CompareValueFunc(this, columnnameuse, a);
  393.  
  394.             Object checkB = CompareValueFunc(this, columnnameuse, b);
  395.  
  396.  
  397.  
  398.  
  399.  
  400.             if((checkA is IComparable) && (checkB is IComparable))
  401.  
  402.             {
  403.  
  404.                 if(OurListView.Sorting==SortOrder.Ascending)
  405.  
  406.                     return ((IComparable)checkA).CompareTo(checkB);
  407.  
  408.                 else
  409.  
  410.                 {
  411.  
  412.                     return ((IComparable)checkB).CompareTo(checkA);
  413.  
  414.                 }
  415.  
  416.  
  417.  
  418.             }
  419.  
  420.  
  421.  
  422.             return 0;
  423.  
  424.  
  425.  
  426.  
  427.  
  428.  
  429.  
  430.  
  431.  
  432.         }
  433.  
  434.  
  435.  
  436.         #endregion
  437.  
  438.     }
  439.  
  440. }
  441.  

As you can see, it it relatively small (overall). the API code at the top might be a bit confusing, but it is a result of what can only be described as an oversight on Microsoft’s part; see, originally, I was changing the sort arrow header by simply changing the columnheader image. This worked, sorta of, but there was no way to remove the image and it had this weird effect where it would basically move the text and make it aligned sorta weird. Turns out that the way the ListView would “normally” show sort order icons was a built in feature of the Listview since Common Controls 6 (XP). After some SDK digging I was able to use the Platform Invoke feature of C# to call all the appropriate API functions and “force” the Listview to show the sort order in the header appropriately.

The class also exposes a custom delegate which can be implemented and passed in to the constructor, which will allow for “custom” sorts. This is useful if columns contain data like dates, or numbers that you don’t want to be sorted using the normal “text” comparison.

All in all, It’s a class I’ve added to my “toolbox”, alongside my INIFile class for accessing INI Files. did I write about that one? I forget.

Posted By: BC_Programming
Last Edit: 21 Dec 2011 @ 08:24 PM

EmailPermalinkComments (0)
Tags
 16 Nov 2011 @ 7:12 PM 

So, as mentioned in the previous post, I added a “sort” of scriptability to BASeBlock.

I made some tweaks, and refactored the code so it was a bit more abstracted; the original implementation was directly in the MultiTypeManager, but that didn’t really have anything to do with it, so I tweaked some of the parameters to a few methods there, added a new class with the static routines required for the needed functionality, etc. I also made it so that a “BASeBlock Script Group file” (.bbsg extension) could be used to both compile a set of files into an assembly, as well as include various other assemblies as required. Future additions will probably include the ability for each assembly to define a sort of “main” method, which can be called when the assembly is initialized.

However, once again, Serialization was the constant thorn in my side. I was able to mess about with a custom block written in a .cs script, and it even saved properly.

But the game encountered an exception when I tried to open that LevelSet; I forget the specifics, something to the tune of “failed to find assembly”Ā  type of error. What could I do?

Ā SerializationBinder

What this basically meant was I was going to have to learn even more about the Serialization structure of .NET. Specifically, SerializationBinder’s. The concept was actually quite simple. You basically just derive a type from SerializationBinder, and use that as the .Binder property on a IFormatter class, overriding one method seems to be enough for the most part:

 

  1. Type BindToType(string assemblyName, string typeName)

 

Simple! it gives you an assembly Name, a Type Name, and you simply return the appropriate type. The reason the default implementation wasn’t working was certainly as a result of the assembly being loaded dynamically, since it wasn’t [i]really[/i] being referenced by the BASeBlock assembly, so the default implementation didn’t find the “plugin” class assembly or the appropriate type, so threw an exception.

The trick here is not to enumerate the referenced assemblies, but rather to use all loaded assemblies in the current AppDomain. The general consensus with regards to using CodeDOM and compiling things like this is to compile them to their own AppDomain; however, since the assemblies were being kept “alive” for the duration of the application, that wasn’t necessary, and in this case would have complicated things. Well, it would have complicated things more than they already were.

The “AssemblyName” parameter, however, was more akin to the FullName property of the System.Reflection.Assembly; for example, BASeBlock’s assembly would (for the current version) be passed in as “BASeBlock, Version=1.4.0.0, Culture=neutral, PublicKeyToken=null”. Since we are only interested in the actual name of the assembly, we can simply grab everything up to the first comma.

Armed with the Assembly’s base name, we can start enumerating all the loaded Assemblies and looking for a match:

  1. public override Type BindToType(string assemblyName, string typeName)
  2.             {
  3.  
  4.                 try
  5.                 {
  6.                     string BaseAssemblyName = assemblyName.Split(‘,’)[0];
  7.                     Assembly[] Assemblies = AppDomain.CurrentDomain.GetAssemblies();
  8.                     foreach (Assembly loopassembly in Assemblies)
  9.                     {
  10.                         if (loopassembly.FullName.Split(‘,’)[0].Equals(BaseAssemblyName,StringComparison.OrdinalIgnoreCase))
  11.                         {
  12.                             return loopassembly.GetType(typeName);
  13.  
  14.                         }
  15.                     }
  16.                 }
  17.                 catch (System.Exception exception)
  18.                 {
  19.                     throw exception;
  20.                 } return null;
  21.             }

Then, we compare the Assembly.FullName.Split(‘,’)[0] (the text before the first comma) to the modified string, BaseAssemblyName that was changed in the same manner. I decided to go string insensitive for no reason; mostly because the assembly names for the scripts are formed from the filenames and I wouldn’t want filename capitalization to prevent a script from serializing/deserializing properly. If we find a matching assembly, we return the result of a GetType() call to that assembly with the same typename passed in as a parameter to the method. The Formatter will than attempt to deserialize the data it has to that type as needed.

There are a few issues with this- for one thing, it doesn’t work with Generic types. At least, I assume it doesn’t; I assume I would need some special code to get the appropriate Type for a generic type given type arguments. I’ll cross that bridge when I come to it.

Right now, I’ve not actually tested this extensively. My main concern would be to test that it can serialize in one session, and deserialize in another. This concern is based on the fact that the two assemblies would in that case be literally distinct- in that it would have been compiled on two occasions. Assuming the Binder is enough to convince the serializer it can deserialize something, there shouldn’t be any issues. Once I decide to figure out how to add Generics support to this Binder, I’ll definitely write about it here.

Posted By: BC_Programming
Last Edit: 16 Nov 2011 @ 07:13 PM

EmailPermalinkComments (0)
Tags
 25 Oct 2011 @ 11:13 AM 

Serialization has always been a thorn in my side. In VB6. in Python, in C#. The biggest annoyance is that most applications consist of somewhat complex object relationships and heirarchy’s, different race conditions about values that need to be initialized first, and who knows what else, all meticulously built during the course of your application, which you eventually need to save to persistent storage.

All applications can benefit from some form of persistence, even if it is only in the form of settings. As a result most Object Oriented languages have a way to allow you to “serialize” an object to a stream. In .NET, this is provided by way of the [Serializable] Attribute and the ISerializable interface, which allows you to customize the serialization somewhat.

What is interesting, at least in the case of .NET object serialization, is that you can choose one of a number of “Formatters” which will take the data acquired by the Serialization support framework and format it to one of any number of formats. Personally, I have only used The BinaryFormatter class, which will allow to write or read a serialized stream to or from a stream.

So, what use is serialization? Well, aside from the obvious ability to save the stream to a file, you can also use it in other ways. For example, since you can send the data across any stream, you could send it through a network stream, and on the other end another instance of your application would be able to rebuild the exact same object. Another usage I’ve found is for usage on the system clipboard; serialize what is being copied, plop it on the clipboard with your own format specifier, and then when you want to see if you can paste check if that specifier exists and when pasting deserialize that data from the clipboard, and you’ve got the objects that need to be pasted, which will be “new” objects separate from those copied (if they are still present).

Copying a object graph to stream, however, has a bit of boilerplate; you need to create the BinaryFormatter(), serialize, and the opposite in the other direction.

However, with generics, this task can be made a tad easier:

  1.  
  2.     public static void ObjectToStream<T>(T saveme, Stream outstream) where T : ISerializable
  3.     {
  4.  
  5.         BinaryFormatter bf = new BinaryFormatter();
  6.         using(GZipStream gz = new GZipStream(outstream,CompressionMode.Compress))
  7.         {
  8.             bf.Serialize(gz, saveme);
  9.  
  10.  
  11.  
  12.         }
  13.    }
  14.  
  15.    public static T StreamToObject<T>(Stream instream) where T : ISerializable
  16.         {
  17.             BinaryFormatter bf = new BinaryFormatter();
  18.             using(GZipStream gz = new GZipStream(instream,CompressionMode.Decompress))
  19.             {
  20.  
  21.                 return (T)bf.Deserialize(gz);
  22.  
  23.             }
  24.  
  25.  
  26.  
  27.         }
  28.  

Two static methods that serve to input and output a object whose type implements ISerializable to and from a given stream. It also uses the GZipStream to compress and decompress that stream to try to save space.

Extending this directly to files is rather easy as well:

  1.  
  2. public static T ObjectFromFile<T>(String filename)  where T : ISerializable
  3. {
  4.    //open the file.
  5.    T acquireobject;
  6.    FileStream fstream = new FileStream(filename,FileMode.Open);
  7.    //input from the stream…
  8.    acquireobject = StreamToObject(filename);
  9.    fstream.Close();
  10. }
  11. public static ObjectToFile<T>(String filename,T Objectsave) where T:ISerializable
  12. {
  13.   //open the file
  14.   FileStream fstream = new FileStream(filename,FileMode.Create);
  15.   ObjectToStream(fstream,Objectsave);
  16.   fstream.Close();
  17. }
  18.  

And huzzah! suddenly you can read and write objects to and from a file with ease.

One might even venture to create extension methods on the Stream class that provide this sort of functionality for input and output of any object supporting ISerializable, like the following, which assumes the previous routines are within a ‘ObjectStreaming’ class definition.

  1.  
  2.  public static class StreamExtensions
  3.     {
  4.  
  5.         public static void WriteObject<T>(this Stream str,T writeobj) where T:ISerializable
  6.         {
  7.             ObjectStreaming.ObjectToStream(writeobj, str);
  8.            
  9.  
  10.  
  11.         }
  12.         public static T ReadObject<T>(this Stream str) where T : ISerializable
  13.         {
  14.  
  15.             return ObjectStreaming.StreamToObject<t>(str);
  16.  
  17.         }
  18.  
  19.     }
  20. </t>

And there you have it, suddenly you can write objects directly to any stream, using methods of that stream Object, and that saved data is automatically GZipped for you as well.

This Does, however, present it’s own issues. If there is an error anywhere in your serialization code, using a “filter” type of stream, such as the GZipStream, may cause difficult to trace errors that cause exceptions to fire from the GZipStream itself, most notably “unexpected end of stream” type errors. You can usually trace these in Visual Studio by checking “thrown” on System.Runtime.Serialization.SerializationException in the Debug->Exceptions dialog, and allowing the data to save to a normal stream (that is, directly to a filestream or memory stream rather than by way of the GZipStream). This will allow you to determine where you made the mistake elsewhere. Typically, in my experience, it’s usually something as innocent as a misspelling, or even inconsistent capitalization.

Posted By: BC_Programming
Last Edit: 25 Oct 2011 @ 11:18 AM

EmailPermalinkComments (0)
Tags
 02 Dec 2010 @ 4:34 PM 

As with most of my projects, progress is usually slow because it’s something I do “when I feel like it” rather then on a schedule. Because of this I often have a lot of “design-time” where I don’t actually write code but idly wonder about what I could do to make it better.

One consideration I recently decided on was supporting the packaging of the various files — images, sounds, etc — into a zip file. This came about as a result of my experience (easy enough) of using gzipStream to make the size of the serialized LevelSet data a tad smaller (the default levelset, which is 5 levels, still weighs in at about 145KB; most of this is because it stores a lot of PointF structures from the PathedMovingBlock that I recently added, but I won’t get into that. In any case, I considered at the same time- why not allow the loading of files from a zip?

Of course, this is hardly a new idea. I never thought it was. placing the application/game data into one monolithic (and easier managed file-system wise) file is ancient; games have been doing it for ages. In either case, since I had decided to use ZIP (rather then, say, define my own package file like I did with my Visual Basic BCFile project) I had to be able to work with zip files.

Thankfully, there are a lot of free solutions to read,extract, and otherwise deal with zip files from .NET. after some searching, I decided on dotnetzip

. The reasons I decided on it were simple: it’s easy to use, and it supports both extracting as well as creating zips. I’d rather learn one library rather then several to perform the various tasks in the future. The first step was to decide how it was all going to be done.

A little overview of how I had it arranged in the code may help. The Sounds and Images are managed by classes called cNewSoundManager and ImageManager respectively. recent changes have caused me to rewrite the SoundManager to create the “New” SoundManager, which supports different adapter classes for using various sound libraries (of which BASS.NET has become my top choice).

Thankfully, during the creation of Both ImageManager and SoundManager, I made it able to accept a number of paths in their constructors via a overload accepting an array of Strings. In fact, it was the “low-level” implementation for loading; the other overrides simply transformed their data into an array and called it, so I knew that worked. Although my ImageManager could probably be modified to load files from a stream (the ZipFile class can retrieve a inputstream for the files in a zip) the SoundManager could not feasibly do so; many sound libraries will only load from files, and since most of them are really wrappers around even lower level libraries, I couldn’t optimistically assume that I would always be able to convert a filestream into something I could use; I realized that the “Driver” classes could always take the passed in stream and create a file, but that sort of redirects the issue. Instead, I decided to leave it as-is (loading from files) and instead make it so that during the bootstrap phase (where it loads images and sounds) it also extracts the contents of any zip files that are in the application data folder as well.

I chose to change the extension I would use to bbp (Base Block Package) so that the game won’t get confused or screwed up if a standard ZIP happens to be in the same folder. The first question however is where I would extract these files too; obviously it was a temporary operation, so I opted to choose the system Temp folder, which is easily obtained in .NET via Directory.GetTempPath(). I then decided that as I enumerated each zip, they would be extracted not to this temp folder but to another folder that would be created beneath it; this way, the files in each ZIP file can have conflicting names, and still extract properly. (although at this time that will cause both ImageManager and SoundManager to throw a fit, I decided it best to not add a third class that didn’t understand that files in different folders can have different names). The next problem was easy; I simply took all the various folder names and added them to the arrays I passed to the SoundManager and ImageManager constructor. Easy as pie.

Now I needed to make sure that when the program terminated, the files were deleted. During startup it detected if the special temp folder existed and deleted it, but it would be ideal if that folder could also be deleted when the program is closed normally. the problem here is that I was initializing all of this in a static constructor (well, not really, since apparently Mono didn’t like me using static constructors for this, but it was still a static routine). There is, however, no Static “Destructor” that I could use. So I opted to create a small private class implementing IDisposable that I could create as a static variable and initialize with the name of the temporary folder to delete; the Dispose() method would then delete it, easy as pie.

However, upon testing, I encountered an error; apparently, the handle was still open in the dispose routine. After a little digging, it was clear that the problem was at least partially as a result of the Image.FromFile() method, which apparently caches that it was taken from a file as well as the filename and will keep it open as long as the image is around; since I couldn’t always be sure that the temporary class would be disposed after the ImageManager (and therefore the various Images it holds) it was difficult to make sure they were closed.

However, I decided to change my use of the FromFile() method to something that won’t pass the Image class any filename data at all; that way the Image class couldn’t possibly hold the file open, as long as I close it properly myself.

To do so, I replaced the code:

  1.  
  2. Image loadedimage = Image.FromFile(loopfile.FullName);
  3.  

With:

  1.  
  2. Image loadedimage = Image.FromStream(new MemoryStream(File.ReadAllBytes(loopfile.FullName)));
  3.  

And so far, it’s worked a treat.

Posted By: BC_Programming
Last Edit: 17 Dec 2010 @ 12:09 AM

EmailPermalinkComments (0)
Tags
 22 Nov 2010 @ 4:55 PM 

No, Not the kissing disease, Infectious mononucleosis, the open-source .NET CLR interpreter and class library.

.NET; I might have ranted about this before, if not on my blog, elsewhere. most of my arguments were against it, being a VB6 using ignorant buffoon. In any case, I’ve found C# to be an awesome language. One of the obvious downsides is that for the most part programs written in C# using Windows forms cannot be run on other systems.

The concept of Mono is to change that; remember, C# isn’t a Microsoft standard, it’s an ECMA specification, and Microsoft holds no copyright over it or anything like that. Mono is a relatively huge undertaking; the creation of something on the scale of a Virtual machine as well as a class library is gargantuan, and of course there is very little hope for 100% success.

On the whole, Mono performs it’s primary goals admirably; there is a GTK# framework that can be used to develop windowed applications… of course then the installation on a windows PC would require the install of the Mono GTK# framework, but I digress. In any case, applications can be developed and the C# code interpreter (for on the fly syntax highlighting) as well as the compiler are top-notch and seem to work well.

My only beefs can of course be in the class library. Of course, re-implementing the class library provided by MS on non-windows systems is not something that can be done in a single afternoon; this stuff takes time. My attempts to create a Mono-compatible project have been stifled, however, by seemingly innocuous issues. AlLlow me to explain.

As many reader may be aware, I have been working on a “upgrade” of sorts to my now ancient “Poing” game, which can be found on my downloads page; the original game was written in Visual Basic 6, and, in it’s earlier incantations didn’t have a single Class; it was all based on User-Defined Types (structures for those privvy to C parlance) and functions; (short explanation: it was made before I understood classes). Later, after I had learned about classes, I refactored everything into classes. This is all rather redundant; in any case, I have since created a new project in C#, in an attempt to learn about GDI+ as well as what appeared to be a different (in some ways) painting model. As one can see by the youtube videos I have posted on it, development has gone well.

The idea occured to me, after Tux2 (of http://www.jrtechsupport.com/) managed to create a Mono-workable, if soundless, version of my earlier C# game, BCDodger that worked in Linux. Sound was unavailable as a result of my choice of sound library, the IRRKLANG library, while truly usable in Linux, doesn’t have a wrapper that works in Linux (or something, I don’t know… it uses DSound or something, I forget). In any case, I have since added the ability for various sound engines to be used, and have added working implementations for Open-Source and Linux-available Sound systems, such as NBass (as well as a broken fmod implementation, let’s ignore that though).

Much obliged, I had decided to try to get it working via Mono as well; this was facilitated by my recent reformatting of my laptop to run a dual boot Windows 7 and Mint 10 system. Installing MonoDevelop and all that, etc.

So, I of course open the project in Monodevelop, quite ready for errors relating to porting.

The version I am using is MonoDevelop (and I assume also Mono) version 2.4, for those following along.

My first hurdle was getting my Appdata files for the program in the right location; on windows systems they are placed in the application data folder; so too they would need to be on a Linux system. Thankfully, a quick C# program run on the Linux machine cured this issue:

using System;

namespace specialfolders
{
	class MainClass
	{
		public static void Main(String[] args)
		{
			foreach(Environment.SpecialFolder sfolder in
Enum.GetValues(typeof(Environment.SpecialFolder)))
				Console.WriteLine(sfolder.ToString() + "=" +
				Environment.GetFolderPath(sfolder));

		}
	}
}

Which gave me, on a Windows system:

Desktop=C:\Users\BC_Programming\Desktop
Programs=C:\Users\BC_Programming\AppData\Roaming\Microsoft\Windows\Start Menu\Programs
Personal=C:\Users\BC_Programming\Documents
Personal=C:\Users\BC_Programming\Documents
Favorites=C:\Users\BC_Programming\Favorites
Startup=C:\Users\BC_Programming\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Startup
Recent=C:\Users\BC_Programming\AppData\Roaming\Microsoft\Windows\Recent
SendTo=C:\Users\BC_Programming\AppData\Roaming\Microsoft\Windows\SendTo
StartMenu=C:\Users\BC_Programming\AppData\Roaming\Microsoft\Windows\Start Menu
MyMusic=C:\Users\BC_Programming\Music
DesktopDirectory=C:\Users\BC_Programming\Desktop
MyComputer=
Templates=C:\Users\BC_Programming\AppData\Roaming\Microsoft\Windows\Templates
ApplicationData=C:\Users\BC_Programming\AppData\Roaming
LocalApplicationData=C:\Users\BC_Programming\AppData\Local
InternetCache=C:\Users\BC_Programming\AppData\Local\Microsoft\Windows\Temporary Internet Files
Cookies=C:\Users\BC_Programming\AppData\Roaming\Microsoft\Windows\Cookies
History=C:\Users\BC_Programming\AppData\Local\Microsoft\Windows\History
CommonApplicationData=C:\ProgramData
System=C:\Windows\system32
ProgramFiles=C:\Program Files
MyPictures=C:\Users\BC_Programming\Pictures
CommonProgramFiles=C:\Program Files\Common Files

Nothing particularly out of the ordinary there. So, running the program on a Linux machine:

Programs=
Personal=/home/bc_programming
Personal=/home/bc_programming
Favorites=
Startup=
Recent=
SendTo=
StartMenu=
MyMusic=/home/bc_programming/Music
DesktopDirectory=/home/bc_programming/Desktop
MyComputer=
Templates=
ApplicationData=/home/bc_programming/.config
LocalApplicationData=/home/bc_programming/.local/share
InternetCache=
Cookies=
History=
CommonApplicationData=/usr/share
System=
ProgramFiles=
MyPictures=/home/bc_programming/Pictures
CommonProgramFiles=

which gave me what I needed: the appdata folder “BASeBlocks” needed to be copied to /home/bc_programming/.config.

Doing so was easy enough; the file manager on Mint 10 (dolphin) is different from windows explorer but hardly paradigm-breaking.

That copied, I simply threw the source folder as it was on the Visual Studio 2008 projects folder into the MonoDevelop projects folder (well, not really, it was /home/bc_programming/projects/ which I suppose means that any program that uses a projects folder will use it, oh well.)

psyched as I was I ripped into it with MonoDevelop, ready for anything! well, nearly anything.

My first error occured on line 107 of “Block.cs”:

mPowerupChanceSum = Powerupchance.Sum();

Java programmers may be thinking “ew uppercase characters” to them I say be quiet you. Anyways, the problem here was that there was no “Sum()” Extension method defined. Which I found odd. Oh well, though, I simply created my own:

#if MONO
	public static class monoextensions
	{
		public static float Sum(this float[] floats)
		{
			float accumulator=0;
			foreach(float loopfloat in floats)
				accumulator+=loopfloat;

			return accumulator;
		}
	}

#endif

this solved the immediate issue of the “Sum()” extension method. (For more info on C# extension methods, see here)

My next hurdle was on line 540 of cBall.cs:

if (wholeref.Blocks.Count((q)=>q.MustDestroy()) == 0)

The error was something to the effect of not being able to pass a delegate or method group to a lambda expression.

oddly enough, the fix was the change the “q” to an x… and after it successfully built I was able to comment out the “new” line (with the x rather then a q) and uncomment the original. very odd.

In either case, now I was confronted with what I knew to be the biggest issue; the fact that I had to now discover how to set it up so that I was able to use the same nBASS library, but so that the nBASS library was “silently” made to use the BASS.so linux library, rather then bass.dll which wouldn’t load either way.

The first step in this process was in finding bass.so. Hoping for the best, I pulled up good ol’ synaptic package manager.

No luck there :( so, I went into the depths of the internet….

the BASS for Linux (note the lack of the n prefix; it’s the core BASS library that the nBASS dll is wrapping) can be found here

this topic; or, the original post, to be precise, gives the download location for the Linux source files for BASS 2.4, which can be found at http://www.un4seen.com/stuff/bass24-linux.zip

So, I downloaded the zip file, extracted it to a folder, and am about to attempt to compile it. (there is a libbass.so that I could probably try, but I think I’ll compile it myself instead).

Before I continue, however, I would like to mention something that has most impressed me about Mint 10; the multiple desktops. Now, this is hardly a new feature; programs can be downloaded that do this on windows, and windows itself has built in API support for multiple desktops; however, what impresses me most is that when you activate a window on another screen, it switches to it; what I mean is, for example, in this instance my FF download window was on another desktop (no idea why) and when I went to open the downloads window via Tools->Downloads, it did the fancy compiz box animation (as I have selected in preferences) and switched to it. very cool. But enough if my gushing over the unexpected presense of sanity in the UI design of a Linux desktop environment! back to my attempts to get BaseBlock working on Linux.

my attempts to make the bass project, however, failed:

bc_programming@Satellite ~/Projects/bass $ sudo make
make -C 3dtest
make[1]: Entering directory `/home/bc_programming/Projects/bass/3dtest'
cc -Os -I/home/bc_programming/Projects/bass -L/home/bc_programming/Projects/bass -lbass -Wl,-rpath,/home/bc_programming/Projects/bass `pkg-config gtk+-2.0 --cflags --libs` `pkg-config libglade-2.0 --cflags --libs` -export-dynamic -D'GLADE_PATH="/home/bc_programming/Projects/bass/3dtest/"' 3dtest.c -o 3dtest
Package libglade-2.0 was not found in the pkg-config search path.
Perhaps you should add the directory containing `libglade-2.0.pc'
to the PKG_CONFIG_PATH environment variable
No package 'libglade-2.0' found
3dtest.c:7: fatal error: glade/glade.h: No such file or directory
compilation terminated.
make[1]: *** [3dtest] Error 1
make[1]: Leaving directory `/home/bc_programming/Projects/bass/3dtest'
make: *** [3dtest] Error 2
bc_programming@Satellite ~/Projects/bass $

Oh the humanity! now I had to learn about this package nonsense. I first suspected perhaps, as evidence by the fact that it wasn’t found, said package wasn’t installed; so I did a quick sudo apt-get install libglade-2.0 … it reported it was installed already.

after a bit of effort, and installing a few dev packages, I gave up. I was able to resolve the missing dependencies but then it complained about a missing .h file (which was indeed missing and clearly should have been present) so I gave up on that, and am at the time currently trying to simply use the .so file included. An additionally problem that arises here is the obvious fact that I am using a x64 Linux system, working with C# code written on a x64 windows system but targeted towards a x86 system, problem being that to my understanding Linux is not as lenient when it comes to architecture differences; but I suppose I’ll figure that out for myself if it’s the case.

In any case, I am now attempting to get the nBASS library to wrapp around libbass.so rather then bass.dll; from my research if the imports are the same I should have no problem creating a dllmap entry in the appropriate config file. From the documentation it would seem that discovering where that config file goes is left as an exercise for the reader.

Actions:

pasted libbass.so in the “Debug” folder (alongside the dll).

Copied the BASeBlock.config file from the project root to the debug folder; renamed to Bass.Net.config.

opened preceding file in gedit; it now looks like this:

< ?xml version="1.0" encoding="utf-8" ?>





And now, I attempt to run BASeBlock… recall that it now compiles on Linux, so it’s just a matter of making it work. I could, in a worst case scenario, construct a “nullsound” driver that simply stubs out the sound playing interfaces. But that seems like a bit of a cop-out. IN any case, attempts to run it resulted in the same error; clearly either the documentation I was reading was incorrect or I was not interpreting it properly.

I did a few more googles and came upon this page, which, despite being about something completely different addressed the same problem; that is, translating the dllimport(whatever.dll) into imports of functions from Linux .so libraries. namely, it told me where the Mono parameter file was- /etc/mono/config. I quickly opened the feller using gedit:

I tossed in the line:


and crossed my fingers…

It still didn’t work. I guessed maybe mono only loaded that stuff up when it was started? So I restarted monodevelop.

excellent! a little progress. Now I was still getting the error, but it was complaining about libbass.so missing. At least we’re getting somewhere.

It still should have found the file; however, I decided that instead of just throwing it in the app directory (because god knows where Mono is truly looking for it; even putting ./libbass.so in the dllmap failed, so Mono clearly thinks something else is the “current” directory. Instead, I decided to simply cp it somewhere globally accessible;

It still didn’t work.

Anyway, I messed around with the config file and the dllmap attribute and no matter what I put it it refused to find the file; clearly I’m missing something obvious (maybe capitalization? a missing slash? who knows). In either case I decided to defer that work to later on; I’m sure there was more to be fixed afterwards.

So, I created the aforementioned “Null Sound” driver; it worked fine. compiled alright. Encountered a bunch of issues during startup relating to my use of the \ as a path separator, whereas Linux uses /, fixed this with a simple Replace to change all slashes to the slashes of the OS (Environment.PathSeparatorChar).

It still refuses to start; Some gdi plus error. I have no idea how to workaround this, since it seems to be related to the windows forms, and has nothing to do with my own code, but rather with some configuration option. I recall Tux2 working around a similar error in BCDodger but I wasn’t paying very close attention and forget what the fix was, or even if he mentioned it. Either way, at least now BASeBlock compiles on a linux system, and most of the code-related oversights have been resolved.

EDIT:

I’ve managed to solve both issues; not at once of course.

First, the loading issue was fixed; pretty troublesome. In my attempts to resolve the problem I created a number of projects that used the same Image.FromFile() method to load pictures, and they worked fine.

Clearly, the problem then was not in what was not visible; the difference between the two. I realized that the difference was pretty clear: in my test projects, I was loading the images from within the form’s Load event; in BASeBlock, they were being loaded in a static constructor. So I decided to try to load the images elsewhere; I converted the static constructor to a static function, and called that function in the form load; there were a few other changes that I needed to make, mostly in the form of initializers attempting to use values that wouldn’t have been initialized.

The game started and ran fine with the NullSound driver.

Now, to fix the Sound; I opted to try to get nBASS working.

the solution was actually quite simple; merely a dllmap for bass.dll to libbass.so, and placing the x64 libbass.so in usr/lib was enough, and sound worked fine.

Unfortunately, it’s still slow as hell but at least I think that’s Mono’s fault.

Posted By: BC_Programming
Last Edit: 17 Dec 2010 @ 12:17 AM

EmailPermalinkComments (0)
Tags
Tags: , , ,
Categories: .NET, API, C#, Games, Linux, Programming, Windows
 03 Nov 2009 @ 12:31 PM 

I have been using Visual Basic 6 for many years; I have come to the point where using it is effortless; nearly any problem I have I can design and program with Visual Basic 6.

However. Visual Basic six is over 10 years old. Mainstream support ended a few years ago, and after Vista Microsoft makes no promises that programs designed with Visual Basic 6 will work. Even creating programs that support the various UI features of XP could be a chore. With Vista, Not only does one need to include the proper manifest resource or fileĀ  to force their VB6 applications to link with the newer version of comctl32, but it is almost always necessary to include an additional set of directives in the manifest to make the program request administrator permissions. I have yet to determine why some of my less trivial programs crash before they even start when run with the same security as the user, but I imagine it’s directly related to COM components, their usage, and the permissions surrounding them.

Another area of concern is with the use of proper icons; Visual Basic complains when you try to use a icon with a alpha channel. However, through a few API techniques and some resource editor trickery, it’s possible to have your application use 32-bit icons both as the program file icon as well as the icon for your forms. Rather then repeat the material here, I will point you in the right direction if this type of this piques your interest. www.vbaccelerator.com- I cannot praise that site and it’s creator enough. While many of the projects and controls he has on-line I have personally attempted before finding the site (I had a somewhat working toolbar control and a control I called “menuctl” that allowed moving the main menu around as a toolbar), the sheer number of completed, documented, and well written controls on his site is simply mind-blowing. There is also a .NET section to his site as well, which brings me to my next point.

There are only a few reasons why a programmer would choose to use Visual Basic 6 for a new project today. The main reason is simply because we are stubborn, for the most part. The fact that .NET is better in many ways then VB6 does not sway us to use it. The fact is, we all feel “betrayed” in a way, but the shift to .NET. Millions of lines of code that were dutifully compatible through all 6 versions of Visual Basic 6 now break when loaded in VB.NET. But I believe, that the majority of VB6 programmers have simply been blinded to the number of problems Microsoft would have faced to continue using the same COM oriented framework that VB4 and higher have used.

COM,or, Component Object Model,(sometimes referred to as “Common Object Model” which is dead-wrong) is a Binary compatible method of providing interoperability between applications. COM was essentially designed to prevent what was known as “DLL hell”, since at that point in time DLLs provided their functionality through exposed functions, some versions not compatible with previous versions, meaning it might be necessary to, for example, have 5 different versions of MFC41.dll on ones PC. The idea was, each version of a COM component would be Binary compatible with the previous version, which means, for example, that a program designed for version 1 of “foocomponent” could still run and use version 4, but without the new features of version 4. This functionality was implemented by the creation of Interfaces. Each version of a component would add a new interface- for example, IFooComponent, IFooComponent2,IFooComponent3, etc, and client applications who want to use FooComponent would use the interface appropriate to the version they wish to use.

There was, however, one problem. Most of the maintenance between versions was left to the programmer of the component- they had to create the new interface, make sure previous interfaces worked, that old clients could still instantiate their objects, etc. Basically, it made the critical mistake of putting the user of the technology (in this case, the programmer) in a critical position and with a number of responsibilities to get things to work properly.

Microsoft, of all companies, should know that putting the programmer in a position of such responsibility is prone to failure; hell, many of them can’t even be bothered to follow standard API documentation; for example, actually reading the documentation; this resulted in hundreds of man-hours of programmer time being consumed by the creation of “compatibility shims” to let these programs work. (otherwise, installing a new windows OS would break these programs; they worked before, so as far as the user sees the new Operating System is to blame). Anyway- this failed miserably. Programmers would sometimes simply change their interfaces rather then implement new and old ones, meaning, like with the DLLs of before, new DLL versions were incompatible with the old ones.

It was clear that COM, or, at least, COM as it was presently designed, was far to dependent on the programmer to “do the right thing” then was reasonable. So, Microsoft, at some point, decided they needed a new object framework architecture.

VB6, as a COM-based language, would have required extensive changes to support this new architecture. the prospect of such a huge revision probably made them take a second glance at the language itself, and the cruft it still has from previous iterations of the basic language. aside from retaining such archaic constructs as the “GoSub…Return”, VB6 also “failed” in a sense on a number of other areas. Error-Handling, for example, was still done using “On Error” statements, which redirected flow to another segment of code. It was up to that block of code to evaluated the error, using the “Err” object (In VB1-3 there was only Err which was the error number and Error$, which was the description), and then either resuming that same statement that caused the error (Resume) skipping that line, and continuing with the next, (Resume Next) or even raising the error again, causing the error to cascade up through the call stack.

This Error architecture had a critical flaw- by using this form of error handling, flow could change to the error block for any reason, at any time. This meant that if the procedure dealt with resources, such as file handles or memory blocks, it would have to keep track of what needs to be undone so that the error code could also double as partial cleanup code. Another critical flaw was simply that it was ugly; it looked and functioned nothing like the Try…Catch statements in many other languages. Also, it could become impossible to trace exactly where an error occured when errors cascaded; and error handler might be forced to handle an error from three levels down in the call-stack, so even if it understood the error in the context of the procedure, the context that the original error occured in and exactly what it means was lost.

My main language is Visual Basic 6, but I am not so blind as to reject VB.NET, or .NET as a whole, merely because it essentially replaced VB6. The truth is- we, as VB programmers, have made a large number of requests to the VB developers. VB .NET answered and fixed a huge number of those requests, and yet it is still shunned; it is clear to me that it is not merely the loss of backwards compatibility that causes such antagonism with VB6 programmers, but also the human element of resistance to change.

With previous versions of Visual Basic, one could migrate all their code to the new version with little or no difficulty.

This, however, had a price- since the new version made few, if any, requirements for conversion, old antique code would often be upgraded and imported into the new environment. Since backwards compatibility was the rule, old elements such as line numbers gotos, and gosubs remained in the language. Antiquated concepts such as type declaration characters remained in the language. Such visages of a forgotten era had no place in a modern language.

All the above being said, VB6 is still a language capable of creating modern applications; however it is important for the programmers who still use it to realize that they aren’t using it because it is superior or because .NET or any other language “sucks” by comparison, but rather as a result of their own stubborness and unwillingness to learn new programming concepts.

A anecdote, if I may, can be found in my introduction to the use of “class modules” within Visual Basic. at first, I had no idea what they were- I simply shied away from them, and stuck to Forms and code modules. I used all sorts of excuses- Class modules are slower, they bloat the code, etc. All of which were, almost universally fabricated or found on the web written by grade 8 students who barely understood the meaning of the word “class” in the context of programming or objects.

After, however, creating ActiveX Controls using the “userControl” Object, I realized the similarities, and the possibilities that could arise. My first conversion attempt was on my Current “flagship” program, the game I called “Poing”. At that time, the entire game was designed using User defined types as functions that operated on them. I understood the concept of encapsulation and managed to convert the entire architecture to a Class based object heirarchy- and it worked. My concepts still contained flaws, such as including critical game logic in down-level objects, but for the most part my udnerstanding was sound.

As my understanding of the concepts involved improved, so too did my antagonism disappear. It was clear to me that the fact that I didn’t understand classes at the time lent itself to a distaste for them- basically, the old adage that one is “afraid” of what one doesn’t understand was at least partly true. This, I feel, is at the very core of the antagonism against .NET. the main detractors of the framework are often people that neither understand the concepts involved nor do they realize how said concepts add increased possiblities and easier maintenance.

Even so- .NET has, in my opinion, one critical flaw. the IDE is slow. even on my quad core machine I see huge delays as intellisense is populated or any number of other operations. Perhaps it is a result of a mere 7200RPM hard drive? I don’t know. perhaps I need more then my current 8GB of RAM? who knows. I think, that using a 10 year old program and expecting and recieving quick responses from it have perhaps jaded me in terms of what the extra features of the new IDE actually cost in terms of performance; the delays feel like minutes, but in general it is only a few seconds. On the other hand- a few seconds is a lot longer then necessary to make one lose their train of thought. At the same time, this same argument was used against the initial usage of Intellisense; and there is no denying that although the initial display of a number of said intellisense lists can take some time, subsequent usage is nearly instantaneous, and the lists provide far more in terms of function information then the VB6 OR C++ 6 IDE could provide; this, in addition to the ease of use of assemblies between multiple .NET languages is not something that should be passed up because of an ego-centric desire to prevent change. The IT industry changes constantly. The fact that VB6 is now a “past item” should not dissuade us from moving forward because of a snobbish desire or fictitious affection for the corridor of our programming efforts for many years; the complaints about VB6 when it was introduced were very vocal. This is, no different with VB.NET, however the very complaints made about VB6 that have been remedied with .NET are now being passed off as inconsequential (since in many cases programmers have devised ways of working around limitations or even forcing behaviour that VB6 was not designed for, such as, for example the creation of Command-line programs.

The mistake Microsoft made was not the creation of .NET, but rather the belief that any sane person would move to a new platform if it was superior. They forgot the take account of the psychological factors involved.

Posted By: BC_Programming
Last Edit: 03 Nov 2009 @ 12:31 PM

EmailPermalinkComments (0)
Tags

 Last 50 Posts
 Back
Change Theme...
  • Users » 734
  • Posts/Pages » 98
  • Comments » 38
Change Theme...
  • VoidVoid « Default
  • LifeLife
  • EarthEarth
  • WindWind
  • WaterWater
  • FireFire
  • LightLight

PP



    No Child Pages.

Windows optimization tips



    No Child Pages.