22 Apr 2015 @ 10:06 PM 

Java has had an interesting feature for some time, Though I must question it’s implementation. Of course Java has been the butt of many jokes about security flaws, and Oracle sought to try to keep customers secure by trying to make sure they are running the latest version. Now, personally, I think the best way to make Java secure is to not allow the software to be used by remote sources such as websites, but maybe I’m just old-fashioned. At any rate, They tried a nagging Auto-updater which complained about Java being out-of-date. They tried having Java ‘expire’ based on looking at the website, at which point it would complain. Their latest work is to effectively hard-code an expiry date within the run-time, which practically forces that run-time to be uninstalled.

Keeping consumers up-to-date makes a lot of sense- they should be given credit for their goal. But, as I said, their implementation does leave something to be desired. For example, if you install Java 8 Update 40- which expired last Tuesday (April 14th) It will install, and then after install it will run the tool which uninstalls old versions. This tool is designed to remove previous versions primarily- to prevent possible vulnerabilities. Unfortunately in that instance it finds that Java 8 update 40 is “unsecure” and uninstalls it.

Great. Thanks. So I managed to install Java, then Java uninstalled itself immediately afterwards because it is unsecure. It receives points for honesty, I suppose. The solution, at that point, is to install a version that hasn’t expired. Unfortunately, this doesn’t at all solve the problem of deploying a Java runtime for applications. Now you need to make sure all clients are running the latest version and update packages include the latest Java installer, because the moment Oracle decides it’s old that version will suddenly start uninstalling itself immediately after installation, leaving the system with no Java installed. Furthermore, this cycle repeats until either the prompt to uninstall unsecure versions is skipped, or you install a version that has not expired manually. Ideally, this process would be more automatic- that is, after all, practically what they are going for. I’m all for Oracle automatically updating the Java version, but I don’t think uninstalling Java and leaving no Run-time at all- while arguably more secure that way- is a good outcome when your software deployment relies on Java.

Posted By: BC_Programming
Last Edit: 22 Apr 2015 @ 10:06 PM

EmailPermalinkComments Off on Java 8 Update Expiry
Categories: Java
 11 May 2014 @ 7:23 AM 

While the title is partially tongue-in-cheek, in that Printing Receipts would generally not be a particularly exciting topic, it still offers it’s own unique challenges. Like many other purposes, The programmatic Printing of receipts actually has a lot of libraries, conventions, and legacy. While it’s surely not as exciting and hardly get’s the coverage of libraries like OpenGL or Direct3D, I think that sort of thing that makes it an ideal topic for a blog post.

The primary challenge when it comes to printing receipts at all is abstraction of the hardware itself. On a Windows system, this can be solved by accessing the Receipt Printer device as you do any other Printer. What you can do from there is use your desired Reporting Tool- Crystal Reports, Jasper reports, etc to do what you want. In my case I used Jasper. For Jasper Reports, there is something of a caveat;In the implementation we were using, we were using Jasper Report’s internal JRViewer control and using that ti display the report. This worked well. However, in adding support for two different compiled Jasper Files (one for a normal printer, one for receipt printers) we encounter the issue that we cannot control what the JRViewer does; if you launch it with a report, that is what it will print if you press the print button.

What are our options?

So close yet so far away- with that one thing missing a goal is within our grasp. How do we conquer this? A good understanding of Java helps. In this specific case the JRViewer control of Jasper Reports was part of our own Java application which we had been using to interface between our C# components and Jasper Reports. To me, the solution seemed almost trivial after some thought- Java has reflection- so we could just examine the internals of the JRViewer control, and redirect the print button to our own Action Listener. This had some drawbacks (in particular, code changes to the JRViewer could break the reflection code), But it worked for our purposes. Observe:

By using reflection, we are able to take control over the JRViewer control and completely redirect click events on the Print button to our own code, which can perform the same logic of the normal Print button but with our added logic for selecting the appropriate report to use (both reports are generated and turned into a JasperPrint based on whether a printer selected is determined to be a receipt printer).

This has a bit of a disadvantage, however, since it requires the POS device to be available as a standard Windows Printer. I’m not convinced this can be considered a guarantee. But what choice do we have?

Introducing Microsoft Point of Service for .NET

As it turns out- and to the surprise of none of us- the task of printing receipts in a general, abstract fashion- without having to custom-code for every possible POS Printer- has been a requirement of countless other companies and individuals for a long time. Microsoft even has a Library designed almost specifically for this service, known as “Microsoft Point of Service for .NET” in fact, the library itself has many parallels to things such as DirectX. It doesn’t completely solve the problem- we still have to manage things involving formats, text, and so forth, but it presents the means by which we can do this.

I’m still learning a lot about it myself, so I can’t really provide anything particularly useful in terms of C# Code. (At least, not yet!). My current approach is to take the hardware abstraction provided by the Library and expand it to create a “Printer agnostic” capability, such that programs can specify what they would like, what can be sacrificed, and so forth, and the Library does what it can using the POS library. In order to use a Printer with the POS library, it needs to be registered and available through OPOS. Every receipt Printer software I was able to download appears to register it’s device for use via OPOS- in fact some of their software provided only that capability, with no Windows Driver- thus the need for this approach since the first one would never work for those.

Once it is functioning and we’ve got it into our own products, I will see if I can make it generic and share it here. Fundamentally what we are building appears to be a “PML” (Printer Management Layer) we are provided a hardware agnostic API which can provide us information such as how fast the printer is, how many characters per line, how wide is the paper, can it print colour or bitmaps? both? etc. and the task is to present as many capabilities as possible to any applications while degrading gracefully when applications want to say print in colour but cannot.

Posted By: BC_Programming
Last Edit: 11 May 2014 @ 07:23 AM

EmailPermalinkComments (2)
 03 Dec 2013 @ 8:19 PM 

Making Programs, Classes, and Source code available for free is a very helpful service to those who would wish to consume that content.

One has to select their audience, however- and know what to expect.

For quite some time I’ve helped with a Plugin called GriefPrevention. Initially, this was because I literally had nothing to do aside from my own personal projects, so I was able to dedicate a lot of time to making very significant changes to address a myriad of problems users of the plugin were having. In some ways, I started to treat it like “my job” (aside from my actual Job of, well, finding one). Most of my Time went into GriefPrevention. BASeCamp/SurvivalChests was abandoned; BASeBlock has been hardly edited since… etc.

A few months ago I got a quite spectacular Job; it involves working heavily with Postgres, C#, SQL, and Java, as well as some legacy libraries and stuff for good measure. Naturally that really only touches the surface of it But the important take-away is that I think it’s awesome. Some work can be a PITA (like making the same slightly complex changes to a query in 19 Jasper Reports) but it beats the hell out of any other Job I’ve had.

I didn’t expect it to be much different. But this rather opened my eyes. The difference between my real work and working on GriefPrevention is quite interesting. Working on GriefPrevention is OK. Fundamentally the plugin is relatively simple. Certainly less strenous than page-long stored procedures used in Reports, or Asynchronous Update Downloading and installation.

But what came as a shock was the fact that much of the time I [i]preferred[/i] to work on work tasks rather than GriefPrevention. I would address WOs instead of GP tickets. To make matters worse, I only get paid for time I put into one of those- take a guess which. Discussions with my co-workers is frequent; meetings take place to plan future additions and changes. The only discussions I’ve had about GriefPrevention are effectively with my inner Monologue since I’m for a number of reasons the only “active” developer (and in this case, “active” means maybe a few hours a week). I work for 8 to 12 hours typically for my Job- I basically go nuts until I’m mentally fatigued. This usually means the chance of any changes to any of my Open Source stuff is nil. It’s sad because I actually play BASeBlock and use BCSearch, and could list off a number of bugs and issues I’ve had with both, but simply don’t have time for them (heck, I didn’t even have time for them when I was unemployed!).


Don’t get me wrong, another interesting part of GriefPrevention are it’s users. This is also one of the parts that makes me wonder occasionally why I bother. I reworked the code arduously over a period of a few weeks around the time I started to work on GP, to address some issues that many people had- per-world configurations and a more flexible configuration for controlling behaviour. Most people are reasonable happy with these changes. However those that are not are like a shrill siren piercing a dark night. In this case, right now, the biggest problems seem to be that Configurations are “complicated”, with any number of suggestions up to and including a complete rollback of the rules feature. I’ve been insulted, both passive aggressively and otherwise, both via PM and through project comments. And then been called “unprofessional” when I respond in kind (well, duh, I’m not getting paid to the requirement for professionalism is a bit less. I doubt I’d be particularly happy if a REAL customer cursed me out, but I’d still be obligated to help them in as professional a manner as possible- not only because I get paid for it but also because I put particular care into my products. Arguably, GriefPrevention is no exception, the difference is that it also represents a loss of my Spare Time. Many folks are reasonably understanding of this situation- Primarily my GP contributions center around Weekends, and most importantly around my own schedule. When an Open Source project starts to feel like more work than your actual Job, it starts to make you ask questions. Then when some people running Minecraft Servers act more entitled from Free Software than Entire Marina’s are of their Line of Business Software, the disillusionment leaves me with no choice but to laugh.

Pull Requests

With Distributed Version Systems such as git through github, anybody can fork a project, make changes, and request those changes be implemented into the main branch. My experience with GriefPrevention has not been promising. With stunning frequency, Pull Requests have basic functionality, make no changes to functionality, completely break functionality, perform basic code cleanup on the source, run IDE Wizards, remove dead code, add extraneous null checks, etc. Usually with any non-trivial PR I have to ask myself, “Are the changes in this PR more significant than what I will probably put into my next few commits?” Because merging a PR is typically a PITA since even if I only update once a week, sometimes PRs are based on a fork from several months ago and make no attempt to merge changes before a PR, leaving that instead to me. What I’d love to see is “Fixes X bug that you’ve been tracking down for Months” in the PRs. YES. Thank you, that is great, no matter the cost of attemtping to Merge it (at very least I can try to figure out the change and what caused the issue to begin with and fix it in the Working Copy, ascribing appropriate credit of course). But what do I see instead? “Ran Eclipse Wizards”, “Removed unused Variables”, “Organized Imports”. etc. Sometimes I can find an ACTUAL fix, but it requires poring over the File Changes in that pull or it’s commits searching for such significance. And then it comes to light that effectively the only useful changes are moving some lines of code so that they execute after some other portion designed to null check. Then I discover that an equal or greater “fix” has been applied to the master branch since, making those “fixes” useless, and even where they aren’t useless, I would have to include all those other changes for them to be added.

If anybody wanting to make PRs against GriefPrevention is reading this, DO NOT EVER run any IDE cleanup wizards on the code before issuing a PR. Your PR WILL need to be merged against a later version after more commits and using a wizard WILL touch every file, meaning that you will force a conflict that requires resolution. I’d be all for merging a change to fix some critical bug occurring because recent commits made a change to the same file. Not so much when the PR touches every single file to sort the imports list at the top of the file, thus forcing a merge conflict with changes that occurred since.

Posted By: BC_Programming
Last Edit: 03 Dec 2013 @ 08:19 PM

EmailPermalinkComments Off on An Open Source Vent
 20 Sep 2013 @ 2:46 AM 

The observant may notice that there have been a rather significant drop in my post frequency over the last month or so. This is because I’ve managed to get a very nice job in the industry working in C#, Java, and things like Jasper Reports and Postgres, therefore I’ve been very busy. Also, When I did have time, I just couldn’t come with anything to write about that I could finish; the only thing I could think of was that ubiquituous generic ListView Sort Handler class but that would take a while to write-up again.

Then I thought, why not find something interesting in my work that I can safely talk about without breeching my confidentiality agreements? Easy enough. So I’ve gone with Mixed-Language concepts.

I have a book published in 1994, titled, “Mixed Language Programming” (ISBN 1-5581-332-9). My recollection of it’s content was that it speaks mostly of interoperation between Visual Basic, C/C++, Object Pascal, and even Word/WordBASIC. Even then the idea was pretty unique- to have a single goal be accomplished by more than one Program was on the very edge of what was considered sane- but to use two or more completely different Programming Environments was considered more trouble than it was worth.

Nowadays, interoperation is usually easier. Many sets of languages share the same application platform. For example .NET Languages all compile to CLR and need to support the Common Type System (CTS); they can use the Base Class Library as well as libraries written in other .NET languages, as long as they conform to the CTS. This means that integrating Visual Basic .NET, C#, F#, IronPython/IronRuby and similar .NET language implementations is relatively easy and more “first-class”.

The Java platform is another one that has a wealth of Development languages that run on it. The Virtual Machine and Run-time have taken a few different routes on the design path than .NET (Type Erasure comes to mind) but is still a useful platform. Scala, Java, Clojure, Groovy and Jython can create and consume standard Java libraries.

Fundamentally what has assisted the more common occurrence of Mixed Language Programming (or at least made it so mentioning it at a social gathering was no longer a social faux pas that caused the room to go quiet) Is these differnet platforms that not only make it easy but practically encourage it by making different languages have their own unique capabilities.

This does bring me however to the idea of [i]cross-language-platform[/i] Programming. In many ways we’ve simply expanded the barriers; In, say, 1994- Programming Languages and their compilers/interpreters were more or less proprietary and they had their own set of concepts. Some Programming languages called something an Overlay; others called it a module; others still referred to them as libraries. So you got a mixing of technical jargon. While most Programming languages compiled to the same Object Code Format, there were still considerations such as Name mangling that could make accessing and using that Object code as imports from another language difficult or even impossible. This is part of why it was typically not worth the hassle; Even if Language B made a certain task take half as much time, you would lose that advantage and fall behind time wise simply because of trying to have to figure out the specifics of your compiler and languages and how they would interact at the binary level. Now it is a question of how to move across platforms; for example, how do you communicate between a C# application and a Java application?

There has been quite a measure of success in this area. First, it was determined that the .NET runtime was almost entirely a superset of the Java run-time, so IKVM was born. IKVM is actually a Java runtime that runs on top of the .NET CLR. This might seem weird or pointless but in doing so you both eliminate the need for the Java runtime but you also gain the ability to more closely couple your .NET and Java logic to work together. Your C# Application can directly access the classes and properties of your Java Application.

However, for my case, our “problem” was more or less that we were using C# for the bulk of our work but it was decided (before I was around at any rate) to go with Jasper Reports to update the Reports. (I use Update because fundamentally it’s a move from an ancient system and codebase to a new, modernized one). I Did some experiments myself with trying to get Jasper reports to run as a .NET assembly and I imagine I could have got that working but there is something fundamentally- “untrustworthy” about doing so. I mean you are changing a rather full-featured library designed to run on the Java Platform and making it run on another, completely separate, platform. Even int he best case there is still the threat of problems. So I decided to take the easier route and simply write a Java wrapper application that could expose the required functionality to a C# Application by simply being called with Command-Line parameters. Of course this is the simplest way of Cross-language communication but it works fine in this case because there is no need to communicate with the launched Java application beyond the passed parameters. One issue that did appear is that the C# application could not easily pass arbitrary parameter types to the resulting report- such as Images or other element types. This resulted in some of that logic being moved directly into the Java Application since it does have direct access to Jasper to add parameters in whichever format it wants to.

The entire thing was actually pretty interesting. I hadn’t made a Java Swing Application for a rather long time and I learned a lot about that, even though I just needed one JFrame with one Report Viewer control. the C# Application that invokes it passed in parameters and information for filtering results, but it also is generic and used for multiple Jasper reports. The data about what inputs to provide and how they get passed to the Java application and subsequently passed as parameters to the report where they get used to control queries, is retrieved through XML files. Here I learned to use XDocument (conclusion: XDocument rules). The Filter application itself is designed to be invoked through the Command Line. This is something that I originally felt was a bit silly but it does make sense on the level of simplicity; Arguably, these components- which are never invoked on their own- could be made separate class libraries, but that would complicate testing, it would complicate deployment, and it would essentially add complication. Overall it was decided that if we limited the actual interface between the different portions to the Command Line, it would be easier to track down where the problem is. I’m still not 100% convinced but at least now I know there were some good reasons and a decision making process behind it.

There is a lot of mixing, because the older system is, well, older. It also uses different data formats and therefore there is interoperation there as well. Connecting to remote mainframe systems, grabbing indexed records created in BASIC, writing them to a Database which then get’s accessed with standard queries to recreate the functionality of the original in a modern environment.

Posted By: BC_Programming
Last Edit: 20 Sep 2013 @ 02:46 AM

EmailPermalinkComments Off on Mixing Languages in Real-World Applications
Tags: , ,
Categories: .NET, C#, Java
 01 Sep 2013 @ 6:40 AM 

I believe I’ve mentioned in posts here on the blog as well as news entries on my main landing site (bc-programming.com itself) regarding my “maintainership” of a popular Bukkit Plugin, GriefPrevention.

I’ve fundamentally changed a lot about the way GriefPrevention works in the existing Development builds. Some people love the changes- others hate them.

Anyway, the reason I am making this post is because It’s getting a bit behind in terms of actually having a proper release- right now the dev builds usually work fine, though there are occasionally rather big issues in new features that cause data loss or ‘damage’ to claim data or other information that would definitely be a big blooper if they were to make it into a “sanctioned” release, or even a beta.

It would be easy to simply select an arbitrary development build, call it a beta, and upload it to the bukkit page as such. However, Personally I would guess that such an action should also include rather copious documentation and very much a re-consideration of pretty much everything written about the plugin so far. A lot of the existing pages written for the plugin will need to be changed extensively.

One of the issues raised is the ‘complexity’ of the newer configuration setup. IMO it’s not so much more complex as it is separated. If you ask me the previous configuration was more complex because settings that seemed unrelated would directly affect one another; and some settings didn’t even act as one would expect. The biggest issue with 7.7 and earlier was the refusal to properly deal with worlds and MCPC+ style servers. This was heckled along by the fact that the changes were insisted as being “impossible” or “requiring a rewrite”. I managed to coaz the changes in by simply changing how claims were loaded; this was also helped along by refactoring the configurations to work on a world-specific basis, which had the advantage of already separating functionality in a world-based manner and gave a basis on which to add new world-specific features.

The primary consideration once a Beta or even Release version of 7.8 is available is that the plugin needs to be reasonably well documented, both in terms of the plugin itself as used by consumers as well as in terms of the changes to the API itself. Another consideration is that it would be ideal to be available for questions as well as be watching the comments page like a hawk to answer questions and comments on the new release, since it’s likely that in promoting the dev build as a beta there would be numerous questions, problems, and general migration considerations being raised and a timely response to such questions would certainly be the ideal situation.

Posted By: BC_Programming
Last Edit: 01 Sep 2013 @ 06:40 AM

EmailPermalinkComments Off on A tidbit on GriefPrevention
Tags: , , ,
Categories: Java
 29 Aug 2013 @ 2:35 AM 

Parameters and Arguments passed on the command line are something that we simply cannot seem to get rid of. Even with today’s UI-Centric Operating System and interaction Model, Application still expose a number of features through the use of Command-Line parameters and arguments.

There are a number of relatively complex libraries for dealing with Command Line parameters in any number of languages, most of which aim for the typical Command-line stuff; switches, switches with arguments, etcetera. Many of these are relatively complex; I created a COM Component in VB6 to parse Command Line Parameters and I believe I even created a C# Port to a self-contained file for some of my C# applications.

There is of course a simpler way of creating, parsing, and evaluating the arguments you are provided on the commandline, though many shrink from the idea- it involves simply changing up how you interpret arguments. Rather than switches, you instead simply interpret all your arguments as a set of key/value pairs.

Most Programming language environments will perform the task of actually splitting your command line at spaces. You have to workaround this since it might interfere with your own parsing. Some languages provide a way to directly access the CommandLine your application ran with, as a single string. Others, like Java, require you to simply paste together the arguments you are provided and hope for the best. (Java also has an anomoly when you are trying to pass arguments through a “java -jar” or “javaw -jar” call, too, but I’ll get to that in a moment).

The method I’ve found ideal is to simply have a method that accepts a string and then returns a HashMap consisting of key/value pairs, as present in the commandline. Both keys and values can be quoted to allow for spaces in their names, too. Here is a Java implementation of that Method:

The logic is exceedingly similar to some of the logic that was involved in my BASeParser XP Expression Evaluator. The ubiquitous “inquote” boolean makes a cameo in this Java implementation. the basic idea is that when it finds a quote, it toggles “inquote”; and it will only recognize separators (spaces) and equals signs (used to separate keys from values) when inquote is false. If it finds a space, it will take what it has for a key and the value it’s building and add those to the HashMap it is building. If it finds an equals sign, it will take what it’s currently got in ValueRunner and throw it into the Key. the purpose being to allow the key and name to be enclosed in quotes if they contain spaces, so they don’t get split apart.

An example usage would require the original command line to be rebuilt:

This works by simply rebuilding the arguments Java has so helpfully split for us.

HOWEVER: this does have some caveats. The first seems to be that Java removes the quotations around any quotes entries, and it obviously get’s confused by our non-standard arguments. So we need a custom Join method for this task:

OK so maybe the Join I had was a lot simpler and just a standard Join() that didn’t take spaces and add quotes to each one if they were found. I only realized the caveat involving quotes (which explains the massive mystery that took me 3 hours to solve this morning, which I ended up chalking up to a known netbeans bug, which no doubt did not help clarify the problems I was having. Ideally I would be able to get the pure unfiltered and untainted Command Line; (sort of like .NET’s Environment.CommandLine Property) But there doesn’t appear to be a good way to do that in Java, as near as I can tell, which is a shame.

And that’s that: Now you have a method to parse a command line like this:

Which will give us these pairs:

Key Value
Username billy
password Hunter42
main weapon slarpy Gun

Tada! And now you can add helper methods, or encapsulate this functionality into a class and give it those helper methods, for all sorts of different features that manipulate or return given parameters or sets of command parameters. I personally have a “popParameter()” method that takes the hashmap, a key name, and a default value, and will retrieve the existing value of the given key if found and remove it or if not found return the default value.

Posted By: BC_Programming
Last Edit: 29 Aug 2013 @ 02:35 AM

EmailPermalinkComments Off on Command Line Parameters: A Java Approach
 09 Apr 2013 @ 10:25 AM 

I’ve already covered this topic from the perspective of why C# is better than Java, In my opinion. This time, I’ll go over the differences as even-handed as possible. This has come about primarily because I’ve been working extensively in Java, and find there are features that I like and dislike in both languages. Though I will admit I lean heavily towards C#.

First, how about a little history on them?


Most, if not all, Languages and platforms have a varied and sometimes tumultuous history. The Java language and platform is definitely no exception. In it’s earliest incarnations, Oak, the purpose behind Java was to provide a platform and language to automate appliances. This is not really as far-fetched as it would seem, since most appliances do run some sort of software. If you pick a toaster off a shelf at random you have a good chance of getting something that runs some sort of executable code. The purpose was, presumably, to make this behaviour something that could be patched and changed more easily by end-users; much like how many car owners who are versed in technology will sometimes change the internal firmware to eke out better performance, one could see a person customizing their coffee maker or kettle for specific purposes.

The language, however, proved too useful for such a niche market, and eventually found it’s way onto the PC platform. It was initially met with some rather exorbinant and out of proportion enthusiasm, as Java was cited as the be all end all of all things on the web. Needless to say, that did not come to pass. Java- the language and technology- have now settled into being used for server-side development and the development of applications and games, instead. A purpose for which it is well suited, for the most part.


There are some proponents- who not surprisingly are strongly biassed towards Java technologies- that claim that C# and .NET are a poor attempt by Microsoft to attempt to replicate Java. This is a rather ill-thought claim. While there is some interesting history behind C#, since it appeared relatively shortly after Sub Microsystems revoked Microsoft’s Java License, it’s very likely it was already in development anyway. Even if we go with that assumption and consider that C# is in fact Microsoft’s Java baby, it has still found itself in a very similar- but different- market.

Design Differences

One of my overriding dislikes of the Java language is mostly in the design strategy, which typically avoids the addition of language features if they can be misused. For this reason, Java does not have Operator overloading, Properties, and various similar features, under the guise that it’s easy to misuse them. In a similar vein, it lacks the ability for the programmer to create their own value types, while at the same time presenting somewhat confusing exposures for it’s own primitive types.

Java is a language designed essentially in tandem with it’s bytecode. Java source is compiled into Java Bytecode; this bytecode is an intermediate executable code that is run by a Java Virtual Machine; the Java Virtual Machine emulates a “stack-based” CPU.

C# is also designed in tandem with the CLR, it’s execution environment, but the CLR is designed with the capabilities of other languages in mind. For example, While Java uses every single feature of the Java Bytecode for Java features, C# does not actually exploit all features of the CLR and the IL bytecode that the language compiles to. What makes this interesting is that while all Java bytecode can be “decompiled” to some equivalent Java source, not all IL code can be decompiled to C#. For example, Visual Basic .NET uses a few features of the CLR that are not used in C#, such as Exception filters.


Generics are one feature that is implemented quite differently between each language. The Java approach is to make the feature something that is dealt with before the Virtual Machine runs it. What this essentially means is that, when compiling a generic class, the Java Compiler replaces all type parameters with their type restrictions (the Java docs call them “bounds”). If the type parameter is unrestricted/unbounded, then the compiler will use the Object type. The compiler will insert type casts where necessary to preserve type safety (which includes both code within the generic class as well as code that utilizes the generic class) and generate appropriate “bridge” methods between a generic base class and a class that extends from it.

C#- thanks to the CLR- has full-on support for Generic types. The ramifications for this go both ways. Whereas the Java method of Type Erasure allows your program to work successfully on older Virtual Machines as well as newer ones (because the VM is not changed) you lose out on the ability to use generics through reflection. C#, on the other hand, allows you to create a new Type based on a generic type and the types of it’s parameters, and then instantiate the applicable classes as desired. Reflection is extremely powerful in both Java and C#, but this particular ability can be very appealing for some designs. On the flip-side, however, in order to use Generics in C#, the code needs to be running on the Version 2 CLR; in fact if you compile for a later version of the CLR, the resulting compilation will not work on earlier versions. This is because the CLR development mantra is to work to add improvements to the system as a whole, while allowing legacy code to run without recompilation by allowing side by side installation.

One interesting way to compare the two platforms is with a direct demonstration and comparison of otherwise functionally equivalent segments of code. Now on e might think I would turn to the Java and C# implementations as part of my ongoing Anagrams Series, but since we will be looking at the IL and Bytecode of each, it might be ideal to go for brevity. I’ve settled on a simple program that uses a Generic structure to store 100 values, and then write them out. Here is the Java implementation:

Something of note is that we need to use List rather than List because generic type parameters must be class types. This is sort of a side-effect of the way Type Erasure was implemented, since it essentially inserts appropriate casts to the proper type when the Type parameter is used. the Integer type is a boxing class that is provided by the Java Class Library, and for which the compiler has special considerations for (like the other boxing classes). The disassembled Java bytecode from this is shown below. This is from the main method, and I stripped out the extra stuff about the methods and whatnot.

Edit: Fixed the markup issue. you would think the &ltpre&gt tag would prevent other tags from being identified within, but apparently WordPress still helpfully tries to auto-complete tags when you save a post…
Some take-aways from this. We can see Type Erasure in action starting at the first invokespecial line, which invokes the constructor. The constructor is of java.util.ArrayList. But this lacks any Generic context. As we can see in the future calls, many of the references to and from the List are cast to an Object when being passed and cast to an Integer when being retrieved. This shows Type Erasure in action.

Moving on to C#:

This one is a lot shorter than the Java version because I’ve used as many language and framework features as I thought I could get away with. To say the resulting IL dissassembly was verbose in comparison would be an understatement:

A lot of the verbosity here is due to the explicit referencing of various framework types. it’s also interesting that the resulting IL has an Exception Handler which is most likely attached through scope. That is, scoping braces in blocks will cause any declared variables within to be deconstructed as necessary. This doesn’t run measurably slower than the Java version. Fundamentally, while this IL looks longer (and a reasonable assumption to base on that would be that it’s slower) it’s also just a representation of the internal IL code. Additionally, the CLR has a very powerful JITter that will compile segments of code on the fly to Machine language, which is particularly helpful for looping constructs, or really any code that repeats more than once.

In order to better flesh out differences as I encounter them or learn enough about them, I’ve decided this will be something I shall repeat- a series, if you will. Expect more blog posts on the subject of C# and Java differences. If necessary consider this post a primer and look at their run-times.

Posted By: BC_Programming
Last Edit: 15 Apr 2013 @ 04:10 AM

EmailPermalinkComments Off on C# And Java Differences: Runtime
Categories: .NET, C#, Java, Programming
 01 Feb 2013 @ 10:23 AM 

Randomization is something that is pretty much a staple in games. But the tricky part is randomizing in an expected way.

Some kinds of randomization, you don’t want to be truly random- just mostly random- and you do in fact want it to go through all the possibilities more frequently, though in a random way.

The best example I can think up is to imagine you have a Enemy that can shoot forwards, backwards, up, and down. Now, targeting the player notwithstanding, let’s assume you want them to shoot randomly. If you go with the approach of just choosing a direction completely at random, you will find that the code will often choose the same direction many times in a row. This is more or less the problem with trying to randomize small sets of data. Each selected element is more or less chosen without regard to those chosen before. This fits probability, of course, but can be a bit weird gameplay wise.

Enter ItemBucket

The solution is fundamentally to make sure that items are chosen at random, but also that every item get’s used. The best solution I could think of was one where you choose elements at random, but you make sure you don’t choose the same elements twice during any one run. The class I created for this purpose I called “CItemBucket”. It’s functionality is fairly simple: it is constructed with the items it will contain. This initializes two lists with those elements. The ItemBucket can “dispense” items; when an item is dispensed, it is removed from the list. if the list is empty, it is reset from the Original List. this makes sure that in any number of elements of size N, any element in that list will occur exactly once during N dispenses. My original idea was to return a randomly indexed element each call, but then I got to thinking that, in many ways, we are simply dealing with a “shuffled deck” of elements, and returning items from that “deck”. So, at the cost of making Adding a bit more expensive, I think I was able to make the retrieval method O(n) for the number of present elements (based on the Queue implementation, that is).

Here, the, is the C# Implementation for this class:

Here is some code that consumes this implementation:

Works quite well, as far as I can tell.

But wait, there’s more!

Perhaps because I like to think of myself as something of a polyglot, let’s go ahead and come up with an implementation of this for Java. Now, doing this in Java would be a bit more tricky- that is, directly. Unlike the C# implementation, we don’t have the convenience of lambda’s to make a ‘pure’ shuffle. Instead, we would have to write our own implementation. Instead of that, I went with the original concept- that is, to choose,remove, and return a random index, and re-create the Bucket contents when we’ve emptied it. Here is the Java version of this class:

Test code for the above Java implementation:

As far as I’m concerned, the most interesting thing in the Java implementation is the “RepeatArray” method. Java’s Generic limitations prevent us from creating Arrays of the Generic Type Parameter directly, so instead we need to use some reflection magic. unfortunately, as far as I can tell there is no way to get the class of the actual type parameter in Java, so I had to resort to accepting that class as a parameter. Also, because of the lack of Generators/Enumerable methods, I ended up simply having that method return a List of the generic type, rather than an Enumerable.

It’s not over yet!

You might think, “OK, he’s covered C# and Java implementations- can I please go home. Well, yes, you can. But then you’ll miss my Python implementation! I went with the same approach I chose for Java- that is, retrieving items randomly and removing them. It’s fully possible to use the same methodology I used for the C# approach- using Queues and sorting on randomized keys- but I found this approach a bit less verbose, and more straightforward. And, it is my opinion that ‘straightforward’ is sort of the “python way”, so I went with that.

And, of course, the Python code that uses it:

The first thing that stands out is just how much shorter this one is to either the Java or C# implementations. This is probably mostly due to the dynamic typing of Python, as well as a few syntactic shortcuts. The only “gotcha” I found was that Python didn’t really support overloaded methods. Technically, I could create one method and then verify what parameters were actually passed, but in this case I wanted one to be a Generator Method, and the other to simply return a single element. Only way I could figure out how to do that was to have separate DispenseSingle() and DispenseMulti() methods. It also doesn’t expose the innards like the other implementations, in that you cannot add Elements to an already constructed instance. In retrospect, I’m not really sure if it’s a good idea to make the design Mutable at all. The Most typical use-case would be to construct it with all the elements it will use, and not change it afterwards- that’s the use case I have in BASeBlock, and the use-case I’m considering using my Java implementation for. So having extra methods to add elements, and keep fields “fresh” and consistent adds implementation complexity for little gain.

Posted By: BC_Programming
Last Edit: 01 Feb 2013 @ 11:46 AM

EmailPermalinkComments (1)
 17 Dec 2012 @ 12:33 PM 

Many developers and programmers may describe their experience with a language or technology as them having “mastered” it. But is this really the case?

Take me as an example- I cannot think of a single technology that I feel comfortable saying I “mastered”; even those that I’ve worked with extensively, such as the C# language itself, or the .NET Framework, or the Java Base Class Library, I don’t feel safe saying I’ve “mastered”. The way I see it, “mastered” implies that for any question about that technology, you will have an answer for. I cannot, personally, say that I’ve reached that stage. In fact, it’s debatable whether any person reaches that stage about anything. C#-wise I’ve worked extensively with the framework, serialization, dynamic dispatch (via C# 4.0/5.0’s “dynamic” keyword).

“Mastered” for me implies that there is nothing left to learn for that person in that field; but when you think about it, that’s sort of impossible, particularly in regards to software development, programming, and even just computers in general. There is always more to learn, there is always ground left uncovered, and as you uncover that ground you reveal just how much you don’t know. One of my favourite quotes, attributable to Dave Ward, is:

“the more you know, the more you realize just how much you don’t know. So paradoxically, the deeper down the rabbit hole you go, the more you might tend to fixate on the growing collection of unlearned peripheral concepts that you become conscious of along the way.”

This is from Scott Hanselmans blog post on a similar subject- titled “I’m a phony. Are you?”  In many ways, I find myself identifying with this- For example, I still often try to rationalize my reception of an MVP Award as “oh, it’s nothing” or “must have been a mistake”; that is, like the post describes and quotes, people that feel like an imposter. The MVP Award is not just given away to anybody, though. Best I can think of would be that my Blog posts with regard to C# Programming (and programming topics in general) were that good. Personally I have a hard time really believing that.

Much like Scott Hanselman describes in the post, I try to learn a new programming language- even if I don’t use it for a large project, the exposure to new concepts and problem domains can really improve my work in those languages that I’ve used for a longer period, and hold off stagnation. But even so, very seldom do I ever get deep enough into those languages to truly grasp their idioms.

And yet, at the same time, When I push myself into a language- I  eventually catch on. For example- and I’ve written about this before- I languished with Visual Basic 6 for a very long time. I thought it was good enough- there is nothing better. This is what I told others, but who was I trying to convince, them, or me? I aim for the latter. I don’t know what prompted me to do so but I moved on to C#. Now in fairness even then I did at least give other languages a shot, but VB6 was the only one that felt “familiar”; that is, that I could easily type code in without looking up documentation. At some point I’d had enough. Visual Basic 6 was an old, dead, language, and so too would my experience if I didn’t do something. I moved to C# instead of VB.NET mostly out of my own self-interest; I still had many projects in VB6 and I (possibly erroneously) thought that learning VB.NET might cloud my ability to work on those projects. That, and C# seemed to be the de riguer standard.

My first applications were rather simple. I made an attempt to duplicate the functionality of HijackThis first- this was a learning experience, particularly since I was now able to use those OO concepts I knew about but was never able to leverage properly in VB6, which only had interface inheritance. I moved forward with a simple game. This was to become the first version of BCDodger, which is a relatively simple game. The major stumbling block here was with regard to the use of multiple threads and handling concurrency and handling repainting. I eventually looked at my ancient ‘Poing’ game, which was an arkanoid/breakout clone I had written in Visual Basic 6. It was terrible- the drawing code was limited, everything was ugly and there was very little “whizbang” to the presentation. I decided to make a variant of the game in C#, using a better design and a class heirarchy. This snowballed pretty quickly, and I now have a game that is able to dynamically load new components from scripts (which it compiles at startup), has a fully-featured editor that is able to find and show any class that implements a specific interface or derives from a given class in portions of the interface; for example the “add block” toolbar dropdown get’s populated with every single block in the game, categorized based on attributes on the appropriate classes.

With Freelancing, my results have been met with an overwhelmingly positive response, in one case, where I was tasked with using Semantic cleanup of a longest common subsequence algorithm, there was some back-and forth over what might be the best output given what we were working with; the client eventually responded that they did some research and are pretty sure it’s impossible. By which time, I had actually finished implementing it. Needless to say, the results were very positive. The same applies for a similar project where I created the Product Key registration and generation logic in a self-contained class.

The nice thing is that these projects exposed me to things I might not have dealt with before. WPF was a technology I didn’t use until it’s appeal in a given situation made it very much preferable. Full screen, resolution independence was a lot easier with WPF than it would be with Windows Forms- so now I have experience with WPF as well. Naturally the overwhelmingly boring nature of Semantic cleanup of the output of a longest common subsequence algorithm (I nearly fell asleep writing that…) meant I wouldn’t otherwise explore it; however it turned out to be very interesting as well as mentally taxing. There was, of course, some confusion. But each time I was able to look at it with freshly rested eyes (apparently staying up for 48 hours working on the same problem clouds your judgement), I was able to find some very obvious fix or addition to resolve that which I was working on. I guess it boils down to- if you just write what you <want> you will always try to work on something interesting, but not always useful. When working on an actual project- for somebody else, or as an otherwise professional undertaking, what you work on might not always be fun, but it will always be useful to somebody. So in some respects this rubs off; with my own projects, I try to make them fun to work on, but might not always pay the closest attention to how useful they are; in retrospect when working in a professional capacity, whether they are useful is the most important goal. A program that isn’t useful is useless by definition.

This isn’t to say the experience isn’t occasionally frustrating; when you provide a product or service to somebody or something, I like to think there is some sort of a promise of the workmanship of that product; for example on more than one occasion, a product has stopped suiting the original purpose; for example, this could be because it was not as scalable as it needed to be, or perhaps a database corruption has caused some other problems. Whatever the case, since the product no longer works for the original intent, I could never charge for the service of getting the product working again- because that almost seems like holding them hostage.

At the same time, however, part of me doesn’t like releasing new products, simply because it feels like a lifetime contract to keep working on and improving them. This is part of why the vast majority of projects I’ve worked on I’ve not released. and by “vast  majority” we’re talking about nearly a hundred projects. Some big, some small; most of them unfinished in some fashion but most quite usable.

But I’m getting off the topic of this post. My point is, that I like to think I’m fairly awesome, but at the same time, not too awesome. There is plenty out there to learn, and the pursuit of awesomeness demands that I seek them out, absorb them, and then continue. Like a sponge that comes alive and wants to suction up all the water in the world, my task will never be completed. But that doesn’t stop me from trying anyway.

This applies in a general sense, as well; It’s not just programming that I’m very interested in, but rather tangential topics such as gaming and whatnot. I do also enjoy science-fiction- statistically, as a person who works in Software Development, this is more likely than not- as well as simply general knowledge. A good example being a tab I have open in my browser, where I was researching Eggplant. Why? I haven’t a clue. Just something I wanted to absorb and learn about, I suppose.

Conclusion: learning about Eggplants is unlikely to make you a better programmer. But it never hurts to stay versed on vegetables.

Posted By: BC_Programming
Last Edit: 17 Dec 2012 @ 12:34 PM

EmailPermalinkComments Off on You’re never as awesome as you think you are
 21 Nov 2012 @ 1:04 AM 

Recently I started working on what turned out to be a lot bigger of a project than original intended. It is a Bukkit Plugin; Bukkit being a server “replacement” for Minecraft. Since it’s written in Java, that means the Plugins are as well. As a result, I’ve been working frequently with Java. In a previous blog post on the subject, I noted how C# Was, in almost every discernable way, better than Java. I still hold to that. That post did not of course (and I believe I mentioned this in the post itself) mean to say that Java was useless. Even though C# is cross-platform, it’s not marketed as such; additionally, many Windows-centric frameworks have appeared (WPF, WCF, etc) which aren’t available on other platforms, causing C# code to be coupled to the platform. Of course this can happen with Java code as well, but it’s probably more common with C# code.

Anyway, since I’ve been working with Java, both it’s strengths and weaknesses have popped out at me. This is more a list of opinions, really, but that’s stating the obvious.

Classes have to be in their own files

I’m not 100% sure about this one. It can really work both ways. With BASeBlock, some of my files have way too many classes, and it makes navigation difficult. On the other hand, a lot of those issues are alleviated by using the Solution Explorer to navigated as a class view, rather than file view. Additionally, I think the Java limitation of one public class per file is one of those design changes to Java that serve more to make it easy to write compilers as well as “force” what the designers of the language thought of as “good design”. I prefer having the ability to declare classes in the same files; a single C# file could add classes to various namespaces, add extension methods to existing classes, and so forth. Of course, it’s quite possible to go overboard with this, but I think that is something that should be dealt with by the programmer, not something entirely prevented in the interest of good design. It also makes file management easier.

Java also enforces a system where a class is either an inner class, or it MUST have the same name as the “compilation unit” (file). For example, a class named MonkeyGizzards must be in a file named MonkeyGizzards. I have to say I really do not like the way java uses the file system to manage packages, it just feels… weird, to me. It also has the odd side effect that package names need to conform to file system rules as well as the rules of java, which is arguably easy to avoid by simply not giving your packages stupid names, but is still a weird effect.

No Delegates

Personally, I actually find this, well, kind of infuriating. It’s one thing to lack lambda’s and closures, but completely lacking any functional data type is just weird to me, now that I’ve grown to use them. There are workarounds, but the problem with those is that they are just that- workarounds. They don’t fix the underlying omission. For example, Let’s go with a relatively simple function- it takes a List, and filters out elements based on the second parameter.

Of course, with C#, this is relatively simple- in fact, I believe the routine is provided as is within linq, but for the sake of the exercise let’s assume we need one:

A call to this function might look something like this…

One line of code within the function; one line to actually use it. This actually leverages several C# Features that Java doesn’t have; first, it uses a delegate as the argument type to the routine, and second is that it uses a lambda in the call to the function, which can be implicitly converted to the argument type, which utilizes operator overloading for implicit and explicit types. It’s also notable that it is possible to pass primitive types as type arguments, which in Java requires to use of one of the Boxing types, such as Integer.

The Java equivalent is more verbose. First, you need to define an interface:

Then you need to write the implementation- in this case, a Filter routine:

This is of course but one possible implementation. Other frameworks often provide much better functionality (apache commons has some excellent extensions of this sort). Anyway, using something like this would simply require the use of an anonymous class declaration. behold!

Quite a lot of code, for something so basic. It is worth noting that writing this sort of stuff is almost an initiation for Java programming. I can see it being useful to learn how to write these things if you are actually learning in a academic setting, but this is still the sort of stuff that should be supported out of the Box. The above could likely be condensed to use the Iterable (java.lang.Iterable) interface instead of List, since it certainly doesn’t need anything specific provided by the List interface. But that is a fringe concern.

the C# Version is supported by the linq namespace. Linq adds All, Select, SelectMany, and various other methods to some core collection interfaces; the result being that these methods appear to be on those interfaces, but are implemented elsewhere. This is good, because those methods really don’t fit anywhere else.

For some time, I wondered two things: One was why Eclipse was adding Imports one by one- importing each specific class; and why the import blah.blah.*; was so frowned upon. Fundamentally, it is because of a lack of flexibility in the imports statement, as compared to the C# equivalent, “using”. the C# using statement supports Aliassing; for example:

Using CollectionsList = System.Collections.List;

would ‘import’ the System.Collections.List Type, allowing you to use it as CollectionsList. java’s import statement lacks this feature, so you need to import more carefully to avoid collisions. The primary concern for those that push importing only those types you use is that adding a new asterisk import might cause issues. Looking this up online and it seems there was a “tribulation” some time ago, when Generics was newly introduced, and there was the new java.util.List class. Many java programs started with:

what ended up happening was that the compiler would prefer java.util. This had no bearing at the time, but with the introduction of generics- and, more specifically, the List class, there was now a List class within java.util as well as java.awt (java.awt.List being the ListBox implementation). proponents of the “import only classes you use” idea cite this rather often; what they don’t cite quite as frequently is that the problem is easily averted by simply adding a new import:

This is because precedence of imports goes to explicit class imports first, then to classes in the same package, and last to asterisk imports. Arguably, explicit imports would have prevented any issues, but then again, usually programmers move to a new SE platform to use new features, so they might actually want to use the new Generics features of the time; meaning they have the same problem either way… there are two classes with the same name declared in different packages and no way of aliasing, so they end up referring to one of them with the fully qualified name.

IDE’s such as Eclipse will allow you to import classes you reference in code explicitly, but I don’t see this as a good thing; imports you are no longer using don’t go away on their own, and good tooling to try to cover up deficiencies in a language is not something I feel should be encouraged. In this case it’s even arguably not a deficiency in the language, but rather a inability to recognize what is realistic; A person usually upgrades a Project to a new version of a platform to use new features, and the above issue is fixed with a single import anyway. Overall, the best compromise is if you are using an IDE with the ability, list all the imports you use. If you are writing with a text editor or another tool, just use asterisk imports. The sky will not implode in itself if you do.

Anyway, for C#, a lot of features really just make code shorter- they are, in many ways, syntactic sugar. But arguably any programming language is syntactic sugar, so trying to use it as a derogatory term doesn’t really work; I’ve had Java programmers tell me that Lambda’s and Delegates are just syntactic sugar for anonymous interface implementations. I agree. But I like quite a bit of sugar in my coffee- why should my tastes for programming language syntax be different? When you write 20 times as much code, you are going to have 20 times as many bugs, which is part of my issue with Java as a whole.

Now, don’t get me wrong; it really does provide enough base functionality to work with. And it’s important to realize that Java has been around for quite a long time, and back then, we didn’t have such prevalent access to features such as Generics. This has the advantage that there is quite a lot of Java code available, in various libraries. But also has the downside that those libraries might be out-dated, replaced by new features in the JVM, and so on.

Posted By: BC_Programming
Last Edit: 21 Nov 2012 @ 01:04 AM

EmailPermalinkComments Off on More stuff about Java

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


    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.