Showing posts with label VB.NET. Show all posts
Showing posts with label VB.NET. Show all posts

Sunday, 31 August 2014

Simple numeric textbox

A simple way to make a textbox which accepts only numbers and a decimal number separator.




First of all we need to declare some properties.

C#
private List<char> ValidCharacters { getset; }
This property would contain the list of valid characters. We'll set its values later in the constructor of the class.

private byte NumberOfDecimalPlaces { getset; }
This property would determine the number of places after decimal separator.

private char DecimalSeparator { getset; }
This property would determine the decimal separator which can be a dot "." or a comma "," in some countries it can be something else.
Lets set the values to these properties. this can be set into the constructor or the form load event.
if (ValidCharacters == null)
{
        ValidCharacters = new List<char>(); // Initializes the property.
}

NumberOfDecimalPlaces = 4; // Sets the number of places after the decimal separator.
DecimalSeparator = ',';// Determines the value for decimal separator.
ValidCharacters.AddRange("1234567890"); // Add valid characters into the list.
ValidCharacters.Add(DecimalSeparator); // Adds decimal separator into the valid characters list.

After setting all the properties into the relevant area just paste the code below into the KeyPress event of the textbox.
C#
    private void NumericTextBoxKeyPress(object sender, KeyPressEventArgs e)
    {
      if (e.KeyChar == (char)Keys.Back)
        return;

      var cursorLocation = NumericTextBox.SelectionStart;

      if (e.KeyChar == DecimalSeparator && NumericTextBox.Text.Contains(DecimalSeparator))
      {
        e.Handled = true;
      }
      else
      {
        if (!ValidCharacters.Contains(e.KeyChar))
        {
          e.Handled = true;
        }
        else
        {
          if (NumericTextBox.Text.Contains(DecimalSeparator))
          {
            var locationOfDot = NumericTextBox.Text.IndexOf(DecimalSeparator);
            var textLengthAfterDecimal = NumericTextBox.Text.Substring(locationOfDot, NumericTextBox.Text.Length - (locationOfDot + 1)).Length;
            if (cursorLocation > locationOfDot)
            {
              if (textLengthAfterDecimal >= NumberOfDecimalPlaces)
              {
                e.Handled = true;
              }
            }
          }
        }
      }
    }


VB
Private m_ValidCharacters As List(Of Char)
Private Property ValidCharacters() As List(Of Char)
                Get
                                Return m_ValidCharacters
                End Get
                Set
                                m_ValidCharacters = Value
                End Set
End Property

Private m_NumberOfDecimalPlaces As Byte
Private Property NumberOfDecimalPlaces() As Byte
       Get
              Return m_NumberOfDecimalPlaces
       End Get
       Set
              m_NumberOfDecimalPlaces = Value
       End Set
End Property

Private m_DecimalSeparator As Char
Private Property DecimalSeparator() As Char
                Get
                                Return m_DecimalSeparator
                End Get
                Set
                                m_DecimalSeparator = Value
                End Set
End Property
If ValidCharacters Is Nothing Then
       ValidCharacters = New List(Of Char)()
End If

NumberOfDecimalPlaces = 4 ' Sets the number of places after the decimal separator.
DecimalSeparator = ","C' Determines the value for decimal separator.
ValidCharacters.AddRange("1234567890") ' Add valid characters into the list.
ValidCharacters.Add(DecimalSeparator) ' Adds decimal separator into the valid


VB
                                Private Sub NumericTextBoxKeyPress(sender As Object, e As KeyPressEventArgs)
                                                If e.KeyChar = CChar(Keys.Back) Then
                                                                Return
                                                End If

                                                Dim cursorLocation = NumericTextBox.SelectionStart

                                                If e.KeyChar = DecimalSeparator AndAlso NumericTextBox.Text.Contains(DecimalSeparator) Then
                                                                e.Handled = True
                                                Else
                                                                If Not ValidCharacters.Contains(e.KeyChar) Then
                                                                                e.Handled = True
                                                                Else
                                                                                If NumericTextBox.Text.Contains(DecimalSeparator) Then
                                                                                                Dim locationOfDot = NumericTextBox.Text.IndexOf(DecimalSeparator)
                                                                                                Dim textLengthAfterDecimal = NumericTextBox.Text.Substring(locationOfDot, NumericTextBox.Text.Length - (locationOfDot + 1)).Length
                                                                                                If cursorLocation > locationOfDot Then
                                                                                                                If textLengthAfterDecimal >= NumberOfDecimalPlaces Then
                                                                                                                                e.Handled = True
                                                                                                                End If
                                                                                                End If
                                                                                End If
                                                                End If
                                                End If
                                End Sub
Please leave a comment if this helps you.

Friday, 29 August 2014

Save image to database using C#

To convert this code to VB.net Click Here. Opens in new window.



Download project


using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.OleDb;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace PictureToDatabase
{
public partial class ImageForm : Form
{
private readonly string connectionString = string.Empty;
private OleDbConnection connection;
private OleDbCommand command;
private List Images;

private MyImage currentImage;

///
/// Gets or sets the current image.
///
///
/// The current image.
///
private MyImage CurrentImage
{
get { return currentImage; }
set
{
currentImage = value;
if (currentImage != null)
{
PictureBox.Image = BinaryToImage(currentImage.FileData);
ImageNameLabel.Text = System.IO.Path.GetFileName(currentImage.FileName);
}
}
}

///
/// Initializes a new instance of the class.
///
public ImageForm()
{
InitializeComponent();
connectionString = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=|DataDirectory|\ImageDatabase.accdb";
}

///
/// Browses the button click.
///
/// The sender.
/// The instance containing the event data.
private void BrowseButtonClick(object sender, EventArgs e)
{
var browseDialog = new OpenFileDialog
{
Filter = "BMP|*.bmp|GIF|*.gif|JPG|*.jpg;*.jpeg|PNG|*.png|TIFF|*.tif;*.tiff"
};

if (browseDialog.ShowDialog(this) != DialogResult.Cancel)
{
var fileName = browseDialog.FileName;
CurrentImage = new MyImage
{
FileData = System.IO.File.ReadAllBytes(fileName),
FileName = fileName
};
}
}

///
/// Saves the button click.
///
/// The sender.
/// The instance containing the event data.
private void SaveButtonClick(object sender, EventArgs e)
{
try
{
var filePath = PictureBox.ImageLocation;
var fileData = System.IO.File.ReadAllBytes(filePath);
connection = new OleDbConnection
{
ConnectionString = connectionString
};
connection.Open();

const string statement = @"INSERT INTO Images VALUES(@imageName, @imageData)";
command = new OleDbCommand(statement, connection)
{
CommandType = CommandType.Text
};
command.Parameters.AddWithValue("@imageName", System.IO.Path.GetFileName(filePath));
command.Parameters.AddWithValue("@imageData", fileData);

command.ExecuteNonQuery();
MessageBox.Show("Image saved successfully");
}
catch (Exception exception)
{
MessageBox.Show(string.Format("Error occured {0}", exception.Message));
}
}

///
/// Retrieves the button click.
///
/// The sender.
/// The instance containing the event data.
private void RetrieveButtonClick(object sender, EventArgs e)
{
connection = new OleDbConnection
{
ConnectionString = connectionString
};
connection.Open();

const string statement = @"SELECT * FROM Images ";
command = new OleDbCommand(statement, connection)
{
CommandType = CommandType.Text
};

var dataTable = new DataTable();
dataTable.Load(command.ExecuteReader());
Images = new List();

foreach (DataRow dataRow in dataTable.Rows)
{
Images.Add(new MyImage
{
FileName = dataRow.Field("ImageName"),
FileData = dataRow.Field("ImageData")
});
}

if (Images.Count <= 0)
return;

Images.Sort((x, y) => String.CompareOrdinal(x.FileName, y.FileName));
CurrentImage = Images.FirstOrDefault();
ToggleNavigation();
}

///
/// Binaries to image.
///
/// The image data.
///
private Bitmap BinaryToImage(byte[] imageData)
{
Bitmap image;
using (var stream = new System.IO.MemoryStream(imageData))
{
image = new Bitmap(stream);
}
return image;
}

///
/// Nexts the button click.
///
/// The sender.
/// The instance containing the event data.
private void NextButtonClick(object sender, EventArgs e)
{
var index = Images.IndexOf(CurrentImage);
if (index < Images.Count - 1)
CurrentImage = Images.ElementAt(index + 1);
ToggleNavigation();
}

///
/// Previouses the button click.
///
/// The sender.
/// The instance containing the event data.
private void PreviousButtonClick(object sender, EventArgs e)
{
var index = Images.IndexOf(CurrentImage);
if (index >= 1)
CurrentImage = Images.ElementAt(index - 1);
ToggleNavigation();
}

///
/// Toggles the navigation.
///
private void ToggleNavigation()
{
NextButton.Enabled = Images.IndexOf(CurrentImage) < Images.Count - 1;
PreviousButton.Enabled = Images.IndexOf(CurrentImage) >= 1;
}

}

///
///
///
public class MyImage
{
///
/// Gets or sets the name of the file.
///
///
/// The name of the file.
///
public string FileName { get; set; }

///
/// Gets or sets the file data.
///
///
/// The file data.
///
public byte[] FileData { get; set; }
}
}



Please leave a comment.



Regex email validator

C#

private static bool IsValidEmailAddress(string email)
{
const string pattern = @"^([\w\.\-]+)@([\w\-]+)((\.(\w){2,3})+)$";
var regex = new System.Text.RegularExpressions.Regex(pattern);
return regex.IsMatch(email);
}


VB

Private Shared Function IsValidEmailAddress(email As String) As Boolean
Const  pattern As String = "^([\w\.\-]+)@([\w\-]+)((\.(\w){2,3})+)$"
Dim regex = New System.Text.RegularExpressions.Regex(pattern)
Return regex.IsMatch(email)
End Function

Monday, 28 July 2008

A Chapter from a book connected to my course

I managed to find a book in the library connected directly to my subject. The book's name is "ASP.NET in VB.NET". I read few chapters from the book and found them quite interesting and useful in future for me. Here I am writing the summary of the chapter I liked most so far.


The Evolution of VB.NET


Traditional ASP development was restricted to the VBScript programming language, which was first developed as a basic scripting language for writing macros and other simple code that would be used by another application. VBScript was never intended for sophisticated, interactive web applications and for that reason expert programmers had to strain the language to its limit to create first-rate ASP pages. To get around many limitations in VBScript, advanced pages needed to rely on separate components written in other languages, which generally had to be installed and configured separately on the web server. In the end even though VBScript was intended to be easier to use than ordinary Visual Basic writing advanced ASP pages actually became much more complicated because of the additional effort needed to circumvent VBScript’s limitations.

Just replacing VBScript with Visual Basic would have been a significant advantage. Some of the features Visual Basic 6 offers that VBScript lacks include the following.

· Access to the platform services: VBScript on the other hand is automatically isolated by the scripting host and has many security-related restrictions.
· Typed programming. VBScript doesn’t allow us to strict control over data types, and works with special ‘variant’ variables instead. Which are supposed to be easier to use. Unfortunately, they also introduce data type conversion problems and difficult-to-detect errors.
· Event-driven programming. Unlike Visual Basic, VBScript is notoriously disorganized and has little flexibility to group or organize code so that code can be easily debugged and reused.
· Support for objects. Visual Basic doesn’t have perfect object-oriented features, but they are still light years over what VBScript can accomplish.

However, ASP.NET has completely skipped over this stage in evolution and moved directly to the advanced capabilities of Visual Bacis.NET. This latest version of Visual Basic is a complete redesign that answers years of unmet complaints and extends the VB Language into new territory. Some of the new features include the following.

· Structured error handling. The end of the aggravating “On Error Goto” construct has finally arrived. VB.NET introduces .NET’s new standard: clean, concise, structured exception handling. We can see in chapter 11
· Language refinements. Every aspect of the VB language has been tweaked and refined. We can now overload functions, declare and assign variables on the same line, and use shortened assignment syntax.
· Strong typing. Even Visual Basic 6 performed some automatic variable conversions that could cause unusual bugs. VB.NET allows us to rein in our program and prevent possible errors with strict type checking
· True object-oriented programming. Inheritance, interfaces, polymorphism, constructors, shared members and abstract classes and the list goes on, and Visual Basic.NET integrates them all into the one language.

The list of new words

Strain
Part of Speech: verb
Synonyms: filter, puree, screen, separate, sieve, sift

First-rate
Part of Speech: adjective
Synonyms: a-one, classy, dandy, excellent, first-class, super, topnotch, tops

Circumvent
Part of Speech: verb
Synonyms: avoid, baffle, balk, bypass, cheat, check, deceive, defraud, detour, dupe, elude, encompass, entrap, evade, foil, fool, frustrate, mislead

Isolated
Part of Speech: adjective
Synonyms: alone, apart, hidden, insular, insulated, lone, lonely, private, random

Notorious
Part of Speech: adjective
Definition: Known widely and unfavorably.
Synonyms: common, infamous