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

Thursday, 28 August 2014

Difference between structure and class .NET


A short summary of each:
Classes Only:
  • Can support inheritance
  • Are reference (pointer) types
  • The reference can be null
  • Have memory overhead per new instance
Structs Only:
  • Cannot support inheritance
  • Are value types
  • Are passed by value (like integers)
  • Cannot have a null reference (unless Nullable is used)
  • Do not have a memory overhead per new instance - unless 'boxed'
Both Classes and Structs:
  • Are compound data types typically used to contain a few variables that have some logical relationship
  • Can contain methods and events
  • Can support interfaces

Another example of recursive method.


Print menus recursively (you can amend the code according to your needs of course)


This is the method you would call to get the menus printed indented according to their level in the hierarchy in a console application

PrintMenus(GenerateAllMenus());


private static string menuLevel = string.Empty; ///
/// Prints the menus. /// /// The menus. private static void PrintMenus(IEnumerable menus) { menuLevel += " "; foreach (var menu in menus) { Console.WriteLine(string.Concat(menuLevel, menu.MenuTitle)); var subMenu = GetSubMenu(menu); if (subMenu != null) PrintMenus(subMenu); } menuLevel = menuLevel.Substring(0, menuLevel.Length - 5); }



///
/// Generates all menus. /// /// private static IEnumerable GenerateAllMenus() { var menus = new List(); var fileMenu = new HeirarchicalMenu { MenuTitle = "File", SubMenus = new List { new HeirarchicalMenu { MenuTitle = "New", SubMenus = new List { new HeirarchicalMenu { MenuTitle = "Class / Hypermodule" } } }, new HeirarchicalMenu { MenuTitle = "Open", SubMenus = new List { new HeirarchicalMenu { MenuTitle = "Class / Hypermodule", SubMenus = new List { new HeirarchicalMenu { MenuTitle = "5th Level", SubMenus = new List { new HeirarchicalMenu { MenuTitle = "6th Level", SubMenus = new List { new HeirarchicalMenu { MenuTitle = "7th Level" } } } } } } } } }, new HeirarchicalMenu { MenuTitle = "Exit" } } }; menus.Add(fileMenu); var editMenu = new HeirarchicalMenu { MenuTitle = "Edit Menu", SubMenus = new List { new HeirarchicalMenu { MenuTitle = "Cut" }, new HeirarchicalMenu { MenuTitle = "Copy", SubMenus = new List { new HeirarchicalMenu { MenuTitle = "Deep Copy" }, new HeirarchicalMenu { MenuTitle = "Shallow Copy" } } }, new HeirarchicalMenu { MenuTitle = "Paste" } } }; menus.Add(editMenu); var viewMenu = new HeirarchicalMenu { MenuTitle = "View Menu", SubMenus = new List { new HeirarchicalMenu { MenuTitle = "Cascade" }, new HeirarchicalMenu { MenuTitle = "Horizontal" }, new HeirarchicalMenu { MenuTitle = "Vertical" } } }; menus.Add(viewMenu); return menus; } /// /// Gets the sub menu. /// /// The menu. /// private static IEnumerable GetSubMenu(HeirarchicalMenu menu) { if (menu.SubMenus != null && menu.SubMenus.Count > 0) return menu.SubMenus; return null; } public class HeirarchicalMenu { /// /// Gets or sets the menu title. /// /// /// The menu title. /// public string MenuTitle { get; set; } /// /// Gets or sets the sub menus. /// /// /// The sub menus. /// public List SubMenus { get; set; } /// /// Initializes a new instance of the class. /// public HeirarchicalMenu() { if (SubMenus == null) SubMenus = new List(); } }



Hope its helpful.


Example of using recursive methods.




The task is to get the Fibonacci series printed in a recursive method.

Its output is every number is a total of previous two numbers i.e. 0,1,1,2,3,5,8,13,21,34,55,89,144,233,377,610



static int Fibonacci(int value)
{
if (value == 0 || value == 1)
return value;
return (Fibonacci(value - 1) + Fibonacci(value - 2));
}


in the above code value represents number of permutations we would like to get this series generated for. The output printed before the code is for 15 permutations.