10 May 2013 @ 1:11 PM 

XNA Game Studio is a finicky bugger, and it’s even more finicky now that it is no longer being maintained. One of the biggest issues is that it doesn’t work properly with the latest version of Visual Studio, 2012. However, you can cajole it and reassure it that things will be OK.

One way to do so is to essentially “translate” an existing, working install, and “hack” it’s configuration so that it works in Visual Studio 2012. In order to get the appropriate file setup, you will have to install XNA Game Studio 4 into Visual Studio 2010.

With Visual Studio 2010 Installed and XNA Game Studio happily installed, you can force the XNA 4 installation to get along with Visual Studio 2012. XNA Game Studio installs by default in

%ProgramFiles(x86)%\Microsoft Visual Studio 10.0\Common7\IDE\Extensions\Microsoft\XNA Game Studio 4.0

the first step in whipping it into shape is to simply copy that folder to the appropriate target location in the Visual Studio 2012 installation. This is located, by default:

%ProgramFiles(x86)%\Microsoft Visual Studio 11.0\Common7\IDE\Extensions\Microsoft\XNA Game Studio 4.0

Not done yet, though- it’s copied over, and VS2012 will try to run it, but it will look inside the plugin manifest, see that it doesn’t say it works with VS2012, and then explode (well, it doesn’t explode, it just doesn’t load the extension, but that’s hardly very exciting.) In order to do so, you will need to open and edit the extension.vsixmanifest file within the XNA Game Studio folder you copied (the new one, that is). You’ll notice this:

What you can do should be pretty clear now; just flooble1 the “Version=”10.0” entry to point to version 11. Save the file, Open Visual Studio 2012, and BAM! Game Studio projects should now be available via the New Project Dialog Templates.

It still doesn’t work

Sometimes- perhaps You’ve been badmouthing Visual Studio behind it’s back; Maybe you complained under your breath about how slow Visual Studio 2012 is when you went to deal with Intellisense. Maybe you told Visual Studio 2012 where it can shove it when it provided you with a helpful popup tip. Visual Studio 2012 has feelings and, like a Cat, never forgets it’s enemies.

On the other hand, you might just need to delete the extensions cache file. The extensions cache file can be found at “%LocalAppData%\Microsoft\VisualStudio\11.0\Extensions”; specifically, the “extensionSdks.en-US.cache” and “extensions.en-US.cache” files in that folder. Delete them with impunity and regret nothing. Visual Studio 2012 has forced your hand. Innocent Files must die so that Game Studio 4.0 may live.

1flooble is a word I just invented now. Patent Pending!

Posted By: BC_Programming
Last Edit: 10 May 2013 @ 01:11 PM

EmailPermalinkComments (2)
Tags
Tags: , ,
Categories: .NET
 01 Apr 2013 @ 4:21 AM 

C#’s linq(language-integrated query) features are some of the more powerful features available through the language. Aside from it’s query operators that are, as it’s name would suggest, integrated into the language, the feature also brings along a large set of Extension methods to the IEnumerable interface type.

One interesting re-use of the IEnumerable type for extension methods is to create ad-hoc language structures using it, for example:

What we have here is similar- but not quite the same- as a switch statement within a loop. What makes this particularly interesting as a structure is that it acts sort of like a seive. The source to the extension EachCase() method is shown here:

The function works by calling the passed Action for all entries in the enumeration that cause TestExpression to return true. Those that return false are yielded to the caller. In the original code the EachCase() calls were chained, one after the other; each one operated on the entries that the previous one didn’t work with. the final .Count() call in the original code is to force it to be enumerated, allowing all the code blocks to evaluate appropriately. What use-cases might this have? I have no idea. However I feel confident in saying that it could make for a more readable alternative to something that might otherwise require a separate Finite-State machine.

Posted By: BC_Programming
Last Edit: 01 Apr 2013 @ 04:21 AM

EmailPermalinkComments Off on EachCase: a IEnumerable extension method
Tags
Tags: , , ,
Categories: .NET, C#
 21 Mar 2013 @ 9:08 AM 

Most application frameworks/languages provide access to the Command Line parameters passed to your application. Generally it is passed to your application as either a string or an array of strings. What you do not get automatically is the functionality to parse out switches.

Command-line parameters used to be the only way to communicate with a program. Fundamentally, the command line was your UI into the program. Different platforms took different approaches. Unix-like systems typically take the “invasive” route; they replace wildcards and then pass the resulting command line to the application. This means that you don’t have to do any shell expansion of wildcards (as it is known) but you have to account for the fact that your command line could include a lot of files. It’s a trade-off, really. Either way, I figured for the purposes of this library, we could stick to the platform- if the program is run with a wildcard, you’ll see the wildcard on windows, but it will have been expanded if you run the same program on Linux. It might be worth adding an option to “auto-expand” wildcards- just for consistencies sake, but that seems like a post for another day.

Either way, most applications also include flags and switches. This is more a De Facto standard that has cropped up- there is no hard and fast rulebook about what flags and switches are or how you are supposed to pass arguments, which can cause no end of confusion when it comes to reading application documentation. the .NET language just gives you the string, and leaves it up to you to decide how to interpret it. Some language libraries provide functionality to parse the Command Line appropriately, such as Python. C# doesn’t come with such a class…. So let’s make one!

First we need to determine what exactly can exist in a command line. My method allows for two things: Switches, and arguments. A Switch can include an argument, separated from the switch with a colon. For example:

In this case, we have three switches- switch, sw, and doall. The first two include an argument. My “syntax” allows for quotes in the arguments of switches as well as the “loose” arguments. We will evidently need classes to represent and parse Arguments, and another one for Switches. The parsing can be done sequentially. Although it’s not a recommended best practice, I chose to use by reference parameters in the class constructors. In order to keep things generic and accessible, both Switches and Arguments will derive from a CommandLineElement abstract class, which will force each base class to implement toString(). the ArgumentItem class will be used for parsing both “loose” arguments, as well as arguments found after a switch.

Arguments

Arguments are simple- if the first letter of the position is a quote, we look for the next quote that isn’t doubled up. Otherwise, we look for either the next whitespace or the end of the string. Each argument only needs the actual argument value.

The constructor is where the important stuff happens. the by reference parameter is used to define the starting position, and we update it when the constructor returns to point at the character after the argument. The class also defines some statics for implicit conversions to and from a string.

Now that we have the Argument class, we can define the Switch class. The actual syntax of switches often depends on the application but also seems to depend on the platform. for example, Linux tools favour the hyphen for single letter flags, and double hyphens for multi-character flags. Switches are also called flags. forward slash is not generally used as a switch or flag indicator. Windows platforms prefer the forward slash but generally allow for single hyphens as well. We aim to support all three syntaxes, and make the client application not have to worry about which it is. We also add support for arguments- a switch can be specific as such:

The element after the colon will be parsed as an argument and attached to the switch itself. But enough waffling- on to the Switch:

With the basic parsing logic completed, we need to consider how we want this to be used. Best way is to think of how we would like to use them:

Some basic take-aways from this. First, the Core Parser Object needs to provide an Indexer. In the above example, we see it is accessing Switches by passing in the Switch name. Other possibilities include using direct numeric indexes to refer to any argument- much like you would access elements in the framework provided args[] String array. Another possibility is to have the Argument of a switch auto-populate, rather than be null, when accessed:

Posted By: BC_Programming
Last Edit: 21 Mar 2013 @ 09:10 AM

EmailPermalinkComments Off on The Lost art of Command Line Parameters
Tags
 20 Jan 2013 @ 8:14 PM 
Note: This Post has been (partly) superceded by the implementation described in the more recent Alpha blended forms revisited Post.

One common problem that comes up in the creation of stylized windows such as Splash screens is the desire to have parts of the form be “shadowed” or, in other words, blend with the forms behind them. You can see this effect in action with other application splash screens, such as photoshop:

Photoshop Splash Screen in front of a dead-sexy website

Photoshop Splash Screen in front of a dead-sexy website

What witchcraft is this? How does Photoshop do it? One of the first things you might try with .NET is something like the TransparencyKey of the form. Of course, this doesn’t work, instead you get this unsightly ring of the transparency key around it.

The solution, of course, is a bit more complicated.

Starting with Windows 2000, the Win32 API and Window Manager has supported the idea of “layered” Windows. Before this, Windows had concepts known as “regions”; this basically allowed you to define regions of your window where the background would show through. This didn’t allow for per-pixel blending, but that sort of thing was not widely supported (or even conceived of, really) by most graphics Adapters. The “Layered” Windowing API basically provided a way to allow Per-pixel Alpha. Which is what we want.

Windows Forms, however, does not expose this layered window API through it’s methods or properties, with the exception of the opacity property. I don’t recall if WPF does either, but I would be surprised if it’s capabilities exposed more of the Layered Windowing API. Basically- we’re on our own

So what exactly do we need to do? Well, one thing we need to do is override the CreateParams property of the desired form, so that it adds the WS_EX_LAYERED style to the window, letting the Windowing Manager know it has to do more work with this window. Since we would like a neatly decoupled implementation, we are going to create a class that derives from Form, but use that as the base class for another form. This let’s us override the CreateParams property within that base class, but this has a bit of a caveat as well, since I’ve found that makes the Designer a bit annoyed and it complains and won’t let you use the designer. So you will have to deal with that particular point yourself. (I imagine there is a way to make it work, but I don’t want to bloat the class with such functionality). If necessary, the appropriate functions and the CreateParams override can be put into the classes that need this functionality instead.

Here is the PerPixelAlphaForm class. By the way, I’m going with Visual Basic.NET because there are already a million hits for this functionality with C#:

This provides the core implementation. The “Win32” class here provides the needed API declarations.

In order to use this, we need to make our form derive from it, and then use the inherited SetBitmap function:

(Here I just used an image on my second Hard disk that had a transparency channel, but the Bitmap constructor parameter can easily be changed.). The result:

The code in action

The code in action:

The Project I used for this can be downloaded from here. This was created using Visual Studio Professional 2012, Update 1- other editions or earlier versions may have problems with the project or source files.

Posted By: BC_Programming
Last Edit: 17 Sep 2016 @ 03:46 PM

EmailPermalinkComments (13)
Tags
 19 Jan 2013 @ 6:25 AM 

Though I do tend to try to write my samples and test applications, as well as any new programs, using Visual Studio 2012, I haven’t yet migrated most of my other applications to it. For BASeBlock and BCJobClock, for example, they started off in Visual Studio 2008. More recently, I migrated them to Visual Studio 2010. BCJobClock had it’s project upgraded to Visual Studio 2012, (but for some reason the admin applet doesn’t work on Windows 8, which is something that certainly bears further investigation). Anyway, I’ve been strongly considering it the more I think about it. In particular, I’ve found Visual Studio 2010 to actually be a lot slower. Originally, I thought this was because my 201 install had several add-ins installed, such as ReSharper, but now that I also have a version of ReSharper that works with Visual Studio 2012, I still find 2012 to be far more responsive.

Now VS2012 has gotten some flak from certain users for adopting the Windows 8 UI style into it’s icons, as well as using Caps in it’s menus. I really have no strong preference here at all, and I personally don’t see what the fuss is about. I’ve heard people say that the capitals “hurt their eyes” but I can honestly say that I don’t understand how that could be the case.

Anyway: I’ve been considering switching BASeBlock over the Visual Studio 2012. If I do I won’t be upgrading the project to use the 4.5 framework, though. At least not yet.

Posted By: BC_Programming
Last Edit: 19 Jan 2013 @ 06:25 AM

EmailPermalinkComments Off on BASeBlock:Visual Studio 2010 to 2012
Tags
Tags: , , ,
Categories: Programming
 18 Jan 2013 @ 11:53 PM 

Undo/Redo Stacks

The BASeBlock Editor has had an Undo/Redo stack for quite a while. The implementation of this logic is relatively simple, but the implementation- or rather, my recent re-implementation- seems like a good subject for a blog post.

Basically, an Undo/Redo Stack Let’s your Program reverse through changes that have been made, and then, if necessary, go forward through those changes. What makes this problem interesting is that, by and large, the core logic is really quite similar. I will attempt to outline the process of creating a Generic Undo/Redo Object that can be used in many contexts.

First, we’ll start with The abstract base class that we will use to represent Undo Elements:

Since we don’t know what, specifically, is being handled, we use this abstract class and provide only very basic methods. The DateTime can be used on appropriate menus or as a sort key, and the Description can be used for any menu text, or other UI elements as needed by the app consuming the class.

This will be used for a generic class, which I will call UndoRedoManager. This will, unsurprisingly, manage the undo and redo operations, or, more specifically, it will manage the data structures dealing with the Undo and Redo information. In order to actually undo, we will need to delegate the task to the caller, on the assumption that they know more about the StackItem. We will call the Events HandleRedo and HandleUndo, and they will take a simple EventArgs. First, we will define the EventArgs class definition.

The Event Argument class is relatively simple; we just have a field for the StackElement, and a field for Cancel, which we will deal with when we fire the event. We use a generic class because we need to support the management of any class type that derives from UndoRedoStackItem, where the appropriate application-specific data will be dealt with and stored.

The “UndoRedoManager” class we will create will be designed as generically as possible. And, to be honest, my original implementation will be a naive one, each Stack Element will be designated as storing a complete “state” for whatever the application is doing. A better approach for applications that have a large amount of state data is to instead store the changes, rather than the entire thing, but that sort of extra functionality is best discussed and designed after we have the basic framework in place.

The first step is to designate what we need to keep track of in the ‘Manager’ Class, as well as our events.

We need a Maximum size, otherwise it’s possible for the stack to fill up with old Undo elements. We keep a stack for Undo as well as Redo elements. The actual public functionality we need to implement is a method to Undo, a Method to Redo, and a Method to “Push” a new element onto the Undo stack (register a change).

We’ll start with the first method that will usually be used: PushUndo. This will accept a parameter that is the type of the generic type parameter. It will need to:

  1. Make a Deep copy of the item being pushed.
  2. Push that deep copy onto the Undo Stack
  3. Trim the stack to the maximum size.
  4. Clear the Redo Stack

Here is the code to do that. TrimStack() is private method who’s implementation I will cover shortly:

Most of this is self-explanatory. TrimStack’s implementation is a bit trickier, since the Stack class is a bit less revealing beneath it’s Clothing, but we can seduce it:

TrimStack here is written to take any Stack Type, though, arguably, this isn’t necessary in this current implementation. (No reason, however, to make it more specific, in my opinion)

First, if the stack has fewer elements than the passed maximum, we have no work to do, so we return right off the bat. Making our work quite easy.

If the Stack does have more elements than the maximum, we pop elements until either the stack to trim is empty (for some reason) or the temporary stack has maxelements elements.

The effect here is to grab the top maxelements items. After this, we clear the stack and push the elements we popped.

The task of performing the Undo has the following steps:

  1. If CanUndo returns false, return only null.
  2. Otherwise, Peek at the top element from the UndoStack.
  3. Create a new instance of the EventArgs class with the peeked element.
  4. Fire the Undo event with the created EventArgs.
  5. If the Event’s Cancel field has not been set, perform a Pop on the Undo Stack, and Push the item we retrieved earlier to the Redo Stack.
  6. Return the Item we removed

The idea here is that the Event handler that is tied to the class will do the application-specific activity for the “undo” operation- we don’t know what the data is, nor what it represents, but the program using us will, so we leave them to it. This also enables the less naive implementation concept that I’ll be using later to extend this.

And that is pretty much the core implementation. Of course, as it is, we don’t actually have an implementation for the StackElement class. Since that is something we left up to the client application, let’s create one. Here is a small Windows Form that utilizes the aforementioned classes as well as providing an implementation of the Stack Item for a TextBox:

The Designer class:

Proper code-behind class:

In the above implementation, TextUndoItem is the UndoRedoStackItem implementation I created for textboxes; this stores the selection start and length as well as the full text. The Actual Undo implementation was less trivial than I had hoped; in this case I created a “Managing” class that uses the UndoRedoManager specifically with Textboxes, hooking the appropriate textbox events and implementing a delay after typing stops before Undo’s are pushed onto the stack. This is a very simple implementation of this particular class design; BASeBlock uses a very similar class in it’s Editor, but for the far more complex structures dealt with there, which include several lists of objects.

The extension and addition to this design that I mentioned earlier consists of storing not the entire state, but rather what changed from the previous element. This is unlikely to be a trivial thing to implement.

Posted By: BC_Programming
Last Edit: 18 Jan 2013 @ 11:54 PM

EmailPermalinkComments Off on Undo/Redo Stacks in C#
Tags
 20 Dec 2012 @ 9:12 AM 

I was working on BASeBlock’s splash screen a bit, and thought it would be neat to have a little animation to expand and contract the list of loaded assemblies. I suddenly found myself wanting something similar to JQuery.

It didn’t seem inexorably difficult; so I got to work. Soon I had a simple little class that could move and size a object.

 

But that wasn’t enough. it wasn’t flexible enough- what if I wanted to animate, say, the background color, too? So I created a new project- BCQuery. The purpose is to provide a simple control animation framework; I came to realize that even restricting it to just controls could be limiting, so it really accepts any object at all.

The design is based around a simple threading model. Obviously, all UI actions (such as moving or interacting with Windows Forms controls) need to occur on the main application thread. Thankfully, Control’s expose a “Invoke” and “BeginInvoke” method that can be used to run code on that thread while closing over local variables, which is immensely useful.

 

This runner thread is only active while things are animating. When an animation is added and there is no thread running, it starts it; otherwise, when the last animation completes, the Thread removes itself. The interesting part is that it only uses one extra thread- All animations are performed concurrently here, with extra operations being queued up for execution in that thread before the iteration runs. One of the main concerns here is with the use of a foreach to iterate through and update each animation; since the animation can easily complete and there is no way to directly remove the instance from the collection without the next iteration of the foreach throwing an InvalidOperationException because the collection was changed. Code that needs or wants to remove or otherwise modify that collection can now do so by simply queuing up a piece of code to run the next time through the main animation loop.

I rather like how the project has come so far; I have it so I now need only two lines of code in a form to set up a basic “expando” whereby one control expands and the expander control moves. Given the amount of effort in dealing with what is essentially a finite state machine otherwise, this is extremely helpful IMO. Currently I have “easers” that can work with Size, Point, float, and int property’s, but it isn’t too much trouble to add more; the Point and Size versions use a corresponding easer of the appropriate type; for example, there is a PointFEaser, which uses two FloatEaser’s to ease the X and Y coordinates. This could be useful if I create custom float easers later on to support say… easing. (Though that is far from easy.

It works a treat, and will definitely be the subject of a future blog post.

It’s worth mention that this sort of library would be valueless for, say, WPF. This functionality is far better provided by WPF Storyboards via the Windows XAML rather than using something like this. But you can’t always use WPF, or don’t want to make something “heavy” that uses WPF, but might want some interesting animations like those you might need a simple storyboard for without writing too much code; and that’s what this library will be for.

 

EDIT: It didn’t exactly come to me quickly, but it did only take one debug run (I accidentally swapped two parameters because I named them poorly) before I had it working; considering it uses reflection to change members and properties on the fly, it works quite well. Definitely a class library to be expected with new releases of most of my projects, and of course available standalone.

Posted By: BC_Programming
Last Edit: 20 Dec 2012 @ 09:16 AM

EmailPermalinkComments Off on new Project: BCQuery
Tags
Tags: , , , ,
Categories: .NET, C#
 28 Nov 2012 @ 10:52 AM 

As many web developers are aware, there are a myriad of ways to develop websites and interactive web applications today. On the server side, one typically chooses from one of two technology stacks; the “Open Source” and the Microsoft. Disregarding political and license concerns, they really are very much equal in core capability. The Open Source stack typically consists of A Linux distribution as the Operating System, Apache as the Web Server, MySQL as the database, and PHP as the server-side language. These can also be installed to a Windows machine as well, and Apache has modules that even allow the use of .NET technologies via the Mono runtime. The Microsoft stack consists naturally of Windows as the OS, IIS as the webserver, and ASP as the core server-side script. ASP itself, of course, supports a number of languages; you can use JScript, VBScript, or a .NET language. Both of these platforms provide a myriad of tools at your disposal. LAMP allows you to leverage the wealth of Apache modules and use a large selection of programming languages like Ruby, Python, Perl, and of course PHP. The Microsoft Stack makes use of the very powerful SQL Server, and is particularly scalable to large operations. Of course there are variations of these; obviously MySQL could be swapped out for PostGreSQL, or even a remote SQL Server.

Costs

The cheapest hosting plans for most WebHosts use a Linux-based stack. This makes PHP one of the more accessible server-side languages to learn. When I started this sight, I wasn’t really sure how well it would turn out, what I would write about, or how much exposure it would give me or my various programs. After three years, I’m still not entirely sure of that; but at the time, I was working predominantly in Visual Basic 6. I was stagnating, and I didn’t even realize it. When starting the sight, I really had two choices- go with the Linux stack, or the Microsoft stack. My choice of the LAMP stack was done purely for a single reason: it was completely foreign to me. That may seem like an odd reason to choose a technology, but I’m always up to a challenge. I won’t try ot say that learning the “Linux way” of doing things was easy, but it did get easier over time. With the server itself of course I didn’t have full access anyway; just a standard CPanel, and I still do; but understanding Linux, Apache, and MySQL were very helpful in using PHP, which was the language I had to learn to get teh site off the ground beyond a few ugly static webpages.

I basically slogged through learning PHP, in an attempt to create a relatively simple CMS. After getting a basic CMS and some crappy side links started, I decided to redesign the site from scratch. I sketched how I wanted it to look on paper, and then set to work duplicating that appearance using the available web technologies, as well as through the use of Photoshop for the various images I needed. The end result is what you see on the main page; of course I’ve made changes to it since, and added features to the underlying CMS to support new functionality such as listing my youtube videos and different categories of items, but the visual appearance is much the same. I toyed recently with the idea of redesigning it, but decided that it could stay as it is now a little while longer; a redesign is a rather big undertaking, and I like how it looks now.

Since then, I’ve also learned and become quite adept (If I may say so) at C#. This has left me rather- annoyed- when I use PHP, which feels very messy in comparison to what is generally a very clean working environment. Not to mention being relegated to having to debug using echo, which I can’t say I really missed from using GW-BASIC.

I did install a MS Stack locally some time ago, and experiment with it for a short time before deciding to avoid it; I reasoned that if I was to use C# for web development start to avoid working on my PHP site even more. I’ve since changed my mind, however; I’ve decided to install a local IIS-based server and experiment some more with what .NET has to offer on the server-side. I’ve been able to make some pretty fine-looking stuff with WPF and Windows Forms, and I know WebForms as well as the Base-Class Library that is not heavily leveraged on the client side are one of the many areas where my abilities and knowledge can be expanded, so I can’t see why not.

Also, I’ve always thought it a bit weird that my site ran on PHP and I focussed mostly in Windows-based and MS technologies and languages. Though I don’t see a switch over occurring anytime soon.

Posted By: BC_Programming
Last Edit: 28 Nov 2012 @ 10:52 AM

EmailPermalinkComments (1)
Tags
Tags: , , , , ,
Categories: .NET, Linux, Windows
 22 Sep 2012 @ 12:13 AM 

This is part of a occasionally updated series on various programming languages. It should not be interpreted as a benchmark, but rather as a casual look at various programming languages and how they might be used by somebody for a practical purpose.
Currently, there are Articles written regarding Python,C#, Java and VB6 (merged for some reason),Scala,F# & Ruby,Perl, Delphi, PHP,C++,Haskell,D, VB.NET, and even QuickBASIC


In order to compare various languages, I will be implementing a anagram search program in a variety of languages and testing and analyzing the resulting code. This entry describes the C# entrant into that discussion. A naive anagram search program will typically have dismal performance, because the “obvious” brute force approach of looking at every word and comparing it to every other word is a dismal one. The more accepted algorithm is to use a Dictionary or Hashmap, and map lists of words to their sorted versions, so ‘mead’ and ‘made’ both sort to ‘adem’ and will be present in a list in the Hashmap with that key. A psuedocode representation:

  1. Loop through all words. For each word:
    1. create a new word by sorting the letters of the word.
    2. use the sorted word as a key into a dictionary/hashmap structure, which indexes Lists. Add this word (the normal unsorted one) to that list.
  2. When complete, anagrams are stored in the hashmap structure indexed by their sorted version. Each value is a list, and those that contain more than one element are word anagrams of one another.

The basic idea is to have a program that isn’t too simple, but also not something too complicated. I’ll also admit that I chose a problem that could easily leverage the functional constructs of many languages. Each entry in this series will cover an implementation in a different language and an analysis of such.

Implemented in C#, the described algorithm might look like this:

One of the contributing factors to the amount of code here is the creation of a method to sort characters in a string as well as availing the use of foreach() with a stream contributes to this. Much of the size (compared to Python) can be attributed to the different typing of the language, too.

In Visual Studio’s default debug mode, all optimizations are disabled and the IDE hooks a lot of the activity of the program itself. My initial run took over 20 seconds to complete. I disabled the Visual Studio hosting process and activated the Release build, as well as changing the target platform from x86 to “Any CPU”. This reduced the time from 20 seconds to around 10 seconds; changing the implementation of the iterator method to read the entire file at once rather than one line at a time reduced it to ~0.8 seconds.

This might actually provide some insight into why so many detractors seem to have such an easy time thinking C# is slow. They will usually start up Visual Studio, make a quick test program, run it, and find it very slow, and then write off the language as slow, almost dismissively. This, without realizing that the language itself is not slow, but debugging a program tends to put a damper on things; what with the lack of optimizations in order to allow for better RTTI for the debugger.

Posted By: BC_Programming
Last Edit: 15 Apr 2013 @ 10:09 PM

EmailPermalinkComments Off on Programming Language Performance Part III: C#
Tags
 20 Jul 2012 @ 9:13 PM 

Gamers are an enterprisey bunch. You don’t give them enough X, so they go prodding around your game’s memory to try to give themselves more. Programs that have this purpose are called “Cheat engines”. Usually, how they work is a multi-step process.

  1. The obvious first step is for the cheater to decide what they want. Lives? More Gold? Maybe they want to up their players attack power?
  2. This is usually fairly easy, and you can usually tell the data type just by the amount of screen space reserved for a value. Though sometimes you just have to guess. Many cheat engines can search for values regardless of the actual data type, too.
  3. Now, the cheater looks for every value in the game’s memory that has the current value of the item they want to ‘hack’. The results will usually be collosal.
  4. In order to revise the search parameters, the gamer/cheater will now “change” that value somehow; by perhaps losing a life or getting a new one, getting more score, using a “attack upgrade” pill, or what-have-you. Armed with the new value, they can now tell the cheat engine program to show them all the values that were the old value before that have now taken on the new value. If they are lucky, this will be only one entry, and they can use the cheat engine and change it, and BAM they have the new value they hacked in.

The typical, and perhaps smartest way, to deal with this problem is to ignore it. A well architected game system will have any multiplayer values centralized on a server which means that a cheat engine will only mess around with a client of the game, and there are ways of checking for those hacked clients as well, (because they can give players a minor advantage). However it bears an interesting topic of discussion- how do you prevent this?

With some considerations, I have determined a method to do this- each time a value is assigned, generate a new random value, store that, and then only store a version of the original value that was encrypted. The idea being that the existence of the “actual” value- the value the cheater would be able to identify- is transient and only exists in limited scopes, making it nearly impossible to find the correct value to change, and even if they do find it, the method of encryption/hashing means they would need to know the corresponding algorithm and number in order to turn a new value they wanted and store it in memory so the Obfuscated class to which said value is associated will decode it properly.

The trouble with this method lies in the fact that it is anything but transparent, and requires copius code changes all over the place.

Enter Generics & Templates

Generics and Templates are the obvious solution to this problem. With C++, this sort of class nearly writes itself, actually; since templates are a compile time feature. you could then replace values that are int with something like Obfuscated and not have to change anything else.

Being that I work primarily in C#, however, this was the focus of my attentions. And it is not quite as simple, though thankfully the addition of dynamics to the language really helps make the code more concise for this sort of purpose.

Everything seems to work fine initially; you can create a generic class Obfuscated, then define operator methods that can cast a T to an Obfuscated and vice-versa without too many problems. problems start to arise as you realize that the original code is using operators and the implicit casts are not being performed (because there is no reason for the compiler to think that casting the two values from Obfuscated to the type T will make the operation valid). So you define operator overloads. The typical result in C# 3 was rather messy. Since there was no way to define a constraint that said to only allow arithmetic operators, nor is there an interface you could cast to to check if the Type T for which your generic instance was constructed supports arithmetic operators, you were left in the cold. For many types you could use the built-in operator methods themselves, op_Addition, op_Subtraction, etcetera. What you would end up with is a large else-if ladder that checked for all of the primitive types, with an else block that used reflection to call the appropriate operator method that way; and failing that throwing an InvalidOperationException.

Dynamics to the rescue, however. Thanks to C# 4.0’s addition of the dynamic keyword, which introduced late-bound variables, we can actually make the call relatively simple. we can perform operators on dynamic variables and the call will be resolved at run-time, and will be handled appropriately even for the primitive types.

With that out of the way, there was only one question left: the encoding. I decided on a simple interface that allowed to decode and encode a arbitrary set of bytes. I implemented a simple xor encryption and used that for my tests. The tricky portion is of course getting some arbitrary set of bytes representing a variable of your generic type; this isn’t something you can really force with constraints. You really need a Type T that is either a structure or a serializable value. For this purpose I created two general purpose generic methods:

First, the method to convert a given value of a Type P to a array of byte[]:

If it is a ValueType, we use the Marshaller to get the actual in-memory representation of the structure, copy it to a array of bytes of the appropriate size, and then return that. Otherwise, we try to save it to a MemoryStream using a BinaryFormatter, slurp out the contents of that memorystream, and return that array of bytes to the caller. The corresponding function that turns a given array back into the corresponding type is obviously just the reverse of this:

by replacing a variable of a given type T with an Obfuscated, you get almost completely transparent obfuscation of the in-memory representation of that type. Assignments result in the generation of a new random number, encrypt the passed value, and store the encrypted value, and retrieving the value or an implicit cast to the type will deobfuscate the value and return that.

The Full source to my test project which contains and uses this class is attached:
Memory Obfuscation Class

Posted By: BC_Programming
Last Edit: 20 Jul 2012 @ 09:13 PM

EmailPermalinkComments Off on In-Memory Obfuscation for your data
Tags
Tags: , , ,
Categories: .NET, C#, C/C++, Programming

 Last 50 Posts
 Back
Change Theme...
  • Users » 47469
  • Posts/Pages » 391
  • Comments » 105

PP



    No Child Pages.

Windows optimization tips



    No Child Pages.

Soft. Picks



    No Child Pages.

VS Fixes



    No Child Pages.

PC Build 1: “FASTLORD”



    No Child Pages.