16 May 2013 @ 1:42 AM 

With the runaway success of Visual Basic 1.0, it made sense for future versions to be released improving incrementally on the existing version. Such was how we ended up with Visual Basic 2.0. In some ways, Visual Basic 2.0 changed Visual Basic from a backwater project like Microsoft Multiplan into something that would become a development focus for years to come- like Microsoft Excel.

Visual Basic 2.0 was quite a leap forward; it improved language features, the IDE, and numerous other things. One of the biggest changes was the introduction of the “Variant” Data type. A full list of new features, from the Visual Basic 2.0 Programmers Guide, with annotations on each by me.

  • Improved Form design tools, including a toolbar and a Properties Window Visual Basic 2.0 adds the ability to select multiple controls by dragging a box around them. It also adds a Toolbar, which replaces the area used by the Property modification controls in Visual Basic 1.0. The new Properties Window moves the Property Editing to a separate Window, which is a massive improvement since you can more easily inspect properties.
  • Multiple-Document interface Support Another rather big feature. MDI was and is the capability that allows a Window to have it’s own Child Windows. This has started to fall out of vogue and is all but forgotten. Earlier Office versions provided an MDI interface. The core of MDI was basically set by Program Manager itself, which was a MDI Application. Visual Basic 2.0 allows you to create MDI Forms, and MDI Applications. This is provided through a few Properties. I will cover MDI stuff that VB2.0 adds later in this Post.
  • New Properties, Events, and Methods Visual Basic 2.0 added several Properties, Events, and Methods to the available controls. It changes the “CtlName” of all Controls to the less stupid “Name”, and added multiple new Events, particularly surrounding Drag and Drop capabilities.
  • Object Variables and Multiple Form instances This is a pretty major shift. For one thing, it established Forms not as their own, distinct objects (as was the case in VB1.0) but rather as their own Class of Object. You were also capable of creating new form instances, inspect Object Types, and various other Object-Oriented capabilities. it was still relatively limited, but it was certainly a step forward and it added a wealth of capability to the language.
  • Variant Data Type This is another Big one. Visual Basic 1.0 had a number of Data Types, as you would expect; Integer, a 16-bit Integer value, Long, a 32-bit Integer value, Single, a 16-bit floating point value, Double, a 32-bit floating point value, Currency, a Scaled Integer value, and String. Visual Basic 2.0 shakes things up by not only adding Forms as their own ‘Data Type’ of sorts, but it also adds Variant, which is basically a Value that can represent anything.

    Variants are an interesting topic because while they originally appeared in Visual Basic 2.0, they would eventually seep into the OLE libraries. As we move through the Visual Basic versions, we will see a rather distinct change in the Language, as well as the IDE software itself to reflect the changing buttresses of the featureset. One of the additional changes to Visual Basic 2.0 was “Implicit” declaration. Variables that hadn’t been referred to previously would be automatically declared; This had good and bad points, of course- since a misspelling could suddenly become extremely difficult to track down. It also added the ability to specify “Option Explicit” at the top of Modules and Forms, which required the use of explicit declarations. Visual Basic 1.0 also allowed for implicit declarations, but you needed to use some of the ancient BASIC incantations (DefInt, DefLng, DefSng, DefDbl, and DefCur) to set default data types for a range of characters. It was confusing and weird, to say the least.

  • Shape,Line, and Image controls The Shape, Line, and Image controls added to VB2 are a new feature known as “windowless” controls, in that they do not actually use a Window handle. One of the larger benefits from this was that the controls were lightweight; the second was that they could be used for simple graphics on a VB2 Form.
  • Grid Custom Control Visual Basic 2.0 comes with a Grid Custom Control. I swear this thing has what feels like an entire chapter devoted to it in the Programmers guide. I’m not even Joking- “Chapter 13: Using the Grid Control”. The Grid control is rather awkward to use for those more accustomed to modern programmatic approaches and better designed control interfaces.
  • Object Linking & Embedding Custom Control OLE (pronounced “O-Lay” I was pronouncing it as Oh-Ell-Eee for the longest time and don’t think I’ll ever live down the embarassment. The basic idea was to allow one application to be “embedded” inside another. functionality- to the user- it would simply look like inserting a document, which was part of the purpose. For example, you can insert an Excel spreadsheet inside a Word document and then edit that Excel Spreadsheet- from within Word- as if it was Excel. What happened? Well it was bloody confusing. While it was (and still is) a very powerful feature, it was far from intuitive and was something far more likely to be used by power users.
  • Added Debugging Features, including Watch variables and a Calls Window. It’s amazing the stuff we did without in older Programming environments, isn’t it? Visual Basic 1.0 provided very simplistic Debugging support. This was not uncommon among the IDE tools of the time. Visual Basic 2.0 added some debugging helpers and in some ways added a new “mode” to the Program; Immediate Mode. Visual Basic 1.0 had similar capabilities, in that it did have something of an “immediate” mode; particularly shown by the Immediate Window. However, Visual Basic 1.0′s implementation was far simpler, and it didn’t support Watch Variables, which is one of the primary new features added in VB 2.0. This paired with with the Toolbar controls that almost emulate “playback” of the application gave rise to the idea of Three Modes; The first, you write code and design forms. The second is where you run the application, and the third. Immediate Mode, is when you are debugging; eg. Your application is Stopped but you can inspect it’s running state.
  • ASCII representation of Forms As far as I’m concerned, this is the single best feature added to Visual Basic 2.0. Historically, many applications- including things like Visual Basic as well as other Language interpreters or editors, saved their source in a proprietary, binary format. This was done not so much to protect it, but for space-saving reasons. When you only have a 160K disk, a difference of a single Kilobyte can be important. Additionally, for text formats it takes longer to load and save (at least with the paltry memory and processing power of the time in comparison to today). Visual Basic 1.0 as well as it’s QuickBASIC predecessor allowed for saving files as text, but this was not the default option. Visual Basic 2.0 adds the ability to save not only source code- as the Visual Basic 1.0 Code->Save Text Option did- but also to save the Form design in a text format. this was a massively useful feature since it allowed external tools to manipulate the form design as well as the code, as well as making your software development less dependent on an undocumented format.
  • 256-Color support for bitmaps and color palettes. Back in those days, Colour was a trade-off. Video Adapters usually had limited Video Memory, so you usually had a trade-off between either higher resolution and fewer colours, or lower resolution and more colours. Today, this isn’t an issue at all- 32-bit and 24-bit Colour has been the standard for nearly two decades. As this was developing, however, we had the curious instance of 256-colour formats.

    256-colour modes uses a single byte to index each colour, and palette entries are stored separately. The index them becomes a lookup into that table. This had some interesting effects; Applications could swap about the colours in their palette and create animations without really doing anything; the Video Adapter would simply change mappings itself. This was a very useful feature for DOS applications and Games.

    Windows, however, complicated things. Because Windows could run and display the images from several Applications simultaneously, 256-color support was something of a tricky subject. Windows itself reserved it’s own special colours for things like the various element colours, but aside from that 8-bit colour modes depended on realized palettes. What this means is that Applications would tell windows what colours they wanted, and Windows would do what it could to accomodate them. The Foreground application naturally took precedence, and in general when an application that supported 8-bit colour got the focus, it would say “OK, cool… realize my palette now so this owl doesn’t look like somebody vomited on an Oil Painting”. With Visual Basic 1.0, this feature was not available for numerous reasons, most reasonable among them being a combination of it just not being very important paired with the fact that VB was designed primarily as a “front end” glue application for other pieces of code. Visual Basic 2.0 however adds 256-color support. This adds quite a few properties and methods that are used. VB itself manages the Palette-relevant Windows Messages, which was one of the reasons VB 1.0 couldn’t even be forced to support it.

Visual Basic 2.0 Manuals

The Three Visual Basic 2.0 Manuals in their native environment of a random Wooden Table. The “Professional Features” guide is about twice as thick as the other two. Note the use of the old cover style that was typical of MS Documentation of the time.

On a personal Note, Visual Basic 2.0 is dear to me (well, as dear as a software product can be), since it was the first Programming Language I learned and became competent with to the point where I realized that I might have a future with software development. Arguably, that future is now, but it hasn’t actually become sustainable (I may have to relocate). But more so than this is the fact that I was given a full, legal copy of the software. This in itself isn’t exceptional, but what is is the fact that it had all the manuals:

Dog-eared, ragged, and well-used, these books- primarily the Programmers Guide and Language Reference- became the subject of meticulous study for me. From VB2 I jumped directly to VB6. This set of Articles, however, will not. Next up- Visual Basic 3. It looks the same- but deos it vary more than it appears?

108 total views, 6 views today

Posted By: BC_Programming
Last Edit: 16 May 2013 @ 01:47 AM

EmailPermalinkComments (0)
Tags
 11 May 2013 @ 6:29 PM 

In what will hopefully be a recurring series on older Development Tools, Languages, and Platforms, I will be covering some information on my old flame, Visual Basic.

Visual Basic has a relatively long history, going back to around 1991. BASIC itself, of course, has an even longer history, starting at Dartmouth College in the 70′s.

The question is- What made Visual Basic Special? One of the big things going for it at the time were that it was the easiest way to develop applications for the booming Windows Desktop. It made many development tasks easy, provided form designers where you would otherwise need to write layout code, and in general made the entire process of Windows Application Development a lot more accessible.

Visual Basic was one of the earliest examples of a “RAD” Tool. RAD- or “Rapid Application Development” essentially allowed a company or other entity to get a feel for how a idealized Application might look and feel with minimal effort. By making UI design something that requires very little to no code, the task requires less expertise- that is, the Company doesn’t need to use their Development Team Resources for that part of the design process. Another huge boon of the technology was that it made Application Development on Windows far more accessible- at least to those with big wallets, but considering the cost of a computer and software in those days finding a person with a computer that wasn’t in a financially secure situation was not very likely. A full synopsis of the history of Visual Basic and it’s origins isn’t really appropriate here, and has been covered far better by those actually involved in the process. You can read one such overview Here .

In this series, I will first cover Visual Basic Versions from 1.0 through 6.0; and possibly go through the various .NET implementations as well. As I flow through one version to the next, we will see the Language and it’s surrounding Toolset (IDE) evolve.

The First Split

Visual Basic 1.0 for Windows was released in 1991. It was part of a move by many companies to get Powerful development Tools on the increasingly popular Windows Desktop Environment. Visual Basic itself grew out of it’s spiritual predecessor, QuickBASIC. It made some cosmetic changes to the language, and changed it to be Event Driven. Visual Basic also introduced two modes of operation, Design-Time and Run-Time. At Design Time you would edit your code and your forms. During Run-time, you could stop the application (using either the Stop statement or a breakpoint).

Visual Basic 1.0 for Windows running under Window 3.11

Visual Basic 1.0 for Windows running under Window 3.11

As we see above, Visual Basic 1.0, Running on Windows 3.11, showing the Form View. I’m not sure why I went with BRICKS.BMP, usually I’m more a MARBLE.BMP guy but hey no accounting for taste. One thing that may surprise those used to later versions of Visual Basic might be that you can still see the Desktop. the MDI interface wouldn’t be around until Visual Basic 5, at which point it was optional for VB5 as well as VB6. (you can invoke both with the /sdi command line argument to switch to SDI and /mdi to switch to MDI, in addition to configuration options). The “Project Explorer” if we can call it that- is shown on the right. Right now it’s showing Global.bas- a Module inserted into every application, and also the only module in VB1 allowed to have Globals, which may be responsible for the name, and FRMLSTVI.FRM, which is the form file I created; that form is shown to the left, and to it’s left is the Toolbox, from which you can choose a variety of Visual Basic Controls. One of the interesting features of Visual Basic was it’s support for Custom Controls. Custom controls were specially coded DLL files with the .VBX Extension, which stands for “Visual Basic eXtension” because I guess using X’s in extensions was the cool thing to do back then- we didn’t know any better. These had to be written in C or another language capable of using the appropriate Visual Basic Control Development Kit, or CDK. There were a lot of Custom Controls Available for VB 1.0 that added a lot to VB Applications.

Along the Main Window (shown at the top) we notice two things: first, it lacks the Toolbar we would normally come to expect, and the Properties Editor is rather spartan, and takes up that area of the window.

Visual Basic 1.0 however did not forget Menus. A Window->Menu Design Window Item exists which gives you this dialog for editing the Menu layout of the Active Form:
Visual Basic 1 Menu Design Window

We’ll watch this Dialog evolve Through each version of Visual Basic- (and eventually disappear, be sure to stay tuned for that exciting conclusion). One interesting thing about This first version of Visual Basic is that it actually was released primary for Windows 3.0. That isn’t particularly amazing in and of itself, but it meant that it had to “hand-weave” scarves that Windows 3.1 gave Applications, because it might be on Windows 3.0. Behold:

Visual Basic 1 File Open Dialog

A hand-built, Custom File Open Dialog. And, a fairly terrible one, at that. Of course the one included with Windows 3.1 wasn’t exactly the pinnacle of UI ease of use either. We will see this dialog evolve over time as well with new versions.

Visual Basic 1 showing the Code of a Command Button

Visual Basic 1 showing the Code of a Command Button

Here we see the code Editor. I’ll be frank: it’s terrible, even for the standards of the time. It’s little more than a glorified Notepad, really. It also forces you to edit your source files one procedure at a time. unpleasant, really. It does auto-correct your casing, which I suppose is something. Breakpoints are shown in bold. The Form Designer doesn’t let you select multiple controls by dragging a box around them, but you can use Control+Click to do that.

One other curious limitation of Visual Basic 1.0 is the lack of the ability to save in text format; All the files are saved in a proprietary, undocumented text format. You can export and import to and from text files, but allow me to be the first to note that this is a gigantic pain in the ass. Using the Code->Export Text Menu option, this is the result:

  1.  
  2. Sub cmdClose_Click ()
  3. End
  4. End Sub
  5.  
  6. Sub cmdLoadFile_Click ()
  7.     Dim FileNum As Integer
  8.     Dim LineRead As String
  9.     On Error GoTo HandleError
  10.     Do While lstContents.ListCount > 0
  11.         lstContents.RemoveItem 0
  12.     Loop
  13.     ‘Open the File in txtInputFile.text
  14.     FileNum = FreeFile
  15.     Open txtInputFile.Text For Input As #FileNum
  16.     Do Until EOF(FileNum)
  17.         Line Input #FileNum, LineRead
  18.         lstContents.AddItem LineRead
  19.     Loop
  20.     Close #FileNum
  21.     Exit Sub
  22. HandleError:
  23.     MsgBox "Error:" + Error$
  24. End Sub
  25.  

To be fair this isn’t much different than the same Program would probably look in VB6; with a few exceptions that we will obviously touch on as we move up through the versions.

Visual Basic 1.0 was a runaway success. For some reason this popularity apparently impacted the DOS toolset teams, since the successor to QuickBASIC PDS 7.1 was a new version of QuickBASIC that did not have the same name- Visual BASIC 1.0 for DOS.

Visual BASIC 1.0 for DOS in Form Design View.

Visual BASIC 1.0 for DOS in Form Design View.

Visual BASIC for MS-DOS in Code View

What makes Visual BASIC 1.0 for MS-DOS interesting is that’s it’s only kinda sorta a Version of Visual Basic. For one, all the literature uses BASIC in capitals for whatever reason, and working with it feels very much the same as working with QuickBASIC 7.1 PDS, but with a special Character-Set GUI thing. In many ways it was more of a stopgap version for transitioning QuickBASIC users to Visual Basic for Windows.

In the next entry in this series, we’ll take a look at Visual Basic 2.0; what does it improve over 1.0 and How does it move RAD forward? Stay tuned and find out!

152 total views, 8 views today

Posted By: BC_Programming
Last Edit: 13 May 2013 @ 05:29 PM

EmailPermalinkComments (0)
Tags
 23 Apr 2013 @ 1:53 PM 

So lately I’ve been doing quite a bit of Java related stuff. I’ve learned a lot. Mostly about how much better C# is, to be honest. But this isn’t about that.

Most Java work get’s packaged into a Jar file. a Java .jar file is really just a .zip file with a .jar extension- so points to Sun Microsystems for coming up with a package format that isn’t something completely new. I found myself having a bit of an annoying time of it, however- from what I can tell there is no “package this stuff into a jar” option in Eclipse. Since the zip format is so widely workable, I decided to create a quick script to package all the appropriate files into a .jar. This saves me selecting everything in the appropriate .bin folder,unselecting the hidden history folder created by my text editor and anything else I don’t want included, etc.

I’m aiming for simplicity here. A script in the bin folder is good enough for me. I encountered quite a few problems creating the script and ended up giving up on it for a while, but I got back to it today and decided to get it working. Here is the script:

  1. #!/usr/bin/env python
  2. import sys,os,zipfile
  3.  
  4. def zipdir(path,rootfolder, zip):
  5.     for root, dirs, files in os.walk(path,topdown=True):
  6.         print(root,dirs,files)
  7.         dirs [:]  =  [d for d in dirs if not (d.startswith(".") or d.startswith("_"))]  
  8.         for dir in dirs:
  9.             zipdir(os.path.join(root,dir),os.path.join(rootfolder,dir),zip)
  10.         for file in files:
  11.             if not (file.lower().endswith(("jar","zip")) or file.startswith(".") or file.startswith("_") or file==scriptfile()):
  12.                 print("adding file:" + file)
  13.                 #print(os.path.join(dirs [0] ,file))
  14.                 zip.write(os.path.join(root, file),os.path.join(rootfolder,file))
  15.             else:
  16.                 print "Skipping file:" + file
  17.         break
  18. def scriptfile():
  19.     dname,fname = os.path.split(os.path.abspath(sys.argv [0] ))
  20.     return fname
  21. if __name__ == ‘__main__’:
  22.     print("main file:" + __file__)
  23.     zip = zipfile.ZipFile(‘packaged.jar’, ‘w’)
  24.     usefolder = os.path.dirname(os.path.realpath(sys.argv [0] ))
  25.     zipdir(usefolder,"", zip)
  26.     zip.close()

Python is quite a powerful language. I particularly like the use of tuples directly in the language; the os.walk() function is a “generator”; each iteration the root variable is set to the root of the search, dirs is filled with all the directories in the current iterating folder, and files is filled with the files. I change the dirs value here and filter out those that start with “.” (which could be, say, a git repo) as well as filtering out those starting with an underscore. The cool thing is that since I specified topdown=True in the call to os.Walk, I can remove directories and os.walk will not go into those directories, so I don’t need additional checks to make sure we aren’t in one of the excluded folders. Then the function calls itself for each directory, and finally it adds all the files in the currently walked folder to the zipfile. It performs similar checks to avoid adding undesired files; it doesn’t add files that start with a period, underscore, or are the same name as the scriptfile itself (which could cause issues, arguably, but with Java I’m unlikely to have a file called “prepare.py” anywhere in the tree that I want to be included). Then it breaks. Works quite well; the zip is created with only the files I want and everybody is happy. I was considering adding extra functionality to it, but decided that it’s possible to over-think it; I just want something simple, and I don’t need- for example- special handling of .gitignore folders to actually exclude files that are specified from the package. Not yet, anyway.

Naturally this script can really be run anywhere; just paste it in a folder and run it, and you’ve got a zip with everything in that folder compressed. could be useful for compressing source trees. I thought I’d share it here because I found it useful.

298 total views, 2 views today

Posted By: BC_Programming
Last Edit: 23 Apr 2013 @ 01:55 PM

EmailPermalinkComments (1)
Tags
Tags: , , ,
Categories: Python, Scripting
 15 Apr 2013 @ 10:12 PM 

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


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

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

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

The Visual Basic.NET implementation I came up with looks like this:

  1.  
  2. Imports System.IO
  3. Imports System.Text
  4. Imports System.Collections.Generic
  5. Module anagrams
  6.  
  7.     ‘Anagrams Application
  8.     ‘Written By: Michael Burgwin for http://bc-programming/blogs
  9.     ‘entry into Anagrams Performance/language comparisons.
  10.  
  11.     Public Function SortChars(sumstring As String) As String
  12.         Dim sortme = sumstring.ToList()
  13.         Dim sorted = From f In sumstring Order By Char.ToLower(f)
  14.         Return New String(sorted.ToArray())
  15.     End Function
  16.     Sub Main(Args As String())
  17.  
  18.         Dim Anagrams As New Dictionary(Of String, List(Of String))
  19.         Dim usefilename As String = "D:\dict.txt"
  20.         Dim StartTime = Now
  21.         Using fDictionary As New StreamReader(New FileStream(usefilename, FileMode.Open))
  22.             Do While Not fDictionary.EndOfStream
  23.                 Dim LineRead = fDictionary.ReadLine().ToLower()
  24.                 ‘get sorted version.
  25.                 Dim SortedVersion = SortChars(LineRead)
  26.                 If Not Anagrams.ContainsKey(SortedVersion) Then
  27.                     Anagrams.Add(SortedVersion, New List(Of String))
  28.                 End If
  29.                 Anagrams(SortedVersion).Add(LineRead)
  30.             Loop
  31.         End Using
  32.         Dim Duration = Now – StartTime
  33.         Console.WriteLine("Calculation Time:" & Duration.ToString())
  34.         Console.ReadKey()
  35.     End Sub
  36.  
  37. End Module
  38.  

Performance? Compiling this with vbc /optimize /debug- resulted in an average run-time of around 1.3 seconds. That’s a bit over twice as slow as C#. So, some C# pundits might go, “Ha! Well that proves C# is faster than C#, doesn’t it, Case closed we can all go home”

Not Exactly.

The slowdown, I suspect, is from the use of Linq:

  1.  
  2. Public Function SortChars(sumstring As String) As String
  3.     Dim sortme = sumstring.ToList()
  4.     Dim sorted = From f In sumstring Order By f
  5.     Return New String(sorted.ToArray())
  6. End Function
  7.  

This is different from the C# implementation of the same method, which uses the Sort() method of List . Let’s ‘port’ that C# implementation to VB.NET and see how that affects the performance:

  1.  
  2.     Public Function SortChars(sumString As String) As String
  3.         Dim sortme = sumString.ToList()
  4.         sortme.Sort(Function(ca, cb) ca.CompareTo(cb))
  5.         Return New String(sortme.ToArray())
  6.     End Function
  7.  

It now runs in 1.1 seconds. But it turns out this is partly due to a bug in the C# implementation, since it didn’t account for mixed case comparisons. The VB.NET implementation I have lowercases each string input. the C# version uses an iterator method; even changing the source to take account of casing, it still runs in 0.7 seconds, so we have some ground to make up. Let’s start by re-implementing the iterator method from the C# version. Here is the new implementation. it doesn’t actually add an iterator Function because the function in C# just returned an IEnumerable anyway, so we just have a similar function and use that, but it gives the same effect:

  1.  
  2. Option Strict On
  3. Option Explicit On
  4. Imports System.IO
  5. Imports System.Text
  6. Imports System.Collections.Generic
  7.  
  8. Module anagrams
  9.  
  10.     ‘Anagrams Application
  11.     ‘Written By: Michael Burgwin for http://bc-programming/blogs
  12.     ‘entry into Anagrams Performance/language comparisons.
  13.  Private Function readlines(Filename As String) As IEnumerable(Of String)
  14.         Dim nl As Char = CChar(Environment.NewLine)
  15.         Return New StreamReader(Filename).ReadToEnd().ToLower().Split(nl)
  16.     End Function
  17.     Public Function SortChars(sumString As String) As String
  18.         Dim sortme = sumString.ToList()
  19.         sortme.Sort(Function(ca, cb) ca.CompareTo(cb))
  20.         Return New String(sortme.ToArray())
  21.     End Function
  22.     Sub Main(Args As String())
  23.  
  24.         Dim Anagrams As New Dictionary(Of String, List(Of String))
  25.         Dim usefilename As String = "D:\dict.txt"
  26.         Dim StartTime = Now
  27.  
  28.         For Each LineRead In readlines(usefilename)
  29.             ‘get sorted version.
  30.             Dim SortedVersion = SortChars(LineRead)
  31.             If Not Anagrams.ContainsKey(SortedVersion) Then
  32.                 Anagrams.Add(SortedVersion, New List(Of String))
  33.             End If
  34.             Anagrams(SortedVersion).Add(LineRead)
  35.  
  36.         Next
  37.         Dim Duration = Now – StartTime
  38.  
  39.  
  40.         Console.WriteLine("Calculation Time:" & Duration.ToString())
  41.         Console.ReadKey()
  42.     End Sub
  43.  
  44. End Module
  45.  

The Execution Time of this version hovers around .62 seconds- .2 seconds faster than the C# implementation, which is fairly surprising. Obviously, this doesn’t mean that VB.NET is faster than C# either; just means that this particular implementation is faster. It also Highlights something I did not expect, which is that the language used really does affect speed; not because one language is innately faster, but because you write code differently in different languages and they compile to different IL in many cases. I was expecting nearly zero difference between C# and VB.NET, which is why I didn’t originally create a VB.NET implementation- and yet here we have it performing .2 seconds faster than the C# version with what appears to be equivalent code.

336 total views, 2 views today

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

EmailPermalinkComments (0)
Tags
Categories: Programming
 13 Apr 2013 @ 3:55 AM 

Integrated Development Environments. These are the programming tools that most of us have come to almost take for granted. They provide the ability to write, debug, edit, and otherwise develop our software within a cohesive software product. You can find Development Environments for nearly every language platform. Microsoft Visual Studio can handle C#, VB.NET, F#, and C++ out of the Box, while also providing a wealth of other language capabilities through aftermarket software. Java has Eclipse and Netbeans, just to name two- the list goes on.

However, for every IDE user, there is a person who ‘looks down’ on the lowly IDE user; “they aren’t actually writing code” they grumble into their bag of cheetos- they are simply selecting things from an autocomplete list. These types of people are, perhaps in a statistically significant way, usually users of *nix based systems. They extoll the virtues of their favourite text editor- emacs, vim, nano, and look down on IDEs, which they will sometimes refer to as “glorified text editors”.

If my patronizing tone in the previous paragraph was not obvious- or if you’ve never read one of my programming-oriented blog entries, I’m firmly on the side that supports and uses IDEs, wherever they are available. The arguments against them are often lame; arguing that getting used to a feature like autocomplete or parameter lists, or dynamic help windows, and tips and whatnot make us “soft” is absurd- the same could be said of keyboards- by extension it just makes inputting data easier, so clearly we should be flipping switches manually. My point is that IDE software aims to make the task of software development easier, and more productive. And IMO it does this is spades.

There are even add-ins for many IDEs that basically provide all sorts of world-class capabilities in the IDE. Resharper is one exceptional such plugin that is available for Visual Studio- at this point, if it’s missing, it’s like I’m missing an appendage. It has made my work in Visual Studio so much more enjoyable and productive, that I almost feel it’s a crime not to have it installed. Similar addons are available for all sorts of IDEs; even Visual Basic 6 has things like MZTools(Free) or AxTools CodeSMART(Commercial).

Of course, IDEs lose a lot of their edge in certain languages, particularly those that lean towards the dynamic end of the spectrum. So much information about the program relies on run-time, that it’s a tricky proposition for a piece of software to try to figure out what is going on and provide any sort of tips or suggestions. Unsurprisingly, most of those that find IDEs childish use languages such as Python, Perl, Ruby, and PHP; I myself do not use an IDE for these languages either; primarily because I couldn’t find one (VS 2012 has an add-in available called “PHP Tools” that apparently brings support for PHP, though I do not know the extent of it’s assistance). However, if there was a software product available that provided the same level of assistance to languages like Ruby and Python as I currently get from Visual Studio or Eclipse, I would jump on it like Mario on a Goomba.

We ought to think of the software as not only our tools, but our own assistants. Most people wouldn’t raise any objections about being given a personal assistant for their work or daily tasks. In the case of Resharper specifically, that assistant is also an 11.

170 total views, no views today

Posted By: BC_Programming
Last Edit: 15 Apr 2013 @ 03:49 AM

EmailPermalinkComments (0)
Tags
Tags: , , , , ,
Categories: Programming
 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?

Java

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.

C#

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

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:

  1. package testdisassembly;
  2. import java.io.IOException;
  3. import java.util.ArrayList;
  4. import java.util.List;
  5. public class testdisasm {
  6.     public static void main(String []  args){
  7.         List <integer>  intlist = new ArrayList<Integer>();
  8.         for(int i=0;i<=100;i++){
  9.             intlist.add(i);
  10.         }
  11.         for(Integer iterate:intlist){
  12.             System.out.println(iterate);
  13.         }
  14.         try {
  15.             System.in.read();
  16.         } catch (IOException e) {
  17.             // TODO Auto-generated catch block
  18.             e.printStackTrace();
  19.         }
  20.     }
  21. } </integer>  

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.

  1. public <init>  ()V max stack: 1,   max locals: 1,    catch blocks: 0
  2. public static main  ([Ljava/lang/String;)V  max stack: 2,   max locals: 4,    catch blocks: 1
  3.  
  4. Bytecode of main method:
  5.  
  6. new #16 = Class java.util.ArrayList
  7. dup
  8. invokespecial #18 = Method java.util.ArrayList.<init>(()V)
  9. astore_1
  10. iconst_0
  11. istore_2
  12. goto 27
  13. aload_1
  14. iload_2
  15. invokestatic #19 = Method java.lang.Integer.valueOf((I)Ljava/lang/Integer;)
  16. invokeinterface #25 = Method java.util.List.add((Ljava/lang/Object;)Z)
  17. pop
  18. iinc 2
  19. iload_2
  20. bipush 100
  21. if_icmple 13
  22. aload_1
  23. invokeinterface #31 = Method java.util.List.iterator(()Ljava/util/Iterator;)
  24. astore_3
  25. goto 60
  26. aload_3
  27. invokeinterface #35 = Method java.util.Iterator.next(()Ljava/lang/Object;)
  28. checkcast #20 = Class java.lang.Integer
  29. astore_2
  30. getstatic #41 = Field java.lang.System.out(Ljava/io/PrintStream;)
  31. aload_2
  32. invokevirtual #47 = Method java.io.PrintStream.println((Ljava/lang/Object;)V)
  33. aload_3
  34. invokeinterface #53 = Method java.util.Iterator.hasNext(()Z)
  35. ifne 43
  36. getstatic #57 = Field java.lang.System.in(Ljava/io/InputStream;)
  37. invokevirtual #61 = Method java.io.InputStream.read(()I)
  38. pop
  39. goto 84
  40. astore_2
  41. aload_2
  42. invokevirtual #67 = Method java.io.IOException.printStackTrace(()V)
  43. return

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#:

  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5.  
  6. namespace testdissasmbly
  7. {
  8.     class Program
  9.     {
  10.         static void Main(string []  args)
  11.         {
  12.             var testlist = new List<int>();
  13.             testlist.AddRange(Enumerable.Range(0, 100));
  14.             foreach (var iterate in testlist)
  15.             {
  16.                 Console.WriteLine(iterate);
  17.             }
  18.             Console.ReadKey();
  19.         }
  20.     }
  21. }

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:

  1. .method private hidebysig static void  Main(string []  args) cil managed
  2. {
  3.   .entrypoint
  4.   // Code size       75 (0x4b)
  5.   .maxstack  3
  6.   .locals init ( [0]  class  [mscorlib] System.Collections.Generic.List`1<int32> testlist,
  7.             [1]  int32 iterate,
  8.             [2]  valuetype  [mscorlib] System.Collections.Generic.List`1/Enumerator<int32> CS$5$0000)
  9.   IL_0000:  newobj     instance void class  [mscorlib] System.Collections.Generic.List`1<int32>::.ctor()
  10.   IL_0005:  stloc.0
  11.   IL_0006:  ldloc.0
  12.   IL_0007:  ldc.i4.0
  13.   IL_0008:  ldc.i4.s   100
  14.   IL_000a:  call       class  [mscorlib] System.Collections.Generic.IEnumerable`1<int32>  [System.Core] System.Linq.Enumerable::Range(int32,
  15.                                                                                                                                   int32)
  16.   IL_000f:  callvirt   instance void class  [mscorlib] System.Collections.Generic.List`1<int32>::AddRange(class  [mscorlib] System.Collections.Generic.IEnumerable`1<!0>)
  17.   IL_0014:  ldloc.0
  18.   IL_0015:  callvirt   instance valuetype  [mscorlib] System.Collections.Generic.List`1/Enumerator<!0> class  [mscorlib] System.Collections.Generic.List`1<int32>::GetEnumerator()
  19.   IL_001a:  stloc.2
  20.   .try
  21.   {
  22.     IL_001b:  br.s       IL_002b
  23.     IL_001d:  ldloca.s   CS$5$0000
  24.     IL_001f:  call       instance !0 valuetype  [mscorlib] System.Collections.Generic.List`1/Enumerator<int32>::get_Current()
  25.     IL_0024:  stloc.1
  26.     IL_0025:  ldloc.1
  27.     IL_0026:  call       void  [mscorlib] System.Console::WriteLine(int32)
  28.     IL_002b:  ldloca.s   CS$5$0000
  29.     IL_002d:  call       instance bool valuetype  [mscorlib] System.Collections.Generic.List`1/Enumerator<int32>::MoveNext()
  30.     IL_0032:  brtrue.s   IL_001d
  31.     IL_0034:  leave.s    IL_0044
  32.   }  // end .try
  33.   finally
  34.   {
  35.     IL_0036:  ldloca.s   CS$5$0000
  36.     IL_0038:  constrained. valuetype  [mscorlib] System.Collections.Generic.List`1/Enumerator<int32>
  37.     IL_003e:  callvirt   instance void  [mscorlib] System.IDisposable::Dispose()
  38.     IL_0043:  endfinally
  39.   }  // end handler
  40.   IL_0044:  call       valuetype  [mscorlib] System.ConsoleKeyInfo  [mscorlib] System.Console::ReadKey()
  41.   IL_0049:  pop
  42.   IL_004a:  ret
  43. } // end of method Program::Main

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.

278 total views, 2 views today

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

EmailPermalinkComments (0)
Tags
Categories: .NET, C#, Java, Programming
 01 Apr 2013 @ 4:21 AM 

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

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

  1. class Program
  2. {
  3.     static void Main(string []  args)
  4.     {
  5.         Random rgen = new Random();
  6.         var doubles = (from p in Enumerable.Range(0, 100) select rgen.NextDouble());
  7.         doubles.EachCase(
  8.             (t) => t < 0.5d,
  9.             (value) =>
  10.             {
  11.                 Console.WriteLine(value.ToString() + " is less than 0.5d.");
  12.             }).EachCase(
  13.             (t) => t > 0.75d,
  14.             (value) =>
  15.             {
  16.                 Console.WriteLine(value.ToString() + " is greater than 0.75d.");
  17.             }).EachCase((t) => true,
  18.             (value) =>
  19.             {
  20.                 Console.WriteLine(value.ToString() + " is not handled…");
  21.             }).Count();
  22.         Console.ReadKey();
  23.     }
  24. }

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

  1. public static class SelectExtension
  2. {
  3.     public static IEnumerable<T> EachCase<T>(this IEnumerable<T> Enumeration,Func<T,bool> TestExpression,Action<T> CodeBlock)
  4.     {
  5.  
  6.         if (Enumeration == null) yield break;
  7.         foreach (var iterate in Enumeration)
  8.         {
  9.             if (TestExpression(iterate))
  10.             {
  11.                 CodeBlock(iterate);
  12.  
  13.             }
  14.             else
  15.                 yield return iterate;
  16.         }
  17.      }
  18. }

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

316 total views, no views today

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

EmailPermalinkComments (0)
Tags
Tags: , , ,
Categories: .NET, C#
 28 Mar 2013 @ 2:27 PM 

BASeCamp Survivalchests is a plugin that originally started as a simple method to randomize the contents of chests on a Minecraft server map. It soon ballooned with extra features into far more. I hope to make this post something of an “official” documentation, aside from the readme, particularly in regards to upcoming features. This is both so I can get feedback on these new features as well as describe them in a relatively verbose manner, something which I’ve come to discover is sort of frowned upon on BukkitDev; speaking of which, the plugin page on BukkitDev can be found here .

The plugin’s primary purpose is randomization features, primarily, of course, for chests. However it has some added facilities that can make things more interesting.

  • out-of-game loot configuration

    While there are a few components in-game that affect what a chest will contain, such as blocks that will keep a chest static and those that will set it to “super-populate”, most of the configuration of just what random items can exist is done from the game configuration. The weighting of the items determine how frequently they appear, and the weighting of enchantments is done as well for those items that include enchantment information, which makes for a relatively flexible configuration.
  • Random enchantments
    While I have seen a few other Chest/loot Randomization plugins, When I started mine I don’t recall finding any that also allowed for the aforementioned random enchantments. These are also configured in loot file, and very rarely you can even find equipment with ridiculously powerful enchantments, such as sharpness IX or Protection IX. These are rare enough that they aren’t as likely to unbalance the game too heavily, in my experience.
  • Chest repopulation

    One of the newest features is Chest repopulation. This is not currently in the version available as of this writing on devbukkit, but the jar available on github has this feature. It allows for a configuration timeout delay after a chest is closed. When that time expires, if the player that last closed it is farther away than another setting (the minimum block distance) it will repopulate the chest with items. This feature also allows a player to see who last viewed the contents of a chest for chests that are pending repopulation. Fundamentally it’s similar, in concept, to the way item respawns work in other games, but with an added feature to try to prevent too much camping of a single chest for good loot.
  • Potion randomization

    While this is currently somewhat hard-coded, the plugin also adds randomized potions. Previously, only their main effect was changed; you could tell what they were fundamentally by looking at them. More recently, I had those effects randomized. Don’t skip over that Green potion, because while it’s main effect might be poison, it might only be 2 seconds while offering a minute of Regen IV or Jump II, or some other powerful, useful effect.

  • Randomized Names

    While not really a main feature, this is still a hilarious one. The plugin generates random names and lore for some items; names like “Irish Slicing bodkin” for a sword or “Strong Ethiopian Fearful sweater” are not uncommon. It also chooses random text effects for some parts of the name. This is all designed to make the otherwise hectic task of trying to find good equipment even more difficult.

  • It repopulates any container

    While fundamentally, this could be a bad feature depending on the map design, the plugin currently repopulates Chests, Dispensers, furnaces, brewing stands, and Dispensers. When the bukkit API supports it, I will likely also have it populate hoppers and Droppers, too.

Other upcoming features aim to make the plugin easier to use in a continuous environment- that is, where the plugin and game is continuously running and players can join and quit as they please. I’m still working on the gameplay as well as technical aspects for how that will work.

654 total views, 10 views today

Posted By: BC_Programming
Last Edit: 28 Mar 2013 @ 02:27 PM

EmailPermalinkComments (0)
Tags
Categories: Programming
 26 Mar 2013 @ 12:21 AM 

A lot can be said about Windows 8. Personally I like it, it’s 2013 and Windows 7 was still using practically the same Window management paradigm; Application Windows minimize to the Taskbar, which serves as a launching point- in conjunction with the desktop- for pretty much everything. A lot can be said in favour of this- and why it’s lasted so long. For one thing, it works, and it works well.

Design

Personally I believe that to be a very strong argument for why Windows should keep the same design strategy. But it’s also very true that the software and hardware ecosystem is changing. There are some proponents that say that the desktop PC as we know it will no longer exist. I agree with that sentiment, but not very far- It won’t change roles, but we are definitely going to see new input devices and innovative UI designs appear, such as touch interfaces. Imagine a touch-screen interface on your laptop or LCD Monitor- pretty powerful feature that you don’t miss until you’ve given it a try. Then you find yourself scratching at your older LCD and wondering how you ever got along without a touch-screen. It’s very much like most other UI additions; the Pointing Device is ubiquitous when it comes to desktop and laptop machines, and unless you happen to have some understanding of a lot of keyboard shortcuts that aren’t really spelled out anywhere (On windows, I mean things like Control-Esc, Alt-Hyphen (to show the control box of an MDI Child) Alt-Spacebar (to show the control box of a Window) Alt menu accelerators, window management using the mouse, Alt-Esc, and of course Tabbing about dialogs, there simply isn’t a lot to go on. I know most of those accelerators and can usually use most applications without a mouse (when I have to charge the batteries, as an example), but I still find myself constantly reaching for it anyway. It’s become a part of the computing experience. Personally, this is how I feel touch-screens will be regarded in the future. In many ways the way we regard touch-screens today have a lot in common with how we thought of mice before the Macintosh popularized Point & Click. It’s just waiting for it’s “Killer App”. For the Mouse, that was the Macintosh, which brought with it the GUI. What will be the Killer App for Touch on the desktop? Impossible to say. But I have no doubt none of the Operating Systems we have available- be they OSX, Linux, or Windows, come close. The way I see it, when this new Killer App/OS finally appears- the one that makes Touch a necessity as the Macintosh and Windows made the mouse a necessity- we will regard the systems we have today in the same way we currently think of DOS and pure CLI machines- that is, not really suited to your average user.

Moving forward

But, back to Windows 8. Taking what I said above, one can perhaps see why I think it’s at least a step in the right direction; we’ve gotten used to working in one way- like we got used to working with CLI interfaces before. What is going to happen will likely be some sort of fundamental shift. The issue of course is that- well, this is the tech industry, so a “fundamental shift” is not something that generally get’s you loud gasps. Part of the reason might be that the news, and of course application marketing- often conflates things so that it seems like there is a fundamental shift every week. But that doesn’t change that we’ve been using the same basic interfaces for nearly a decade. Nonetheless, Windows 8 is more a “transient” in-between thing. It’s not quite a touch OS, and it’s not quite a Mouse interface. It tries to deliver on both fronts, and I think it does a reasonable Job of it.

Developers,Developers,Developers!

My concerns lie primarily in the developer side of things. Switching from a Command-Line Application programming model to a Event-Driven User-Interface model has caused a fundamental shift in the development landscape. Developers that can’t keep up, give up. And, fundamentally, that’s what worries me. Will I be one to keep up, or will I give up? Either way, I don’t doubt that desktop applications on Windows will be with us for the foreseeable future, but one still has to consider the fact that time, as it moves inexhorably forward, will move past that temporal horizon we can currently see. But we don’t know what skills we’ll need. This is what drives many developers insane- trying to keep up with all the technologies today is pretty much impossible. But at the same time, it’s what attracts many of us to the field; while no doubt other industries are constantly making new discoveries, I’ve always found the discoveries and ‘ah ha’ epiphany moments totally worth it. For example, when I first started using C# a year or two ago, I struggled. I was moving from Visual Basic 6- an old frazzled language and platform that was put out to pasture years before. I distinctly remember the most frustrating part was having a understanding deep enough to know that the language was not giving me all it’s secrets, but not deep enough to fully understand them. It was the promise of knowing more that kept me going onwards. the C# Reference that came as part of the MSDN library with Visual Studio 2008 was a constant companion, as I referred to it for things like the syntax of declaring a lambda or anonymous delegate. At some point, the underlying concepts clicked; the last two neurons on the chain of learning suddenly touched dendrite to axon and it just clicked. Suddenly I found myself going back over my code and refactoring it using my sudden deeper knowledge. Naturally, it didn’t stop there, and I ended up having similar experiences with Delphi as well as (back to C#) LINQ. To some extent working with a bit of JSON suddenly made me understand what a prototype language was, and so on.

The Chase

Am I saying I’m at the end of the road? Of course not. What I’m saying is that I worry that perhaps the next hurdle will be too high. The mild euphoria that such epiphanies promise being beyond my grasp. For a time, I suspected that the Windows 8 Development model was simply beyond my grasp.

I received an E-mail through the Microsoft MVP Program that provided some very helpful information on creating a Windows 8 App based on a Open Source framework, Metropress. Metropress has been renamed since to ideapress . It w as very promising. After some effort I was able to create this:

basecampblog

Now that’s a sexy Windows 8 App.

And it was pretty awesome. I could read posts and started to consider putting images in more posts as a result. Unfortunately I wasn’t able to get it on the App store; even though I had a free Developer Account through MSDN, it required a Credit card number. Oh well! Perhaps I can plonk it up there in the future at some unspecified time. At least I was able to learn a bit about the Windows 8 development model.

My reaction to the Windows 8 development model is anger. There is nothing fundamentally bad about it, but from what I could tell (from looking at the default sample applications) there is a lot to it. That is- we’re talking the level of boilerplate required to extremely basic Windows Application in C. That’s what initially got me thinking of the historical precedent. But it is interesting because behind all these technologies and APIs, there really is a single goal. To make everybody else play catch-up. If people are spending time learning to develop a Windows 8 Application, for example, they won’t be innovating their own products. It’s not a 100% airtight theory, of course, but it rings true in a lot of cases. In this case I think software development is still trying to get a foothold on exactly how a touchscreen application should look and act. Just as windowing systems all acted brutally different in the early days, so too is a lot of touchscreen-oriented behaviour very much OS-specific.

For the next few iterations, OS and software vendors will be simply trying to find out how a touchscreen application should work. They will experiment. Some attempts will fail. Others will succeed. And we cannot predict how times river will flow, so it’s best ot just ride out the rapids and hope you have a fast enough reaction time to prevent yourself getting dashed against the rocks.

346 total views, no views today

Posted By: BC_Programming
Last Edit: 04 Apr 2013 @ 07:25 AM

EmailPermalinkComments (0)
Tags
Categories: Programming
 21 Mar 2013 @ 9:08 AM 

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

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

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

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

  1.  
  2. someprogram.exe /switch:argument /sw:"file 1.txt" "filename.txt" /doall
  3.  

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

Arguments

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

  1.  
  2.   /// <summary>
  3.         /// Represents an Argument. This includes arguments that exist bare on the command line as well as arguments used with a given switch.
  4.         /// </summary>
  5.         public class ArgumentItem : CommandLineElement
  6.         {
  7.             public static ArgumentItem Empty = new ArgumentItem();
  8.             private String _Argument;
  9.  
  10.             protected internal ArgumentItem()
  11.             {
  12.                 _Argument = "";
  13.             }
  14.  
  15.             /// <summary>
  16.             /// Construct an Instance from the given string, assuming the start of an Argument element at the given position.
  17.             /// </summary>
  18.             /// <param name="strParse">Command Line to parse.</param>
  19.             /// <param name="Position">Location to start. This variable will be updated with the ending position of the argument that was discovered upon return.</param>
  20.             public ArgumentItem(String strParse, ref int Position)
  21.             {
  22.                 int startpos = Position;
  23.                 int sloc = startpos;
  24.                 while (char.IsWhiteSpace(strParse.ElementAt(sloc))) sloc++;
  25.                 if (strParse.ElementAt(sloc) == ‘"’)
  26.                 {
  27.                     sloc++;
  28.                     while (true)
  29.                     {
  30.                         if (sloc >= strParse.Length) break;
  31.                         bool doublequote = strParse.Length > sloc + 2 && strParse.Substring(sloc, 2).Equals("\"");
  32.                         //if we found a quote and it’s not a double quote…
  33.                         if (strParse.ElementAt(sloc) == ‘"’ && !doublequote)
  34.                         {
  35.                             sloc++;
  36.                             break;
  37.                         }
  38.                         if (doublequote) sloc++; //add an extra spot for the dual quote.
  39.  
  40.                         sloc++;
  41.                     }
  42.                 }
  43.                 else
  44.                 {
  45.                     sloc = strParse.IndexOfAny(new char []  {‘/’, ‘ ‘}, sloc);
  46.                 }
  47.                 _Argument = strParse.Substring(Position, sloc – startpos);
  48.                 Position = sloc;
  49.             }
  50.  
  51.             /// <summary>
  52.             /// returns the Argument this Object represents. This will include quotation marks if they were used in the originally parsed string.
  53.             /// </summary>
  54.             public String Argument
  55.             {
  56.                 get { return _Argument; }
  57.             }
  58.  
  59.             /// <summary>
  60.             /// implicitly converts an ArgumentItem to a String.
  61.             /// </summary>
  62.             /// <param name="value">ArgumentItem to implicitly convert.</param>
  63.             /// <returns>the result from calling Chomp() on the given instance.</returns>
  64.             public static implicit operator String(ArgumentItem value)
  65.             {
  66.                 return value.Chomp();
  67.             }
  68.  
  69.             /// <summary>
  70.             /// returns the Argument value. If it starts with and endswith quotation marks, they will be removed.
  71.             /// </summary>
  72.             /// <returns></returns>
  73.             public String Chomp()
  74.             {
  75.                 if (_Argument.StartsWith("\"") && Argument.EndsWith("\""))
  76.                     return _Argument.Substring(1, _Argument.Length2);
  77.                 else return _Argument;
  78.             }
  79.  
  80.             public override string ToString()
  81.             {
  82.                 if (Argument.Any(Char.IsWhiteSpace))
  83.                     return "\"" + Argument + "\"";
  84.                 else return Argument;
  85.             }
  86.         }
  87.  

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

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

 
someprogram /d:argument.exe
 

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

  1. public class Switch : CommandLineElement
  2. {
  3.     internal static String []  SwitchPreceders = new string []  {"–", "-", "/"};
  4.     private ArgumentItem _Argument = ArgumentItem.Empty;
  5.     private String _SwitchValue;
  6.  
  7.     public Switch(String strParse, ref int StartLocation)
  8.     {
  9.         while (String.IsNullOrWhiteSpace(strParse.ElementAt(StartLocation).ToString())) StartLocation++;
  10.         var sLoc = StartLocation;
  11.         var retrieved = SwitchPreceders.
  12.             FirstOrDefault((s) => !(sLoc + s.Length > strParse.Length) &&
  13.                                   strParse.Substring(sLoc, s.Length)
  14.                                           .Equals(s, StringComparison.OrdinalIgnoreCase));
  15.         if (retrieved == null)
  16.         {
  17.             throw new ArgumentException("Passed String " + strParse +
  18.                                         " Does not have a switch preceder at position " + StartLocation);
  19.         }
  20.         var NextSpace = strParse.IndexOfAny(new char []  {‘ ‘, \t, ‘/’, ‘:’}, sLoc + 1);
  21.         //if(((NextSpace-sLoc)-sLoc+1) <= 0) throw new ArgumentException("Error Parsing Switch");
  22.         _SwitchValue = strParse.Substring(sLoc + 1, NextSpace – sLoc – 1);
  23.         sLoc += retrieved.Length; //we don’t want the switch itself.
  24.         //now we need to determine where the Switch ends. colon or space seems reasonable. If a colon, the next entity will be an argument.
  25.         StartLocation = NextSpace;
  26.         //if the char at NextSpace is a Colon…
  27.         if (strParse.ElementAt(NextSpace) == ‘:’)
  28.         {
  29.             //interpret as an argument
  30.             NextSpace++;
  31.             _Argument = new ArgumentItem(strParse, ref NextSpace);
  32.         }
  33.         StartLocation = NextSpace;
  34.     }
  35.     public String SwitchValue
  36.     {
  37.         get { return _SwitchValue; }
  38.     }
  39.     public String Argument
  40.     {
  41.         get { return _Argument; }
  42.     }
  43.     //Constructs an instance of a switch from the given location.
  44.     public static bool SwitchAtPos(String strParse, int Location)
  45.     {
  46.         var retrieved = SwitchPreceders.
  47.             FirstOrDefault((s) => !(Location + s.Length > strParse.Length) &&
  48.                                   strParse.Substring(Location, s.Length)
  49.                                           .Equals(s, StringComparison.OrdinalIgnoreCase));
  50.         return retrieved != null;
  51.     }
  52.     public override string ToString()
  53.     {
  54.         return "//" + _SwitchValue + ":" + _Argument.ToString();
  55.     }
  56.     public bool HasArgument()
  57.     {
  58.         return _Argument.Equals(ArgumentItem.Empty);
  59.     }
  60.         }

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

  1. CmdParser cp = new CmdParser();
  2. if(cp.HasSwitch("f") && cp ["f"] .HasArgument()) _usefilename=cp ["f"] .Argument;

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

  1.  _usefilename=cp.HasSwitch("f")?cp ["f"] .Argument:_usefilename;

926 total views, 4 views today

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

EmailPermalinkComments (0)
Tags

 Last 50 Posts
 Back
Change Theme...
  • Users » 856
  • Posts/Pages » 191
  • Comments » 67
Change Theme...
  • VoidVoid « Default
  • LifeLife
  • EarthEarth
  • WindWind
  • WaterWater
  • FireFire
  • LightLight

PP



    No Child Pages.

Windows optimization tips



    No Child Pages.