XML De/serialization

Here’s a way to serialize and deserialize between a (serializable) type and XML (string).

Serialization from a type into XML (string) via a memory buffer:

public static string SerializeMyType(MyType obj)

{

      XmlSerializer xml = new XmlSerializer(typeof(MyType));

      MemoryStream ms = new MemoryStream();

 

      xml.Serialize(ms, obj);

 

      UTF8Encoding enc = new UTF8Encoding();

      ms.Seek(0, SeekOrigin.Begin);

 

 

      return enc.GetString(ms.ToArray());

 

}

 

 

Deserialization from an XML (string) into a type:

 

public static MyType DeserializeMyType(string xml)

{

      XmlSerializer xml = new XmlSerializer(typeof(MyType));

      TextReader tr = new StringReader(xml);

 

      return (MyType)xml.Deserialize(tr);

 

}

Posted in Uncategorized | Leave a comment

String Interning

In the (.NET) CLR (Common Language Runtime), there exists a table known as the intern pool. It contains a single reference to every unique string literal in your program. It does this to reduce the amount of memory used. This should come as no surprise as you’d have probably wondered at some point if the CLR is ‘smart’ enough not to make multiple copies of the same string. It basically is, but it’s not all that simple.

Taking note that strings in .NET are immutable, consider the following code;

string s1 = “hello world”;

string s2 = string.Concat(“hello”, ” world”);

 

Console.WriteLine(s1 == s2);

Console.WriteLine(Object.ReferenceEquals(s1, s2));

 

The output for the above code is:

True

False

 

The strings are equal, but they are different objects. In the case above, the strings are not interned. Let’s look at the next piece of code:

string s1 = “hello world”;

string s3 = “hello world”;

string s4 = s1;

 

Console.WriteLine(Object.ReferenceEquals(s1, s3));

Console.WriteLine(Object.ReferenceEquals(s1, s4));

Console.WriteLine(Object.ReferenceEquals(s3, s4));

 

This time, all thee comparisons are True. All the variables are actually the same objects as the CLR retrieved the same reference to the literal string from the intern pool and assigned it to each of the variables.

The good news is, you can intern strings yourself, and you do it with:

string String.Intern(string str);

 

The Intern() function will return an interned string reference. If the literal already exists in the intern pool, it will return the reference to it, if not, a reference to str will be added to the intern pool and that reference will be returned.

 

string s1 = “hello world”;

string s2 = string.Concat(“hello”, ” world”);

string s3 = string.Intern(s2);

 

Console.WriteLine(Object.ReferenceEquals(s1, s2));

Console.WriteLine(Object.ReferenceEquals(s1, s3));

 

The output of the above code is:

False

True

 

So, when would it be practical or reasonable to intern strings yourself? Your program would probably need to be working with a lot of string operations that likely end up creating many strings containing the same content. This is different from, for example, declaring const or static string literals and referencing them.

You’ll have to consider that string interning has the following side effects (from MSDN):

  • the memory allocated for interned String objects is not likely be released until the common language runtime (CLR) terminates. The reason is that the CLR’s reference to the interned String object can persist after your application, or even your application domain, terminates
  • to intern a string, you must first create the string. The memory used by the String object must still be allocated, even though the memory will eventually be garbage collected
Posted in Uncategorized | Leave a comment

Windows Phone MessageBox WTF

So, everybody’s used the messagebox in Microsoft platforms in one form or another. The good ol’ fashioned Win32 API version, or any of the .NET variants. So, I recently got bit in the ass by Windows Phone. Here’s how.

This was what I was doing:

      MessageBox.Show(“Something went wrong…”, “Oopsie!”, MessageBoxButton.OK);

 

      if (NavigationService.CanGoBack)

      {

            NavigationService.GoBack();

      }

 

 

 

Basically, when something went wrong, display a messagebox, and when it is closed, by the [OK] button being pressed (which, I thought, was the only way it could be closed, because there is no other button including a close [X] button), the app navigated back. So I get a crash report. And what could go wrong?

 

Here’s what went wrong. Apparently, if the messagebox (modal, mind you) is being shown, and you switch away from the app, like by pressing the Start button, MessageBox.Show() returns. What? Since when? If you look at it closely, when the app navigates away, you can actually see the messagebox being closed. So, the code above crashes because you cannot navigate when your app is not active.

 

So, I looked through the documentation in MSDN, and did not notice any remark about this behaviour at all. I think it is more than reasonable to expect that the messagebox will still be there where you ‘go back’ to your app. Apparently, some people didn’t think so. What’s the rationale in that?

 

Oh, and when the Show() method magically returns, the result is MessageBoxResult.None. Therefore, I’d have to actually check the return result of the call like so:

 

      MessageBoxResult result = MessageBox.Show(“Something went wrong…”, “Oopsie!”, MessageBoxButton.OK);

 

      if (result == MessageBoxResult.OK)

      {

            if (NavigationService.CanGoBack)

            {

                  NavigationService.GoBack();

            }

      }

 

 

Not obvious, not documented. Not impressed.

 

Posted in Uncategorized | 2 Comments

ASUS UX31 Zenbook Sentelic Touchpad Driver Problem – With Solution

For those of you who use the UX31 and have installed the Sentelic touchpad driver (FspUip.exe), you might have noticed it’s severely buggy behaviour of constantly chewing the up CPU when your Windows 7 system is has gone into power save and turned off the display. You can hear the fan running hard during this time.  And you know that this will heat up your machine real bad. If you have your Task Manager or Process Explorer (Sysinternals) turned on and running before it goes into power save, you should be able to see the CPU usage history.

You should also have found that a lot of people have been looking for solutions to this problem. I probably isn’t a solution until Sentelic has a newer version that fixes this. They might have by now, I don’t know.

I decided to work around it myself and wrote a small app to basically kill FspUip.exe when the system goes into power save and turns off the display, and restarts it when it comes out of power save. So far it’s been working well for me. You can download the tool here.

AutoPowerApp.exe is the tool, and you can save somewhere in your system, and add it to your system startup. It assumes that your Sentelic software is installed in the default path of C:\Program Files\FSP\FspUip.exe. If it isn’t, it won’t work. Too lazy to make that configurable.

Posted in Uncategorized | Leave a comment

Help! I’m blinded!

Ever since people have seen screenshots of Visual Studio 11 Beta, there has been a lot of gripe concerning the new flat and gray look. Myself included. But quite frankly, that is nothing compared to the removal of macros. I think I shall not rant about that in this post.

The Visual Studio Blog claims: “In this and subsequent studies more developers have expressed a preference for the glyph style icons over the former style, especially after having spent time getting used to the new glyph style icons.”

While that may be true, it is unsubstantiated, and unqualified. “More developers”. I like this one. Well unqualified. More compared to what? I think maybe it could be “more than before, which was none.” Which would make it a true statement. So, the real essence which they did not share, is the percentage of developers tested that preferred the new glyphs. Regardless, we have our own preferences, as everybody’s brains works in their own way. It is true that one or the other will work better people most of the time. But what’s not cool, as many has pointed out, is there isn’t any choice/option. For now, if the glyphs don’t work for you, then you’re screwed. Point to note, graphics in the past were grayscale because we did not have coloured displays.

Check out the Visual Studio Iconography. It is a sort of test to see whether the coloured icons or the grayscale glyphs work better for you. Take note, it’s to see which is better for you. “Better” requires a frame of reference. So that would be yourself. The ‘game’ basically names an icon/glyph and you pick it out from a batch of them. Simple. Here are some points:

  • The icons are represented by both the coloured and non-coloured versions
  • There is a list of all the icons/glyphs with their names. You need not memorize them all, and you shouldn’t. Part of the test is to see if you are able pick out an icon/glyph based solely on a description. This will demonstrate the effectiveness of its design
  • The icons/glyphs are presented in a group like a toolbar, basically and without context. This neutralizes any contextual advantage, and each of them must stand on the merit of their design. You will then be able to see which (of those available) ‘get lost’.
  • Poorly designed glyphs will standout here, in particular, the Class View and Object Browser glyphs. They are identical. This is where the fun is in the game when you have to pick one of those out. Refer to image at the end of this post

I have played it a fair amount of times, and here’s what I found:

  • It generally takes longer, sometimes twice as long to figure out the glyphs. But that is because they are new. However, this is a valid point as part of the issue is how great the learning curve is for the new glyphs. Ideally, they should not impact you greatly as they are new representations of existing things. If it’s significantly difficult to figure out the new representation of something you already know, then it is a problem
  • It is actually easier to pick out some of the new glyphs. I noticed that this is not because it is grayscale, but because it has been redesigned into something more effective. If the coloured icons were redesigned as such, I believe they would be even more effective than the glyphs
  • If you have to pick glyphs that you are familiar with, or are standouts or well designed, the times taken for both were the same down to the second for me.

 

So, as usual, you can’t please everyone. And in this instance, it looks like Microsoft, bent on their Metro-gone-wild approach (this is my opinion and allegation) is pleasing what appears to be a minority. Some people don’t care what it looks like, and some do. Both are legitimate. Personally, I can’t even use a computer (notebook) I can’t stand the look and feel of. But that’s just me. But alas’, Visual Studio 11 is in beta at the moment. Lets see what happens after the feedback has been gone through.

Just so Microsoft remembers, most Visual Studio users are using it to make their living, and somebody is forking out the cash for the hefty price tag. I don’t know if this is supposed to appeal to a new category of users or not, but I certainly hope they are paying attention to those who are paying the premium (whether for or against).

My fave new glyphs:

vs11-glyph fail

Posted in Uncategorized | Leave a comment

.NET Preprocessor Visual Studio 2010 Add-In Update

The latest version of VSDotNetPP (Version 0.2.0.0) is available and can be downloaded here.

Following is the post from NTSTATUS:

Major updates and additions in this version:

Macros in open documents are now expanded in the file itself, therefore eliminating the previous message saying that the file has been updated outside the editor. This makes ‘Restore Macros In Source’ practical, but still not recommended

Context-menu item to expand macros. This expands all macros in the current document.

DOTNETPP.EXE is no longer included in the install

‘Expand Macros’ in context-menu:

Expand Macros

As before, building will automatically expand the macros. If ‘Restore Macros In Source’ is set, then the macros will be restored in the document after the build is completed.

All postings on the .NET Preprocessor in chronological order:

The .NET Preprocessor – Part 1

The .NET Preprocessor – Part 2

The .NET Preprocessor – Part 3

The .NET Preprocessor – Part 4

The .NET Preprocessor Visual Studio Add-In

.NET Preprocessor Update

.NET Preprocessor Visual Studio 2010 Add-In Update

Posted in Uncategorized | Leave a comment

Deferred Procedure Call

One feature available in the Windows kernel that I really like is the Deferred Procedure Call. It’s a mechanism that basically let’s you defer lower-priority tasks. This is because high-priority tasks such as interrupt handlers should complete as quickly as possible, but they may have other required tasks that are of lower-priority. DPC’s allow these tasks to be scheduled for later execution when the kernel drops to an IRQL (Interrupt Request Level) of Dispatch/DPC level. When the kernel is in this IRQL, it will execute DPC’s that have been queued.

In kernel mode, a DPC object is initialized with:

VOID KeInitializeDpc(

  __out     PRKDPC Dpc,

  __in      PKDEFERRED_ROUTINE DeferredRoutine,

  __in_opt  PVOID DeferredContext

);

 

This is the Custom DPC function prototype:

KDEFERRED_ROUTINE CustomDpc;

 

VOID CustomDpc(

  __in      struct _KDPC *Dpc,

  __in_opt  PVOID DeferredContext,

  __in_opt  PVOID SystemArgument1,

  __in_opt  PVOID SystemArgument2

)

 

You queue a DPC with:

BOOLEAN KeInsertQueueDpc(

  __inout   PRKDPC Dpc,

  __in_opt  PVOID SystemArgument1,

  __in_opt  PVOID SystemArgument2

);

 

I had a need for something like that in one of my .NET projects. However, I needed something deferred by time, rather than scheduling priority. This need is nothing new, of course. It’s commonly implemented with timers to basically delay the execution of code. Since I needed to do this kind of deferred procedure calls in a lot of places, I decided to write a nifty little class to do it for me instead of littering my code with a ton of timer creations and handlers.

And since I liked the Windows kernel’s DPC mechanism so much, I called it the same thing. The source can be downloaded here.

The class is DeferredProcedureCall. It can be built for Silverlight as well. Instantiating one instance for the lifetime of your class/app/program is enough. In fact, it is meant to be used this way. The function prototype for the DPC routine is as follows:

public delegate object DeferredRoutine(params object[] args);

 

This is in the same tradition as the kernel’s Custom DPC routine. However, the variable argument list in C#/.NET makes it all the more convenient. So, you may pass in any and any amount of parameters as you wish to suit your needs. The return type is also entirely up to you. It should be obvious that in callbacks of such traditions, you are responsible for the types being passed in and out.

The DPC class also has an event you can register a handler to which notifies you that a scheduled DPC has completed. Here’s how you register a handler, and the handler itself (from the sample source code):

      private DeferredProcedureCall _dpc = new DeferredProcedureCall();

 

      _dpc.DpcProcCompleted += new DeferredProcedureCall.DpcProcCompletedHandler(_dpc_DpcProcCompleted);

 

      void _dpc_DpcProcCompleted(object reference, DeferredProcedureCall.DeferredRoutine proc, object result)

      {

            AddMessageProc(string.Format(“DPC Completed: [{0}] {1}”, proc.Method.Name, result.ToString()));

      }

 

Here’s the method to schedule a DPC:

public object ScheduleDpc(double delayMs, DeferredRoutine proc, params object[] args)

Therefore, scheduling a DPC is merely so:

      _dpc.ScheduleDpc(1000, AddMessageProc, “First message”);

 

      _dpc.ScheduleDpc(4000, (x) => { lbStatus.Items.Add(x[0]); return true; }, “Second Message”);

 

 

As you can see, you could use Lambda Expressions to define callbacks as well. This can be convenient when you have fairly small and random functions you want to schedule. Do note of course that you don’t have to pass any parameters to the callback if there is no need for any.

Posted in Uncategorized | Leave a comment