Tuesday, March 20, 2012

Strategic video promotion to get high traffic

Sorry, I could not read the content fromt this page.Sorry, I could not read the content fromt this page.

View the original article here

Microsoft Office 365 Mobile Platform

The Microsoft Office 365 mobile platform recently extended its scope by adding support for business services using BlackBerry. After spending a year in beta testing, the platform now operates on BlackBerry phones and tablets, extending its reach to make it compatible with the majority of mobile devices used in business settings.

Office 365 is a combination of software and services that extend the well-known Microsoft Office productivity suite off of the desktop and into the cloud. This enables individual users to access and edit their data anywhere through cloud storage. The platform also makes it easier for teams to work collectively thanks to online versions of tools such as Exchange, SharePoint and Lync. It includes both desktop and web versions of Office applications and ample storage. In a typical Office 365 installation, each user receives a 25 gigabyte email storage allowance coupled with 10 gigabytes of storage accessible through their company’s intranet. Microsoft also backs the platform with a 99.9 percent up time guarantee and includes the ability to set up web conferences.

On the BlackBerry platform, Office 365 has unique capabilities that make it one of the most useful business services using BlackBerry devices. It integrates with Exchange to allow BlackBerry users to access their Outlook mail. Unique to the BlackBerry platform is support for the BlackBerry Balance application that makes it easier to separate work documents, events and contacts in the Office 365 environment from personal data elsewhere on the BlackBerry device.

With attractive monthly pricing per user, Microsoft Office 365 makes it affordable for companies to give their employees the latest productivity and collaboration software. The mobile aspect of Office 365 lets the software’s productivity benefits extend past the desktop and to home computers, tablet computers and smart phones. Now that it is available for the leading business smart phone platform, Microsoft Office 365 is a complete solution for businesses needing to stay productive and connected everywhere.


View the original article here

Monday, March 19, 2012

WPF Datagrid and Linq to SQL

When I started working in WPF, in my first sample I tried to locate the control in the toolbox. To my surprise I couldn’t find it. I started searching it in the web for some information on that. I found though the DataGrid is not available in WPF under the framework. It is available from CodePlex for public downloading.

The above paragraph is not applicable for the .Net framework 4.0, as the .net framework 4.0 already preloaded with the WPF DataGrid control. Only difference I faced is, when you are dragging the control from the toolbox. The CodePlex DataGrid is putting defaults to the AutoGenerateColumns as true but the .Net framework control defaults the AutoGenerateColumns as false.

After downloaded from CodePlex, install it. It will not be available in the tool box right out of the box. You have to choose the installed component to be listed in the toolbox. In order to get DataGrid on Toolbox we should select from the list of components. This is available in the “Choose Tool Box Item” dialog box and under the WPF Components section.

Now no matter we are using .net Framework 4.0 or .Net Framework 3.5 we have a DataGrid to start work on. There are not many changes from the way we bind the ListBox in WPF. But here we got a lot of options as we have in GridView. For e.g., we have some standard set of predefined columns for simple usages. For advanced usages we can go for the template controls as we do in GridView.
For making this sample simpler, we go for AutoGenerateColumns = True. This has taken care of all the column creations. So we can just bind the WPF DataGrid with ItemsSource.

It is much easier to use Linq to SQL to fetch the data from the database.  Firstly add the Linq to SQL class by choosing them from Add New Item window as shown in the following screen shot
Go to Add New item \ Select Linq to SQL Classes
Name it as NorthwindData.dbml

Then drag the table category from the server explorer window to the NorthwindData.dbml’s designer

Now you can simply bind the data as follows
DataGrid1.ItemsSource = (New NorthwindDataDataContext).Categories

Now it is time to move a bit to know how to use the Linq and Lambda to deal with data. Using the lambda expressions and select method of the list we are trying to transform the category object to anonymous type. Basically we don’t want to display code and picture in the DataGrid. So we don’t pass it to the control.
Though it is easier to do it with templates, I am trying to explain how to transform objects easily using the lambda expressions.  Using lambda expression you can create a new anonymous type using the New With keyword. After specifying the new with whatever you are putting inside {} will become members of the anonymous type.
Using linq will be much more readable than the Lambda expressions.

xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="522" Width="525" >

Export CSV from Dataset

Before XML is widely used for data communications between the systems/applications, we have used CSV. Even now for when the new systems are being developed which needs to be communicated with these legacy applications, we have no choice if we cant choose anything other than those systems are using. I am planning to develop a class which can be useful for exporting CSV.

CSV is a character separated values format so we have to choose a character as a delimiter. As delimiters are chosen based on various factors we need our class to be delimiters configurable.

As there will be a risk if the delimiter is already present in the data, the text qualifiers are used to identify the text element’s boundary. Within this boundary if a delimiter character is present then the class will not consider it as a delimiter.

Some of the interfaces will not like headers, so make a switch to turn off the column header generations.

For generating the file with text quantifiers, surround the item with quantifier character both the side. Once done add a delimiter character next to that. If this is done for all rows then the string is ready to be written into the file system.

Imports System
Imports System.Collections.Generic
Imports System.ComponentModel
Imports System.Data
Imports System.Drawing
Imports System.Linq
Imports System.Text
Imports System.Windows.Forms
Imports System.Data.SqlClient
Imports System.IO
Public Class Form1
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim Csv As New Exporter()
Using CsvWriter As New StreamWriter("C:\TestFile.csv")
CsvWriter.Write(Csv.CsvFromDatatable(GetSampleData()))
End Using
System.Diagnostics.Process.Start("C:\TestFile.csv")
MessageBox.Show("done")
End Sub
Private Function GetSampleData() As DataTable
Dim con As New SqlConnection("Data Source=.\SQLEXPRESS;Initial Catalog=Northwind;Persist Security Info=True;Integrated Security = True")
Dim CategoryAdapter As New SqlDataAdapter("SELECT CategoryID,CategoryName,Description FROM Categories", con)
Dim ProductData As New DataSet()
CategoryAdapter.Fill(ProductData, "Categories")

        Return ProductData.Tables(0)
End Function

End Class

Public Class Exporter
Public Sub New()
TextDelimiter = ","c
TextQualifiers = """"c
HasColumnHeaders = True
End Sub
Private _TextDelimiter As Char
Public Property TextDelimiter() As Char
Get
Return _TextDelimiter
End Get
Set(ByVal value As Char)
_TextDelimiter = value
End Set
End Property
Private _TextQualifiers As Char
Public Property TextQualifiers() As Char
Get
Return _TextQualifiers
End Get
Set(ByVal value As Char)
_TextQualifiers = value
End Set
End Property
Private _HasColumnHeaders As Boolean
Public Property HasColumnHeaders() As Boolean
Get
Return _HasColumnHeaders
End Get
Set(ByVal value As Boolean)
_HasColumnHeaders = value
End Set
End Property
Public Function CsvFromDatatable(ByVal InputTable As DataTable) As String
Dim CsvBuilder As New StringBuilder()
If HasColumnHeaders Then
CreateHeader(InputTable, CsvBuilder)
End If
CreateRows(InputTable, CsvBuilder)
Return CsvBuilder.ToString()
End Function
Private Sub CreateRows(ByVal InputTable As DataTable, ByVal CsvBuilder As StringBuilder)
For Each ExportRow As DataRow In InputTable.Rows
For Each ExportColumn As DataColumn In InputTable.Columns
Dim ColumnText As String = ExportRow(ExportColumn.ColumnName).ToString()
ColumnText = ColumnText.Replace(TextQualifiers.ToString(), TextQualifiers.ToString() + TextQualifiers.ToString())
CsvBuilder.Append(TextQualifiers + ColumnText + TextQualifiers)
CsvBuilder.Append(TextDelimiter)
Next
CsvBuilder.AppendLine()
Next
End Sub
Private Sub CreateHeader(ByVal InputTable As DataTable, ByVal CsvBuilder As StringBuilder)
For Each ExportColumn As DataColumn In InputTable.Columns
Dim ColumnText As String = ExportColumn.ColumnName.ToString()
ColumnText = ColumnText.Replace(TextQualifiers.ToString(), TextQualifiers.ToString() + TextQualifiers.ToString())
CsvBuilder.Append(TextQualifiers + ExportColumn.ColumnName + TextQualifiers)
CsvBuilder.Append(TextDelimiter)
Next
CsvBuilder.AppendLine()
End Sub
End Class


View the original article here

Replace Text in a TextBox

Everyone has probably used or at least seen the find and replace feature in programs. This allows the user to find everything that matches the specified text string and replace it. This source sample demonstrates a very bare bones version of that same functionality in Visual Basic. In general to find a sub string in a parent string you can use the InStr function which is demonstrated below. However, in order to replace the found strings with a new one you need to get a little bit trickier. See below for how this can be done in a text box.

To try out this code create a new project, add a command button to the main form, add a text box as well. Double click the command button to into the click event handler for your button. In this method add the following code.

Dim StartPos, Counter As IntegerDim FindString, ReplaceText As StringFor Counter = 1 To Len(Text1.Text)        StartPos = InStr(Text1.Text, FindString)                Text1.SelLength = Len(FindString)                Text1.SelText = "" + ReplaceText

Once you have the code in place run your application and add some text that has the string test in it. Hit the button and you will see all of these instances of the word test replaced with the string 'MyString'.

Note: The source for this was found at DreamVB which is no longer online.


View the original article here

Launch a program from VB

An often requested task that new developers to VB ask is how can I write a program that will launch other programs. Its fun to create your own little launcher program that does things like allows you to quickly launch just the programs you want. Obviously program launchers already exist out on the market that you could simply use. But one of the great things about learning a programming language like Visual Basic is that you can create your own programs that behave exactly how you want them to.

To try out the this sample source code snippet simply create a VB project, add a command button to the main form, double click this button to get into the click event handler for it and add the following code.

    Filename = "C:\windows\notepad.exe" 'Check file is here first    MsgBox Filename & " not found", vbInformation    Res = Shell("Start.exe " & Filename, vbHide)

This source code uses the VB6 Shell command to launch a new program. We specifically call the Start.exe program as it can be used to launch other programs easily.

Note: The source for this was found at DreamVB which is no longer online.


View the original article here

Naming Database Objects

Just as using an object and variable naming convention can help you write cleaner code, a database object naming convention can help you manage the many objects you create in a database schema. I've developed and refined a standard that has worked exceptionally well for me in my database applications. The following rules are applied to all identifiers and serve two basic objectives: Provide a reasonable degree of compatibility across various platforms. Eliminate tedious "nuisance work" delimiting identifiers with square brackets in code and SQL statements. Maximum Identifier Length: 30 Characters
This is based on the maximum length of identifiers for Microsoft SQL Server. Jet/Access databases can have much longer identifiers, but staying within the 30 character maximum is easy to accomplish and avoids naming problems if a database is scaled from Access to SQL Server. Only letters, numbers, and the underscore are allowed in names.
No spaces, punctuation, or extended characters are allowed. This provides compatibility with MS SQL Server and avoids the need to use square brackets as delimiters around identifier names in Visual Basic code and SQL statements. This provides considerable simplification when writing code and SQL statements will little or no loss in readability. A column name of CustFirst is just as easy to understand as Customer First. The first character in a name must be a letter.
This also provides compatibility with Visual Basic identifiers and eliminates the need to use square brackets. Use mixed case to delimit words where required.
The underscore can also be used to separate words in exceptional circumstances, although the use of mixed case is preferred. Use the shortest possible name without using pointless or obscure abbreviations.
Abbreviations should be avoided entirely if possible, and only used if the savings in the number of characters is significant. For example, "Itm" saves only one character in comparison to "Item" at a cost of loss of readability and added obscurity.
Be consistent in the use of abbreviations when used. For example, if you like to use "Num" for columns representing some type of count, then always use "Num" - don't use "Num" in one place and "Cnt" somewhere else.
Note: A good "rule of thumb" for identifier names is that you should be able to read them over the phone without needing to spell them out. Different database platforms, Oracle, Sybase, and so on may all impose their own restrictions on identifier names. You should develop your own standard to comply with the rules of your own platforms. In xBase compatible databases table names are limited not only by the database engine but by the file system as well. Column names are similarly restricted. For example, in Microsoft Visual FoxPro 5.0, column names for free tables are limited to 10 characters. Some of these engines (including FoxPro) do allow you to assign longer identifiers if the table is included in a data dictionary. Check the documentation for your database engine and develop your standards based on the rules it imposes. The following rules are applied for naming tables: Regular Tables
Tables are named using the plural form of the object they represent. This convention is similar to the Microsoft Consulting Services naming convention for collection classes. For example, if the table contains customer data, the name would be Customers. Junction Tables
Tables used as the junction of a many-to-many relationship use the name of both tables. For example, if a table is the junction between an Orders table and an Items table, the name would be OrdersItems. Extension Tables
Tables used as extensions to a base table in a one-to-one relationship are named using the base table name and a word describing the nature of the extension. For example, you may have a generic Persons table with basic name and address columns that has a one-to-one relationship with an extension for only a few individuals. If, for example, you have an extension table storing information specifically about people who are doctors, info for the doctors would be in the PersonsDoctors table. General rules for identifiers apply to all table names. Microsoft Access databases use a prefix of "MSys" for database engine system tables and "USys" for user-defined system tables. Microsoft SQL Server databases use a prefix of "sys" for system tables. In order to eliminate naming collisions in queries with multi-table joins, a column name prefix is determined for each table. By prefixing column names with a few characters, every column name within the name space of a database will be unique. Use an abbreviated form of the table name for the prefix.
For example, the prefix for a Customers table would be "Cust". Each prefix must be unique within the database.
This guarantees that all columns names within the database will be unique. Special rules for junction tables.
For tables that act as the junction of a many-to-many relationship, you may use either the first letter of each table, or if that is not unique, use the prefix from each of the other tables. For example, the prefix for a table named OrdersItems could be either "OI" or "OrdItem". Counter/Identity Columns
Columns with autoincrement values used as the primary key column for a table are named with the table prefix followed by "ID". For example, the primary key column for the Customers table would be CustID. All Other Columns
Use the table prefix followed by a noun describing the attribute the column represents. For a Customers table, column names would include CustFirst, CustLast, CustCity, CustState, etc. General rules for identifiers apply to all column names. The column name prefixing concept is not a standard convention in the industry, but I've found that it works well, is easily understood, and avoids a variety of problems when building queries with multi-table joins. The following rules are applied for names of indexes and contraints: Primary Key
Use "apk" followed by the name of the table. For example, the primary key for the Customers table would be apkCustomers. The table name is used because there can be only one primary key, so using the table name means you can determine the name of the index without knowing what columns are used.
Note: The "apk" prefix is used instead of the more obvious "pk" to provide compatibility with server tables attached to Jet/Access databases. When Jet attaches a remote server table, it assumes that the first index found alphabetically is the primary key. Using "apk" places this index first in an alphabetical list. Other Unique Indexes
Use "udx" followed by the names of the column or columns in the index. If, for example, you have a table of states in the U.S., you could use an autoincrement column as the primary key but define a unique index on the state name or the two character postal code (or both).
Note: Not all tables will have this kind of alternate key. Foreign Key Constraints
Use "fk" followed by the column name or names. Remember that foreign keys are defined in the table on the many side of a one-to-many relationship. For the case of a one-to-one relationship, define the foreign key on the table that is a subset of the data in the larger table.
Note: In Jet databases, foreign key constraints are called Relation objects and are managed using the relations collection. However, you can still define them using CREATE TABLE or ALTER TABLE with a CONSTRAINT clause. Clustered Indexes
Use "cdx" followed by the table name. Like a primary key, there can only be one clustered index in a table, so the table name is used based on the same reasoning as that for naming the primary key. All Other Indexes
Use "idx" followed by the name of the column or columns used in the index. General rules for identifiers apply to all indexes and constraints. Not all database engines, Jet included, support clustered indexes. If you are not familiar with clustered indexes, a clustered index is an index where the leaf pages are the actual data pages. In normal indexes, the leaf pages are pointers to data pages. If you use Microsoft Access to create your database and define relationships using the Access Relationships window, all of your foreign key constraints will have names like "Relation1", "Relation2", etc. Although it is rare to reference this type of index in code, having more useful names is helpful if you do. Most database engines do not create an index that can be used for query optimization when you define a foreign key constraint. You should add an additional index for performance reasons on any column used as a foreign key. Microsoft SQL Server and other server databases support several different types of constraints other than foreign key constraints. You can, for example, name defaults and check constraints (known as validation rules in Jet databases). Defaults
Use "def" followed by the column name. Check Constraints
Use "chk" followed by the name of the column or table, as appropriate. Rules for objects other than tables, columns, and indexes can be more difficult to define, although the general rules for identifiers are followed wherever possible. Queries
The simplest method for naming saved queries is to prefix query names based on the purpose of the query. For example, "rpt" for report record sources, "frm" for form record sources, etc. User Accounts
There are several commonly used formulas for generating user account names, but the most common is to use a comination of the names or initials of the user's name. For example, if the user's name is John Q. Public, several possibilities would be "jpublic", "johnp", and "jqp". Synchronizing database account names with network account names will simplify the life of the user by reducing the number of account names and passwords the user needs to remember.
Note: Some database systems, including Microsoft SQL Server, allow you to use security systems that are integrated with the network security system, making the management of user accounts easier for both administrators and users. Stored Procedures
The SQL Server convention is to use "sp" as a prefix to the procedure name. Extended stored procedures are prefixed with "xp". Triggers
In most cases there will be three types of triggers available: insert, update, and delete. Trigger names use a combination of either "i", "u", or "d" to represent the type of trigger and the table name. If the trigger is used for more than one operation, the appropriate characters are combined.
Note: Jet databases do not support triggers. Just as is the case with variable and object naming conventions in Visual Basic code, the particular convention you choose is less important than developing or adopting a convention and following it faithfully. Rather than thinking of a naming convention as yet another complex set of rules to follow, it is helpful to think of a naming convention as a means of simplifying the task of database design and development. A well thought-out naming convention makes your life as a developer easier by eliminating one area of decision making (or at least consolidating that decision making process into the process of developing the naming convention) and making the design more consistent by applying a set of standards to at least one area.

Originally written by Joe Garrick


View the original article here

Link building tool: Buy relevant traffic with a pay per click

Sorry, I could not read the content fromt this page.Sorry, I could not read the content fromt this page.

View the original article here

Sunday, March 18, 2012

What are the Benefits of Wireless Internet Providers

Sorry, I could not read the content fromt this page.Sorry, I could not read the content fromt this page.

View the original article here

List of Top 10 Forums for Back Links

Sorry, I could not read the content fromt this page.Sorry, I could not read the content fromt this page.

View the original article here

Activate Any Window With API

One of the most common questions I've seen posted on newsgroups and online services involves activating another Windows application. The VB AppActivate statement falls hopelessly short of being truly useful since the window title of an application can change without notice. A much more reliable means of activating another application is by using the window class name. It's much more reliable because the class name of a window will not change once the application has been installed.

So, you ask, how do I get the class name of another application? While many will tell you that you need some sort of "spy" program, this is completely unnecessary. You can find the window class name for any application by running a few lines of code in the debug window. This is a one-time-only procedure.

Disclaimer: This will not help you activate a program written in VB. All VB form windows have the class name "ThunderForm". You'll have to revert to the old method of using the window text, or if the program is your own, make it an OLE server and provide a public Activate method. You can also check out this article in the Microsoft Knowledge Base:

How to Get a Window Handle Without Specifying an Exact Title
Article ID: Q113475

That being said, here's what you do:

Create a blank new module or use an existing module.

Place the following in the declarations section: Private Declare Function FindWindow Lib "user32" _ Alias "FindWindowA" _ (ByVal lpClassName As String, _ ByVal lpWindowName As String) As LongPrivate Declare Function GetClassName Lib "user32" _ Alias "GetClassNameA" _ (ByVal hWnd As Long, _ ByVal lpClassName As String, _ ByVal nMaxCount As Long) As Long

Enter the following procedure: Public Sub GetClassNameFromTitle() Dim sInput As String Dim hWnd As Long Dim lpClassName As String Dim nMaxCount As Long Dim lresult As Long ' pad the return buffer for GetClassName nMaxCount = 256 lpClassName = Space(nMaxCount) ' Note: must be an exact match sInput = InputBox("Enter the exact window title:") ' No validation is done as this is a debug window utility hWnd = FindWindow(vbNullString, sInput) ' Get the class name of the window, again, no validation lresult = GetClassName(hWnd, lpClassName, nMaxCount) Debug.Print "Window: " & sInput Debug.Print "Class name: " & Left$(lpClassName, lresult)End Sub

Run GetClassNameFromTitle in the debug window. If you enter the window title correctly, the class name will be printed in the debug window.

Once you have the window class name, you can always get a window handle by using FindWindow with the class name and vbNullString. For example: hWnd = FindWindow("OpusApp", vbNullString)

...will find the hWnd for the Microsoft Word window. Actually, I typically will code constants for the applications I will need to activate on a regular basis. Public Constant gcClassnameMSWord = "OpusApp"

I also use a wrapper function for the whole process: Public Function fActivateWindowClass(psClassname As String) As Boolean Dim hWnd As Long hWnd = FindWindow(psClassname, vbNullString) If hWnd > 0 Then ' ShowWindow returns True if the window was previously hidden. ' I don't care so I use the sub style ' ShowWindow and SW_SHOW declared elsewhere ' SW_SHOW will display the window in its current size and position Call ShowWindow hWnd, SW_SHOW fActivateWindowClass = True Else ' FindWindow failed, return False fActivateWindowClass = False End IfEnd Function

You can now activate the Word window with this simple code: If fActivateWindowClass(gcClassnameMSWord) Then ' succeeded, do what you willElse ' failed, handle with graceEnd if

This procedure could easily be extended to shell the application if FindWindow fails. That is left as an exercise for you.

Originally written by Joe Garrick


View the original article here

VB DataTable Sort

When there is a need of sorting rows in a DataTable, there is no direct support available in DataTable. There is no direct way to get the sorted records into a DataTable out of the box.  There are few ways to sort the data in the DataTable but that needs a few lines of code that I would like to discuss here. We have already discused how to sort a records in Gridview using DataView.

Basically I like the DataView to sort the records as there is a support natively available as a property DataView.Sort. And the sorted records can be forced to a DataTable using a ToTable () method in a DataView. Not only sorting available but also there are other useful functions like filter, and distinct etc... So we can filter and sort altogether.

Like I said earlier there are few ways to achieve sorting in the DataTable. The select method of the DataTable also offers the row filtering and sorting altogether. But the biggest drawback (at least to me) is the out put is a array of data rows.  This is not easier to be used as good as a DataView or DataTable. If that output as a DataTable with same structure, there will be a lot of places we don’t need to go to DataView.

However this is a very subjective view of usage, as I have seen developers working comfortably with arrays. So if select method fits you well, then sorting and filtering is a breeze.

Imports System.Data.SqlClient
Public Class Form1
Private ReadOnly Property ConnectionString() As String
Get
Return "Server=.\SQLEXPRESS;Database=NorthWind;Trusted_Connection=True"
End Get
End Property
Private Sub Button1_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles Button1.Click
ListBox1.Items.Clear()
ListBox1.DisplayMember = "ProductName"
ListBox1.ValueMember = "ProductID"
ListBox1.DataSource = GetSortedDataView()
End Sub
Public Function GetSortedRows() As DataRow()
Dim SelectQry = "select * from Products"
Dim SampleSource As New DataSet
Try
Dim SampleDataAdapter As New SqlDataAdapter(SelectQry, ConnectionString)
SampleDataAdapter.Fill(SampleSource)
Return SampleSource.Tables(0).Select("", "ProductName asc")
Catch ex As Exception
Throw ex
End Try
End Function
Public Function GetSortedDataView() As DataView
Dim SelectQry = "select * from Products"
Dim SampleSource As New DataSet
Dim SortableView As DataView
Try
Dim SampleDataAdapter As New SqlDataAdapter(SelectQry, ConnectionString)
SampleDataAdapter.Fill(SampleSource)
SortableView = SampleSource.Tables(0).DefaultView
SortableView.Sort = "ProductName asc"
Catch ex As Exception
Throw ex
End Try
Return SortableView
End Function 
End Class

View the original article here

VB6 Naming Conventions

A good naming conventions for objects you use in your code can go a long toward making the code easier to read and maintain. Here's what I'll be covering: IntroductionChoosing Identifier NamesNaming ProceduresNaming VariablesModifier TablesSummaryI'm going to give you a little warning right from the start. The use of naming conventions is a religious issue for many programmers - sometimes ranking as high as the age-old goto debate or the choice of language. Some like naming conventions and some hate them. Most large programming organizations, however, do use them. I also think that many of those that passionately hate having naming conventions imposed on their work would probably (perhaps grudgingly) admit their usefulness.

Like many other "standards", what's more important than any particular naming convention, is that you choose a naming convention and use it faithfully. While you can probably get away with using your kids names for variable names in a 100 line program, you're inviting chaos if you take that approach with any serious application.

I will state one thing as a rule up front. Use Option Explicit. If you're new to Visual Basic and not familiar with it - its a feature that requires you to declare each variable in your program. Without Option Explicit, every time you type a new variable name, VB will create a new variable for you. As you can imagine, this can create bugs that are extrememly difficult to find if you happen to mistype a variable name somewhere. Other than pure laziness, there's simply no excuse for not using Option Explicit, so I have absolutely no sympathy for you if you ever have a bug caused by letting the compiler create a variable you didn't intend to create.

In the rest of this page, I'll describe the standards I've used for naming procedures, variables, and other objects of various types. Feel free to use my convention or invent your own.

Most of the papers and books I've read that cover naming conventions spend a lot of time covering things like prefixes for different data types, etc., and neglect to cover the most basic concept - creating a good name for an identifier. Sure, it can help to use variable data type prefixes, but it doesn't help much if the name of your loop counter is intBunny and the procedure that contains the loop is called strDoSomething.

If you've done a decent job designing the application and the code, it doesn't take much effort to come up with decent names for the identifiers. The only problem that you're likely to run into is that the names may become excessively long. While very long names can be tiresome to use, its my opinion that you're better off to take the time to type an extra character or two than to use a meaningless or hard to interpret name.

Let's take a look at an example of how using appropriate variable names can help you write better code. Have you ever seen something like this: For i = 0 To 10 For j = 1 To 100 List1.AddItem x(j, i) NextNextIts more likely than not that in this case the array indexes have been reversed inside the inner loop. The programmer probably meant to do this: List1.AddItem x(i, j)Its easy to eliminate this problem before its created by giving the loop indexes more meaningful names: For iDivisionIdx = 1 To iDivisionCount For iDistrictIdx = 1 To iDistrictCount lstCustomers.AddItem sCustNames(iDivisionIdx, iDistrictIdx) Next ' iDistrictIdxNext ' iDivisionIdxThere's no confusion now over what loop index we're dealing with. Not only has the problem of transposing the indexes been elimiated - the entire loop construct is easier to read and understand because the names reflect the data being used.

Here are a few things to consider when naming identifiers in general: Use a name that represents the data or the function.
The name chosen should represent the data being used. If you are creating a variable that represents the total number of employees, EmployeeTotal or EmployeeCount would be good names. Use abbreviations consistently.
While its not necessary to have variable names that are 30 characters long, don't go overboard in abbreviating names. "Tm", for example, is only two characters shorter than "Time" and much less readable. There some common tags that are often used, such as Num for Number, Idx for Index, and so on. Feel free to use these if you wish, but if you do, use them consistently. Don't use Num some of the time and Number or Count at other times. Make the name readable.
A good rule to apply here is that you should be able to read your code to someone over the phone and have them be able to write it down without asking you for spellings. Use a noun for variables.
Pick a word that represents the data. This will make the code somewhat self-documenting and considerably easier to read. Use a noun and a verb for procedures.
If a procedure performs an action on an object, use a verb describing the action and a noun describing the object. For example, if a procedure adds a new contact to a database, "AddContact" might be an appropriate name. Use caution with temporary variables.
This is an area that can often cause problems such as the loop index error shown earlier. You may often need a temporary variable, such as a loop index or dummy variable to hold a return value from a function that you don't need. However, consider this: There's really no difference between a temporary variable and any other type of variable. They are all temporary since they only exist in the memory of the computer while the program is running and are always an abstraction created for the benefit of the programmer. The computer doesn't care what name you use, so why not take the time to type an extra character or two and use a meaningful name. In a large, complex program, you may have hundreds or thousands of procedures. Using a naming convention and good identifiers can make your job of finding and using the procedures considerably easier.

One standard that is commonly used for procedure names is to use a verb describing the action performed followed by a noun describing the object acted upon. I have to say that I'm not particularly fond of this convention, mainly because it makes it difficult to find a procedure in an alphabetical listing. If you are using "Get" as a prefix to functions which return values (such as GetWindowText), you'll end up with a long list of GetThis and GetThat procedures. I've always thought that it makes more sense to use the same technique but to reverse the noun and the verb. GetWindowText would become WindowTextGet. This groups all the procedures associated with a particular object together. Unfortunately (for me anyway), I'm probably the only person to have attempted to use such a convention - so make your own choice to be consistent with the rest of the world or make up your own standard. Perhaps something else entirely works best for you.

Regardless of the naming convention you choose, there are a few things which a procedure name should do for you: Use a name that represents an object and an action.
Whether you use verb-noun or something else, the name of the procedure should indicate what the procedure does and what it does it to or with. Be consistent in the order of the words.
If you're going to use verb-noun, always use verb-noun. If you mix and match the two, you're only making your own life harder. While you may be able to remember all of the procedure names in a program with 100 procedures, you are unlikely to accomplish the same feat in a program with 1,000 or 10,000 procedures. Be consistent in the verbs and nouns used.
Just as you should be consistent when naming variables, you should also be consistent when naming procedures. If you're going to use SetFirstName, also use SetLastName rather than AssignLastName. There's one other thing I'll mention which crosses the line between a coding standard and a naming convention. A well written procedure should do one task. If it does this, it will be easy to create a name for it. On the other hand, if the procedure does six things to four different objects, you may end up with a name like "AddCustomerAndUpdateRepPhoneAndFaxNumber". If you end up with a procedure name that looks like a run-on sentence, you probably haven't written a good procedure. If you need a name like "DoABunchOfStuff", you've almost certainly written a poor procedure. Before fudging a half-baked name, take another look at the code. Clearly its important with variables, just as with procedures and all identifiers, to use a name that is readable and representative of the data in use. There is, however, a debate among programmers over the use of various means of identifying variables by data type and usage. Some programmers like to use prefixes to identify the data type of the variable, while others prefer to use type declaration characters, and still others use neither and omit data type identification from the name entirely. The closest thing you'll find to a "sanctioned" naming convention for variables can be found in the MSDN/Visual Basic Starter Kit on the VB4 Professional edition CD under Visual Basic Programming Conventions from Microsoft Consulting Services.

I happen to like using data type prefixes, although I don't follow the Microsoft standards in all cases. Here's why: The code is easier to read.
I find that type declaration characters distracting when reading a code listing and difficult to verbalize. You aren't bound to VB's data types.
If you wish to define "hWnd" as a prefix for window handles, you can do so without breaking the standard. You can design your own standard.
The convention published by Microsoft specifies using "int" as a prefix for integers. I happen to prefer using just "i" - it saves a fair amount of typing for one of the most frequently used data types without sacrificing readability. Some of the data types introduced in VB4 have no type declaration character.
While I don't expect VB to drop the type declaration characters entirely in future versions, I also don't expect type declaration characters to be supported for any future data types. Also, many of the variables you work with are object variables which also have no type declaration character. There are two other notable sets of tags I use for variable names.

The first is a prefix indicating the scope of the variable. I use "m" for module level variables and "g" for global variables. These tags not only identify the scope of the variable but also avoid name collisions and name shadowing between variables at different scopes.

The second is a prefix for parameters. I use this to avoid naming collisions between parameters and local variables and to distinguish between input and output variables. Input parameters are prefixed with "p" and output with "rp".

By using these additional modifiers, I can normally be sure that I never two variables in scope with the same name.

Here are most of the modifiers I use, grouped as follows: Data Type ModifiersScope ModifiersMiscellaneous ModifiersControl TagsDAO ObjectsThe data type modifiers are prefixed to the variable name. The scope modifiers are used before all other prefixes. Variant
This is used with normal data type prefixes to indicate that a variant is being used but a specific data type is expected. For example, in a database application a foreign key might normally be a long (l) but may also be Null, thus the use of a variant. The resulting prefix would be vl. Procedure Parameter
This prefix is used to help avoid name collisions when working with local variables and procedure parameters which otherwise share the same name. This modifier is prefixed to the base data type modifier. Return Parameter
Used to indicate output (return values) passed through the parameter list in a procedure. This modifier is prefixed to the base data type modifier. User Defined Type
This modifier is used to indicate that the variable is a user-defined data type. It precedes all but the scope modifier. Array
This modifier is appended to the variable name and is used to indicate that the variable is an array. Form
The single upper case F is used in form names as specified at design time. The frm tag is used for variables representing forms. For variables, this tag follows the scope modifier. These tags are used in control names and in variables representing controls. These tags are used with DAO objects and precede all but the scope modifier.

Given the number of available objects, custom controls, etc., that are available for use in Visual Basic, it would be impossible to come up with a comprehensive list of tags for every type of object. For those not listed (or maybe for those that are as well) you'll need to come up with your own tags. What's more important than using any particular set of tags is to choose a convention for the names and use it consistently. You're sure to be kicking yourself if you go back and look at your code after six months and discover that half of your Byte variables and half of your Boolean variables are prefixed with "b". That was a lot to take in, but don't let yourself be confused or intimidated by the number of different modifiers and rules I use in naming objects. Once you get used to using a convention like this it becomes second nature and really does make life easier by allowing you to recognize the nature of the object by merely reading the name.

I'll repeat this again - it doesn't really matter what particular naming convention you choose as long as you name objects consistently. There's enough to learn and do in writing an application without expending excess effort in deciphering poor object names. Using a naming convention will eventually become automatic and that ultimately saves effort because its one less thing to think about.

Note: I have also published a Database Object Naming Conventions page. You might find it helpfull.

Originally written by Joe Garrick


View the original article here

Find duplicate files using VB.Net

When you are receiving files from different server hosting but the content is same, there is a possibility of having a different filename for the same content. Hence finding a duplicate file just by file name may not be sufficient. To compare by file data, there are several ways.

To find duplicate files even after renamed, the content/data has to be compared after the content of files fetched. Once the file content is in data format, the data can be encoded with MD5 hash algorithm. The string result after hash can be used for comparing. MD5 is a widely used cryptographic hash function with a 128-bit hash value, and is also commonly used to check the integrity of files

.NET Framework has very rich support for encryptWing and decrypting. Computing hashes and encrypting data using a variety of algorithms is very easy. Use the ComputeHash() method to compute the MD5 Hash.

For the MD5 to work we should give which encoding it should follow, basically we are using ASCIIEncoding. This same function can be used in a recursive call to check all the duplicates. Once all the files in the directory are scanned and compared it is much easier to delete the duplicate files found.

Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
If (CompareFiles("D:\FirstFile.txt", "D:\FirstFile1.txt")) Then
MsgBox("duplicate")
Else
MsgBox("diff")
End If
End Sub
Public Function CompareFiles(ByVal FirstFile As String, _
ByVal SecondFile As String) As Boolean
Return ReadFile(FirstFile) = ReadFile(SecondFile)
End Function
Private Function ReadFile(ByVal Path As String) As String
Dim ReadFileStream As FileStream
Dim FileEncoding As New System.Text.ASCIIEncoding()
Dim FileReader As StreamReader
Dim HashData As New MD5CryptoServiceProvider()
ReadFileStream = New FileStream(Path, FileMode.Open)
FileReader = New StreamReader(ReadFileStream)
Dim FileBytes = FileEncoding.GetBytes(FileReader.ReadToEnd)
Dim FetchedContent = FileEncoding.GetString(HashData.ComputeHash(FileBytes))
FileReader.Close()
ReadFileStream.Close()
Return FetchedContent
End Function

View the original article here

HTML Head Title Access Denied

The great helpful thing about developing with .NET is, a lot of objects introduced in .Net framework.One of them is this web client object. Earlier days we need to send the XmlHttp request or Web Request to send the request and receive the response. WebClient not only reduced the effort in downloading text, but also helpful in a lot of areas such as security and form submission etc…

As I said before the download string function makes the life easier. You can simply pass the URL to this function and it will return the response text. If the resource is secured you can send the Network Credentials to authenticate,
Dim webClient As New WebClient()
Dim Downloaded= webClient. DownloadString(URI)

Now that is the error we are receiving, means that the access is denied while calling the resource. So we need to authenticate. Use the following to authenticate. The Response can be received using DownloadStringAsync(Uri, Object) method Asynchronously as well
webClient.Credentials = New NetworkCredential(username, password)


View the original article here

Saturday, March 17, 2012

List of Top 10 Article Directories to Submit Articles

Sorry, I could not read the content fromt this page.Sorry, I could not read the content fromt this page.

View the original article here

Browse, Open, and Save Dialogs

Often when writing a VB.NET application we need to either open a file from the system or save a file to the system somewhere (many times both). Other times we need to browse for a folder instead of a file. Each one of these can be accomplished with a different Common Dialog that ships with VB.NET. To open a file we use the OpenFileDialog control. To save a file we use the SaveFileDialog control. Lastly, to browse for a folder we can use the FolderBrowserDialog. This tutorial and source sample demonstrates how to make use of each of this VB.NET common dialogs.

This tutorial walks through a portion of a Visual Basic .NET source code sample. It is suggested that you download the file and look at the code as it is explained in this tutorial. Note we will be focusing on the code in the following buttons: Open a file, Save a file, Browse Folders, and Retrieve Multiple Files (on the second tab).

image    image

As we go through each one of these snippets of the source code will be listed in line with the tutorial. However, by looking at the code yourself you will see detailed comments that help explain each area.

As the name suggests we can use the OpenFileDialog control to show a built in Windows common dialog in which the user can select the file they want to have opened. To do this we simply drag the OpenFileDialog control from the toolbox onto our form.

image

Once this control is on our form we can give it a name and begin to use it. On our sample we named it: odlgTextFile. The Open File Dialog has many properties to help us customize how it behaves. We are going to set a few of these to give you an idea of some of the things we can customize when opening a file (MainForm.vb – Line 12):

With odlgTextFile.CheckFileExists = True.CheckPathExists = True.DefaultExt = "txt".DereferenceLinks = True.Filter = _"Text files (*.txt)|*.txt|All files|*.*".Multiselect = False.RestoreDirectory = True.ShowHelp = True.ShowReadOnly = False.ReadOnlyChecked = False.Title = "Select a file to open".ValidateNames = TrueEnd With

Here is a description of what each of these properties does:

CheckFileExists – Tells windows to make sure that the file that’s selected does in fact existCheckPathExists – Again tells windows to verify the path existsDefaultExt – This is the extension type you want selected by default (notice leave the . off)DerefrenceLinks – This makes it so that if the user selects a link to a file the actual file is returnedFilter – This is what shows up in the filter drop down list. Notice its description, file type, separated by |’sMultiselect – This makes it so they can only select one fileRestoreDirectory – If you set this to false (the default) then whatever directory they are on when they open the file will be saved off and used for future file opens.ShowHelp – Makes the help button appear in the dialogShowReadOnly – Makes the checkbox appear that lets the user say to open the file in ReadOnly modeReadOnlyChecked – Sets if this checkbox is checked or not by defaultTitle – Is the title that appears in the dialogs headerValidateNames – Makes it so that we only accept valid Win32 file names.

So now we have our dialog all set up and ready to go the next thing we need to do is show the dialog and read the file that is selected:

If .ShowDialog = Windows.Forms.DialogResult.OK ThenTrytxtFileContents.Text = My.Computer.FileSystem.ReadAllText(.FileName)Catch fileException As ExceptionThrow fileExceptionEnd TryEnd If

Notice that the ShowDialog method takes no parameters and returns if the user clicked the Ok button or not. If the user did select a file and clicked ok then we try to open the file and set our TextBox to its contents. If for some reason there is an error doing this then we throw an exception. That’s all there is too it we can easily allow our users to open files from our VB.NET program.

The user of your program has spent hours creating the perfect thing. Now they don’t want to lose it when they restart the computer. They are looking for the all important search feature. They need to be able to select a folder and type in a filename to save what they are working on to the hard drive. How do you as a VB.NET developer give them this. Simple – use the SaveFileDialog control.

To begin using this control all we need to do is select it from the control toolbox and drag it onto our form. In our sample we named ours sdlgTextFile.

image

Next we need to hook up our Save button to make use of this control. To see this in action check out the click event handler for the Save File button in our sample (around line 77).

With sdlgTextFile.AddExtension = True.CheckPathExists = True.CreatePrompt = False.OverwritePrompt = True.ValidateNames = True.ShowHelp = True.DefaultExt = "txt".FileName = filename.Filter = _"Text files (*.txt)|*.txt|" & _"All files|*.*" If .ShowDialog() = Windows.Forms.DialogResult.OK ThenMy.Computer.FileSystem.WriteAllText(.FileName, _txtFileContents.Text, False)End IfEnd With

Some of the properties we are setting are the same as the OpenFileDialog above. However, some of them are specific to this dialog:

AddExtension – If the user just types a filename the DefaultExt will be appendedCreatePrompt – Prompts the user if they want to create the fileOverwritePrompt – If the file already exists Windows will ask the user if they want to overwrite it

Notice once again we call the ShowDialag method and check the return value to see if the user clicked the Ok button. If they did then we write our textBox contents to the file they specified.

Sometimes we want to allow our users to select a folder (either for us to read from or to write to). This is different from the File Dialogs as we don’t want to force the user to select a file within a folder but rather just the folder. Microsoft Windows has a common dialog for this and we can make use of it in VB.NET with the FolderBrowserDialog. To use this we once again drag the control from the toolbox onto our form.

image

Once the FolderBrowserDialog is on your form give it a name (ours is fldlgList) and once again we will hook up our Browse Folders button to interact with it (See line 264).

With fldlgList.RootFolder = Environment.SpecialFolder.Personal.Description = "Select the directory you want to use as the default.".ShowNewFolderButton = True If .ShowDialog = Windows.Forms.DialogResult.OK ThentxtDirectory.Text = .SelectedPathEnd IfEnd With

By now you should be getting pretty used to this code. We take our FolderBrowserDialog and set its RootFolder to where we want to the path we want the dialog to show when it starts up. We also give it a description and we tell it to allow the user to add a new folder with the built in NewFolder button.

Our final code is like the other dialogs. We verify that the user clicked the ok button and then we store away the SelectedPath that the user chose. Obviously in a real application we would do something with this path.

The last thing this tutorial goes over is how we can use the OpenFileDialog (the same one we used before) in order to let our users select multiple files. You will want to add a OpenFileDialog control from the toolbox to your form (like we did above). We named ours odlgFileNames. We will then hook up a button to show this dialog and to populate our list of files. You can see this in the button on the second tab of our sample project.

image

The code we use to allow our users to select multiple files is similar to what we did for the single file dialog with a few modifications.

With odlgFileNames.InitialDirectory = My.Computer.FileSystem.SpecialDirectories.Temp.AddExtension = True.CheckFileExists = True.CheckPathExists = True.DefaultExt = "txt".DereferenceLinks = True.Filter = _"Text files (*.txt)|*.txt|" & _"All files|*.*" .Multiselect = True .RestoreDirectory = True.ShowHelp = True.ShowReadOnly = False.Title = "Select a file".ValidateNames = True If .ShowDialog() = Windows.Forms.DialogResult.OK ThenDim strName As StringFor Each strName In .FileNames lstFiles.Items.Add(strName)NextEnd IfEnd With

Most of this code is the same as what we did for the single file dialog. One of the main things to notice are that we set the Multiselect property to true (this allows the users to select more than one file). Another thing to notice is that after the user clicks the Ok button we loop through the FileNames property instead of the using the FileName property (like we did before). The FileNames property gives us a list of each file that the user selected. For this sample we simply add each of these file names to our list.

VB.NET makes it very easy for us to interact with the Microsoft Windows Common Dialogs. The nice part when using these Dialog Controls is that our end users will experience the dialogs they are used to when they interact with our program. Microsoft has also made it very easy for us Visual Basic developers to interface with this dialogs through the controls they provide.

This tutorial went through a source sample that Microsoft produced to help us understand these Common Dialog Controls. You can download this source sample below:


View the original article here

Simple and advanced Conditional Experssions

Conditional expressions are used for so many things in VB.NET including branching, selection, and repetition. We use Conditional expressions all the time in real life. They evaluate to being either true or false, and are important in programming because they can be used to signal the computer to take one action (or set of actions) if the condition is true and another set of actions if the condition is false. With selection, a set of actions is taken if a condition is true; an alternative set of actions is taken if the condition is false; with repetition, a set of actions is repeated as long as a certain condition prevails.

Conditional expressions in VB statements must be preceded by certain keywords, such as If or Do While. The conditional expression itself is formed as follows:

               

The expression on either side of the relational operator can be a constant (string or numeric), variable (string or numeric), or an expression using symbols like +, -, etc.

The relational operator can be one of six symbols (or pair of symbols):

            Relational Operator                    Meaning

                        <                                  less than

                        >                                  greater than

                        =                                  equal to

                        <>                                not equal to (same as ¹ in algebra)

                        >=                                greater than or equal to (same as ³ in algebra)

                        <=                                less than or equal to (same as £ in algebra)

The expressions on either side of the relational operator should be "compatible" - that is, you should only compare a numeric item to a numeric item or a string item to a string item.  (As with assignment statements, if Option Strict is off, VB will perform "implicit conversion" if you compare two data items of different types; if the conversion cannot be performed, an "invalid cast exception" error will occur. If Option Strict is on, VB will not attempt to compare items of different types and will instead generate a compiler error.)

Following are some examples of conditional expressions involving the numeric variables intI and intJ.  Assume intI contains the value 5 and intJ contains the value 10:

When the conditional expression involves a character string compare, you can think of the relational operators as performing a comparison based on "alphabetical order".  For example, the expression "A" < "D" is true, because "A" precedes "D" alphabetically.  Likewise, the expression "Z" > "Q" is true, because "Z" follows "Q" alphabetically.

Following are some examples of conditional expressions involving the string variables strA and strB.  Assume strA contains "MARY" and strB contains "JOE":

Technically, when character string data is compared, each character is compared one by one from left to right until the computer can determine whether the first string is less than, equal to, or greater than the second string.  The determination is based on the ASCII value of each character.

If you look at a chart of the ASCII characters, you should see that, generally speaking:

            special characters < digits < uppercase letters < lowercase letters

Bear in mind that when digits are used in character string comparisons, the comparison is based on the digits' ASCII value.  Consider these two examples:

You can have two or more individual conditions in a conditional expression if you join those conditions with the keywords And or Or.  The rules for multi-condition conditional expressions are as follows:

(1)        ALL conditions joined by the keyword And must be TRUE in order for the entire conditional expression to be considered TRUE - otherwise, the expression will be evaluated as FALSE.

(2)        If ANY of the conditions joined by the keyword Or are TRUE, the entire conditional expression will be considered TRUE - only if ALL the conditions joined by ORs are FALSE will the entire conditional expression be considered FALSE.

(3)        If you mix Ands and Ors in the same conditional expression, And has precedence over Or.

(4)        The And/Or precedence can be overridden with parentheses.

Examples follow.  Assume the following variables contain the indicated values:

            A = 4    B = 6    C = 10 D = 3     E = 2    F = 5    G = 4

The truth-value of any condition can be negated by placing the keyword Not in front of the conditional expression.  For example, if the condition A > B is true, then the condition Not A > B is false.

The keywords And, Or, and Not are called logical operators.

With And and Or, the system will evaluate all of the conditions within the conditional expression, even if the result is clear before all of the conditions are evaluated. For example (still using the variable values above), in the conditional expression

C > B And D > C And A >= G

it is clear that when “D > C” is evaluated, the result of the entire expression will be deemed to be False – but the system will still continue to evaluate “A >= G”.

Similarly, in the conditional expression

A = G Or F = G Or B = G

it is clear that as soon as “A = G” is evaluated, the result of the entire expression will be deemed to be True – but the system will still continue to evaluate “F = G” and “B = G”.

VB.NET introduces two new logical operators which address this inefficiency – AndAlso and OrElse. These operators work similar to And and Or, however, they apply a technique called short-circuiting - they stop evaluation of conditions as soon as the result is clear. Obviously, short-circuiting increases the performance of the application.

We know that for And to return true, all conditions must be true. AndAlso stops evaluating further the moment it encounters a false condition and returns False. So a more efficient alternative to the "And" example above would be:

C > B AndAlso D > C AndAlso A >= G

We also know that for Or to return true, any one condition must be true. OrElse stops evaluating further the moment it encounters a true condition and returns True. So a more efficient alternative to the "Or" example above would be:

A = G OrElse F = G OrElse B = G

(Note: In most other computer languages, short-circuiting of the "and" and "or" operators is standard behavior. The main exception was pre-.NET (classic) Visual Basic. However, rather than change the behavior of the "And" and "Or'" oeprators when .NET came along, MS decided to leave those as is and introduce "AndAlso" and "OrElse".)

Extra Topic:

When regular relational operators (like >, <, =) won't do, you can use the Like operator to compare a string against a specified pattern. The Like operator is similar to the LIKE operator found in the SQL of most DBMS products (although the syntax differs somewhat).

An expression using Like has this format:

string Like pattern

where string is any string expression and pattern is any string expression conforming to the pattern-matching conventions described below.

A Like expression can be used anywhere a conditional expression can be used, such as in an If statement or Do While statement:

If  string Like pattern Then . . .

Do While string Like pattern

A Like expression (or any conditional expression) can also be assigned to a Boolean variable to yield a True or False value:

BooleanVariable = stringLikepattern

If string matches pattern, the result is True; if there is no match, the result is False.

Built-in pattern matching provides a versatile tool for string comparisons. The pattern-matching features allow you to use wildcard characters, character lists, or character ranges, in any combination, to match strings. The following table shows the characters allowed in pattern and what they match:

Any single character in charlist.

Any single character not in charlist.

A group of one or more characters (charlist) enclosed in brackets ([ ]) can be used to match any single character in string and can include almost any character code, including digits.

Note: To match the special characters left bracket ([), question mark (?), number sign (#), and asterisk (*), enclose them in brackets. The right bracket (]) can't be used within a group to match itself, but it can be used outside a group as an individual character.

By using a hyphen () to separate the upper and lower bounds of the range, charlist can specify a range of characters. For example, [A-Z] results in a match if the corresponding character position in string contains any uppercase letters in the range A–Z. Multiple ranges are included within the brackets without delimiters.

Other important rules for pattern matching include the following:

· An exclamation point (!) at the beginning of charlist means that a match is made if any character except the characters in charlist is found in string. When used outside brackets, the exclamation point matches itself.

· A hyphen () can appear either at the beginning (after an exclamation point if one is used) or at the end of charlist to match itself. In any other location, the hyphen is used to identify a range of characters.

· When a range of characters is specified, they must appear in ascending sort order (from lowest to highest). [A-Z] is a valid pattern, but [Z-A] is not.

· The character sequence [] is considered a zero-length string ("").

Examples follow:

True (because "aBBBa" fits the pattern "letter a" – any characters – letter a")

True (because "F" is within the range "A to Z")

False (because "F" is "not not" within the range "A to Z")

True (because "a2a" fits the pattern "letter a – any single digit – letter a")

True (because "aM5b" fits the pattern "letter a – a letter between L and P – a single digit – a letter not between c and e)

True (because "BAT123khg" fits the pattern "letter B – any single character – letter T – any characters")

False (because "CAT123khg" does not fit the pattern "letter B – any single character – letter T – any characters")

To demonstrate the Like operator using the examples described above, set up another "Try It" Console project, and place the following code in the Main method:

Sub Main()Dim strTestString AsString strTestString = "aBBBa"If strTestString Like"a*a"ThenConsole.WriteLine("'{0}' matches the pattern 'a*a'.", strTestString)ElseConsole.WriteLine("'{0}' does not match the pattern 'a*a'.", strTestString)EndIf strTestString = "F"If strTestString Like"[A-Z]"ThenConsole.WriteLine("'{0}' matches the pattern '[A-Z]'.", strTestString)ElseConsole.WriteLine("'{0}' does not match the pattern '[A-Z]'.", strTestString)EndIf If strTestString Like"[!A-Z]"ThenConsole.WriteLine("'{0}' matches the pattern '[!A-Z]'.", strTestString)ElseConsole.WriteLine("'{0}' does not match the pattern '[!A-Z]'.", strTestString)EndIf strTestString = "a2a"If strTestString Like"a#a"ThenConsole.WriteLine("'{0}' matches the pattern 'a#a'.", strTestString)ElseConsole.WriteLine("'{0}' does not match the pattern 'a#a'.", strTestString)EndIf strTestString = "aM5b"If strTestString Like"a[L-P]#[!c-e]"ThenConsole.WriteLine("'{0}' matches the pattern 'a[L-P]#[!c-e]'.", strTestString)ElseConsole.WriteLine("'{0}' does not match the pattern 'a[L-P]#[!c-e]'.", strTestString)EndIf strTestString = "BAT123khg"If strTestString Like"B?T*"ThenConsole.WriteLine("'{0}' matches the pattern 'B?T*'.", strTestString)ElseConsole.WriteLine("'{0}' does not match the pattern 'B?T*'.", strTestString)EndIf strTestString = "CAT123khg"If strTestString Like"B?T*"ThenConsole.WriteLine("'{0}' matches the pattern 'B?T*'.", strTestString)ElseConsole.WriteLine("'{0}' does not match the pattern 'B?T*'.", strTestString)EndIf Console.WriteLine("")Console.WriteLine("(Press Enter to close this window.)")Console.ReadLine()EndSub

When you run the project, it will show the following output:

image

Download the VB.NET project code for this example: Comparisions in VB.NET Source Code

Note: While most types of applications will not require the pattern matching power offered by the Like operator, it’s nice to know it's available if it is needed. If you need pattern matching capabilities beyond what is offered by the Like operator, you are encouraged to look into Regular Expressions, which can be used by VB.NET as well as earlier versions of VB. (Regular Expressions are not covered here.)

Now that you are an expert on conditional expressions,feel free to look at the selection and the repetition control structures.

This article was original written by The VB Programmer.


View the original article here

Hide Linkwithin Gadget on Home Page

Sorry, I could not read the content fromt this page.Sorry, I could not read the content fromt this page.

View the original article here

Friday, March 16, 2012

VB6 Animated Charts (With FusionCharts)

Introduction

In VB, when it comes to visualizing data in the form of charts, developers seldom think beyond MSChart. The MSChart component may seem adequate, but the fact is - it has some serious limitations. Some of the most significant limitations of MSChart are that it is not interactive, doesn’t support animation and drill-down. So with MSChart, it is only possible to incorporate monotonous static charts in Visual Basic applications. 

In this tutorial, you will be introduced to FusionCharts for VB – a charting component that helps you develop Flash-based animated and interactive charts for VB applications. No knowledge whatsoever of Flash is required to be able to use the component. The only requirement is for Adobe Flash Player 9 plugin to be installed. The plugin is widespread and can be downloaded from here.

Creating Charts for VB Applications

It is extremely easy to implement FusionCharts for VB. We will take a step-by-step approach to first see how to incorporate a chart in a VB application and then set up advanced features like drill-down and saving the chart as an image.

FusionCharts for VB can be downloaded from the FusionCharts Website. To install the component – just double click the setup.exe file and follow the instructions displayed on the dialog box.

So you are all set. Let's get started.

A simple example: Creating a pie chart

1. Create a Visual Basic project.

2. Open the component window using CTRL + T or by selecting the ‘Component’ option from the ‘Project’ menu. Next, select FusionCharts for VB, and then click ‘Apply’ and finally the ‘OK’ button.  

3. Notice, that a FusionCharts icon has now been added to the toolbox. 

4. Double click the FusionCharts icon – a chart control will be added to the Form, with a 3D column chart displayed by default.

FusionCharts for VB supports multiple data input methods - from XML string (called dataXML method), XML file (called dataURL method), using individual data input, arrays and from databases too.

Since I said this will be a simple example, we will be taking a look at only the dataXML and Individual Data input method. And we will use the other methods in other examples later on in the tutorial.

5. Add the following three buttons to the Form: 



6. Switch to the code view and enter the following code in the code window.

Private Sub cmdExit_Click()
End
End Sub

Private Sub cmdIndividualData_Click()
FusionCharts1.ChartType = pie3d
FusionCharts1.Data.setChartParams "caption=Match Score; xAxisName=Player Name;yAxisName=Score"
FusionCharts1.Data.addChartData "90", "label=David"
FusionCharts1.Data.addChartData "70", "label=Josh"
FusionCharts1.Data.addChartData "80", "label=Brain"
FusionCharts1.RenderChart
End Sub

Private Sub cmdXMLString_Click()
Dim XML As String
XML = ""
FusionCharts1.ChartType = pie3d 
FusionCharts1.setDataXML = XML
End Sub

7. Press F5 to run the project - the following screen will be displayed. The screen doesn’t display a chart as data is yet to be loaded.



8. Click on ‘Using Function’ or ‘XML String’ button – a 3D pie chart will be displayed.

 

Text Box: Explanation of the Code •	cmdExit_Click(): This function terminates all processes and quits the application. •	cmdXMLString_Click(): This function creates the XML string and passes it to the chart using the dataXML method. •	cmdUsingFunction_Click(): This function automatically creates XML for the chart – using the AddChartData API. •	setChartParams(): This function configures various parameters of the chart such as; caption, X axis name, Y axis name etc. •	FusionCharts1.ChartType: This property is used for selecting the type of chart which is to be plotted. For the above example ‘FusionCharts1.ChartType’ was set to ‘pie 3d’. •	RenderChart(): This function performs the task of rendering the chart.

Wowed? Let's try out a different chart type now.

Creating a multi-series column chart using data arrays

1. Create a new project and add the FusionCharts control to the form (steps 1 - 4 of instructions for creating a single-series chart).

2. Add the following controls to the form:

3. Switch to the code view and enter the following code in the code window.

Private Sub cmdArrayData_Click()
' Array to store category names
Dim arrCatName(0 To 5) As String

   ' Array to store datasets and chart data
Dim arrDataArray(0 To 1, 0 To 7) As String

   ' Variable to store chart parameters
Dim chartParameters As String
' Assigning chart parameters
chartParameters = "ShowValues=0;caption=Business Results 2008 v 2007;xAxisName=Month;yAxisName=Revenue;numberPrefix=$"

   ' Assigning Category names
arrCatName(0) = "Jan"
arrCatName(1) = "Feb"
arrCatName(2) = "Mar"
arrCatName(3) = "Apr"
arrCatName(4) = "May"
arrCatName(5) = "Jun"

   ' Assigning First Dataset seriesnames
arrDataArray(0, 0) = "2008"

   ' Assigning Second Dataset seriesnames
arrDataArray(1, 0) = "2007"

   ' Assigning chart data to First Dataset
arrDataArray(0, 2) = "27400"
arrDataArray(0, 3) = "29800"
arrDataArray(0, 4) = "25800"
arrDataArray(0, 5) = "26800"
arrDataArray(0, 6) = "29600"
arrDataArray(0, 7) = "32600"

   ' Assigning chart data to Second Dataset
arrDataArray(1, 2) = "10000"
arrDataArray(1, 3) = "11500"
arrDataArray(1, 4) = "12500"
arrDataArray(1, 5) = "15000"
arrDataArray(1, 6) = "11000"
arrDataArray(1, 7) = "9800"

   ' Sets chart's parameters
Call FusionCharts1.Data.setChartParams(chartParameters)
' Passing array to the FusionCharts component
Call FusionCharts1.Data.addChartDataFromArray(arrDataArray, arrCatName)
' Sets Chart Type
FusionCharts1.ChartType = mscolumn3d
' Calling Chart Rendering Method
FusionCharts1.RenderChart

End Sub

Private Sub cmdExit_Click()
End
End Sub

4. Press F5 to run the code and then click the ‘Using Array’ button to render the chart.

 

Creating a combination chart using data drawn from a database

1. Create a new project and add the FusionCharts control to the form (steps 1 - 4 of instructions for creating a single-series chart).

2. Next, add the following controls to the form:

3. Open the component window using CTRL + T or by selecting the ‘Component’ option from the ‘Project’ menu. Next, select ‘Microsoft ADO Data’, and then click ‘Apply’ and finally click the ‘OK’ button. Once the control is added to the form, drag it out of the visible area of the form – in order to make it invisible to the user.

4. Switch to the code view and enter the following code in the code window.

Private Sub cmdDatabase_Click()
' Configures ADODC control
Adodc1.ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & App.Path & "\FactoryDB.mdb" & ";Persist Security Info=False"
Adodc1.CommandType = adCmdTable
Adodc1.RecordSource = "MSCommon"
Adodc1.Refresh
' Variable to store chart parameters
Dim chartParameters As String
' Dataset parameters array
Dim arrDatasetParams(0 To 2) As String
arrDatasetParams(1) = "renderAs=Area;showValues=0"
arrDatasetParams(2) = "renderAs=Line;showValues=0"
chartParameters = "showValues=0;caption=Business Results 2007 v 2008;xAxisName=Month;yAxisName=Revenue;numberPrefix=$"
' Passing Chart's Parameters
Call FusionCharts1.Data.setChartParams(chartParameters)
' Changes Chart Type to Combination3D
FusionCharts1.ChartType = mscombi3d
' Sets ADODC recordset reference and database parameters
Call FusionCharts1.Data.addDatasetsFromDatabase(Adodc1.Recordset, "Months", "2008;2007;Quantity", arrDatasetParams)
' Calls render chart method
FusionCharts1.RenderChart
End Sub

Private Sub cmdExit_Click()
End
End Sub

5. Press F5 to run the code and then click the ‘Data from Database’ button – to render the chart.

Now that we have explored a number of chart types, we will look at how to improve the functionality of the chart.

Saving chart as image

For this example we’ll build upon the combination chart project itself.

1. Add the following controls to the form.

2. Arrange the form as shown below.

3. Switch to the code view and enter the following code in the code window.

Private Sub cmdSaveImage_Click()
FusionCharts1.SaveAsImage (True)
End Sub

Private Sub cmdCaptureImage_Click()
Picture1.Picture = FusionCharts1.GetPicture
End Sub

4. Press F5 to run the application and then click the ‘Data from Database’ button to render the chart.

5. Click the ‘Capture Image’ button the image of the chart will now be displayed in the Picture Box.

6. Next, click the ‘Save’ button, and in the ‘Save As’ dialog box specify the location where you wish to save the image of the chart.

Creating a chart with drilldown functionality

1. Create a new project and add the FusionCharts control to the form (steps 1 - 4 of instructions for creating a single-series chart).

2. Add the following controls to the form.

3. Arrange the form in the following manner.

4. Switch to the code view and enter the following code in the code window.

Private Sub cmdExit_Click()
End
End Sub

Private Sub SetFirstChart()
FusionCharts1.ChartType = column3d
Dim sChartParameters As String
' Setting chart parameters.
sChartParameters = "caption=Half Yearly Sales Summary;subcaption=For the year 2008 - First Half;xAxisName=Month;yAxisName=Sales; numberPrefix=$"
' Adding data to the chart,
' And at set parameter we are using link attribute with "J-" parameter, which helps us
' to track the click event.
' We are passing single parameter.
Call FusionCharts1.Data.addChartData("500", "label=Factory 1;link=J-CallFunctionOne-SingleParameter")
' We are passing two parameters separated by comma (,).
Call FusionCharts1.Data.addChartData("400", "label=Factory 2;link=J-CallFunctionTwo-1st Parameter,2nd Parameter")
' Passing without any parameter.
Call FusionCharts1.Data.addChartData("350", "label=Factory 3;link=J-CallFunctionThree")
' Finally render the chart.
Call FusionCharts1.RenderChart
End Sub

Private Sub Form_Load()
' Generates chart data and renders chart.
Call SetFirstChart
End Sub

Private Sub FusionCharts1_DrillDown(ByVal ActionName As String, ByVal ActionParameter As Variant)
' At ActionName, we will get the value which is given just after J-
' At ActionParameter, we will get the value which is given just after J-ActionName-
' XML String variable
Dim XML As String
' Applying Select statement with ActionName
Select Case ActionName
' If ActionName is CallFunctionOne
Case "CallFunctionOne":
' Creates XML
XML = ""
XML = XML & ""
XML = XML & ""
XML = XML & ""
XML = XML & ""
XML = XML & ""
XML = XML & ""
XML = XML & "
"
' If ActionName is CallFunctionTwo
Case "CallFunctionTwo":
' Creates XML
XML = ""
XML = XML & ""
XML = XML & ""
XML = XML & ""
XML = XML & ""
XML = XML & ""
XML = XML & ""
XML = XML & "
"
' If ActionName is CallFunctionThree
Case "CallFunctionThree":
' Creates XML
XML = ""
XML = XML & ""
XML = XML & ""
XML = XML & ""
XML = XML & ""
XML = XML & ""
XML = XML & ""
XML = XML & "
"
End Select
' Changing chart type to column2d
FusionCharts2.ChartType = column2d
' Providing XML to the chart.
FusionCharts2.setDataXML = XML
End Sub

The drill down functionality enables a click event on any of the column/bars of the chart to further enhance that data set and display another chart. For this we use a link attribute with J- parameter followed by function name (CallFunction(one/two/three)),  and the necessary function parameters. Now when we drill down into any of the column/bars, it invokes FusionCharts1_DrillDown event. Here we specify the XML for each of the new charts. 

5. Press F5 to run the project and then click ‘XML String’ button to render the chart.

6. Click on any of the columns of the chart – this causes another chart to be displayed in the ‘Detail Report’ window.

In these examples, you have seen how you can easily create exciting charts in VB. The examples demonstrated only few of the features of FusionCharts for VB. Some of the other highlights are:.

Great chart cosmetics, with gradients and 3D lighting.About 37 chart types with both 2D and 3D charts.Supports custom animation.Supports user-end interactivity in the form of tooltips and allows client-side rotation, slicing and scaling of charts.Allows advanced drill-down.Multiple modes of data configuration, which includes:Data from XML string.Data from Array.Data from a database.

View the original article here

VB Send Email

If you are still working in classic VB, sending email is not as easy as we do in asp.net. Especially for notifications emails are one of the best ways to communicate. Normally the SMTP server will be in separate email hosting server reachable from application server. In this scenario we need to configure CDO to use our SMTP server. Then only the mail relay will be successful.

The function we are discussing will support most of the email functionalities like CC, BCC and attachment.
The function will return the status about sent. Since this function is designed for applications, the related settings can be fetched from settings file rather than changing the code and re compiling to take changes.

Basically the following configurations are necessary before sending mail with CDO object
•  CDO.Message
• CDO.Configuration

This object is used to set the various properties like following

• To
• From
• Subject
• TextBody
• Attachment
• CC
• BCC
Finally we can call the Send method to send the mail. 

This object is used to set the configurations like
• Send using
• SMTP server
• SMTP server port

Please change the respective SMTP server in the "change your SMTP server here" section. Or else you will get the "The transport failed to connect to the server." error message. 

Most of my applications are using this function which needs SMTP Authentication. In order for this function to work, you must have a valid SMTP server with a valid user name and password.

It happened to me that my user account was locked or grey listed once since I have tried several times with bad password. Then the setting won’t work for a while until it gets released. So it is better if you have any doubts, use any utilities which may help to test the email before using this function. So make sure you have valid credentials and information regarding the SMTP server before using this function.


View the original article here

VB.NET Input Box

An often used feature in classic Visual Basic is the InputBox function. It provides an easy way to prompt the user for simple text input. VB.NET carries this handy function forward for all to use. Although you probably won’t use this any time you need to request a large or amount of data or in other complex scenarios, it does provide a simple and effective way to get input in your Visual Basic.NET apps.

Displays a prompt in a dialog box, waits for the user to input text or click a button, and returns a string containing the contents of the text box.

Usage :

stringvariable = InputBox(prompt[, title] [, default] [, xpos] [, ypos])

The arguments to the InputBox function are described below:

Required. String expression displayed as the message in the dialog box. The maximum length of prompt is approximately 1024 characters, depending on the width of the characters used.

Optional. String expression displayed in the title bar of the dialog box. If you omit title, the application name is placed in the title bar.

Optional. String expression displayed in the text box as the default response if no other input is provided. If you omit default, the text box is displayed empty.

Both optional. Numeric expressions that specify custom positioning of the box on screen (by default, the box is displayed in the center of the screen, which is usually desired).

Remarks

If the user clicks OK or presses ENTER , the InputBox function returns whatever is in the text box. If the user clicks Cancel, the function returns a zero-length string ("").

Sample Program

The sample program uses a form with two buttons and a label, laid out as shown below:

image

The properties set for these controls are as follows:

(First Button):

Name: cmdGetInputText: Get Input

(Label):

Name: lblInfoAutoSize: FalseBackColor: KhakiBorderStyle: Fixed SingleText: (clear)

(Second Button):

The code for the program is shown below:

Public Class Form1 PrivateSub cmdGetInput_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdGetInput.Click Dim strUserName AsString  strUserName = InputBox("Enter your name:", "InputBox Test", "Type your name here.")  If strUserName = ""Then ' user cancelled the InputBox, so clear the label lblInfo.Text = "" Else lblInfo.Text = "User Name: " & strUserName EndIf EndSub  PrivateSub cmdExit_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdExit.Click Me.Close() EndSubEnd Class

When the program is run and you click the "Get Input" button, the following input box is displayed. Note the content of the box based upon the values used as the arguments for the InputBox function:

        strUserName = InputBox("Enter your name:", "InputBox Test", "Type your name here.")

image

Enter your name in the text entry portion of the box (in this example, the name John is entered):

image

After you click OK, the text "User Name: " concatenated with the name you entered will be displayed in the label:

image

You can download the example code for this tutorial here: InputBox VB.NET Example

This article was original written by The VB Programmer.


View the original article here

Scalability of the blog: How to implement social media strategies?

Sorry, I could not read the content fromt this page.Sorry, I could not read the content fromt this page.

View the original article here

Use API To See If Windows Started In Safe Mode

Visual Basic gives us access to the Windows API which allows us to do virtually anything. In this source sample we will use the GetSystemMetrics API located in the user32 dll to find out how Windows was started. This is helpful if you want to do something different with your application based on if Windows started in Safe Mode, Safe Mode with Network Support, or Normal mode.

The easiest way to call Windows API's is to declared them in a module so to try this out create a new VB project. Then go to the Project Menu and click Add Module. Inside this module add the following code.

Declare Function GetSystemMetrics Lib "user32" _        (ByVal nIndex As Long) As LongPublic Const SM_CLEANBOOT = 67

No go to your main form, add a command button, double click on the button to go to its click event handler, and add the following code.

Select Case GetSystemMetrics(SM_CLEANBOOT)    Case 1: MsgBox "Windows was Started in Safe Mode."                "Windows was Started in Safe Mode with Network support."    Case Else: MsgBox "Windows is running normally."

Once you've added the source code run your application and click on the button. You should see a message box that corresponds to the way you started Windows.

Obviously this just barely scratches the surface on what you can do with the Windows API. Check out the links below to find out more.


View the original article here