Finally got around to posting my first article to CodeProject.com. I’ve found the site to be quite useful, and I’ve been wanting to contribute to it for some time now. I figured I could fill a niche related to saving and retrieving files to/from a SQL 2005 and above database.

Check it out here – http://www.codeproject.com/KB/database/sqlFileExample.aspx

I have gotten a few comments about the FILESTREAM storage new to SQL 2008. This MSDN technical article shows a nice chart comparing various ways to store files used with a database application – http://msdn.microsoft.com/en-us/library/cc949109%28v=sql.100%29.aspx.

And the comments are correct – FILESTREAM is nice, but only works with SQL 2008. I will be planning to add a short section to my article, explaining FILESTREAM. Check back for updates soon!

My first app is for sale – RunAsPlus – on AllMyApps.com, a new windows app store that is trying to capture the idea that the iPhone and Android have been making waves with. The pic below is linked right to the product page.

It surprises me that something similar has not been established before (if it was, I wasn’t paying attention!).

Windows has provided developers with a rich SDK for far longer than iOS or Android, yet there has been little work to centralize application distribution until now. Furthermore, I’m much handier with .NET right now than I am with xCode/Cocoa or Eclipse/Java, and I have far more ideas about web- or desktop-based apps since I spend more time using a desktop or laptop than a mobile device. Perhaps that trend will change for me in the future, but right now, AllMyApps.com is the outlet I’ve been looking for. My experience thus far has been positive (albeit no sales in the first few days…).

Creating my app was the easy part. It was the extra stuff that took more time (EULA, licensing, icons, deployment, etc.). You do have to plan before you can submit your app. Here are some short explanations of how I conquered these issues:

  • EULA
    • I have little experience with creating a EULA, as this is my first app that is officially for sale…so I searched around and found a free trial of RocketLawyer.com would allow you to generate the software EULA by answering straightforward questions. Good stuff!
  • Licensing
    • This was probably the part that caused me the most trouble. License key generation can be a complex matter, and managing them can be even worse! Without much experience in the matter, I was able to cook up a simple scheme to meet my needs.
    • AllMyApps.com will maintain a license pool for you or connect users to your licensing server. I went with the pool and pre-generated a couple hundred keys.
    • While my scheme is far from hack-proof, it provided a valuable learning experience related to integrating license keys and license key checks into an application.
    • Note that Android and iOS apps don’t have to deal with this issue in the same way since their target platforms are more restricted than a full PC operating system.
  • Icons
    • I was surprised at how tricky it is to get a “good” icon into Visual Studio and have it scale appropriately. Before this project, I had just used freebie icons and took for granted the way they had different images embedded to meet scaling needs.
    • I was also disappointed to see that Photoshop Elements 8 doesn’t include any sort of “Save As…” functionality for Windows icons. I ended up using gimp to take the multiple images (png images, 16×16, 32×32, 48×48) and squish them into a single icon file.
  • Deployment
    • AllMyApps.com attempts to provide users with a sort of automatic deployment (click-once-to-install thinking), thus, they require a silent installer option.
    • Visual Studio 2010 can do InstallShield LE or a traditional MSI…I didn’t care to register for the InstallShield stuff, so I went with the MSI package. Silent install is a snap – it’s included with normal MSI packages as a “/qb” parameter.
    • Visual Studio’s setup projects don’t give you a way to create “normal” shortcuts – only advertised shortcuts. The idea behind the advertisement is to allow your application to self-repair or run user-based setup tasks during first launch, etc. I had no need for this type of behavior, and in fact, the advertised shortcuts caused issues since they do not allow a user to shift + right-click and select “run as a different user” or similar option. Instead, I hunted down a special MSI property that disables shortcut advertisement, allowing me to utilize the handy MSI builder in Visual Studio without the shortcut problem!
      • If you want to know how I did this, please email me and I’ll be happy to share.
  • User Account Control
    • Ah…yet another challenge. My app store the settings file (an XML document of commands and parameters that the user can customize), by default, in the “C:Program FilesRunAsPlus” area.
    • If an application does not properly request admin rights at launch and requires write access to certain registry or files system areas (like C:Program Files), the application will be forced into a virtual file and registry system and the “real” areas will be unaffected. So, if unabated, a save on the settings file actually does save…but in a totally different area!
    • Fortunately for RunAsPlus users, I fixed this issue by adapting the manifest to request admin right at each launch. If you don’t use UAC (I don’t, by the way, as I think it is annoying!), no worries. If you do, you’ll get a prompt like you would for any other app that requires “admin” rights and things will work as expected.
      • Again, if you’d like to know how I did this, please email me and I’ll be happy to share.

Whew! Solving these issues certainly took a few evenings, but I came away with a better understanding the entire development and deployment process for .NET winform applications. Many thanks to my wife who helped keep me on track despite challenges!

Feel free to post with questions or comments…thanks for reading.

 

I’ve been doing some reading about differences between Visual Basic .NET and C# of late, and I’ve used both a bit now. I’m at a crossroads in my learning and am working to bridge the gap from forms- and console-based apps into the world of ASP .NET.

Frankly, I’m torn between VB and C# when attempting to pick a language to work with on my ASP .NET studies.
Here are a few articles I’ve been reviewing. Some old, some new.

Eventually, I think I settled on C# rather than VB. One thing I’m getting  a bit tired of is the excessive typing in VB. It seems that even simple statements can be quite lengthy.

For instance…

VB -

Dim strX as string = "123"

C# -

string strX = "123";

A small difference, but one that adds up over several hundred lines of code. Intellisense helps, but is really just a band-aid for the issue.

VB also lets you be sloppy and get away with it – anyone heard of “option strict”… albeit, C# can be too detail oriented for my liking – case sensitivity…*sigh*

My opinion, in general, follows with the idea that VB is simply an old language that is purely for “Microsoftish” stuff, while C# is built from the ground up to attract Java and C-based programmers. It seems everything I run into related to programming nowadays – Android SDK, iOS SDK, Apex for Salesforce.com, etc. is using something that is similar to C# syntax. I’m wishing I wouldn’t have stopped using C# after grad school now! Fortunately, I do think learning more about one topic teaches about another – and programming is no different. Just as learning Spanish deepens your understanding of English, exploring VB helped me appreciate more of the C# syntax and structure.

As a final note, one VBish thing that rocks is the My. namespace – and C# doesn’t have it by default! This namespace allows easy access to the file system, registry, audio, etc. Perhaps there are better ways to accomplish some of this stuff, but it’s nice to know it’s there. I’m sure I’ll be exploring alternatives.

To use statements like “My.Computer” in C#:

  1. Import a reference to “Microsoft.VisualBasic”
    • Right-click References in Solution Explorer and select Add Reference…
    • Look on the .NET tab and find “Microsoft.VisualBasic” – I’d sort by Component Name to make this easier
  2. Add a “using” statement so you don’t have to fully qualify the names all the time
    • “using Microsoft.VisualBasic.Devices;”   -> will give you traditional access (like “Computer objX = new Computer();”)
    • “using My = Microsoft.VisualBasic.Devices;”   -> will give you a VBish feel (like “My.Computer objX = new Computer();”)
  3. Refer to these two posts for more information, if desired…
  4. Enjoy your VB crutch!  :)

PS – VB did away with needing a “& _” for line breaks…maybe C# will dump the “;” at the end of each line sometime?

I was looking for a way to build a simple exception method for lots of try blocks in a .NET app today.
Here’s what I came up with. I like it. I am enjoying reflection for sure!
This is the method I placed into my module. It takes an exception and a string as parameters. The exception allows me to add extra stuff later if I want (like stack trace, etc.). Right now, I just care about ex.Message.

Public Sub mod_Show_Error_Message(ByRef ex As Exception, ByVal strMethod As String)
MessageBox.Show("Current method: " & strMethod & vbCrLf & "Exception message: " & ex.Message, "IA&P error message", MessageBoxButtons.OK, MessageBoxIcon.Error)
End Sub

This allows me to place very simple, identical calls into each of my Try statements. Here is a sample block with a call to the above subroutine.

Public Sub mod_Set_Form_DefaultTitle()
Try
frmMain.Text = mod_m_strMainFormTitle
Catch ex As Exception
mod_Show_Error_Message(ex, Reflection.MethodBase.GetCurrentMethod.Name)
End Try
End Sub

Note that the MethodBase.GetCurrentMethod.Name passes a string (just as designed) back to my error message subroutine. This simply grabs the method that calls the sub, which is half of what I want in my error message anyway – the exact code causing the issue! The other half is the message that goes with the error, and I get that by receiving the exception object.

Here is a screen shot of the resulting error message (I used another method than the one shown to generate the error).

Sample error message

Note that one caveat of this approach is that you must use meaningful sub and function names.

Continued from part 1

For the brave (and those with programming experience), CodeProject (as usual) has a lengthy, thorough article with a complete example.
See http://www.codeproject.com/KB/dotnet/Reflection.aspx if you wish.

My example is much more focused. So…how to call a certain method at runtime by passing a string…

Couple of “big deals” to keep in mind:

  • Reflection should not be your first choice – thus far, I think of it as a “monkey wrench”. It works, but a regular box-end wrench holds much better. There are better tools for a job perhaps, but this will work
    • Note that my example here could no doubt be redesigned I believe, but I thought reflection was appropriate based on the business and technical cases…plus it seemed like a fun topic to learn about and discuss!
    • My “better tools” idea would probably mean rethinking what you are doing in general
  • Reflection makes things more difficult to troubleshoot
    • If you are changing your program at run time you are certainly changing the way it operates in a fashion different from simple user interaction, and if your method throws an exception, you may have trouble figuring out what caused it
    • You may also be more likely to call the wrong method at the wrong time unintentionally – attention to detail is key
  • From what I know of reflection, it seems like the concept of late binding – which hurts performance, thus I think it is reasonable to believe that reflection-based method calling is slower than traditional method invocation.

OK – here’s my code from my form class that runs the method passed in as a string.

code sample – reflection

Let’s break it down…

This dimensions the variable that will hold the passed in property which signifies what method to look up and invoke.

Private m_strLinkProcedureToRun As String

This is simply the property setup related to the above dim statement.

Public WriteOnly Property prop_strLinkProcedureToRun() As String
Set(ByVal value As String)
m_strLinkProcedureToRun = value
End Set
End Property

This part performs the “magic” of looking up the passed in string that matches a method in the selected module (modLink.vb in this case). Note that all the methods I can possible call here have to have the same number of parameters, and they have to be passed as an array. In this case, my method will use two strings. The first string (item 0 in the array) represents the main thing you are linking a record to (i.e. a user, etc.).

Dim t As Type = GetType(modLink) 'pick what module the sub or funct is in!
Dim m As MethodInfo = t.GetMethod(m_strLinkProcedureToRun) 'search for what we passed in
Dim array(1) As String  'create an array to hold our params
array(0) = m_strIdFromMainForm 'our first parameter - from the main grid

This part gets the id you selected that you wish to link to the “main ID” you passed in (i.e. group you want the user to be added to, etc.). Note that in the full code example, you will see two sections for this method call – this is a way to handle multiple selected items in the DevExpress XtraGrid control that this form uses. Here I just show you the single selection. The invoke method of the methodinfo class will run our desired sub or function, assuming it’s found. The array gets sent with both parameters.

array(1) = gridViewLink.GetFocusedRowCellValue(m_strIdInGridViewLink).ToString '2nd parameter
m.Invoke(Me, array) 'call the function we passed in as a variable

Here is an example of the call to create the class instance and show the form to the user. The XtraGrid on this class is public so it can be bound at runtime as needed – this could have been done with reflection as well, but I wanted to minimize the use to keep things simpler, at least to start with. You can ignore the various properties – the only real important one for our purposes is prop_strLinkProcedureToRun. You may also notice a call to a Fill_Grid sub – that refreshes our main grid after linking has taken place so we see the new relationship.

Dim frmX As New frmLink_Template
Dim strMainID As String = gridView_UserInv.GetFocusedRowCellValue("UserID").ToString

mod_Fill_Grid_UsersGroups_UsersInvLinkForm(strMainID, frmX.gridControlLink, frmX.gridViewLink)
frmX.prop_strIdFromMainGrid = strMainID
frmX.prop_strIdInGridViewLink = "GroupID"
frmX.prop_strFormTitle = "Link groups"
frmX.prop_boolEnableMultiSelectForGrid = True
frmX.prop_boolFormIsSizeable = False
frmX.prop_boolFormIsWideFormat = False
frmX.prop_strLinkProcedureToRun = "mod_Link_UserToGroup"

frmX.ShowDialog()
Fill_Grid_UsersGroups()

Closing

The above example shows a use for .NET reflection for searching and invoking methods in a certain module during runtime, with the method name being a variable. There are other useful methods besides GetMethod – such as GetEvent, but I’ll leave those up to you. My hope is that someone facing a similar issue will find some answers by looking at my example. Please post any relevant questions, and I’ll work to answer them. Thanks for reading!

I’ve been toiling away on a decent-size ADO .NET front-end application for several weeks now.
I was having an issue that caused me to create several “link forms” for linking records to one another (i.e. create relationships in the data model – like a many-to-many mapping record that exists in a fact or relation table).

table example

I was working with my own “data layer”, so to speak. So each form would call a different query, passing the same types of parameters to a different method. An example of the “link” query, as I refer to it, wrapped in a public sub (VB .NET here):

Public Sub mod_Link_UserToGroup(ByVal strUserID As String, ByVal strGroupID As String)
Dim strQuery As String = "INSERT INTO tblFactUsersGroups ([UserID], [GroupID]) VALUES (@UserID, @GroupID)"
Dim sqlCmd As New SqlCommand(strQuery, mod_m_sqlConnIDB)
sqlCmd.Parameters.AddWithValue("@UserID", strUserID)
sqlCmd.Parameters.AddWithValue("@GroupID", strGroupID)
sqlCmd.ExecuteNonQuery()
End Sub

As you can see from the snippet above, this is a straightforward process – just a simple insert query to put the two foreign keys into the fact table.

Here is a thumbnail of the link form. Click it to get an idea of what the form should look like. In short, you are launching it form a form after having selected a user (which gets your userID) and you simply pick the group (which picks up the groupID) you wish to link to that user.

link form

(click to see full image)

By itself, this doesn’t seem to be much of an issue…but suddenly the application requirements began evolving and more and more “link” forms and matching subs were needed. Before the app was actually completed, I ended up with over a dozen similar (but different) forms, which was becoming difficult to manage.

So…I began asking questions…how could I simplify this easily? There has to be a better way!

The answer for this lies in calling the right subroutine. If I could call that dynamically, I could forget about all those like forms and maintain one.

I eventually stumbled across .NET reflection (system.reflection namespace). See .NET Reflection on MSDN for extreme details. The long to short is that reflection allows you to manipulate and inspect types, objects, etc. You can also invoke methods, as well as several other things.

Stay tuned for my next post – there I’ll post my reflection code.