Search This Blog
Sunday, July 17, 2011
Using progress bar in VB.NET
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
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
Imports System.Drawing.Drawing2D
Imports System.Messaging
Imports System.ServiceProcess
Public Class Form1
Dim rd As New Random(255)
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()
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)
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
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)
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 :-
- Copy and paste the following address in your My Computer Address bar.
%userprofile%\Local Settings\Application Data\Google\Google Talk\themes\system\chat
- Copy the classical picture theme and move back to the themes directory.
- Navigate to user directory.
- Create a folder named "chat" in it.
- Paste the classical picture folder in the chat folder.
- Rename the folder to any other name. eg. MyTheme.
- In the mytheme folder navigate to contents->resources.
- Create a folder named images.
- Paste the picture in the folder which you want to make your back ground.
- Rename the picture to "background.jpg".
- Resize the image to 300x225 pixels.
- 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;
} - Add the background url to the body class
BODY
{
margin: 6px;
background-image: url("images/background.jpg");
} - You can also change the alignment and the fronts according to your wish.
- To apply the theme close all chat windows.
- Goto settings in gtalk->appearance->chat theme.
- Select mytheme.
- Then open the chat window to see the effect.
Saturday, January 8, 2011
Access specifier in VB.NET
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.
Tuesday, December 28, 2010
Difference between VB.NET and C#.NET
natural style and some like professional and terse C# syntaxes. Both
use the same framework and speed is also very much equivalents. But
still let’s list down some major differences between them :-
Advantages VB.NET :-
- Has support for optional parameters which makes COM interoperability much easy.
- With Option Strict off late binding is supported.Legacy VB functionalities can be used by using Microsoft.VisualBasic namespace.
- Has the WITH construct which is not in C#.
- The VB.NET part of Visual Studio .NET compiles your code in the background. While this is considered an advantage for small projects, people creating very large projects have found that the IDE slows down considerably as the project gets larger.
- XML documentation is generated from source code but this is now been incorporated in Whidbey
- Operator overloading which is not in current VB.NET but is been introduced in Whidbey.
- Use of this statement makes unmanaged resource disposal simple.
- Access to Unsafe code. This allows pointer arithmetic etc, and can improve performance in some situations. However, it is not to be used lightly, as a lot of the normal safety of C# is lost (as the name implies). This is the major difference that you can access unmanaged code in C# and not in VB.NET.
Monday, December 27, 2010
Common Language Runtime ( CLR )
- Garbage Collection :- CLR automatically manages memory allocation thus eliminating memory leaks. When objects are not referred Garbage Collector automatically releases those memories thus providing efficient memory management.
- Code Access Security :- CAS grants rights to program depending on the security configuration of the machine. Example the program has rights to edit or create a new file but the security configuration of machine does not allow the program to delete a file. CAS will take care that the code runs under the environment of machines security configuration.
- Code Verification :- This ensures proper code execution and type safety while the code runs. It prevents the source code to perform illegal operation such as accessing invalid memory locations etc.
- IL( Intermediate language )-to-native translators and optimizer’s :- CLR uses JIT(Just In Time) and compiles the IL code to machine code and then executes. CLR also determines depending on platform what is optimized way of running the IL code.
Saturday, November 20, 2010
.NET Framework 4 Unleashed
.Net 4 is highly compatible with applications that are built with earlier .NET Framework versions, except for some changes that were made to improve security, standards compliance, correctness, reliability, and performance.The .NET Framework 4 does not automatically use its version of the common language runtime to run applications that are built with earlier versions of the .NET Framework. To run older applications with .NET Framework 4, you must compile your application with the target .NET Framework version specified in the properties for your project in Visual Studio
.Net 4 also supports much more language in its client profile than its earlier versions.
Moreover it supports in process side by side execution which enables it to compile and run a project using components based on .net 4 as well as add ins based on earlier versions.
Performance monitoring :
Using Earlier versions of the .NET Framework it was not possible to determine whether the application was affecting other applications or not.But .net 4 enables us to get processor usage and memory usage estimates per application domain.We can monitor CPU and memory usage of individual application domains.
Garbage Collection :
The .NET Framework 4 provides background garbage collection. This feature replaces concurrent garbage collection in previous versions and provides better performance and memory utilization.
Other new features :
- It support big integers(system.numerics.biginteger) which supports all the standard integer operations, including bit manipulation.
- it support complex numbers(system.numerics.complex) which supports arithmetic and trigonometric operations with complex numbers.
- It supports the feature of identifying a 64-bit operating system and a 64-bit process.
And there are lots more features packed into .NET 4 framework which makes a programmers friendly heaven.
Friday, July 30, 2010
Fetching image from database in ASP.NET
Next we would follow the steps to do that :
Now we shall add a page named image.aspx and in the image.aspx.vb we shall write the code given below
Partial Class image
Inherits System.Web.UI.Page
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Dim s As String = Request.QueryString("val")
Try
con.Open()
com.CommandText = "select * from items where pid ='" & s & "'"
com.Connection = con
dr = com.ExecuteReader
dr.Read()
Dim bytImage As Byte() = New Byte() {}
bytImage = dr.Item(7)
Response.ContentType = "image/jpeg"
Response.Expires = 0
Response.Buffer = True
Response.Clear()
Response.BinaryWrite(bytImage)
Response.End()
Catch ex As Exception
MsgBox(ex.Message)
Finally
con.Close()
com.Cancel()
dr.Close()
End Try
End Sub
End Class
In this page we will get the image from the database an a binary form and will binarywrite the image in this page.We shall get the pid from the querystring which we shall pass from the page where the image control is. In that page we will direct the image url as below :
Image1.ImageUrl = "~/image1.aspx?vall=" & DropDownList1.SelectedValue
where dropdownlist1.selected value returns a element of the pid coloum in the items table
I have already shown how to connect the database using the module in my earlier blog
Wednesday, July 21, 2010
Adding image to database in ASP.NET
The module should look like this
Imports Microsoft.VisualBasic
Imports System.Data
Imports System.Data.SqlClient
Public Module connection
Public con As New SqlConnection("Data Source=.\SQLEXPRESS;_AttachDbFilename='J:\shopping\App_Data\Database.mdf';Integrated_ Security=True;User Instance=True")
Public com As New SqlCommand
Public dr As SqlDataReader
End Module
Now to add the image follow the following steps :
Try
Dim imgByte As Byte() = Nothing
If FileUpload1.PostedFile IsNot Nothing AndAlso FileUpload1.PostedFile.FileName <> "" Then
Dim File As HttpPostedFile = FileUpload1.PostedFile
imgByte = New Byte(File.ContentLength - 1) {}
File.InputStream.Read(imgByte, 0, File.ContentLength)
End If
Dim b As Boolean
con.Open()
com.CommandText = "insert into items values('" & TextBox1.Text & "','" & TextBox2.Text & "','" & TextBox7.Text & "','" & TextBox3.Text & "','" & TextBox4.Text & "','" & TextBox5.Text & "','" & TextBox6.Text & "',@eimg)"
com.Parameters.AddWithValue("@eimg", imgByte)
com.Connection = con
com.ExecuteNonQuery()
MsgBox("inserted")
Catch ex As Exception
MsgBox(ex.Message)
Finally
con.Close()
com.Cancel()
com.Parameters.Clear()
dr.Close()
End Try
First we shall upload the file using a fileupload control then we shall convert it into a byte stream and would store it into a byte array.Next we would store this byte array into the items database using parametarised query.Hence the image gets stored into the image field
Thursday, July 8, 2010
JAVA Threads
Multithreading has several advantages over Multiprocessing such as;
- Threads are lightweight compared to processes
- Threads share the same address space and therefore can share both data and code
- Context switching between threads is usually less expensive than between processes
- Cost of thread intercommunication is relatively low that that of process intercommunication
- Threads allow different tasks to be performed concurrently.
Thread Creation
There are two ways to create thread in java;
- Implement the Runnable interface (java.lang.Runnable)
- By Extending the Thread class (java.lang.Thread)
public interface Runnable {
void run();
}
One way to create a thread in java is to implement the Runnable Interface and then instantiate an object of the class. We need to override the run() method into our class which is the only method that needs to be implemented. The run() method contains the logic of the thread.
The procedure for creating threads based on the Runnable interface is as follows:
1. A class implements the Runnable interface, providing the run() method that will be executed by the thread. An object of this class is a Runnable object.
2. An object of Thread class is created by passing a Runnable object as argument to the Thread constructor. The Thread object now has a Runnable object that implements the run() method.
3. The start() method is invoked on the Thread object created in the previous step. The start() method returns immediately after a thread has been spawned.
4. The thread ends when the run() method ends, either by normal completion or by throwing an uncaught exceptionExtending Thread Class
The procedure for creating threads based on extending the Thread is as follows:
1. A class extending the Thread class overrides the run() method from the Thread class to define the code executed by the thread.
2. This subclass may call a Thread constructor explicitly in its constructors to initialize the thread, using the super() call.
3. The start() method inherited from the Thread class is invoked on the object of the class to make the thread eligible for running.
When creating threads, there are two reasons why implementing the Runnable interface may be preferable to extending the Thread class:
- Extending the Thread class means that the subclass cannot extend any other class, whereas a class implementing the Runnable interface
has this option. - A class might only be interested in being runnable, and therefore, inheriting the full overhead of the Thread class would be excessive.
Friday, June 25, 2010
The Java Virtual Machine (JVM)
Java bytecode executes on a special type of microprocessor. Strangely enough, there wasn't a hardware implementation of this microprocessor available when Java was first released. Instead, the processor architecture is emulated by what is known as a "virtual machine". This virtual machine is an emulation of a real Java processor - a machine within a machine. The only difference is that the virtual machine isn't running on a CPU - it is being emulated on the CPU of the host machine.
The Java Virtual Machine is responsible for interpreting Java bytecode, and translating this into actions or operating system calls. For example, a request to establish a socket connection to a remote machine will involve an operating system call. Different operating systems handle sockets in different ways - but the programmer doesn't need to worry about such details. It is the responsibility of the JVM to handle these translations, so that the operating system and CPU architecture on which Java software is running is completely irrelevant to the developer.
The Java Virtual Machine forms part of a large system, the Java Runtime Environment (JRE). Each operating system and CPU architecture requires a different JRE. The JRE comprises a set of base classes, which are an implementation of the base Java API, as well as a JVM. The portability of Java comes from implementations on a variety of CPUs and architectures. Without an available JRE for a given environment, it is impossible to run Java software.
Differences between JVM implementations Though implementations of Java Virtual Machines are designed to be compatible, no two JVMs are exactly alike. For example, garbage collection algorithms vary between one JVM and another, so it becomes impossible to know exactly when memory will be reclaimed. The thread scheduling algorithms are different between one JVM and another (based in part on the underlying operating system), so that it is impossible to accurately predict when one thread will be executed over another.
Initially, this is a cause for concern from programmers new to the Java language. However, it actually has very little practical bearing on Java development. Such predictions are often dangerous to make, as thread scheduling and memory usage will vary between different hardware environments anyway. The power of Java comes from not being specific about the operating system and CPU architecture - to do so reduces the portability of software.
-Subham Basak
www.subhambasak.weebly.com
Friday, April 9, 2010
Stop Hard Drive Crashes
What Noise Is The Drive Making?
The first thing to take into account is whether or not the hard drive is making any unusual noises. Often times when there is a problem with the read or write head within the drive or a firmware issue in the logic board a “clicking” sound will be heard. If this is the case, then you should immediately power down the system and refrain from reapplying power. Same thing goes for any unusual sound, whether it’s grinding, squealing, or sounds like a “laser gun”. See samples in the upper left column.
If any of these occur you should immediately power the system down, don’t even attempt to go through the normal shut down procedure, just pull the plug. Unfortunately in the situations listed above, there is little that you can do to recover the data yourself. If the failure is mechanical, unless you have a clean room, fully equipped with the right tools and a trained technician there is nothing that can be done. Even hard drive manufacturers avoid this line of work, and many who do offer data recovery services are only sub-contracting the work out to an established data recovery firm.
Never Ever Open Your Hard Drive
If the data on a hard drive has even the most minimal value to you, then it is imperative that you do not open the drive. We often get calls or e-mails from people who felt they had the right equipment and know-how to perform something as serious as a head replacement. Once they’ve removed the hard drive’s protective case, we often times ask them not to send the drive in, because more often than not, the damage is irreparable. Working with the internal components of a hard drive requires at least a Class-100 clean room. A clean room does not mean a room that you just vacuumed and dusted (believe it or not people say that to us all the time). A clean room is a special work area in which air quality is heavily controlled and it is vital to hard drives during the manufacturing or assembly process. The air in the room is regulated in term of air particles, temperature and humidity. A Class-100 clean room means there exists no more than 100 particles that are larger than 0.5 microns in one cubic foot of air. Opening a hard drive in air meeting anything less than the standard listed above will mean certain death for your hard drive and any data contained therein.
The Freezer Method
There has been a long running wive’s tale about putting your hard drive in the freezer when it crashes in order to revive it just long enough to pull your data off of it. We’ve run this test for fun on many occasions in different scenarios with junk test drives that we have in our lab. So far we have yet to see this actually produce any positive results. In fact, in one instance we actually began to see the formation of tiny microscopic ice crystals on the platter themselves, which is a definite crash waiting to happen.
See the problem with this theory is, drives are not completely sealed. Regardless of what you’ve heard or read, nearly all hard drives have a tiny breather hole (usually marked with a label that says DO NOT COVER). This hole not only aids in cooling but it also helps to equalize air pressure in the drive when the platters are spinning. On the other side of this hole is a filter, which keeps dirt and debris from getting inside the drive. However, this filter does not stop heavy amounts of moisture (especially in flood situations) or moisture vapor (such as found in a freezer). This moisture vapor has been known to settle on the platters when the drive warms there is really nothing you can do about it. Then when the drive is powered up, the read/write head resembles an airplane flying into a mountain.
In closing, If you’ve experienced a hard drive crash, it is imperative that you consider the value of the data, before you consider the money you might save by doing it yourself. Data recovery is a specialty, and it requires a number of specialized tools, skills and software to complete successfully. Many times you run the risk of taking data that may be perfectly recoverable and destroying it permanently. If you have any questions, it is best to consult with a recovery firm first. Most reputable data recovery companies will perform a free diagnostic and evaluation on most standard IDE hard drives. Many will even include a list of the recoverable files with that evaluation before you proceed. In some cases, we even work with our customers on a payment plan to help ease the burden of the recovery costs. Of course the best way to avoid all of this is to simply backup anything and everything of value