Archive for Desktop applications

Background process in vb.net

This month i started a new software, it’s a SEO Analisys Tool, and i needed to threat multithreading and background operations handling. Giving a look inside the .Net Framework i found a very interesting class, the BackgroundWorker class. First of all i have to tell you where it’s placed, in most articles on the web they forget to tell the reader where he can find it. It’s placed into the System.ComponentModel namespace.
The BackgroundWorker class is a really simple to use class, it gives you the opportunity to handle multitasking in a very easy way.

Basic informations about the class

The BackgroundWorker class exposes just few events to control the status of the process an to notify what’s going on.

  1. DoWork (in this you’ll write all the code to execute)
  2. ProgressChanged (raised when the thread execution process changes)
  3. RunWorkerCompleted (when the thread job is finished)

All that you have to know is

  1. On the top of your code page include the System.ComponentModel namespace (imports System.ComponentModel)
  2. In the DoWork event write your code loop and remember to throw the ProgressChanged event if you need to handle it (RaiseEvent ProgressChanged(me)
  3. Handle the process cancellation in the DoWork loop checking for CancellationPending flag (if bgWork.CancellationPending then e.cancel)
  4. if you need the thread cancellation support you have to add a line of code to the New sub (bgWork.WorkerSupportsCancellation = true)

I know it seems too easy to be true but it’s really so…

Here you can find a sample piece of code to get download progress in vb.net


TAGS: Asp.net, dotnet, code snippet, seo, search engine optimization, visual studio.net, sample code, c#, vb.net

Play wav file in vb.Net

Today i was working on a restaurant software, the customer asked me to play a sound alarm when a new order arrives because he can’t stay all the time looking at the software. I found it very easy, the .net framework is really rich of useful classes to use :)

Here is the code to play a wav file:

Dim Sound As New System.Media.SoundPlayer()

Sound.SoundLocation = “your path to the .wav file” ‘ex.: c:\mysound.wav
Sound.Load()
Sound.Play()

That’s all, extremely easy… i really don’t know why i wrote this :) maybe you could save 1 minute of time


TAGS: Asp.net, dotnet, code snippet, seo, search engine optimization, visual studio.net, sample code, c#, vb.net

Age calculation function in vb.net

I know this is a really simple task but i needed it in a project and i found a working function on www.freevbcode.com so i decided to publish it here too :)

Public Function GetAge(ByVal Birthdate As System.DateTime, _
Optional ByVal AsOf As System.DateTime = #1/1/1700#) _
As String

‘Don’t set second parameter if you want Age as of today

‘Demo 1: get age of person born 2/11/1954
‘Dim objDate As New System.DateTime(1954, 2, 11)
‘Debug.WriteLine(GetAge(objDate))

‘Demo 1: get same person’s age 10 years from now
‘Dim objDate As New System.DateTime(1954, 2, 11)
‘Dim objdate2 As System.DateTime
‘objdate2 = Now.AddYears(10)
‘Debug.WriteLine(GetAge(objDate, objdate2))

Dim iMonths As Integer
Dim iYears As Integer
Dim dYears As Decimal
Dim lDayOfBirth As Long
Dim lAsOf As Long
Dim iBirthMonth As Integer
Dim iAsOFMonth As Integer

If AsOf = “#1/1/1700#” Then
AsOf = DateTime.Now
End If
lDayOfBirth = DatePart(DateInterval.Day, Birthdate)
lAsOf = DatePart(DateInterval.Day, AsOf)

iBirthMonth = DatePart(DateInterval.Month, Birthdate)
iAsOFMonth = DatePart(DateInterval.Month, AsOf)

iMonths = DateDiff(DateInterval.Month, Birthdate, AsOf)

dYears = iMonths / 12

iYears = Math.Floor(dYears)

If iBirthMonth = iAsOFMonth Then
If lAsOf < lDayOfBirth Then
iYears = iYears - 1
End If
End If

Return iYears
End Function

As you can see it’s really simple, just cut & paste in your project, it works fine and you don’t loose 10 minutes of work :)


TAGS: Asp.net, dotnet, code snippet, seo, search engine optimization, visual studio.net, sample code, c#, vb.net

High quality thumbnails in VB.Net

When i started .Net programming i appreciated all the new functionalities of the framework, everything was easier and faster to do. I tought the same thing about thumbnails generation when i found the GetThumbnailImage method of the System.Drawing.Bitmap class but giving a deeper look at it’s behaviour i understood it was not so easy.

WHY IT WASN’T SO EASY
The GetThumbnailImage method isn’t so useful because image formats like JPG can store the thumbnail image inside the same file. A lot of graphics softwares store the thumbnail version of the image into the .JPG file and you can’t choose it’s width, height and quality. The GetThumbnailImage method checks if there’s a thumbnail image stored into the file and, if the thumb is found, it returns that thumbnail version scaled to the width and height you requested. If the thumbnail version of the image is smaller then the size you asked for you can imagine what will be the result, a very low quality and pixelated image. If you want to have the full control over the thumbnail quality you have to use something different by the GetThumbnailImage method.

THE APPROACH
What we have to do is to load the JPG file into a System.Drawing.Image object, scale it to the desired width and height preserving a good quality and save it to a new file.

To preserve the image quality we have to follow these few steps:

  • Load the original file into a System.Drawing.Image object
  • Create the target image with the desired size as System.Drawing.Bitmap
  • Create a System.Drawing.Graphics object from the target Bitmap to draw the scaled image
  • Set the System.Drawing.Graphics object property SmoothingMode to HighQuality
  • Set the System.Drawing.Graphics object property CompositingQuality to HighQuality
  • Set the System.Drawing.Graphics object property InterpolationMode to High
  • Draw the original image into the target Graphics object scaling to the desired width and height
  • Get the System.Drawing.Imaging.ImageCodecInfo object of the JPEG file format
  • Set the Codec param System.Drawing.Imaging.Encoder.Quality to the desired quality (for jpg is 0-100)
  • Save the new image using the Codec and the filled quality parameter

THE CODE
I wrote a simple class CImageHelper where i put all the imaging routines, here there’s a simple version with the SaveImage function to save ThumbNails (or scaled versions of any image) with a very high quality.

Click here to download the code


TAGS: Asp.net, dotnet, code snippet, seo, search engine optimization, visual studio.net, sample code, c#, vb.net

Unhandled exception Win32Exception,Error creating window handle

————————————
Unhandled exception Win32Exception,Error creating window handle.,System.Windows.Forms, at System.Windows.Forms.NativeWindow.CreateHandle(CreateParams cp)
at System.Windows.Forms.Control.CreateHandle()
at System.Windows.Forms.Control.get_Handle()
at System.Windows.Forms.Control.CreateGraphicsInternal()
at System.Windows.Forms.ThreadExceptionDialog..ctor(Exception t)
at System.Windows.Forms.ThreadExceptionDialog..ctor(Exception t)
at System.Windows.Forms.ThreadContext.OnThreadException(Exception t)
at System.Windows.Forms.Control.WndProcException(Exception e)
at System.Windows.Forms.ControlNativeWindow.OnThreadException(Exception e)
at System.Windows.Forms.NativeWindow.Callback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)
at System.Windows.Forms.UnsafeNativeMethods.DispatchMessageW(MSG& msg)
at System.Windows.Forms.ComponentManager. System.Windows.Forms.UnsafeNativeMethods+IMsoComponentManager. FPushMessageLoop(Int32 dwComponentID, Int32 reason, Int32 pvLoopData)
at System.Windows.Forms.ThreadContext.RunMessageLoopInner(Int32 reason, ApplicationContext context)
at System.Windows.Forms.ThreadContext.RunMessageLoop(Int32 reason, ApplicationContext context)
at System.Windows.Forms.Application.Run(Form mainForm)
————————————————

This is a very boring error, it means that all the available windows handlers are finished so your application can’t create new windows. The limit seems to be 1000 windows but as you can imagine it’s really hard to think that someone could write a program that uses 1000 opened windows. The problem is that somewhere in your code you think you have closed forms and released controls but they’re just hidden and continue to occupy memory and handlers. I had this problem with a software developed by my company, RYHAB Solutions, and we lost a lot of time to figure out where the problem was. At the end we understood what was going on.

We had in our code something like this:

public sub CloseWindow()
if typeof(me) is mybaseclass then
me.visible=false
else
me.close()
end if
end sub

We used this sub in a base class so all the classes that hinerited by this returned “mybaseclass” when calling typeof(me). This caused all the windows to be hidden instead of closed so they occupied all the available handlers in few hours and program crashed.

I searched a lot on the web and a lot of people talked about freeing manually resources and other strange things, someone assumed that it could be a .net bug. Actually i can say that it was my fault, no strange things behind, just a programming bug. I’m sure that most of the people that have the same problem could solve it as i did just ensuring that they close their forms properly.
Don’t waste time searching for strange solutions, just check what you do with forms :)

If you have this error message in your application use the CLR Debugger provided by Microsoft. It’s a graphical tool that shows you everything appening in a managed application, opened forms, memory usage, controls, events … everything. This is really useful to understand if something you tought was closed is opened instead.

Here is the link to download the tool:
http://msdn2.microsoft.com/en-us/library/7zxbks7z.aspx

maybe it requires the Platform SDK, you can get it on Microsoft site too.


TAGS: Asp.net, dotnet, code snippet, seo, search engine optimization, visual studio.net, sample code, c#, vb.net

Custom ListBox with icons in .Net

Having a nice interface is a must for professional software, it’s why the Custom Controls market is growing so fast. Programmers can have a nice interface without writing a single line of code, all that they have to do is to buy a Control Library. If you’re planning to save money and write your own custom controls i hope that this small sample could show you something interesting. In this sample i created an extended listbox control that shows:

  • An icon for each item
  • A title for each listbox item
  • A subtitle for each listbox item

The main things to do are:

  • Add a New() method and setup the listbox to be drawn in ownermodevariable
  • Create a new class to handle single items (in our case ItemEX)
  • Create the functions to add custom items (ItemEX) to listbox
  • Create the DrawItemHandler function to draw the items as you like
  • Handle the Resize,DrawItem and MeasureItem event for the new control

When you decide that a control will be drawn by code you have to handle all these events and mainly the DrawItem event. To make a control ownerdrawn use Me.DrawMode = DrawMode.OwnerDrawVariable in the constructor of your control ( New() )I think that giving a look at the code will be easier to understend.

Public Class ListBoxEX
    Inherits System.Windows.Forms.ListBox
    Public Shadows Event Resize(ByVal sender As Object,_
        ByVal e As EventArgs, ByVal i As Integer)
    Public Shadows Event DrawItem(ByVal sender As Object,_
        ByVal e As DrawItemEventArgs)
    Public Shadows Event MeasureItem(ByVal sender As Object,_
        ByVal e As MeasureItemEventArgs)
 
    Private WithEvents mListBox As System.Windows.Forms.ListBox
    Private IcoFolder As String = Application.StartupPath() + "\Ico\"
    Private Icons As New ArrayList
 
    Public Shadows Function Items(ByVal idx As Integer) As ItemEX
        Return mListBox.Items(idx)
    End Function
 
    Public Class ItemEX
        Public IconIndex As Integer
        Public Text As String
        Public UserID As Integer
        Public User As String
 
        Public Sub New(ByVal _User As String, ByVal _Text As String,_
            ByVal _IconIndex As Integer, ByVal _UserID As String)
            User = _User
            Text = _Text
            IconIndex = _IconIndex
            UserID = _UserID
        End Sub
    End Class
 
    Public Property IconsFolder()
        Get
            Return IcoFolder
        End Get
        Set(ByVal Value)
            IcoFolder = Value
        End Set
    End Property
 
    Public Sub AddIcon(ByVal filename As String)
        Dim icona As Icon
        Dim fname As String
 
        fname = IconsFolder.ToString + filename
        icona = New Icon(fname)
        Icons.Add(icona)
    End Sub
 
    Public Sub New()
        MyBase.New()
        Me.DrawMode = DrawMode.OwnerDrawVariable
        mListBox = Me
    End Sub
 
    Public Sub Add(ByVal _User As String, ByVal _Text As String,_
         Optional ByVal _iconindex As Integer = -1,_
         Optional ByVal _UserID As Integer = -1)
        mListBox.Items.Add(New ItemEX(_User, _Text, _iconindex, _UserID))
    End Sub
 
    Private Sub mListBox_Resize(ByVal sender As Object,_
          ByVal e As System.EventArgs) _
      Handles mListBox.Resize
        RaiseEvent Resize(sender, e, 1)
    End Sub
 
    Private Sub DrawItemHandler(ByVal sender As Object,_
        ByVal e As DrawItemEventArgs) Handles mListBox.DrawItem
        e.DrawBackground()
        e.DrawFocusRectangle()
        Dim titFont As New Font("Tahoma", 12, FontStyle.Bold,_
          GraphicsUnit.Pixel)
        Dim subTitFont As New Font("Tahoma", 11, FontStyle.Regular,_
         GraphicsUnit.Pixel)
        Dim titBrush As New SolidBrush(Color.DimGray)
        Dim subTitBrush As New SolidBrush(Color.Gray)
        Dim idx As Integer = e.Index
        e.Graphics.DrawString(DirectCast(mListBox.Items(idx),_
           ItemEX).Text, titFont, titBrush, e.Bounds.Left + 30,_
            e.Bounds.Top)
        e.Graphics.DrawString("Utente: " + DirectCast(mListBox.Items(idx),_
            ItemEX).User, subTitFont, subTitBrush, e.Bounds.Left + 30,_
             e.Bounds.Top + titFont.Height + 2)
        e.Graphics.DrawLine(New Pen(Color.LightGray), 0, _
           e.Bounds.Bottom - 1, e.Bounds.Right, e.Bounds.Bottom - 1)
        If Items(idx).IconIndex > -1 Then
            e.Graphics.DrawIcon(DirectCast(Icons(Items(idx).IconIndex),_
             Icon), e.Bounds.Left + 1, e.Bounds.Top + 2)
        End If
    End Sub
 
    Private Sub MeasureItemHandler(ByVal sender As Object,_
     ByVal e As MeasureItemEventArgs) Handles mListBox.MeasureItem
        e.ItemHeight = 40
        RaiseEvent MeasureItem(sender, e)
    End Sub
End Class

Download this code: ListBoxEx.vb.txt

Download the Demo project Simple Extended ListBox


TAGS: Asp.net, dotnet, code snippet, seo, search engine optimization, visual studio.net, sample code, c#, vb.net

Get Hard Disk Serial and CPUID in .Net

When we sell a software we may decide to make it work only on a specific computer generating a license key that works only for that PC. When the customer changes his hardware he has to ask for a new license key. We can identify a computer retrieving it’s CPU ID and it’s primary disk serial number. In .Net we can do this using the win32 APIs or WMI.
WMI stands “Windows Management Instrumentation”. WMI is a new management technology allowing scripts to monitor and control managed resources throughout the network. Resources include hard drives, file systems, operating system settings, processes, services, shares, registry settings, networking components, event logs, users, and groups. WMI is built into clients with Windows 2000 or above, and can be installed on any other 32-bit Windows client. (description from http://www.rlmueller.net/terms.htm)

Here is the code to query the infos we need:

Public Function GetHDSerial() As String
   Dim disk As New ManagementObject(_
       "Win32_LogicalDisk.DeviceID=""C:""")
   Dim diskPropertyA As PropertyData = _
       disk.Properties("VolumeSerialNumber")
   Return diskPropertyA.Value.ToString()
End Function
 
Public Function GetCPUId() As String
   Dim cpuInfo As String = String.Empty
   Dim temp As String = String.Empty
   Dim mc As ManagementClass = _
       New ManagementClass("Win32_Processor")
   Dim moc As ManagementObjectCollection =_
       mc.GetInstances()
   For Each mo As ManagementObject In moc
     If cpuInfo = String.Empty Then
        cpuInfo = _
         mo.Properties("ProcessorId").Value.ToString()
     End If
   Next
   Return cpuInfo
End Function

Download this code: hdserialandcpuid.vb.txt

there are a lot of ways to query devices info thowards WMI but it’s really difficult to find a good and complete documentation but i found on the web a good tool to explore wmi (WMI Explorer), you can download it here http://www.ks-soft.net/hostmon.eng/wmi/index.htm


TAGS: Asp.net, dotnet, code snippet, seo, search engine optimization, visual studio.net, sample code, c#, vb.net

Using a class as ListItem in a ListBox in .Net

Sometimes it could be useful to use classes as listitems in a listbox. This way you can have extra item info directly into the listbox control so when you click on the item you can easily access the full class data. I always use this solution when i work with databases so i don’t need to requery each time i need the data.
The only important thing to do is to provide a ToString() method for your class so when the ListBox draws the items it knows which text to show :)

Here is a simple example:
If you try it, create a listbox and call it “listDoc”

'define a class containing the document info
Public Class CDocument
    Public ID As Long
    Public FileName As String
    Public DocType As String

    Public Sub New(ByVal idf As Long, ByVal FN As String,_
        ByVal DT As String)
        ID = idf
        FileName = FN
        DocType = DT
    End Sub
 
    Public Overrides Function ToString() As String
       Return FileName + " (" + DocType + ")"
    End Function
End Class
 
Public Sub FillDocumentList(ByVal IDMask As Integer)
    Dim i As Integer
    listDoc.Items.Clear()

    For i = 1 To 20
	 listDoc.Items.Add(New CDocument(i.ToString(), _
         "File " + i.ToString() + ".txt", "txt")
    Next
End Sub
 
Private Sub listDoc_SelectedIndexChanged(ByVal sender _
    As System.Object, ByVal e As System.EventArgs) _
    Handles listDoc.SelectedIndexChanged
    Dim d As CDocument
    d = listDoc.SelectedItem

    MessageBox.Show("Document ID : " + d.ID.ToString() + vbCrLf +_
          "Document name : " + d.FileName + vbCrLf +_
          "Doc Type : " + d.DocType + vbCrLf)
End Sub

Download this code: ClassIntoListBox.vb.txt

That’s all, i find this really useful instead of using the Value of ListItem object.


TAGS: Asp.net, dotnet, code snippet, seo, search engine optimization, visual studio.net, sample code, c#, vb.net

Using MySQL database in .Net

Last year i had to choose a Database Server for a new application i had to develop for my customer. The options was Access, SQL Server, Oracle. As you can imagine i decided to exclude Access from the list due to it’s slow performances. I had to decide between SQL Server and Oracle but, considering my customer budget, i decided to add to the list another database server, MySQL. I think that MySQL is a very interesting option when u have to save money for your projects, it’s cheap and fast enough to compete with SQL Server and Oracle.
To use a MySQL database you need to download the MyODBC 3.51 or better driver. I use 3.51 because it’s more stable. So to go on with the test please download MyODBC and install it before testing. Obviously you need MySQL and a database too.

Here is the simple code to access a MySQL database from VB.Net using MyODBC.
In this test we’ll connect to a MySQL database and read all the records of a table then we display one field in a web page.
In a desktop application you can use it the same way but remove the Response.write and use something else.

Dim SQL As String
Dim ConnString as string
 
ConnString= "DRIVER={MySQL ODBC 3.51 Driver};_
    SERVER=localhost;DATABASE=DatabaseName;_
    UID=UserID;PWD=thePassword;OPTION=35"

Dim Conn As New System.Data.Odbc.OdbcConnection(_
     _ConnString)
 
SQL = "SELECT * FROM TableName"
Conn.Open()
 
Dim Cmd As New System.Data.Odbc.OdbcCommand(SQL, Conn)
Cmd.CommandTimeout = 20
 
Dim Reader As System.Data.Odbc.OdbcDataReader
Reader = Cmd.ExecuteReader()
 
While (Reader.Read)
        Response.Write(Reader("FieldName") + "<br>")
End While
 
Reader.Close()
Cmd.Dispose()
Conn.Close()
Conn.Dispose()

Download this code: MySQLVB.vb.txt

That’s all :) really simple


TAGS: Asp.net, dotnet, code snippet, seo, search engine optimization, visual studio.net, sample code, c#, vb.net

Download a file from web in .Net

This article is just written to help people with this task if they don’t know how to do. As you will see there’s not so much code to write to do this, it’s just provided by the .Net Framework

All that you have to do is:

  • add a reference to System.Net namespace
  • create a new WebClient object
  • call the WebClient method DownloadFile

it’s done.

Example:

Imports System.Net

public sub DownloadFile(SourceURL as string, DestFile as string)
dim WebC as new WebClient()

WebC.DownloadFile(SourceURL,DestFile)
end sub


TAGS: Asp.net, dotnet, code snippet, seo, search engine optimization, visual studio.net, sample code, c#, vb.net