Search This Blog

Sunday, July 17, 2011

Using progress bar in VB.NET

A simple example of how to user a progress bar.  Here we will do a
simple query, and advance through the records while showing a
progress bar.  In order to try this, simple create a new Windows
Application, and drap a progress bar control onto your form.Next,
you can add the code from below, and you should be all set.
The progress bar will automatically increase steps based on the
number of records we have in the database.This gives an idea to
the user of how long they will be waiting.


Progress Bar Code :-


DataSet DS = new DataSet();DS = GetDataSet("select * from Employees");
//Verify we have recordsif (DS != null && DS.Tables.Count > 0 && DS.Tables[0].Rows.Count > 0)
{
      
//Set Progress Bar
      
ProgressBarMigration.Visible = true//Make it visible
      ProgressBarMigration.Minimum = 0;  //Set Min Steps
      ProgressBarMigration.Maximum = DS.Tables[0].Rows.Count;  //Set Number of Max Steps
      ProgressBarMigration.Value = 0;  //Initiliaze to beginning

      //parse through each record
      
foreach (DataRow dr in DS.Tables[0].Rows)
      {
            ProgressBarMigration.Value += 1;
            System.Threading.
Thread.Sleep(50);  //Sleep to slow down to see steps

            //Ideally here you would do your transactions
      }
      ProgressBarMigration.Visible =
false;
      
MessageBox.Show("Migration Complete.");
}

Destroy cookie using VB.NET and ASP.NET

This is a small function which allows you to destroy a cookie.
All that is needed is to pass the cookie name.  If the cookie is
found, it'll set it so that it has expired.

Public Shared Sub DestroyCookie(ByVal CookieName As String)
 Dim CookieObj As HttpCookie = HttpContext.Current.Request.Cookies("CookieName")
   
    If CookieObj IsNot Nothing Then
        CookieObj.Expires = DateTime.Now.AddDays(-1d)
        HttpContext.Current.Response.Cookies.Add(CookieObj)
       
    End If
End Sub


Just call this static function and.If you are calling it from a regular
class you may want to make it a non static method.  I had this is
a HttpHelper class, which I would just call by using
HttpHelper.DestroyCookie("mycookiename")

Saturday, June 11, 2011

Drawing a pie chart in .NET

This program shows how to draw a pie chart from the values obtained from a table..

Imports System.Data.OleDb
Imports System.Drawing.Drawing2D
Imports System.Messaging
Imports System.ServiceProcess

Public Class Form1
Dim Conn As OleDbConnection = New OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\mdb1.mdb")
Dim dr As OleDbDataReader
Dim rd As New Random(255)
Dim Arr As New ArrayList
Dim pos As Integer
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Bind()
End Sub
Public Sub FinalDrawPieChart()
         Dim APiePercent(Arr.Count) As Integer
         For index = 0 To Arr.Count - 1
          APiePercent(index) = Convert.ToInt32(Arr.Item(index))
         Next
         Using PieGraphic = Me.CreateGraphics()
         DrawPieChart(APiePercent, PieGraphic, New Point(20, 20), New Size(130, 130))
         End Using
     End Sub

     Public Sub DrawPieChart(ByVal PiePercents() As Integer, ByVal PieGraphic As Graphics, ByVal PieLocation As Point, ByVal PieSize As Size)

         Dim sum = 0
         For index = 0 To Arr.Count - 1
         sum += PiePercents(index)
         Next

         Dim eachper As Double
         eachper = 0.0
         For index = 0 To Arr.Count - 1
         eachper = CSng((PiePercents(index) * 100) / sum)
          Next

         Dim PiePercentTotal = 0
         Dim percy As Integer
         percy = 40

         For PiePercent = 0 To Arr.Count - 1
         Using brush As New SolidBrush(Color.FromArgb(rd.Next()))
         PieGraphic.FillPie(brush, New Rectangle(Location, PieSize), CSng((PiePercentTotal * 360) / 100), CSng(((PiePercents(PiePercent) * 100) / sum) * 360) / 100)

         PieGraphic.FillRectangle(brush, 250, percy, 20, 20)
 
         PieGraphic.DrawString(Arr.Item(PiePercent), New Font("Arial", 16), New SolidBrush(Color.Black), New Point(290, percy))

              percy = percy + 30
              End Using

             PiePercentTotal += ((PiePercents(PiePercent) * 100) / sum)
             Next
            Return
            End Sub

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Arr.Clear()
         Try
             Conn.Open()
             Dim cmd As OleDbCommand = New OleDbCommand("Select Age From Student", Conn)
             dr = cmd.ExecuteReader
              While dr.Read()
                  Arr.Add(dr.GetValue(0).ToString())
                 pos += 1
              End While
Catch ex As Exception
              MessageBox.Show(ex.ToString())
          Finally
              dr.Close()
             Conn.Close()
         End Try
FinalDrawPieChart()

End Sub

Tuesday, February 15, 2011

File operations in VB.NET

In this article we will learn how to delete, copy and move files in VB.NET

This method shows how to delete files in a folder.Using System.IO class Directory 

class we will check whether the folder name in "sourcePath" exists or not.If directory

is not present in the disk then we will create it. Then we will check any files are present

in that folder.If present then we loop through all files one by one and delete those file 

using File.Delete method.

Public Sub DeleteFilesFromFolders(ByVal sourcePath As String)
        If (Directory.Exists(DirPath)) Then
            For Each fName As String In Directory.GetFiles(DirPath)
                If File.Exists(fName) Then
                    File.Delete(fName)
                End If
            Next
        End If
    End Sub

 

This method shows how to move files from one folder to another folder.

  Public Sub MoveFiles(ByVal sourcePath As String, ByVal DestinationPath As String)
        If (Directory.Exists(sourcePath)) Then
            For Each fName As String In Directory.GetFiles(sourcePath)
                If File.Exists(fName) Then
                    Dim dFile As String = String.Empty
                    dFile = Path.GetFileName(fName)
                    Dim dFilePath As String = String.Empty
                    dFilePath = DestinationPath + dFile
                    File.Move(fName, dFilePath)
                End If
            Next
        End If
    End Sub
 

This method shows how to copy files from one folder to another folder.

    Public Sub CopyFiles(ByVal sourcePath As String, ByVal DestinationPath As String)
        If (Directory.Exists(sourcePath)) Then
            For Each fName As String In Directory.GetFiles(sourcePath)
                If File.Exists(fName) Then
                    Dim dFile As String = String.Empty
                    dFile = Path.GetFileName(fName)
                    Dim dFilePath As String = String.Empty
                    dFilePath = DestinationPath + dFile
                    File.Copy(fName, dFilePath, True)
                End If
            Next
        End If
    End Sub

Adding data to an existing file using VB.NET

In this article we will learn how to append data to an existing file.

Here I am using FileStream object to write contents to a file.
First a FileSteam and File object is created. Using file object we will compare wether file is exists are not.

If file exits in the disk then we will truncate it otherwise we will create new file and allow that file for read and write using file steam object.

If file already exists then we will open that file in append mode.
Then we will point the stream reader to last line using streamwriter.
Example : sw.BaseStream.Seek(0, SeekOrigin.End)

If file does't exists then we will create new file and open that file in create mode.Then we will point the stream reader to first line using streamwriter.
Example: sw.BaseStream.Seek(0, SeekOrigin.Begin)

The code follows :

Public Sub ExportToFile(ByVal oFileName As String, ByVal myContent As String)

Dim file As FileStream
Dim f As IO.File

If (f.Exists(oFileName)) Then
file = New FileStream(FileToWrite, FileMode.Append, FileAccess.Write)
Else
file = New FileStream(FileToWrite, FileMode.Create, FileAccess.ReadWrite)
End If

Dim sw As New StreamWriter(file, System.Text.Encoding.Default)
If (f.Exists(oFileName)) Then
sw.BaseStream.Seek(0, SeekOrigin.End)
Else
sw.BaseStream.Seek(0, SeekOrigin.Begin)
End If

sw.Write(myContent)

sw.Close()

End Sub

Tuesday, January 25, 2011

Creating Google Talk Themes


Google's gtalk offer you with various self defined themes like classic, bubble ,
bubble picture , orkut etc. To create your own personalised theme follow the
following steps :-
  1. Copy and paste the following address in your My Computer Address bar.
    %userprofile%\Local Settings\Application Data\Google\Google Talk\themes\system\chat
  2. Copy the classical picture theme and move back to the themes directory.
  3. Navigate to user directory.
  4. Create a folder named "chat" in it.
  5. Paste the classical picture folder in the chat folder.
  6. Rename the folder to any other name. eg. MyTheme.
  7. In the mytheme folder navigate to contents->resources.
  8. Create a folder named images.
  9. Paste the picture in the folder which you want to make your back ground.
  10. Rename the picture to "background.jpg".
  11. Resize the image to 300x225 pixels.
  12. The code would look like this
    BODY { color: #000000; background-color: #FFFFFF; }

    BODY a:link { color: #0000FF; }

    BODY a:hover { color: #0000FF; }

    BODY a:active { color: #0000FF; }

    BODY a:visited { color: #800080; }BODY {

    margin: 6px;

    }

    DIV#content {

    font: 12px Arial;

    }

    DIV#insert {

    display: none;

    }

    DIV.system1st {

    margin: 4px 0px 4px 0px;

    }

    DIV.systemNth {

    margin: 4px 0px 4px 0px;

    }

    /* Two ways to do icons with these rules:

    Some code here

    */

    DIV.chat .icon {

    }

    DIV.chat DIV.msg {

    margin: 0px 0px 0px 0px;

    }

    DIV.chat DIV.Nth {

    margin: 5px 0px 0px 0px;

    }

    DIV.chat SPAN.salutation {

    font-weight: bold;

    }

    DIV.out {

    text-align: left;

    }

    DIV.out .icon {

    float: left;

    margin: 2px 5px 0px 0px;

    }

    DIV.in {

    text-align: left;

    }

    DIV.in .icon {

    float: left;

    margin: 2px 5px 0px 0px;

    }

    DIV.clear {

    clear: both;

    height: 1px;

    overflow: hidden;

    }

    DIV.break {

    height: 1px;

    margin: 3px 0px 4px 0px;

    overflow: hidden;

    }
  13. Add the background url to the body class
    BODY

    {

    margin: 6px;

    background-image: url("images/background.jpg");

    }
  14. You can also change the alignment and the fronts according to your wish.
  15. To apply the theme close all chat windows.
  16. Goto settings in gtalk->appearance->chat theme.
  17. Select mytheme.
  18. Then open the chat window to see the effect.

Saturday, January 8, 2011

Access specifier in VB.NET

Welcome readers......Wish you all a Happy New Year
So coming back to .NET, today I would discuss about the different access specifier
in VB.NET.

Access specifiers describe the accessibility scope of a variable, method or a class. By using access specifiers we can control the scope of the member object of a class. Access specifiers were used for providing security of our applications. In Visual Basic .Net there are five access specifiers and they are as follows:

Public: It have no restriction on accessibility. We can use the public members from any were inside the class or outside the class.

Private: Their accessibility scope is limited to only inside the class in which they are declared. We can't access the Private members from outside the class and it is the least permissive access level.

Protected: The protected members have scope of accessibility within the class and classes derived(Inherited) from that class.

Friend: Friend members have the accessibility scope from the same assembly and program that contain their declarations.

Protected Friend:
It behave like both protected and friend access specifiers. We can access the protected friend member from anywhere in same assembly and the classes inherited from the same class.