CodeProject, Explorer, iPod, Microsoft, Music, VB.NET, Visual Basic, Windows

GetMyMusicOffOfMyIpodAndOntoMyComputer Application in VB

getmymusicoffofmyipod-open-graph

Originally this application was a console application that I developed to get the music off of my iPod. After my post on transparent forms in Visual Basic I decided to port it to a Widget format to make it easier to use and demonstrate what goes into creating a transparent Windows Forms application…

Necessity Drives Innovation – The Need For This App

Let’s start with the music eating iTunes application. My iPod is the only music player that I have ever owned that does not make it easy to get my music files off of. Even the very cheapest music player you can buy allows you to get your music off of the device easily. If I want to play the music on my computers’ speakers I get a purchase driven interface that concentrates more on selling me something than anything else.

OK, enough applesauce for now. Suffice it to say, I like my iPod – I just don’t like iTunes. I needed to get my music files off of my iPod so that I could play them on my computer without tying up a USB port. I would rather run my code than anyone else s’ on my computer – so an application was born. This application does only one thing without any other options, so it’s a sure fire shoe-in for a widget.

Creating The Background For The Application

ipod_start

My transparent forms application startup screen.

In my opinion, transparent forms applications are really only good for developing widget style application. So the background image you choose should be relatively small. However, with modern new tablet/hybrid systems your interface should be designed to handle both desktop/laptop and tablets. Think small form size with big buttons that are easy to pluck at with your digits. Also, your application should stay the same size (width and height) throughout execution.

Visual Studio will automatically tile whatever image you choose for your background on the form designer by default. This will help you with the layout for the multiple panel interface you will most likely need to come up with. The size of your interface (form) should be the width and height of the tile in the upper left corner of the designer. 

ipod_tiles_background

My application background tiled in the forms designer with the panels in place.

You should create as many panels as needed to hold the different UI states of your app inside of the different tiles. The tiled background gives you a chance to see what your app states UI will look like as you design them. Use the upper left tile inside of the designer to place your designed chrome buttons (min,  close etc…). Like I stated earlier, your interface should be panel based to make it easier to swap them out between application states. Simply take note of the size and location of the panel in the upper left corner tile and swap out panels assigning those values to the other panels as you need to in code. 

Beyond that, read my previous post on transparent forms for more info – it’s an easy and short read through.

Adding Modern Application Features

Windows forms applications lack some of the more modern features that their XAML based counterparts come with out of the box. One of those features, specifically the taskbar based progressbar, can be added to any winforms application with a quick visit to Nuget.

nuget_shell

WindowsAPICodePack in the Nuget package manager.

Being able to see the progress of a long running task while the application is minimized is an important feature for an application such as this. So, with the Nuget package manager opened, search for WindowsAPICodePack and add it to your project. That package gives you all of the code pack API goodness you’ll need to implement that taskbar progressbar functionality. Coding it is pretty much like coding a regular progressbar. You just have to Import the taskbar library from that package in your form and use it.

Most of the time you’ll be coding something like:

TaskbarManager.Instance.SetProgressState(TaskbarProgressBarState.Normal)
TaskbarManager.Instance.SetProgressValue(somecountingint, somecountedint)
' update somecountingint till done
TaskbarManager.Instance.SetProgressState(TaskbarProgressBarState.NoProgress)

Take a look at the file on Github to see how I coded everything.

Recovering Music from an iPod in Visual Basic

ipod_copying

Most of the music files on my iPod were imported from CD which iTunes turns into .m4a files instead of .mp3 files. The extended properties are the same in both cases however.

Recovering the music from an iPod involves reading the extended properties from the music files themselves (which is what the iPod uses). The music files on the iPod itself are contained within a hidden folder named “iPod_Control\Music” (on my iPod video). My code enumerates the connected external drives and searches for the existence of that folder. Inside that folder there are a bunch of randomly named folders – your music files exist in those folders, randomly named of course.

Getting the extended property values turned out to be a bit more daunting than I first thought. I searched to internet and came across a good stackoverflow post that helped me. That code gave me problems – so it wasn’t as easy as cut and paste, but it “got the job done” in the end.

ipod_winexplorer

Windows Explorer doesn’t use the Shell – it IS the graphical shell of the Windows OS.

I used the Windows Shell to parse out the extended properties of the music files and used those values to rename and sort them. I wrote a class to hold all of the information about the music files as I parsed them and made it sort-able by implementing the IEquatable and IComparable interfaces on it. See the file on GitHub to see how I coded it.

The About Page

ipod_complete

When the application completes an about pane pops up with my information. Do I use PictureBox controls with the pointer set to a hand for all of my links? You bet I do! It’s probably the easiest way to get an Internet shortcut in your Visual Basic application. Don’t forget to code the PictureBox.Click handler to open the default browser with my URLs.

Dim strUrl As String = "https://someniftywebaddressgoeshere.something"
Process.Start(strUrl)

What This Application Does Not Do

This application just copies the music files into the folder on the desktop. It doesn’t copy any album art or anything else other than the music files. Also, none of the files on the iPod are altered in any way.

ipod evaluating

Evaluating the music files on the iPod takes an excruciatingly long time in my opinion. Everything is being done over a USB wire and it takes a toll.

On Porting and Portability

Most of the code can probably be moved to .NET Core 3 without a problem by removing all of the Windows specific code such as the Taskbar Progressbar code. The problems come in when you try to port the code used to read the extended properties of the music files. I’ve read that there is a way to make the code portable by using the actual byte offsets of the extended properties on the files to get the values. Maybe I’ll experiment with that at a later date. But for now, not experimenting with byte offsets seems the wisest and less frustrating path to take for me.

 

 

 

 

 

Advertisement
Standard
Microsoft, VB.NET, Visual Basic, Windows

Transparent Forms in VB.NET WinForms Applications

Creating transparent irregular shaped forms in a WinForms applications using Visual Basic is not too difficult. Using a photographic background with a transparent color, a programmer can create some really attractive interfaces. Of course creating an interface sans the standard titlebar chrome requires a bit more work and programming. However, if you want to provide a memorable interface that is attractive as well as personalized – its worth the extra effort required.

 

Start With a New Windows Forms Application

A few form properties need to be changed before your application form is ready for your photographic background. You’ll change these properties using the IDE (its just easier than coding).

  • Set AutoScaleMode to None
  • Set the BackColor to something like Lime or any other color that you will notice right away (it shouldn’t show anywhere in the completed application)
  • Set the FormBorderStyle to None
  • Set the TransparencyKey to White or whatever color you desire to be transparent in your background image (see below)

Create Your Background Image

Your background image should be created with the background color selected in the previous section for transparency in mind. Anything created or painted on the background image using that color will be transparent. So paint the entire background of the image with that color (on its own layer if possible).

Getting the transparency color exactly right in the image can become an issue (as it did for myself in the past). One version of Lime Green isn’t always someone elses version of the same color. Added to this is the fact that there is nowhere to enter or retrieve a hex color value in the IDE at all.

What I do is use the eyedropper tool in Photoshop on a screenshot of the IDE with the TransparencyKey property showing. This way the color is always right and I know I’ll have no problems afterward. Another way of getting it right is to simply use White as the transparency key color. In this case anywhere you would need white inside the interface you would just use an off shade of white instead. Either way you should always set up the TransparencyKey in Visual Studio first.

Adding the required buttons

After adding your background image to the form you have to add at least one button to the interface – the Close button. A minimize button probably wouldn’t be a bad idea eaither. Keep in mind that if you are adding a maximize button to your interface the extra effort that will be required to support it (graphics wise).

Keep in mind that you really don’t have to use the Button control for buttons. You can use any control that emits a Click event. I find using the Label control with the Cursor changed to a pointer is often the easiest way to get the desired effect in many cases.

Coding these buttons is as simple as creating the Click handler function for the button and closing the application or setting the window state.

close button handler

Making the form draggable

Coding the form to be draggable in Visual Basic is a bit easier than most think. Most of the time I create small, widget like applications when I use transparent forms. Applications like these should be easy to move around so I make the entire form draggable. If you are working on something larger the methodology is pretty much the same except for the fact that you’ll be coding it to a specific part of the form (for instance a custom titlebar – you code the extra math) instead of the entire form.

I use one form global to hold the initial MouseDown location on the form which is considered the offset (remember you’re moving the entire form). In the MouseMove event handler you change the Location property by subtracting that offset from the cursor location and setting it. In the MouseUp event handler  you just set the form global to nothing this way it can be used as a check in the MouseMove event handler.

mouse move code

Finally

Although creating a basic transparent form application seems simple at first glance, your project can get complicated quickly. The more functionality you want, the more things can get more tedious. Creating a maximize button means you’ll have to work out horizontal and vertical tiling on the form and certain components. A custom titlebar means more math in the mouse handler functions. If your application has a lot of animations, perhaps the project should be moved to a XAML imterface instead.

Still, if you’re after a custom look and feel for your app – there’s no better start than a transparent form with a photographic background.

Standard
VB.NET, Windows

FileSystemWatcher Class in VB.NET

 

FileSystemWatcher in VB Example

FileSystemWatcher in VB Example

Just a quick post on using the Microsoft file system watcher component in the .Net framework with Visual Basic. Utilizing the Microsoft file system watcher component in .Net with Visual Basic, you’re able to watch a directory structure for changes to its contents and respond with Visual Basic code.

Using the.net file watching component is pretty simple on the surface. Microsoft provides enough example code in their documentation to give any new user a great head start. Basically, to use the file system watcher component you have to first set permissions to full trust, create a new file system watcher object, set its properties, create handlers for the events the file system watcher object raises, and then set it to enable raising events.

When I first started tinkering around with the file system watcher component everything worked as expected. I did, after watching the events closely, come across one caveat. If you set the file system watcher object to include subdirectories, when you delete a subdirectory that has files contained in it the event raised by the file system watcher will only show the event for that subdirectory being deleted not for any of the files contained in that directory. This makes it a bit more difficult to keep track of the directory structure.

My solution was to create a list in order to compare file paths of the files contained in the folder to the path of the sub folder being deleted. Eventually, I found it easier to break this functionality off into a new class that I could adapt for reuse. I felt that using a list to keep track of the folders and files was better for performance then re-parsing the file system every time a subfolder was deleted. I wrote a simple dialog project for demonstration purposes that I’ll post on github so that you can check out the code.

 

Reference:

https://docs.microsoft.com/en-us/dotnet/api/system.io?view=netframework-4.7

https://docs.microsoft.com/en-us/dotnet/api/system.io.filesystemwatcher?view=netframework-4.7

 

 

Example Code on Github

Imports System.IO
Imports System.Security
Imports System.Security.Permissions

''' <summary>
''' Singleton that initializes and handles file watcher changes
''' </summary>

<CLSCompliant(True)> Public Class MyDirectory
    Public Shared Event Change(path As String)
    Public Shared Event Create(path As String)
    Public Shared Event Delete(path As String)
    Public Shared Event Renamed(oldpath As String, newpath As String)
    Private Shared watched As String
    Private Shared retList As List(Of String)
    Public Shared ReadOnly Property Count As Integer
        Get
            Return retList.Count
        End Get
    End Property
    Private Sub New()
    End Sub
    Public Shared Function ListDirectory(path As String) As List(Of String)
        retList = New List(Of String)
        watched = path
        Try
            Dim di As DirectoryInfo = New DirectoryInfo(path)
            For Each file In di.EnumerateFiles("*", SearchOption.AllDirectories)
                retList.Add(file.FullName)
            Next
            For Each folder In di.EnumerateDirectories("*", SearchOption.AllDirectories)
                retList.Add(folder.FullName)
            Next
        Catch ex As DirectoryNotFoundException
            Console.WriteLine("Directory not found: {0}", ex.Message)
        Catch ex As SecurityException
            Console.WriteLine("Security Exception:\n\n{0}", ex.Message)
        Catch ex As Exception
            Console.WriteLine("Exception occurred: {0}", ex.Message)
        End Try
        Return retList
    End Function
    <PermissionSet(SecurityAction.Demand, Name:="FullTrust")>
    Public Shared Sub WatchDirectory(path As String)
        Dim fswatcher As New FileSystemWatcher
        fswatcher.IncludeSubdirectories = True
        fswatcher.Path = path
        fswatcher.Filter = ""
        AddHandler fswatcher.Changed, AddressOf onChanged
        AddHandler fswatcher.Created, AddressOf onCreated
        AddHandler fswatcher.Deleted, AddressOf onDeleted
        AddHandler fswatcher.Renamed, AddressOf onRenamed
        fswatcher.EnableRaisingEvents = True
    End Sub
    Private Shared Sub onChanged(src As Object, evt As FileSystemEventArgs)
        RaiseEvent Change(evt.FullPath)
    End Sub
    Private Shared Sub onDeleted(src As Object, evt As FileSystemEventArgs)
        Dim tList As List(Of String) = New List(Of String)
        Dim thepath As String = evt.FullPath
        For Each path As String In retList
            If path.StartsWith(thepath) Then
                tList.Add(path)
            End If
        Next
        For Each path As String In tList
            retList.Remove(path)
            RaiseEvent Delete(path)
        Next
    End Sub
    Private Shared Sub onCreated(src As Object, evt As FileSystemEventArgs)
        retList.Add(evt.FullPath)
        RaiseEvent Create(evt.FullPath)
    End Sub
    Private Shared Sub onRenamed(src As Object, evt As RenamedEventArgs)
        Dim thepath As String = evt.OldFullPath
        Dim fname As String = ""
        Dim dicRename As Dictionary(Of String, String) = New Dictionary(Of String, String)
        For Each path As String In retList
            If path.StartsWith(thepath) Then
                If Equals(path, thepath) Then
                    dicRename.Add(path, evt.FullPath)
                Else
                    fname = path.Substring(path.LastIndexOf("\") + 1)
                    dicRename.Add(path, evt.FullPath & "\" & fname)
                End If
            End If
        Next
        For Each KVPair As KeyValuePair(Of String, String) In dicRename
            retList.Remove(KVPair.Key)
            retList.Add(KVPair.Value)
            'Console.WriteLine("Renamed from: {0} \n To: {1}", KVPair.Key, KVPair.Value)
            RaiseEvent Renamed(KVPair.Key, KVPair.Value)
        Next
    End Sub
End Class

Standard
VB.NET, Windows

Synchronous Delegate in VB.NET

I didn’t know why I would need one either until the need came up (“Oh no, my UI is on a different thread!”). Delegates are described as similar to function pointers in C++ in the Microsoft documentation. When I read that I said to myself “yeah, but Visual Basic doesn’t work like that wonderful and painfully frustrating language that AT&T invented so long ago”. So Microsoft still has to learn that Chinese is painful if you’re not from China. I’m discovering in the new VB, it does kinda work like that – a little.

In my case I had a shared class and a form that were working together. My class raised an event that was handled on the form to update a control on the form. The event also had parameters that were passed with the event to the event handler on the form. When the handler was invoked I received an exception that stated the control I was accessing was on another thread. I didn’t have to deal with this in the old VB under ‘normal’ circumstances. If I did I would have to be the C++ programmer working in VB – and that would have been considered a work around at best. So this is vast new territory for me, and I apologize ahead of time if something isn’t perfect. And yes, its a Windows Forms project with no XAML.

So… How To

Conceptually, you have to create a Delegate (a function pointer in C++) for your method (yeah, the one that updates the control) that gets used (dereferenced and called) by the user control Invoke method which invokes the method (yeah, that one) on its thread. On an aside, don’t ask why I think Microsoft put a C++ programmer in charge of Visual Basic NET. However, I’m taking the bad with the good here – the new Thread way is really powerful in my opinion. I just really would have preferred this kind of ‘icky’ stuff to be abstracted away. I guess you can’t have that multi-thread evil at Microsoft with VB without a bit of ‘ick’. In other words, I can’t help but to be critical; it’s still kind of ‘hakish’ if you ask me.

OK, as I stated earlier, the event was handled on a form to update a control on the form. The first thing to do is to declare a Delegate at the top after the opening of the form class. The declaration is similar to an interface declaration in that there is no body to the declaration, just the function (or method) signature. Name the Delegate something like controlUpdateDelegate. Now go and code the controlUpdate method, which should be easy considering its probably the same code you wrote in your original handler. Now, in the original event handler, you’ll need to start an If block that tests for the control you’re updating InvokeRequired property (no autocomplete from the IDE unfortunately). If that boolean is true you have to create a New Delegate (updateControlDelegate) with the AddressOf the function you wrote to update the control (controlUpdate). After that you have to call that controls (the one you’re updating) Invoke method with the Delegate you created and the parameters you originally sent to the event handler. If that InvokeRequired boolean is false just call that method you created.

That’s it – that’s what worked for me.

Some Example Code Structure

' on the form is someControlPublic 
Class someForm
 Public Delegate Sub controlUpdateDelegate(someParam as String) 

 Public Sub New()
   AddHandler someClass.coolEvent, AddressOf  coolEventHappened
   someClass.doSomethingCool()
 End Sub

 Private Sub coolEventHappened(someParam As String)
   If someControl.InvokeRequired Then
     Dim del = New controlUpdateDelegate(AddressOf controlUpdate)
     someControl.Invoke(del, someParam)
   Else 
     controlUpdate(someParam)
   End If
 End Sub

 Private Sub controlUpdate(someParam As String)
 ' update someControl here with someParam
 End Sub
End Class

Public Class someClass
  Public Shared Event coolEvent(someParam As String) 

  Public Shared Sub doSomethingCool() 
    RaiseEvent coolEvent("Cool!") 
  End Sub

End Class.
Standard
VB.NET, Visual Basic, Windows

Getting System Information With WMI and VB.NET

35608522201_0687ca50aa_o

Machine Information app

I’ve been getting back into developing with Visual Basic lately. I’ve learned much of what I need to know in the past while in college; or so I thought. Much has changed since those days of Visual Basic 6. Everything is done a bit differently now using dot NET. Before, everything was Component Object Model components – and I really liked Visual Basic 6 for making it easier to develop those type of components. ActiveX controls, servers, hell – even application documents that ran inside of Internet Explorer was just easier to develop with VB than anything else. The Visual Basic runtime dll was in charge of running a lot of business infrastructure in the past.

Now a days its the mighty ubiquitious framework called Dot Net that drives business development. Made up of a huge collection of classes, dot NET is central to every language that runs on Microsoft. Even C++ developers write managed code these days. Instead of a runtime dll we get the Common Language Runtime, which interprets code written in any Microsoft language and churns out a bit of Intermediate Language that runs on a virtual machine. While its true that almost everything I am doing in VB now is a learning experience I see the value in this managed code base already; a lot just got easier.

One of the wisest decisions Microsoft has made recently was the release of the Community Edition of Visual Studio. A corresponding version of Microsofts flagship IDE used to cost a fortune in the past. Now, for the lone developer, its free to download and code with – great! All the code here is written and compiled with this IDE so download it and give it a try.

35570506482_ca1635cb8f_o

Explicitly adding the System.Management assembly reference to my project

Getting system information by querying into the Windows Management Instrumentation system isn’t that difficult. Setting up the project to use the namespace was out of the ordinary – you have to explicitly add the reference to the System.Management namespace assembly to the project. There will be no help from the IDE with this. So you have to go to the Project properties page, click on References in the left column, hit the Add button, click on Assemblies->Framework in the left column, go down to the System.Management namespace and make sure the checkbox is checked. The same goes for the System.ServiceProcess namespace if you’re going to look at the running services as I have.

Basically, I’ve been working off of Microsoft code examples to get to where I am with this. To query WMI you set up and use a ManagementObjectSearcher class with your query and then iterate over the results. The sample application turns the query results into a List of string Dictionaries. Most of the time you’ll want to do a custom query to retrieve the specific information you desire instead of returning entire classes of information the way I have in the example application. Also, the queries take time more time than you might be used to, and this may become a problem. Using a separate thread to run your queries will improve response time. For instance I get a ContextSwitchDeadlock Exception if I do not run the Product query on a separate thread.

Why do the application at all? The one problem I have had is remembering the exact members of the different WMI classes I am querying for. The example app returns the entire class, or array of classes, with null values turned into empty strings for reference sake. It should be enough to get anyone started with building and testing the exact query they need.

There are dozens of scenarios where you would want to glean a bit of information from the System.Management namespace. Hopefully this example can help you on your way.

Download Links:

MachineInfo.exe

Entire Project on GitHub

References:

Standard