24 Jun 2015 @ 7:17 AM 

Previously, I wrote about String Interpolation and Expression-bodied members, new features to C# 6.0. Today I will be looking at the Null-Conditional operator, which is also new to C# 6.0.

Null

This will be a bit of a tangent, but I thought I’d cover null itself. Most of us, I expect, have an understanding of what “Null” is (or rather, what it isn’t). Nonetheless, The idea of null itself has some controversy surrounding it, in a sense. Many programming languages use a concept of null to represent Nothing; Visual Basic’s equivalent to Null is in fact called Nothing. There is a “movement” of sorts which effectively claims that programming would be less trouble-prone if we got rid of Null; if Null was non-existent. Generally, the idea is that a lot of programming exceptions are errors such as Null Reference Exceptions and null pointers; therefore, the logic is that by removing the possibility for null, we remove the possibility for those errors and therefore we eliminate the problem.

I think that eliminating nulls to simplify programming is like trying to eliminate 0 to simplify math; we created the concept because it made it easier to demonstrate and express abstract thinking. In eliminating Nulls, we simply end up with other bugs. The only real alternative would be to force no instance to ever be null by making a “Empty” instance be instead a blank instance. But that just raises further issues, both in terms of how that default get’s set (What is a default state for a Socket?) as well as exactly what problems that would solve- instead of trying to access a method throwing a NullReferenceException erroneously, that instance will be a default instance and the method call will not cause that error but may cause other errors within the method which may simply be even harder to trace than the NullReferenceException. It is trading one set of errors for another set of errors entirely, and furthermore that new set of errors will be even more difficult to diagnose.

Now that I’ve got that out of my system, we still don’t want to deal with NullReferenceExceptions if we can avoid it. Thankfully, it is fairly easy to program defensively if you suspect an instance variable might be null:

In this instance we have a Plugin abstract class definition but it is also possible that a Plugin implements an extended interface ICorePlugin. In this case if we find it is a core plugin we need to take extra steps- for obvious reasons we cannot simply index into the dictionary or call a method on the instance if it doesn’t implement the type, as if it doesn’t implement the interface the As case will return null. With the Null-Conditional operator, we can replace the null checks with- well, the operator:

As we can see here, after casting the type to a ICorePlugin, we merely access the possibly-null value via the conditional operator, as well as call functions and indexers which accept that parameter differently, via the conditional. The Conditional operator using a question mark makes semantic sense given that the null coalescing operator is ??.
improve discussion

Thank you very much

The ?. usage has become known to some as the “Elvis Operator”. The stroke of the question mark, I’m told, looks like his hair. Presumably this naming scheme takes after the “Spaceship” operator “< =>” in that it is named after what it looks like rather than what it does. Not that that is a bad thing but I’m of the mind that it rather makes sense to name and call operators by names that describe what they do, however once you get passed this sort of jargon such a name reasonably becomes far less amusing, so funny names I suppose keep interest.

One interesting consideration is that it is sort of the ? that is the operator on it’s own, and you can simply use it in a few instances for implicit null-checks. ?. allows you to have an implicit null check when accessing an instance member, and you can do something similar for index access operators (as shown) as well.

The flip-side

Adding a lot of operators with interesting capabilities definitely expands the language but there is an argument to be made about language complexity. Furthermore, while it can be argued that if we do not like a new feature, we can simply not use it, that realistically only applies to code we write. If we are working in a team, than decisions need to be made about how things are done and these sorts of operators might be considered “off-limits” simply to reduce the complexity of the codebase. This is hardly an argument against adding these features but more complex languages tend to become less accessible to newer developers and adding complex syntax and parsing rules can result in confusion. Thankfully these operators are effectively syntax sugar and can be learned after learning the “long way” involving proper null-checking, before these operators are introduced.

Posted By: BC_Programming
Last Edit: 24 Jun 2015 @ 07:17 AM

EmailPermalinkComments Off on C# 6 Features: Null-conditional Operator
Tags
Tags: ,
Categories: .NET, C#, Programming
 20 Jun 2015 @ 12:07 AM 

More babbling about BASeBlock. It’s actually rather sad in a way because I would actually prefer to work on my work projects than on my own, simply because there is so much code involved in the changes I want to make to BASeBlock.

My biggest mistake when originally writing BASeBlock was in using the built-in .NET Serialization capabilities. The biggest problem with doing so is that the data stream is not very accessible, data errors are difficult to localize, and it is basically a huge nightmare- not to mention that there is no guarantee of data being portable from one build to the next. This was actually why I created my XML Serialization library a few months ago, “Elementizer”. The aim of Elementizer is to provide XML save/load functionality and have it implementable in a very similar fashion to ISerializable. This is in contrast to the existing XML Serialization solutions I found which tend to rely on saving and restoring public properties, and I do not want to change my object heirarchy and how values are exposed simply so they can be saved/loaded by a XML library. Right now my task is quite monumental- I need to go through and add support for my IXmlPersistable interface to every serializable class in the project. I’m trying to do it peacemeal and do a bit of testing as I go (so I don’t have to just press F5 later and hope it all works!) and while I’ve only got a rather basic amount working it works alright- I’m able to save and load a few block types to and from XML. The real question is going to be what it looks like with an entire LevelSet, which naturally requires quite a lot of other classes to support the feature. The biggest issue was adding support for some less-than-standard data types to Elementizer, such as Bitmaps and certain data types like DateTime and TimeSpans, which themselves implement ISerializable but for obvious reasons can’t implement IXmlPersistable. My solution consisted of using Elementizer’s ability to add deserializers and serializers for specific data types and I just slapped those into the Standard Helper.

It’s a daunting task but it is very sad seeing something that I used to take so much pride it be sort of abandoned in an unfinished state. And I think it is the Serialization that really keeps me from getting motivated- if I can fix that to use XML, I might be more inclined to fix other issues with the program, much like how I started to fix the GameState implementation. And, it will serve as a great example for Elementizer, since the serialization that BASeBlock needs is quite complicated- it needs to save an EditorSet which has lists of sounds and images that are added on and optional music, as well as a LevelSet which has sets of Levels which in addition to their own properties such as music and themes also have a set of various blocks and block types as well as Balls that the level starts with- so I won’t be able to really test saving very well until later.

The one great advantage of the ISerializable Interface implementation is how I was able to utilize it for the Copy-Paste feature of the Level Editor. I actually think the level editor is probably my favourite part of the program, actually.

Posted By: BC_Programming
Last Edit: 20 Jun 2015 @ 12:07 AM

EmailPermalinkComments Off on BASeBlock Babble
Tags
 11 May 2015 @ 11:50 AM 

A bit of a shorter post. Sort of a “progress” report on some of the personal stuff I’ve worked on recently.

BASeBlock

I’ve come to form a love/hate relationship with BASeBlock. This is mostly because there are a lot of things I like about it’s design, and a lot of things I hate, and the things I dislike tend to be difficult to change. Some of the basic dislikes includes a lack of DPI support and how it won’t actually scale to larger sizes. On my monitor it is now tiny which is annoying and pretty much trash in the form of an action game. I’ve brainstormed a few solutions. The simplest would be to simply scale up the bitmap that get’s drawn to the screen. That is still a pain but is doable. Another would be to go a step further and actually scale everything in the game itself to larger sizes. That would be a rather large undertaking, to the point that I’m not even sure it would be worth the effort. I made a few minor revisions to try to get it to scale using the first method but ended up shelving that work for the moment. It’s rather disappointing to find such glaring problems with your old projects that you put so much time into, and almost painful to even consider just shelving the project entirely and just moving on. I certainly made a lot of mistakes with BASeBlock but I think it does well for a game using such basic capabilities (GDI+ drawing for a Game is rather unorthodox!).

Prehender

3-D programming is incredibly annoying and uses math that is far beyond my abilities to actually comprehend. Viewmatrices, rotation matrices, dot products. It’s basically a case of Googling to find out how to do things, then hoping I can figure out how to get the math to work with OpenTK. Nonetheless, I have managed to make a bit of progress.

As with BASeBlock and realistically any game I make going forward most likely, it’s primary purpose is for learning stuff. BASeBlock is at this point “learning” how to refactor an old codebase to improve it, whereas originally it was for learning C#. Prehender is going to be both applying the design techniques I learned since creating BASeBlock as well as being my first 3-D game. With that in mind, it is a rather simple concept.

Originally, I was going to just create some sort of 3-D Block breaker. I have a rather unhealthy fetish with them or something. But I decided to change it up a bit. I decided to “steal” a bit of the design of the 2-D Game, “Spring-up Harmony” which effectively uses a physics engine, and you shoot coloured balls at coloured blocks. If you hit a matching block it will “loosen” from the static background and will interact with other blocks. Then you can catch them with your “bucket” at the bottom of the screen. I haven’t worked out all the details but right now I have it so you shoot coloured balls at an arrangement of cubes, and when a coloured ball touches a coloured block, the block loosens and will fall. I haven’t actually figured out the gameplay specifics, though. That does bring me to the title, though- 3-D programming is quite difficult. I haven’t used Unity before, I may give it a go at some point, however my interest in creating games is typically in what I can learn about actually making them- Unity seems to be more for people interested in making games, as it abstracts some of the parts I find interesting. But in my case, I’m using C# and OpenTK. Unfortunately this means I get the fun of dealing with concepts such as Projection and View Matrices, Dot Products, cross products, and the like. My math also fails me as I’m not able to determine the Camera position from the projection and view matrix, which is a bit goofy when I want to shoot the balls from the position of the camera.

On the bright side, this does make it (IMO) a more useful learning experience. I find it rather strange that I’ve had to resort to third party libraries (OpenTK and BASS.NET) for providing 3-D display and compressed audio capabilities into my C# Program. XNA has been rather left behind (Though still works) and it has a few omissions that I found frustrating when I was working on BCDodger. I would hope that .NET is given first-party support for creating games in the future that makes the task much easier but allows us to use the full power of .NET and C#. Sort of an XNA successor allowing us to also publish to XBox One. (Heck if such a library was made available even at cost I think I could justify an XBox One.)

BCSearch .NET

BCSearch, my VB6 program works, but working on it is pretty much a non-starter these days. I am impressed with the patience I used to have working with Visual Basic 6 only 7 short years ago. Some features of the program will simply not be brought to completion.

Instead, I would like to create a modern WPF Windows Application that uses modern programming (and async await and such) for the same purpose. The effective goal is to create a rather straightforward on-demand search program. This differs from standard Start->Search and the search tool of Windows Explorer in that it is a full application oriented around searches and dealing with the results of those searches. I often find myself trying to find files based on rather specific criteria, and in that context I can see myself using an imagined BCSearch.NET that allows me to write a short C# method in a textbox for filtering each file. This would also allow me to rethink some of the weird architecture decisions I made with BCSearch, while also allowing me to work with WPF again (my work is almost exclusive Windows Forms, and the last time I really worked with WPF was with BCJobClock).

Posted By: BC_Programming
Last Edit: 11 May 2015 @ 11:50 AM

EmailPermalinkComments Off on 3D Programming is still hard
Tags
 05 May 2015 @ 10:53 AM 

After my recent minor troubles with web hosting and domain name weirdness,I decided to look into possible ways to branch out, or improve the site. While discussing the issue, I was reminded of Azure.

Microsoft Azure

Microsoft Azure is essentially Microsoft’s cloud computing service and platform. I must confess that I knew very little about it (not much more than I knew about most web technologies, to be honest) but as I had some Azure credit I decided I should at least make use of them to try to learn something. If there is one thing I haven’t been doing quite enough of lately, it’s branching out and learning new things. It’s one of those things that it seems like even with all the time in the world, keeping up with it will be a struggle. At any rate, I dove in.

Setup was surprisingly straightforward. I was quickly guided through a series of steps and able to setup a Windows Server VM. My understanding, so far, of the service is that you can create a VM which then runs endpoints, cloud services, and web apps. Depending on how you configure it and how many of these you setup (as well as your chosen specs for the VM itself) you will use differing amounts of credits. Effectively, how much traffic you get will be the main determining factor.

My first hurdle came with the Azure SDK. After a few failed attempts, I decided it might be time for a reboot- just to make sure that wasn’t related. What do you know- it worked, and I was able to install the SDK. With that installed, I opened Visual Studio 2013 and was able to create a new ASP.NET project. I chose a basic Razor sample web application.

After this was setup, I was able to publish the project directly to Azure via a publish option shown in the lower pane view. “So far Visual Studio and Azure had certainly worked for me” I thought, as I pointed my browser at the new website.

Server timeout, was the response to my optimism. After some head-scratching and googling the problem, I discovered I had missed an important step- I had not added a new “endpoint” to Azure. I needed to add an endpoint for Port 80, to allow HTTP traffic. After doing so, my example website worked like a charm. of course I still have no idea how it works, but now I’ve got a very reliable and easy-to-use platform on which to play with some of the web-based capabilities of .NET. This could mean great things- if I’m able to get a grasp on web applications in C#, it may be worth it to create a new Azure subscription for the purpose of a web application for managing BASeCamp Downloads. My current “technique” is over 5 years old now and it’s built using old, crusty PHP code I wrote while learning PHP, and I’ve actually forgotten how a lot of it works- so if I can create something via C# I may be able to make something that is more powerful and may allow for better integration into my existing applications. At the very least, it would be interesting since I could create a Service-type program which sits in the background and can address requests from various Updaters and interact directly, rather than via HTTP; or the data could be piped via XML in some fashion, etc. The usage of Azure opens up these possibilities and in ways that encourage experimentation.

I’d include a link to the Azure instance, but it really is effectively a fiddled-with version of the default template. I have a lot of learning (and catching up, arguably) to do to get up to date with many of the new design methodologies that are put into play. It is much different from the “seat of your pants” style that PHP seems to encourage. I think the trick is to think of something interesting and that I might find useful to create via an Azure instance, and then work towards that goal, learning as I go. It worked for BASeBlock, after all.

Posted By: BC_Programming
Last Edit: 05 May 2015 @ 10:53 AM

EmailPermalinkComments Off on Wherein I dive into the Azure cloud
Tags
Tags: , , , ,
Categories: .NET, Azure
 24 Apr 2015 @ 7:21 PM 

BASeBlock was one of my first projects that I wrote in C#. I wrote a program that sort of worked like HijackThis and a INI file reader class- which I Discussed 5 years ago (That long? Amazing), But BASeBlock was my first attempt at creating a project using a language that wasn’t horribly lobotomized. (I refer to Visual Basic 6).

I’ve found myself avoiding it somewhat for quite a long time. It is using code that I have since extracted, repurposed, and improved (such as my update library) for other projects. Another problem is that there are some glaring architecture issues in it’s design (when isn’t there) which were because I was unfamiliar with certain design patterns. For example, my game state management is a switch in the drawing and game tick routines on a game state enumeration, whereas a better design is to use a gamestate interface of some sort and have your different game states compartmentalized better.

However I’ve more recently come to rather like one aspect of BASeBlock. I designed it. I wrote it. While I imagine there are some helper classes and such which I may have acquired elsewhere, the bulk of the implementation is me. There is an aspect of that that I find particularly tantalizing, especially compared to my work. Don’t get me wrong I do love what I do and I have a lot of input in engineering decisions that affect my work, but like any software it is designed to a certain requirement, and with a certain timeline, and a lot of that simply isn’t mutable.

This brought my personal projects into new light for me somewhat when I think of it this way. For some time I’ve only thought of them in the back of my mind as a burden- after working 10 hours dealing with invoice printing considerations, I’ll remember my personal projects and feel bad that they have fallen so far by the wayside they’re stuck in the radiator. But I also forget that, unlike my work- my personal projects have no external director. I can add, change, remove, refactor, and redesign anything I want, and I have to answer to nobody- I’m “in charge” of what they become and how they get there.

Which that in mind I’ve taken it upon myself to actually start progress on making BASeBlock more palatable for me to actually work on. The GameState oddity is like an unsightly mole or other minor annoyance- you don’t notice until you have it pointed out to you (or in my case, until I learned of the pattern, and used it successfully in my poorly named Prehender and BCDodger). It is a major change/refactoring that I wasn’t really keen on doing even when I was working on the game almost daily and had a fairly good understanding of it’s architecture and design, so trying it now is perhaps putting too much faith in not only my abilities but also in my abilities when I was writing it, but if I want to improve it, I need to eliminate that unsightly implementation or I’ll just avoid it until I do.

What is this “GameState” implementation?

In my haste, I did rather forget to explain the particulars of what I was talking about when I talk about “Game States”. Game states are basically what state a game is in and are rather commonplace. A Game will have a different “state” for being paused, showing a menu, showing an introduction sequence, etc. an “Enumeration-based” approach like the one I described might implement things like so (halfpsuedocode)

The basic architecture is to have a switch or similar style of conditional processing within any of the routines which will act differently based on the games current state. This does the task and works as intended, but it tends to lead to long rambly routines, and then all your different states get mixed up in one function. The interface-based approach creates an interface and then each State will be a class that implements that interface. This can be implemented in a number of ways, but the effect is to separate the information and implementation required for each state to a separate class. This allows you to add new features to a state without affecting the “namespace” of other states or interfering with it’s variables, which is sort of the entire point of having separate scope abilities to begin with. It also allows some interesting Chaining abilities. If the Running State stores all the information about game objects, for example, and knows how to draw or tick those objects, a “Slow Motion” state could simply delegate to a provided standard State but only call the tick once for every two calls; a Pause screen could not call the Tick function of a provided composite class, and instead call the draw method and then render a 25% shaded box atop it, or apply a color transformation to wash out the result, or a pause logo of some sort on top to provide the “Pause” effect. An “introductionImage” type state may have a single purpose- you give it an image and a GameState, and it will fade the image in, wait a few seconds, fade it out, and then set the current state to the provided state. Games often show various startup logos, and this can be used to easily fade in and fade out through numerous images and then go to the main menu (presumably a Menu state), and so on and so forth. This can all be implemented, of course, with the enumeration method but it requires a lot of plumbing which also tends to get in the way of everyday development and iterative design.

Posted By: BC_Programming
Last Edit: 24 Apr 2015 @ 07:21 PM

EmailPermalinkComments Off on Back to BASeBlock
Tags
Tags: , ,
Categories: Programming
 03 Apr 2015 @ 3:26 AM 

Somehow I’ve managed to never write about my Debug log class, looking through my post history.

It’s a versatile Debug Logging class that effectively hooks into and allows tracing of Trace.Write and Debug.Write method call output. I use it to redirect all Debug.Print() output to a text file for later examination. Some of my original considerations included being easy to use and add to existing software programs, as well as being able to do it’s job with as little interaction as possible. I’ve been able to use this successfully in it’s original program (BASeBlock) as well as inserting and using the class for Debug log functionality in software created and maintained as part of my Job, and it has worked wonderfully.

Example usage is straightforward- you enable logging by simply accessing the “EnableLogging” property; typically I set it to true for obvious reasons. The Static initializer of the class sets everything up from there:

And BAM! We’ve got a fully functional debug log- after the debug logs become a week old, they get purged, too! How is that for convenience?

Posted By: BC_Programming
Last Edit: 03 Apr 2015 @ 03:27 AM

EmailPermalinkComments Off on Debug Logs- a C# approach
Tags
Tags: ,
Categories: .NET, C#, Programming
 30 Mar 2015 @ 1:12 AM 

We have had a lot of different options for creating Zip Files in .NET Applications for some time. .NET 4.5 has added built-in framework-based support for Zip files, which is a very valuable tool. The absence of built-in ZIP support meant there have been several useful libraries that provided that capability. In this post I will be comparing three such alternatives- DotNetZip, SharpZipLib, and the built-in .NET Framework 4.5 implementation.

In particular I am focusing on ease of use- how much code does it take to create a zip file? Libraries that provide these capabilities often fall into categories- libraries which make something possible, and libraries which make it easy.

First, we should look at the “testing framework” that will be used. The idea is straightforward- we want to simply have each one zip up a given folder to a given zip file, with different implementations. an Interface is the obvious choice:

A single-method interface. We’ll create an implementation for each of the selected libraries implementations, then test each one. Though performance is not the primary focus, we’ll go ahead and try to implement a basic average/total framework over 100 runs:

Nothing fancy- just as described above. A short helper will ensure the folder exists and the target zip does not when running one of the instances, simply so we don’t need to implement it in every single one.

DotNetZip

DotNetZip is the one I was most familiar with before this particular experiment, having used it in a few projects.

Incredibly straightforward, overall- create a new Zip File, add the directory to it, and save the zipfile.

SharpZipLib

I don’t remember using SharpZipLib but I do remember discounting it over DotNetZip for some reason when I was originally looking for a ZIP tool. I was reacquainted with my reasoning in the process of writing the implementation here, which should be fairly obvious:

This is just plain silly- this I suppose falls into the category of a library that makes something possible but doesn’t make a big effort to make it easy, or leaves out higher-level capabilities. Effectively when using SharpZipLib you’ll need to deal with the insertion of each ZipEntry yourself, or create your own wrappers for it. The wrappers are not super difficult to make but if you already have a zip task you want to write simply that is more overhead that needs to be considered.

Framework 4.5’s System.IO.Compression

The Framework implementation is as I mentioned a great addition to the framework. It’s usage is also surprisingly easy:

If you include a reference to System.IO.Compression.FileSystems, you get access to some helper capabilities such as the ZipFile class, which I use here- the method is literally identical the interface method I defined myself.

I think the built-in .NET Version is the clear winner here, but DotNetZip is certainly a better alternative if using the 4.5 Framework has it’s other considerations. SharpZipLib is surprisingly unfluent and requires a lot of boilerplate to be used well, but it is an excellent low-level library for compression overall. Additionally, we have the performance considerations. After a single run, the program emitted the following results. I was testing with a reasonable set of files including a number of PNG images, text files, source code, and other data.

DotNetZip comes in first, with the Framework lagging just behind. SharpZipLib executed a full second longer with each execution, which may be due to the lack of optimization within the program itself (Debug mode) since more of the processing was actually taking place within the code in the project. Unfortunately, this turned out to not be the case- setting the configuration to release did not significantly improve the performance of the SharpZipLib implementation, though it may simply be a less-than-optimal implementation. However if so, that does raise the further point that having to write your own boilerplate means you may not write the most effective and optimal boilerplate for a given task.

Posted By: BC_Programming
Last Edit: 30 Mar 2015 @ 06:10 AM

EmailPermalinkComments Off on File Zipping in .NET
Tags
Tags: ,
Categories: .NET, C#, Programming
 09 Dec 2014 @ 10:05 PM 

I found this to be an interesting discovery. I always somewhat expected each .NET language to work in a similar way with regards to things such as field initialization, but as it turns out, C# and VB.NET work differently in this regard, and in both cases it is due to design decisions with the language themselves. To best show this, I created two equivalent class heirarchies in C# and VB.NET

VB.NET:

C#:

Both are effective a base class with a non-default constructor which has a static field and a instance field, and a class derived from that class which implements a similar non-default constructor and sets a derived instance which along with a static field are both initialized at their declaration, then creates an instance of the derived type.

I breakpointed all statements in the program, and traced through each one. in C# the progress was:

  1. Derived Static field initialized
  2. Derived Instance field initialized
  3. Base Static Field Initialized
  4. Base Instance Field Initialized
  5. Base Constructor execution
  6. Derived Constructor Execution

In VB.NET, we have the following order:

  1. Derived Static Field Initialized
  2. Base Static Field Initialized
  3. Base Instance Field Initialized
  4. Base Constructor Execution
  5. Derived Instance Field Initialized
  6. Derived Constructor execution

This has interesting repercussions. for VB.NET the main repercussion is that if you call a virtual (Overridable) method from the base constructor, within that virtual method the instance fields will not be initialized, whereas, with C#, they will be. On the C# side, it is likely the reason that derived instance fields cannot be initialized by calling an instance method, because the initialization of instance fields occurs before the base class static and instance fields have been initialized, so the class state within that method would be difficult to predict. Arguably, it seems that Visual Basic .NET takes a more “You probably know what you are doing” approach, whereas C# is more careful and “safety” conscious.

Posted By: BC_Programming
Last Edit: 09 Dec 2014 @ 10:05 PM

EmailPermalinkComments Off on C# and VB.NET: Field initialization differences
Tags
Tags: , ,
Categories: Programming
 29 Oct 2014 @ 3:04 AM 

It is a rather basic concept. The idea of saving some state within your program to disk, and restoring it later. Particularly when you are dealing with an object graph in memory and want to restore it. Unfortunately, the easiest way isn’t always the best way.

BinaryFormatter

Interestingly, .NET actually contains built-in serialization capabilities. The basic premise is that your class implement ISerializable and also implement a constructor and a specific constructor, as seen here:

This method does work, really- it’s not super hard to use and setup though it can be a bit of a pain in the butt to maintain. Of interest is that you can GetValue() and AddValue() arbitrary objects, as long as they are also ISerializable. You can use particular Formatters to take your Serialization Information and save it. BinaryFormatter is in particular the one I found most reliable.

There are however some rather significant issues. The first is that you really don’t have a lot of options when it goes to actually serializing data. There is BinaryFormatter and a few JSON converters which don’t work particularly well. The main issue is not so much the underlying interfaces and requirements, but really it’s two-fold; there are few reliable IFormatter implementations that you can rely on from launch to launch (BinaryFormatter fails very easily, and the errors are rather generic) and additionally when dealing with deep object heirarchies small mistakes such as forgetting to mark a method as virtual or forgetting to implement a constructor can cause hard-to-trace bugs in the program.

I speak mostly from my experience writing the logic in BASeBlock to save and load Levelsets. It has been some time, but the serialization nightmares still pester me. Additionally, it bothers me that the Binary format that the files end up as are not very transparent; I cannot easily look inside them without deserializing them in the game editor and if it fails- well, delete it and try again. This rather dampens my attempts to create a “standard” levelset that shows off it’s capabilities.

Recently I set to the task of switching to a new Serialization scheme. I quickly gave up when I realized how much work it would be and just how much code I had written and how many classes needed changed and so on. For that moment I rather gave up. Ideally, however, I would be able to save to XML, ideally with the XDocument/XElement logic. Then save load from XML in much the same way as now. Originally I thought “simple, I’ll just make something like what I already have but create methods that serialize to a XElement and constructors that accept and read from an XElement. This framework would work, but the thing that bothered me is that it was duplication; I had two completely separate but similar save methods strewn about. I gave up on it at the time.

I did attempt previously to create a way to serialize and deserialize from XML via the Formatter method, but this has some rather troubling issues. The main one is that you cannot access the property bag of the object (the SerializationInfo); otherwise it would be relatively straightforward; just take the propertybag of t =he main object and save it and it’s descendants to nodes and attributes and values and such. But this does not appear to be the case. Instead, you serialize in place to a stream, serializing each object directly to the stream. It might be possible nonetheless but it will certainly require that I rethink my approach. At any rate for the “long-term” goal, BASeBlock would be greatly serviced by simply having it use XML files rather than binary files, if only for compatibility.

In looking over BASeBlock while writing this, I’ve come to find a lot of older code that I thought was quite robust which, in the process of my work I have copy-pasted into classes for our products which have subsequently morphed in form, function, and in generall been extended vastly in capability. Some of these I even discussed previously on this blog, such as my DebugLogger. I’m uncertain of how “safe” it would be to copy them BACK to BASeBlock, so I’ve not done so; I’d rather keep my personal projects and work projects as far away from each other to prevent “code ownership” issues. If I copy code from my personal projects to my work projects than from that point on I like to consider them “forked”. But this has the additional issue- If I improve the work version, would writing the same improvements to my personal version still cause it to count as belonging to my employer? It’s a tricky question which I’ve pretty much avoided altogether by taking the rather unsavoury approach of avoiding my personal projects (though to be fair the real reason I’ve not gotten back to them is simply due to time constraints). At any rate it is interesting to think that at any one point a programmer/developer might have code or programs they are proud of, but a few years down the line they look back on that program in disgust. BASeBlock doesn’t quite fit that criteria, but parts of it do. Components and classes that I used to consider excellent, robust, and awesome have ended up getting improved and now that old version feels like getting into a go-kart after driving a Pagani. I like to think this is a good thing. At the same time, I do wonder if perhaps I should try to create personal projects in another programming language just to “top up” on that language. Continuous self-improvement is particularly important I feel but I’ve also not exactly followed my own advice on that front for a while. I’ve got less time to work on this blog than I used to and in some ways that bothers me. Additionally I feel severely outclassed by the C# expertise I see in the insiders mailing list as well as C# community that I’m almost skeptical I belong there. Then I think about how that might fall into Scott Hanselman’s “imposter syndrome”… then I think that only somebody subject to the Dunning-Kruger effect would say that. Then I think that only a person with imposter syndrome would think they were subject ot the Dunning Kruger effect for thinking they had imposter syndrome, then I think….

Posted By: BC_Programming
Last Edit: 29 Oct 2014 @ 03:04 AM

EmailPermalinkComments Off on Serialization Pitfalls
Tags
Tags: ,
Categories: Programming
 16 Oct 2014 @ 7:30 AM 

Console applications are fairly common for handling simple, routine tasks; sometimes the task is straightforward and otherwise runs on it’s own with little to no user input. Sometimes it has to generate a lot of output that isn’t really necessary. But inevitably, we find we want to launch one of those Console applications from a Windows program, and in order to integrate well into your program you figure you should do something other than just have the program appear in a console window. Enter Standard handle redirection.

Launching a Process in C# is fairly straightforward:

This is just one way to do it; another common approach is to create the ProcessStartInfo structure and use that as part of Process.Start(); this won’t give you the process object until it launches though- that can be troublesome, particularly if you decide you want to standard output, input, or error streams.

There are a few different approaches to redirecting the standard handles from within the .NET Framework. You can set the RedirectStandardOutput, RedirectStandardInput, and RedirectStandardError properties of the ProcessStartInfo to true, and then manipulate the StandardOutput, StandardInput, and StandardError Streams yourself. This can make for very complex code if you want a responsive design. A better alternative is actually built into the Process class itself- and that is to actually use an event-based approach and have an event fire when and only when one of your redirected output streams has output. There are a few gotchas in this approach that can trip you up if you aren’t careful though. the appropriate ProcessStartInfo setting, RedirectStandard* Property should be set to true; UseShellExecute should be false, and “EnableRaisingEvents” on the process should be set to true. Connect event handlers to OutputDataReceived or ErrorDataReceived, Start the program, and then Begin asynchronous reading of the Output and Error streams with BeginOutputReadLine and BeginErrorReadLine. The events you setup will fire, and e.Data will, for example, contain the line of text that was output. Here is a quick example:

With this you can fairly easily redirect the output and error from a command line (or any other) program, and do with it what you like. You could even parse each output line and present standard input to “emulate” a user running the program. This could be useful for test harnesses as well as for when you use a command line tool but would rather that not be made prevalent- the command line program can be run hidden and you can parse and interpret the standard output as needed to update your UI. (this is in some part how many Linux GUI applications function)

Posted By: BC_Programming
Last Edit: 16 Oct 2014 @ 07:30 AM

EmailPermalinkComments Off on Redirecting Standard Handles – C#
Tags
Tags: , ,
Categories: .NET, C#, Programming

 Last 50 Posts
 Back
Change Theme...
  • Users » 47469
  • Posts/Pages » 388
  • 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.