Archive

Posts Tagged ‘VB.Net’

Drag and Drop files from Windows to your application

July 4th, 2009 Anuraj P No comments

While working around an Script Editor application, I found that in almost all the editors we can drag and drop files from Windows.(Even MS Notepad supports it.) Then I searched for an implementation, but unfortunately I can’t find a perfect one. Then I thought of implementing the same. I am not sure this one is a perfect implementation or not, but it works fine for me. :)

Here is the code. Seems like it is self explanatory

Imports System.IO
Public Class frmMain

    Private Sub txtEditor_MouseDown(ByVal sender As System.Object, _
                                    ByVal e As System.Windows.Forms.MouseEventArgs) _
                                    Handles txtEditor.MouseDown
        'Initiating the Drag and Drop
        txtEditor.DoDragDrop("", DragDropEffects.Copy)
    End Sub

    Private Sub txtEditor_DragEnter(ByVal sender As System.Object, _
                                    ByVal e As System.Windows.Forms.DragEventArgs) _
                                    Handles txtEditor.DragEnter
        'Ensures the dragging data is valid type.
        'Then only setting the drop effect.
        'Otherwise you will see no drop cursor, instead of Copy
        If (e.Data.GetDataPresent(DataFormats.FileDrop)) Then
            e.Effect = DragDropEffects.Copy
        Else
            e.Effect = DragDropEffects.None
        End If

    End Sub

    Private Sub txtEditor_DragDrop(ByVal sender As System.Object, _
                                   ByVal e As System.Windows.Forms.DragEventArgs) _
                                   Handles txtEditor.DragDrop
        'Getting the filename.
        'The length of files array will be based on the number of files dragging.
        Dim files As String() = e.Data.GetData(DataFormats.FileDrop)
        'Checking the files(0) is Sql File.
        If Path.GetExtension(files(0)).Equals(".sql", _
                                              StringComparison.CurrentCultureIgnoreCase) Then
            'Reading it using Stream reader
            Me.Text = String.Format("Drag Drop demo - {0}", _
                                    Path.GetFileNameWithoutExtension(files(0)))
            Using sr As New StreamReader(files(0))
                Me.txtEditor.Text = sr.ReadToEnd
            End Using
        Else
            'Otherwise displaying message box
            MessageBox.Show("Only supports SQL files")
        End If
    End Sub
End Class

Here is the screen shot

Drag and Drop Demo - Screenshot

Drag and Drop Demo - Screenshot

If some one know a better implementation please let me know.

More details from MSDN :Performing Drag-and-Drop Operations in Windows Forms

Debugging Windows Services

June 18th, 2009 Anuraj P No comments

In the current project, I have to develop some windows services to sending out notification mails.
The first challenge I faced is I can’t directly run and debug the Windows service.
For that I need to install the service (using installutil –I ServiceName) and attach the process to Visual studio, and then only I can debug it.

It works fine for me.

Then the next challenge was, debugging the code in the onStart event. Because once the service started, then only we can able to attach it to Visual Studio. So I put some code to write to text file, and/or event log. But I feel like it’s not a good method. After searching in the net I got a nice workaround.

protected override void OnStart(string[] args)
{
System.Diagnostics.Debugger.Launch();
//Rest of the code
}

While starting the Service, it will display a dialog like this

Visual Studio Debug dialog

Visual Studio Debug dialog

After selecting Yes, Visual Studio will open up and you can start debugging. You can get more information from these links

  1. http://blogs.msdn.com/yaleeyangmsblog/archive/2007/05/02/three-ways-debugging-net-windows-service.aspx
  2. http://geekswithblogs.net/GertVerhoeven/archive/2007/11/28/117181.aspx
  3. http://msdn.microsoft.com/hi-in/magazine/cc301845(en-us).aspx

Getting and Setting properties on runtime using Reflectoion

March 9th, 2009 Anuraj P No comments

In series of Reflection related posting this is the second post. You can see the post here. Now I am posting about Properties. We can set / read properties of Class using reflection.

Setting Properties

1) For setting properties, we enumerate all the properties using Type.GetProperties() method
2) Then we will check, whether the property is readonly or not.
3) Read the value(if the datatype of property and the datatype of the value you are trying to set, didn’t match it will throw some error.)
4) If datatype is mismatching, convert the value to property data type using “Convert.ChangeType” *
5) Call the PropertyInfo.SetValue method.

Here is the source code, here I am reading from Registry and Loads the required data in a class level variable.

Dim result As MyCustomClass
Dim PropertyValue As Object
Dim converter As New TypeConverter
For Each CurrentProperty As PropertyInfo In MyType.GetProperties
If CurrentProperty.CanWrite Then
PropertyValue = GetValue(CurrentProperty.Name)	'GetValue function retuns the value based on the parameter given.
If PropertyValue IsNot Nothing Then
	CurrentProperty.SetValue(result, Convert.ChangeType(PropertyValue, CurrentProperty.PropertyType), Nothing)
End If
End If
Next

* Convert.ChangeType – Works only with basic datatypes.

And for getting we will do almost reverse operation.
Getting values from Property

It is simple and strait forward, and here is the code

Dim propertyValue As String
For Each CurrentProperty As PropertyInfo In MyType.GetProperties
If CurrentProperty.CanRead Then
propertyValue = CurrentProperty.GetValue(MyCustomClass, Nothing).ToString
End If
Next

Happy Reflection.

Reading POP3 mailbox using VB.Net

March 2nd, 2009 Anuraj P No comments

Few days back I got an R&D from my friend, it is like, in Blogger, we can send mails to a specific mail address and we a can Post. He want the same implementation in asp.net, but the mail Id will be static. So I thoght of reading POP3 mailbox using .Net. And I didn’t done the same in ASP.Net, but I created a POC in VB.Net, which will help you to check you POP3 account.

Dim _tcpClient As New TcpClient
        Dim _networkStream As NetworkStream
        Dim _Msg As String
        With _tcpClient
            .Connect(Me.txtServerIp.Text, Integer.Parse(Me.txtPortNum.Text))
            _networkStream = .GetStream
            Dim sw As New StreamWriter(_networkStream)
            Dim sr As New StreamReader(_networkStream)
            If Not CheckError(sr.ReadLine()) Then
                sw.WriteLine(String.Format("USER {0}", Me.txtUsername.Text))
                sw.Flush()
            End If

            If Not CheckError(sr.ReadLine()) Then
                sw.WriteLine(String.Format("PASS {0}", Me.txtPassword.Text))
                sw.Flush()
            End If

            If Not CheckError(sr.ReadLine()) Then
                sw.WriteLine("STAT ")
                sw.Flush()
            End If
            _Msg = sr.ReadLine
            Dim MsgCount As String = _Msg.Split(New String() {" "},  _
StringSplitOptions.RemoveEmptyEntries)(1)
            If Integer.Parse(Me.lblMsgCount.Text) < Integer.Parse(MsgCount) Then
                Me.lblMsgCount.Text = MsgCount
            End If
            sw.WriteLine("Quit ")
            sw.Flush()
            sw.Close()
            sr.Close()
            _networkStream.Close()
            _tcpClient.Close()
        End With

And the check error method will check for the ERR status and display a generic error messgae.

Private Function CheckError(ByVal Msg As String) As Boolean
        Dim result As Boolean = False
        If Msg.IndexOf("+OK") >= -1 AndAlso Msg.IndexOf("-ERR") >= 0 Then
            MessageBox.Show(My.Resources.UI.Msg_GenericError, Me.Text, MessageBoxButtons.OK, MessageBoxIcon.Warning)
            result = True
            Me.tmr.Enabled = False
        End If
        Return result
    End Function

I am planning to write a simple utility using this code, and to host it on codeplex, which will give the count of unread mails in your mailbox.

SqlCeExplorer – Alpha release

February 27th, 2009 Anuraj P No comments

Hi All

My first open source project, SQLCEExplorer, a small utility to explore the SQL CE Database, yesterday uploaded the Alpha version to codeplex.

You can get this one from sqlceexplorer on Codeplex

Comments / Feedbacks : Welcome :)
You can send mail to : anuraj dot p at live dot com

Freehand drawing with .Net Windows forms

February 26th, 2009 Anuraj P No comments

Few days back, I got a requirement to implement Free Hand drawing in .Net. I searched a lot but I didn’t get any good solution, the one I found from code project was Invalidating the picture box every time. So today I got a solution, it not seems to be a perfect solution because Paint events occurs, we need to re-paint the whole lines again.

I am attaching the code here. I will update the post once I get some perfect solution for this.

 Private m_Drawing As Boolean = False
    Private m_List As List(Of Point) = Nothing
    Private Sub MyPic_MouseDown(ByVal sender As System.Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles MyPic.MouseDown
        If e.Button = Windows.Forms.MouseButtons.Left Then
            m_Drawing = True
        End If
    End Sub
    Private Sub MyPic_MouseUp(ByVal sender As System.Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles MyPic.MouseUp
        If m_Drawing AndAlso m_List IsNot Nothing Then
            If m_List.Count >= 2 Then
                MyPic.CreateGraphics.DrawLines(New Pen(Color.Blue, 1), m_List.ToArray())
            End If
            m_Drawing = False
            m_List.Clear()
        End If
    End Sub

    Private Sub MyPic_MouseMove(ByVal sender As System.Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles MyPic.MouseMove
        If m_List IsNot Nothing AndAlso m_Drawing Then
            m_List.Add(e.Location)
        End If
    End Sub
    Private Sub frmMain_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        m_List = New List(Of Point)
    End Sub

Code is pretty self explanatory. So I am not putting any comments ;)