Thursday, 11 September 2014

Introduction to WPF

What is WPF

Windows Presentation Foundation (WPF) is a next-generation presentation system for building Windows client applications with visually stunning user experiences. With WPF, you can create a wide range of both standalone and browser-hosted applications. 
The core of WPF is a resolution-independent and vector-based rendering engine that is built to take advantage of modern graphics hardware. WPF extends the core with a comprehensive set of application-development features that include Extensible Application Markup Language (XAML), controls, data binding, layout, 2-D and 3-D graphics, animation, styles, templates, documents, media, text, and typography. WPF is included in the Microsoft .NET Framework, so you can build applications that incorporate other elements of the .NET Framework class library.
This overview is intended for newcomers and covers the key capabilities and concepts of WPF. Experienced WPF developers seeking a review of WPF may also find this overview useful.

Programming with WPF

WPF exists as a subset of .NET Framework types that are for the most part located in the System.Windows namespace. If you have previously built applications with .NET Framework using managed technologies like ASP.NET and Windows Forms, the fundamental WPF programming experience should be familiar; you instantiate classes, set properties, call methods, and handle events, all using your favorite .NET Framework programming language, such as C# or Visual Basic.
To support some of the more powerful WPF capabilities and to simplify the programming experience, WPF includes additional programming constructs that enhance properties and events: dependency properties and routed events. We will discuss Dependency Properties and Routed Events in another chapter.

References
http://msdn.microsoft.com/en-us/library/aa970268(v=vs.110).aspx

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.


Wednesday, 4 June 2014

LINQ - Standard Operators - Filtering Operators

LINQ - Filtering Operators

The two filtering operators in LINQ are the Where and OfType operators. An example follows.

 ArrayList list = new ArrayList { "Sheraz", new object(), "London", new object() };  
             var query = from name in list.OfType<string>()  
                                     where name == "Sheraz"  
                                     select name;  

Above query returns only "Sheraz" and narrows down the search to strings only.

The Where operator generally translates to a WHERE clause when working with a relational database and has an associated keyword in C# as shown in the code above. The OfType operator can be used to coax a non-generic collection (like an ArrayList) into a LINQ query. Since ArrayList  does not implement IEnumerable, the OfType operator is the only LINQ operator we can apply to the list.OfType is also useful if you are working with an inheritance hierarchy and only want to select objects of a specific subtype from a collection. This includes scenarios where LINQ to SQL or the Entity Framework are used to model inheritance in the database. Both operators are deferred.