Sunday, March 30, 2008

Copy function with API and VB

Here we go, another article about API function and VB. For VB developer, maybe you all familiar with Filecopy function. Yes, that function is to use copy and paste file we want into the directory we want.

Now, I want to make my own Filecopy with API function. In API, we can use CopyFile function, where the statement is:

CopyFile(lpExistingFileName, lpNewFileName, bFailIfExists)

lpExistingFileName = Source of our file
lpNewFileName = Destination of our file
bFailIfExists = checked first if we gave value 1, and replace it if we gave value 0


Now here the code:

Declare Function CopyFile Lib “kernel32.dll” Alias “CopyFileA” (ByVal lpExistingFileName As String, ByVal lpNewFileName As String, ByVal bFailIfExists As Long)

Application I want to make is copy file from source directory into destination directory, but checking first the existing of the file and return the message whatever success or not.

Private Sub CopyData()

Dim ErrVal as Byte

ErrVal = CopyFile (“c:\autoexec.bat”, “d:\autoexec.bat”, 1)

If ErrVal = 0 then

Msgbox “Operation Not Success. File already exist”

Else

Msgbox “Operation Success.”

End If

End Sub

Now we can modify our copy function with the rules we want. Enjoy it…




| Read More | Join My Community | Grab RSS | Stumble it |

Tuesday, March 25, 2008

Check free space of hard drive with API and VB

Maybe we always see the message from the installer when our hard drive space doesn’t enough. We can get the free space of our hard drive with API function and integrate it with VB.

We can use API function: GetDiskFreeSpace on Kernel32.

Here the code:

Declare Function GetDiskFreeSpace Lib “kernel32.dll” Alias “GetDiskFreeSpaceA” (ByVal lpRootPathName As String, lpSectorsPerCluster As Long, lpBytesPerSector As Long, lpNumberOfFreeClusters As Long, lpTotalNumberOfClusters As Long) As Long


Private Sub CheckFreeSpace()
Dim x As Long
Dim Free As Long

x = GetDiskFreeSpace (“c:/”, SecPerClus, BytePerSec, FreeClus, TotalClus)
Free = SecPerClus * BytePerClus * FreeClus

Msgbox “Free Space of Drive C:/ is: “ + Str(Free) + “ bytes”

End Sub

Simple.. huh.. 

Enjoy it…




| Read More | Join My Community | Grab RSS | Stumble it |

Saturday, March 22, 2008

How to Beep PC with API and VB

Today I will post code still related windows API function with VB. Now, I will show you how to beep the PC with the code on VB

First, we need declare an API function on VB:

Public Declare Function Beep Lib “kernel32” (ByVal dwFreq as Long, ByVal dwDuration As Long) As Long

That’s it. We just need it only to beep the PC.

Now, how to use on VB code:


Private Sub Command1_Click()
Dim x As Byte

For y = 1 to 100

Beep y,100

Next

End Sub

It will beep 100 times with 100 durations.

Okay. Enjoy the Code….




| Read More | Join My Community | Grab RSS | Stumble it |

Tuesday, March 18, 2008

Total Solutions for Your Online Store

Do you want to expand your business into e-store business with internet? Need shopping cart on your site? But, do you confuse to get the right software with your needs? To expensive buying a software or hire the programmer?

GET READY. We can get what you need. Good shopping cart software with a good price. Please visit us at: www.ashop.com.au. With us, CREATE YOUR ONLINE STORE. We can provide you a web based application with no installation needed, Affordable e commerce software, Accept credit cards online, Thousands of features, easy to use, Start selling your products online right now, Fully customizable design, 10 day free trial.


There are 6 reasons why you should choose Ashop Commerce as your partner for creating shopping cart software, are: AFFORDABLE, EASY, TECHNICAL SUPPORT AND CUSTOMER SERVICE, GET FOUND ON SEARCH ENGINES, CUSTOMIZABLE DESIGN WITHOUT RESTRICTIONS, and TOTAL SOLUTION.

Need to try first? We can provide you with a test drive with our demo version first. You can access it at here.

Find out our features here and get the right package on your needs here.

With AShop Commerce, we give our clients the best solutions and the best pricing. Over 4 years, we have developing shopping cart software regards functionality and usability. You can read our clients testimonials at here, and don’t hesitate to contact us, we are ready to help you to find a good solutions for your online store.

Contact Us:

International : +1(312) 239 0874
Canada : (312) 239 0874
United Kingdom: (1582) 84 15 87
USA : (312) 239 0874
Australia : 1300 726 360 and 02 9907 1981
New Zealand : (612) 9907 1981

Our Website: www.ashop.com.au




| Read More | Join My Community | Grab RSS | Stumble it |

UpperCase and LowerCase with API in VB

Uppercase and lowercase are general functions in every programming language. Now, I want to show how to use uppercase and lowercase in API functions.

I do it with visual basic 6 and windows library ( user32.dll ).

Okay, we start with uppercase first.

Uppercase is a function to generate anything string into uppercase string.

Here the code:

Declare Function CharUpper Lib “user32.dll” Alias “CharUpperA”
(ByVal lpsz As String) As String

Private sub command1_click()

Text1.Text = CharUpper(“layong”)

End Sub


The result will be: “LAYONG”

Okay. We move on the lowercase function. Lowercase is a function to change a string into the lowercase string.

Here the code:

Declare Function CharLower Lib “user32.dll” Alias “CharLowerA”
(ByVal lpsz As String) As String

Private Sub Command1_Click()

Text1.Text = CharLower (“LAYONG”)

End Sub

The result will be “layong”.

Simple huh… :)

Enjoy it…




| Read More | Join My Community | Grab RSS | Stumble it |

Sunday, March 16, 2008

Load Images from and Save Images to a Database

Introduction

Sometimes you need to store images in a database instead of as physical files. This sample application will show you how to build a Windows Forms interface that allows you to do the following:

* Browse for an image on your hard disk
* Load the selected image into a PictureBox control for viewing
* Save an image displayed in the PictureBox control to the database
* Select an image from a ListBox control, and load it from the database

The new concepts in this article center around the abstract Stream class and how it's used to convert an image file to and from the Image data type that SQL Server uses to store images. Be sure not to confuse the Image data type with the word image, as if to imply that only images can be stored therein. Rather, the Image data type can store anything as variable-length binary data.

A byte array is used to send data to an Image field. Thus, the main question is: How does one convert an image file—whether a JPEG, Bitmap, or other format—into an array of bytes? There are several ways to accomplish this in .NET. One of the easiest ways is to use a concrete implementation of the Stream class. A stream in .NET is essentially an abstraction of a sequence of bytes, whether these bytes came from a file, a TCP/IP socket, a database, or wherever. Stream classes allow you to work with binary data, reading and writing back and forth between streams and data structures (such as a byte array).

Once the image is converted to a byte array, it's saved to a database by using coding.
Creating Database

The first step you have to do is to create a Database table name it Pic, which should contain the two, fields 1: Name 2: Picture. The data Type of the Name field is (nVarChar) and data type of Picture is (Image) in Sql Server 2000.

Note: This Database should be in SQLS erver. I have included the database file in the zip file that you can attach in SQL Server databases. The name of database file is Images_Data.




Browsing for and Displaying an Image

The first task is to find an image on your hard disk. To do this, use an OpenFileDialog object in conjunction with a standard Button control. In the btnBrowse_Click event handler, you can see how this is done. The first few lines of code merely set properties of the OpenFileDialog object.

With OpenFileDialog1
.InitialDirectory = "C:\"
.Filter = "All Files|*.*|Bitmaps|*.bmp|GIFs|*.gif|JPEGs|*.jpg"
.FilterIndex = 2
End With

A pipe-delimited pair of file types is provided to determine the valid file types that can be accessed through the dialog box. Among other properties, you can also set FilterIndex to the default file type that you want to appear in the dialog box's Files Of Type menu. The index is not zero-based, so in this example, Bitmaps will appear as the default.

The dialog box is not actually opened until its ShowDialogmethod is called, which can be combined in an If/Then statement to check which button was pressed and perform follow-on tasks:

If OpenFileDialog1.ShowDialog() = DialogResult.OK Then
With PictureBox1
.Image = Image.FromFile(Me.OpenFileDialog1.FileName)
.SizeMode = PictureBoxSizeMode.CenterImage
End With

End If
Me.Label1.Text = Me.OpenFileDialog1.FileName.ToString

Although an OpenFileDialog object contains an Open button instead of an OK button, there is no DialogResult enumeration for the Open button. Instead, use the OK enumeration. Once it's confirmed that the Open button has been clicked, properties of the PictureBox control are set. Notice how the Image property—which requires an object of type System.Drawing.Image—is assigned. The Image class is abstract and exposes a number of shared methods for working with images, one of which is FromFile. This method creates an Image object from a fully qualified path; although the OpenFileDialog.FileName property might lead you to think that it contains only the file name, it actually has the full path.

Now that your image file is represented by an Image object, you can use a stream to convert it to a byte array. In the btnSave_Click event handler, the first line of code creates a MemoryStream object:

Dim ms As New MemoryStream()

A MemoryStream object is simply a stream that uses memory as its backup store instead of some other medium. As a result, a MemoryStream object usually provides better performance. Streams are flexible. You could, for example, have used a FileStream object to open the image file directly and read it in. There are certainly numerous other ways, too. The implementation here, however, is simple and straightforward.

The MemoryStream is then passed as an argument to the Save method, another member of the Image class. You can optionally pass the image format—for example, by accessing the Image's read-only RawFormat property:

picSave.Image.Save(ms, picSave.Image.RawFormat)

The actual byte array conversion comes in the next line. GetBuffer returns an array of unsigned bytes being held by the stream.

Dim arrImage() As Byte = ms.GetBuffer
ms.Close() 'It is good to always close the stream rather than
' to leave it for the garbage collector

The last data-gathering task is to extract the filename from the full path; there is no need to store the entire path in the database:

Dim strFilename As String = _
lblFilePath.Text.Substring(lblFilePath.Text.LastIndexOf("\")"+"1)

This might look a bit complex and convoluted, but all you're doing is indicating that you want a substring of the full path that starts after the last backslash.

With the filename extracted and the image converted to a byte array, you're now ready to use the ADO.NET practices you've already learned to push these to the database.

Dim cnn As New SqlConnection(connectionString)
Dim strSQL As String = _
"INSERT INTO Picture (Filename, Picture)" & _
"VALUES (@Filename, @Picture)"
Dim cmd As New SqlCommand(strSQL, cnn)

With cmd
.Parameters.Add(New SqlParameter("@Filename", _
SqlDbType.NVarChar, 50)).Value = strFilename
.Parameters.Add(New SqlParameter("@Picture", _
SqlDbType.Image)).Value = arrImage
EndWith
cnn.Open()
cmd.ExecuteNonQuery()
cnn.Close()

As you can see, at this point there is nothing new except the use of the SqlDbType.Image enumeration. Set the value of the @Picture parameter to the byte array, and execute the INSERT statement as you would with any other type of data.
Reading an image

From this point forward, you're essentially reversing the process. To display an image, you have to convert it from a byte array to an Image, and then assign it to the PictureBox.Image property:

Behind the ClickImagesInDatabase button, write this code:

Me.SqlConnection1.Open()
Me.SqlDataAdapter1.Fill(Me.DataSet11.Pic)

With Me.ListBox1
.DataSource = Me.DataSet11.Pic
.DisplayMember = "Name"
End With
Me.SqlConnection1.Close()

Choose from the SelectedIndexChanged Event from the Listbox event and write the code in the subroutine body:

Private Sub ListBox1_SelectedIndexChanged(ByVal sender As Object, _
ByVal e As System.EventArgs) _
Handles ListBox1.SelectedIndexChanged

Dim arrayImage() As Byte =

CType(Me.DataSet11.Tables(0).Rows(Me.ListBox1.SelectedIndex) _
("Picture"), Byte())
Dim ms As New MemoryStream(arrayImage)
With Me.PictureBox1
.Image = Image.FromStream(ms)
.SizeMode = PictureBoxSizeMode.CenterImage

End With
End Sub

The SelectedIndex property of the ListBox control is used to to retrieve the contents of the associated Picture field in the DataSet object, which is then explicitly cast to a byte array. Following this, a MemoryStream is created by passing the byte array to its constructor. The last step is to invoke the shared FromStream method to convert the stream contents to an Image, and then assign this to the PictureBox.Image property.

Note: I have generated DataAdapter and Dataset via a wizard, but you can create the Dataset and DataAdapter objects explicitly and perform the required task.



About the Author
Fatima Ahmed is a B.S. in Computer Sciences and recently working in VC++ and .NET applications. Her interests include teaching, helping others, travelling, writing articles on different topics and studying more and more.


| Read More | Join My Community | Grab RSS | Stumble it |

Using the System Tray with Visual Basic

This week's article demonstrates how to add, remove and respond to user input in the System Tray. (For those of you that asked, I hope this helps.) What else this will remind us of is part of the motivation for .Net. As you will quickly see VB6 allows you to interact with the System Tray but only through heavy use of the Windows API. This has always been a complaint about VB6: anytime we want to do something advanced we have to go to the API. Well, in this article I will demonstrate how to manipulate the System Tray in VB6, but keep in mind, that the Common Language Runtime (CLR) in Visual Studio .Net integrates these kinds of capabilities more closely with .Net languages. Huzzah!

Interacting with the System Tray requires the definition of a type, the declaration of a method defined in the shell32.dll API, and interacting to user feedback via mouse inputs. Additionally, you will have to know a little bit about Windows messages and some arbitrary, disparate constant values related to working with the System Tray. We will cover each of these aspects in turn, followed by the complete code listing for the sample program.
Defining the NotifyIconData Type

The NotifyIconData structure is a simple type that is used to package all of the necessary information up in order to send that information to the shell32.dll API. (The fact that we have to declare this in our VB6 applications every time we want to use it, or schlep a module around with it pre-defined, is a drag.) The following user-defined Type mirrors the structure needed to interact with the System Tray.


Private Type NotifyIconData
Size As Long
Handle As Long
ID As Long
Flags As Long
CallBackMessage As Long
Icon As Long
Tip As String * 64
End Type

Size will be used to represent the size of NotifyIconData variables. Handle represents the Windows handle (hWnd) of the calling application. ID is an application-defined identifier. Flags is a bit-field indicating which of CallBackMessage, Icon, and Tip will contain valid data. (One of the problems Visual Basic.Net addresses is transmogrifying the generic nature of working with the Windows API to working with strong-named entities and types.)

Each time we call Shell_NotifyIcon we will be passing an initialized NotifyIconData variable to that method.

The reason NotifyIconData is defined as Private is because VB6 does not support Public types in private modules, forms. This is another limitation of VB6. Access modifiers should be up to the discretion of the programmer, not a limitation of the language.
Declaring the Shell_NotifyIcon API Method

Shell_NotifyIcon data is an API method. We need to know the signature and API DLL containing the method we want to use to properly add the method declaration. More than likely you have some experience with this, so I will just provide the signature for the method we need.

Private Declare Function Shell_NotifyIcon _
Lib "shell32" Alias "Shell_NotifyIconA" ( _
ByVal Message As Long, Data As NotifyIconData) As Boolean

As a reminder the Lib "shell32" clause indicates the DLL containing this method. The Alias clause, Alias "Shell_NotifyIconA", indicates that we want to use the ASCII rather than the Unicode version of this method. The API method is a Function that takes a long and a NotifyIconData variable, returning a Boolean.

A Declare statement is the implicit equivalent of the call to LoadLibrary, another API method. LoadLibrary allows you to load an API DLL on demand. When you use the Declare idiom in VB6, Windows manages loading and unloading the library.
Adding and Deleting Icons from the System Tray

When the user-defined type has been added and the API method declared, we can invoke that method in our application as if it were just another method in our application.

The following subroutine demonstrates initializing a NotifyIconData variable and calling the Shell_NotifyIcon API method. The subroutine is appropriately named AddIconToTray.

Private Data As NotifyIconData

Private Sub AddIconToTray()

Data.Size = Len(Data)
Data.Handle = hWnd
Data.ID = vbNull
Data.Flags = IconFlag Or TipFlag Or MessageFlag
Data.CallBackMessage = WM_MOUSEMOVE
Data.Icon = Icon
Data.Tip = "System Tray Demo - codeguru.com" & vbNullChar
Call Shell_NotifyIcon(AddIcon, Data)

End Sub

From the listing you can easily determine that the length of Data is stored in the Size field. Data.Handle is initialized to the hWnd property of the Form containing this code. No application identifier is used; thus Data.ID is initialized to vbNull. Data.Flags indicates that CallBackMessage, Icon, and Tip will all contain data. This is indicated by Or'ing the three constants suitable for the Flags field.

Data.Icon is initialized to the Form's Icon property. The tip is initialized to a gratuitous plug for www.codeguru.com. Because Tip is an ASCIIZ string-a string of characters ending in 0-we have to append the vbNullChar to the end of the Tip string. Finally, the API method is called passing the constant indicating we want to perform an add-icon operation and the NotifyIconData variable.

To delete the Icon we pass the same instance of NotifyIconData, Data, to the same message, passing a constant representing the delete operation. That subroutine is listed next.

Private Sub DeleteIconFromTray()
Call Shell_NotifyIcon(DeleteIcon, Data)
End Sub

Responding to Mouse Inputs in the System Tray

Our Data.CallbackMessage indicates that we want to respond to MouseMove messages. In order for this to work we will need to implement a Form_MouseMove event handler. (The event handler is defined in the form whose hWnd property we used to initialize the Data.Handle field. You can implement the Form_MouseMove event in the usual way in the code editor, or you can type the code manually and VB6 will automatically make the connection.

Private Sub Form_MouseMove(Button As Integer, _
Shift As Integer, X As Single, Y As Single)

Dim Message As Long
Message = X / Screen.TwipsPerPixelX

Select Case Message
Case WM_LBUTTONDBLCLK
Visible = Not Visible
' False = 0 = Minimized; Abs(True) = 1 = Normal. Bad code!
WindowState = Abs(Not Visible)
End Select
End Sub

The statement Message = X / Screen.TwipsPerPixelX yields the mouse message. This is pure unnecessary obfuscation. There is no way someone would figure that out unless they were told or implemented this bizarre behavior. Why this was done probably has to do with assembly language, the ROM BIOS, and limitations on earlier computers. This kind of code will hopefully disappear altogether in the future.

When the user double-clicks over the System Tray icon the form visibility is toggled, and my own obscure code that treats a Boolean like a Windows state toggles the form between minimized and Normal states. (WindowState = Abs(Not Visible) is another example of frivolous obfuscation. This can be resolved with the Refactoring Extract Method. We'll save that discussion for another day.)

Listing 1 contains the complete code listing for the example program. The Windows messages and constants can only be discovered by digging around in the help files. Fortunately, Intellisense and the improved framework of Visual basic.Net will make performing these tasks easier in the future.

' FormMain.frm - Add an icon to the system tray.
' Copyright (c) 2001. All Rights Reserved.
' By Paul Kimmel. pkimmel@softconcepts.com

Option Explicit

' Type passed to Shell_NotifyIcon
Private Type NotifyIconData
Size As Long
Handle As Long
ID As Long
Flags As Long
CallBackMessage As Long
Icon As Long
Tip As String * 64
End Type

' Constants for managing System Tray tasks, foudn in shellapi.h
Private Const AddIcon = &H0
Private Const ModifyIcon = &H1
Private Const DeleteIcon = &H2

Private Const WM_MOUSEMOVE = &H200
Private Const WM_LBUTTONDBLCLK = &H203
Private Const WM_LBUTTONDOWN = &H201
Private Const WM_LBUTTONUP = &H202

Private Const WM_RBUTTONDBLCLK = &H206
Private Const WM_RBUTTONDOWN = &H204
Private Const WM_RBUTTONUP = &H205

Private Const MessageFlag = &H1
Private Const IconFlag = &H2
Private Const TipFlag = &H4

Private Declare Function Shell_NotifyIcon _
Lib "shell32" Alias "Shell_NotifyIconA" ( _
ByVal Message As Long, Data As NotifyIconData) As Boolean

Private Data As NotifyIconData


Private Sub Form_Load()
AddIconToTray
Visible = False
End Sub

Private Sub Form_Terminate()
DeleteIconFromTray
End Sub

Private Sub AddIconToTray()

Data.Size = Len(Data)
Data.Handle = hWnd
Data.ID = vbNull
Data.Flags = IconFlag Or TipFlag Or MessageFlag
Data.CallBackMessage = WM_MOUSEMOVE
Data.Icon = Icon
Data.Tip = "System Tray Demo - codeguru.com" & vbNullChar
Call Shell_NotifyIcon(AddIcon, Data)

End Sub

Private Sub DeleteIconFromTray()
Call Shell_NotifyIcon(DeleteIcon, Data)
End Sub

Private Sub Form_MouseMove(Button As Integer, _
Shift As Integer, X As Single, Y As Single)

Dim Message As Long
Message = X / Screen.TwipsPerPixelX

Select Case Message
Case WM_LBUTTONDBLCLK
Visible = Not Visible
WindowState = Abs(Not Visible)
End Select
End Sub

Summary

This article demonstrates how to invoke methods in the Windows API as well as add an application's icon to the System Tray. These applications are especially useful in some instances; one such instance is the Volume control. I can't tell you how many times I have had to mute David Gray, Beethoven, Creed, or Johnny Cash when I was jamming and the phone rang.

Another message I hope you got is that there are deficits in VB6. (Clearly Microsoft's .Net initiative is an indicator of this fact.) Perhaps after reading this article you will have a little better understanding of the everyday problems VB.NET resolves.

If you're like some of the programmers I know, you program in more than one language. If you are like all of the programmers I know, you know a lot and forget stuff you used to know. To this end I have begin creating a Code Database, allowing me to quickly access solutions I have used in the past. If things go as planned, this code database will be available as an ASP.NET application available to the development community at www.softconcepts.com. In the interim I will shortly begin posting the code from these articles on that website.
About the Author

Paul Kimmel is a freelance writer for Developer.com and CodeGuru.com. Look for cool Visual Basic .Net topics in his upcoming book Visual Basic .Net Unleashed. Paul founded Software Conceptions, Inc. in 1990. Contact Paul Kimmel at pkimmel@softconcepts.com for help building VB.NET applications or migrating VB6 applications to .NET.


| Read More | Join My Community | Grab RSS | Stumble it |

Wednesday, March 12, 2008

Get Paid For Blogging - SMORTY

Do you like writing? Do you have a blog? Do you want to get paid to blog? So don’t waste it. Because now you can writes on your blog for money. Are you interesting? You must visit www.smorty.com.

What Smorty offered at? Smorty is a tool which provides advertising for advertiser and cash for blogger. Smorty is a paid to review.

What are your benefits if you join Smorty at the advertiser side? With Smorty you can boost your website ranking, because your website can get a back link from your reviewer in their blog. Also, you can get a good review from a thousand good quality blogs, and the most important you can monitor and only approving the review that match your criteria.


And what are your benefits if you join Smorty at the blogger side? Smorty is a fastest way to get paid for blogging. You just review a Smorty advertiser products, services, or websites on your blogs or websites that match your blogs or webs criteria. And when your review is approved by the advertiser, you will get some payment from Smorty and sending the money directly into your Paypal account.

So, what you waiting for? Get your blog advertising if you are blogger and advertise on blog if you are advertiser.

For advertisers, sign up here.
For bloggers, sign up here.

Enjoy it...


| Read More | Join My Community | Grab RSS | Stumble it |

Monday, March 10, 2008

RTrim, LTrim, Trim on Visual Basic

Rtrim, LTrim, and Trim are functions to delete the empty or space character.

RTrim is function to delete empty or space character on the right side.
LTrim is function to delete empty or space character on the left side.
Trim is function to delete empty or space character on the whole strings.

Here the example of using those functions:

Dim MyString As String
MyString = " Layong Lim Okay " -> 36 Characters


Debug.Print "Using RTrim Function: " + RTrim(MyString) + ", And Length of Strings = " & Len(RTrim(MyString))
Debug.Print "Using LTrim Function: " + LTrim(MyString) + ", And Length of Strings = " & Len(LTrim(MyString))
Debug.Print "Using Trim Function: " + Trim(MyString) + ", And Length of Strings = " & Len(Trim(MyString))

Here the result:

Using RTrim Function: Layong Lim Okay, And Length of Strings = 24
Using LTrim Function: Layong Lim Okay , And Length of Strings = 27
Using Trim Function: Layong Lim Okay, And Length of Strings = 15

Okay. Hpe you understand.. :P:P

Enjoy it…




| Read More | Join My Community | Grab RSS | Stumble it |

RTrim, LTrim, Trim on Visual Basic

Rtrim, LTrim, and Trim are functions to delete the empty or space character.

RTrim is function to delete empty or space character on the right side.
LTrim is function to delete empty or space character on the left side.
Trim is function to delete empty or space character on the whole strings.

Here the example of using those functions:

Dim MyString As String
MyString = " Layong Lim Okay "  36 Characters


Debug.Print "Using RTrim Function: " + RTrim(MyString) + ", And Length of Strings = " & Len(RTrim(MyString))
Debug.Print "Using LTrim Function: " + LTrim(MyString) + ", And Length of Strings = " & Len(LTrim(MyString))
Debug.Print "Using Trim Function: " + Trim(MyString) + ", And Length of Strings = " & Len(Trim(MyString))

Here the result:

Using RTrim Function: Layong Lim Okay, And Length of Strings = 24
Using LTrim Function: Layong Lim Okay , And Length of Strings = 27
Using Trim Function: Layong Lim Okay, And Length of Strings = 15

Okay. Hpe you understand.. :P:P

Enjoy it…




| Read More | Join My Community | Grab RSS | Stumble it |

Saturday, March 08, 2008

Cast and Convert Function

Sometimes we need to change our data type, example: from Integer type, we want to change into String type. In VB, we can user Cstr, Cint, Clng, etc. but how if we want do that in SQL Query?

In SQL Server, they already provide it for us. We can use Convert or Cast Function. These two functions have a same usability. The different on these two functions only their syntax.




Here the Cast Function Syntax:

CAST ( expression AS data_type ) *


and the Convert Function Syntax:

CONVERT ( data_type [ ( length ) ] , expression [ , style ] )*


Now, I will show a little experiments how to use those functions.


We will use the legendary database: Northwind.


Then, we use the Employees Table on Northwind.


Ok. if you open the object browsers with F8 in SQL Query Analyzer, and in Employees Table you right click and choose “Script Object to New Windows As” -> “Create”, we will get the Create Query automatic generated from SQL Query Analyzer.


Here the code:

CREATE TABLE [Employees] (

[EmployeeID] [int] IDENTITY (1, 1) NOT NULL ,

[LastName] [nvarchar] (20) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL ,

[FirstName] [nvarchar] (10) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL ,

[Title] [nvarchar] (30) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,

[TitleOfCourtesy] [nvarchar] (25) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,

[BirthDate] [datetime] NULL ,

[HireDate] [datetime] NULL ,

[Address] [nvarchar] (60) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,

[City] [nvarchar] (15) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,

[Region] [nvarchar] (15) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,

[PostalCode] [nvarchar] (10) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,

[Country] [nvarchar] (15) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,

[HomePhone] [nvarchar] (24) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,

[Extension] [nvarchar] (4) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,

[Photo] [image] NULL ,

[Notes] [ntext] COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,

[ReportsTo] [int] NULL ,

[PhotoPath] [nvarchar] (255) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,

CONSTRAINT [PK_Employees] PRIMARY KEY CLUSTERED

(

[EmployeeID]

) ON [PRIMARY] ,

CONSTRAINT [FK_Employees_Employees] FOREIGN KEY

(

[ReportsTo]

) REFERENCES [Employees] (

[EmployeeID]

),

CONSTRAINT [CK_Birthdate] CHECK ([BirthDate] <>

) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]

GO


you can see the EmployeeID field is Integer. Okay, we will change it with Cast and Convert Function.


The Cast Function:

Select Cast(EmployeeID As Nvarchar(10)), BirthDate from Employees


the result will be:











you see the result, the first column will be set into (No Column Name), it's mean employeeId has been changed and not given name yet.


Let's prove EmployeeID has Change. In the beginning, the EmployeeID was Integer Type, that means, if we use statistic function on it, it will work. But, when we change it into the nvarchar type, we will get error from our query.


Testing Query:

Select Sum(EmployeeID) As Summary from Employees


The Result:

Summary

------------

45


compare with this query:

Select Sum(Cast(EmployeeID As Nvarchar(10))) As Summary from Employees


The result:

Server: Msg 409, Level 16, State 2, Line 1

The sum or average aggregate operation cannot take a nvarchar data type as an argument.


Ok. The same conditions is working for Convert Function.


Here the Convert Function Example:

Select Convert(Nvarchar(10), EmployeeID), BirthDate from Employees


The result is same with the Cast Function Result. You can see the image.


Ok Folks. That's all for today.


Enjoy it...



| Read More | Join My Community | Grab RSS | Stumble it |

Thursday, March 06, 2008

Visual Studio 2008: LAUNCH

This moment maybe the most i waiting for. I'm a VB 6 maniac, and when VS 2003 Launch, I never touch it. Cos I think VB 6 is more efficiency than VS 2003.

But, When Microsoft Launch VS 2005, I a little bit leaving VB 6, why?

VS 2005 provide more simple for developer to more concentrate in their business rules not their code or syntax.

because in the VS 2005, every standard code is more easier to use. example: we can use gridview to preview data from SQL Server by using their wizards, compared with VB 6 when we setup datagrid to preview data.

not only the wizards make us comfort, we can use the wizards to update, delete, and insert. we just only need to setup and write a little code on it.

and then what make VS 2008 more than VS 2005. if you have attend Microsoft Server Wave 2008: Launch (only in Indonesia), you will see the different between VS 2005 and VS 2008.

The technology from VS 2008 is MVC, Silverlight, LinQ and much more.. And for the first time since VB 6, I have motivated by VS 2008 for learning it.

from now on, this blog will be the witness of my journey to learn VS 2008. but, don't worry, this blog still posting the VB 6 and it's friends (SQL Query, CRYSTAL REPORT) if I got something interesting case with it.

so, don't scare to move from VB 6 to VS 2008.

Question: Can I learn the VS 2008 directly if I from VB 6? the answer is YES. :)

Enjoy it...

| Read More | Join My Community | Grab RSS | Stumble it |

doteasy - The Leading of Web Hosting

Are you looking a good web hosting for your site? but you don't want the expensive one. It's that you looking for, you should try Doteasy - web hosting .

doteasy is the leader of web hosting, because they provide a quality, low cost and 24 hours support. Their products have been trusted more than 160,000 domains server.

Their package for web hosting that you can choose is very variations. You can choose from free hosting to $9.95/month with various benefit depend your needs.

With the free account, you still can get benefits more than you imagine. The benefits you can get are: 100 MB storage, banner free (so our website still looking pretty and professional), 1 GB traffic / month, 10 emails accounts, and the most important NO FEE at all.


So, what you can get with $9.95/month? You can get 20 GB storage for your file, Unmetered monthly bandwidth, Unlimited email accounts, and their system accept PHP files, provide MySql Database, dedicated IP Address and many more benefits.

So, what you waiting for? Get yourself into – doteasy - the most powerful web hosting. You can see others package at: Doteasy - web hosting .

With doteasy - you're getting the best quality, reliability, and service!

Contact:
Doteasy Technology Inc.
Suite 210 - 3602 Gilmore Way
Burnaby
, B.C., V5G 4W9 Canada
Phone: 604-434-4307
(Available Monday to Friday, 8am to 5pm Pacific Standard Time)

| Read More | Join My Community | Grab RSS | Stumble it |

DoEvents Funtion on Visual Basic

Looping in programming is very powerful, but sometimes looping can be an annoying function if we use it wrong.

Looping can make our program stop responding or loops forever.

How can those things happen?

Here the simple example of looping forever:

a = 1
For i = 1 to b
If a = 1 then b = b + 1
Next i


As long as “a” still have value “1” then looping can’t be stop.

Here another example:

a = 100000000

For i = 1 to a

If a = 800000 then exit for
a=a+1
Next i

As long as “a” still not have value “800000” then loops again. You can see how long the loops can be. The impact is the program is like stop responding and we can’t do anything on that software

In visual basic, we can use “doevents” statement to control unexpected loops.

Doevents allows us to control our program even loops still running, so our program not stops responding.

Here the example of using doevents:

rs.movefirst

For i = 1 to rs.recordcount

If rs![name] = “newbiprogrammer” then exit for
rs.movenext
doevents
Next i

The code shows us to search the name of “newbieprogrammer” and then get off from the loop function, but as long as the name not have value like that, loops will continue looping and searching with the recordset. The code will not get stop responding as long as we have the doevents function.

Ok.. try it..

Enjoy it

| Read More | Join My Community | Grab RSS | Stumble it |

Saturday, March 01, 2008

Using Statistic Function on SQL Query

In SQL Query, we can use statistic function or math function to customize our query design.
some of statistic or math function can be use on SQL query, are:

AVG -> return average of value on behalf column.
COUNT -> return how many of the objects on behalf column
MAX -> return the highest value on behalf column
MIN -> return the lowest value on behalf column
SUM -> return the summary of object on behalf column


*************************************************

EmployeeID Salary
----------- -------

31000 800000
31000 850000
31000 900000
32000 775000
32000 800000
32000 825000

*************************************************

Example AVG:

Select MAX(EmployeeID) as ID, AVG(Salary) as Salary
From PayrollTable
Group by Employee ID

Result: The Average of Salary Field based on EmployeeID
***********************************

ID Salary
----- ------
31000 850000
32000 800000

***********************************

Example COUNT:
Select MAX(EmployeeID) as ID, COUNT(Salary) as Salary
From PayrollTable
Group by Employee ID

Result: The Count Record of Salary Field based on EmployeeID
***********************************

ID Salary
----- ------
31000 3
32000 3

***********************************

Example MAX:
Select MAX(EmployeeID) as ID, MAX(Salary) as Salary
From PayrollTable
Group by Employee ID

Result: The Maximun Value of Salary Field based on EmployeeID
***********************************

ID Salary
----- -------
31000 900000
32000 825000

***********************************

Example MIN:
Select MAX(EmployeeID) as ID, MIN(Salary) as Salary
From PayrollTable
Group by Employee ID

Result: The Minimun Value of Salary Field based on EmployeeID
***********************************

ID Salary
----- -------
31000 800000
32000 775000

***********************************

Example SUM:
Select MAX(EmployeeID) as ID, SUM(Salary) as Salary
From PayrollTable
Group by Employee ID

Result: The Minimun Value of Salary Field based on EmployeeID
***********************************

ID Salary
----- -------
31000 2250000
32000 2400000

***********************************

that's all from me...

enjoy it...




| Read More | Join My Community | Grab RSS | Stumble it |
Google

Microsoft News for ADO .NET:

Our Email Address:

blog.programming@gmail.com