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.

Thursday, 26 February 2009

American Standard Code Information Interchange (ASCII)

ASCII, Hexadecimal, Characters and their Names

ASCII 

Hex 

Char 

Name 

0 

00 

NUL 

Null 

1 

01 

STX 

Start of Header

2 

02 

SOT 

Start of Text

3 

03 

ETX 

End of Text

4 

04 

EOT 

End of Transmission

5 

05 

ENQ 

Enquiry

6 

06 

ACK 

Acknowledge

7 

07 

BEL 

Bell

8 

08 

BS 

BackSpace

9 

09 

HT 

Horizontal Tabulation

10 

0A 

LF 

Line Feed

11 

0B 

VT 

Vertical Tabulation

12 

0C 

FF 

Form Feed

13 

0D 

CR 

Carriage Return

14 

0E 

SO 

Shift Out

15 

0F 

SI 

Shift In

16 

10 

DLE 

Data Link Escape

17 

11 

DC1 

Device Control 1 (XON)

18 

12 

DC2 

Device Control 2

19 

13 

DC3 

Device Control 3 (XOFF)

20 

14 

DC4 

Device Control 4

21 

15 

NAK 

Negative acknowledge

22 

16 

SYN 

Synchronous Idle

23 

17 

ETB

End of Transmission Block

24 

18 

CAN 

Cancel

25 

19 

EM 

End of Medium

26 

1A 

SUB 

Substitute

27 

1B 

ESC 

Escape

28 

1C 

FS 

File Separator

29 

1D 

GS 

Group Separator

30 

1E 

RS 

Record Separator

31 

1F 

US 

Unit Separator

32 

20 

[Space] 

Space

33 

21 

! 

Exclamation mark

34 

22 

" 

Quotes 

35 

23 

# 

Hash 

36 

24 

$ 

Dollar 

37 

25 

% 

Percent 

38 

26 

& 

Ampersand 

39 

27 

' 

Apostrophe 

40 

28 

( 

Open bracket 

41 

29 

) 

Close bracket 

42 

2A 

* 

Asterisk 

43 

2B 

+ 

Plus 

44 

2C 

, 

Comma 

45 

2D 

- 

Dash 

46 

2E 

. 

Full stop 

47 

2F 

/ 

Slash 

48 

30 

0 

Zero 

49 

31 

1 

One 

50 

32 

2 

Two 

51 

33 

3 

Three 

52 

34 

4 

Four 

53 

35 

5 

Five 

54 

36 

6 

Six 

55 

37 

7 

Seven 

56 

38 

8 

Eight 

57 

39 

9 

Nine 

58 

3A 

: 

Colon 

59 

3B 

; 

Semi-colon 

60 

3C 

< 

Less than 

61 

3D 

= 

Equals 

62 

3E 

> 

Greater than 

63 

3F 

? 

Question mark 

64 

40 

@ 

At

65 

41 

A 

Uppercase A 

66 

42 

B 

Uppercase B 

67 

43 

C 

Uppercase C 

68 

44 

D 

Uppercase D 

69 

45 

E 

Uppercase E 

70 

46 

F 

Uppercase F 

71 

47 

G 

Uppercase G 

72 

48 

H 

Uppercase H 

73 

49 

I 

Uppercase I 

74 

4A 

J 

Uppercase J 

75 

4B 

K 

Uppercase K 

76 

4C 

L 

Uppercase L 

77

4D 

M 

Uppercase M 

78 

4E 

N 

Uppercase N 

79 

4F 

O 

Uppercase O 

80 

50 

P 

Uppercase P 

81 

51 

Q 

Uppercase Q 

82 

52 

R 

Uppercase R 

83 

53 

S 

Uppercase S 

84 

54 

T 

Uppercase T 

85 

55 

U 

Uppercase U 

86 

56 

V 

Uppercase V 

87 

57 

W 

Uppercase W 

88 

58 

X 

Uppercase X 

89 

59

Y 

Uppercase Y 

90 

5A 

Z 

Uppercase Z 

91 

5B 

[ 

Open square bracket 

92 

5C 

\ 

Backslash 

93 

5D 

] 

Close square bracket 

94 

5E 

^ 

Caret / hat 

95 

5F 

_ 

Underscore 

96 

60 

` 

Grave accent 

97 

61 

a 

Lowercase a 

98 

62 

b 

Lowercase b 

99 

63 

c 

Lowercase c 

100 

64 

d 

Lowercase d

101 

65 

e 

Lowercase e 

102 

66 

f 

Lowercase f 

103 

67 

g 

Lowercase g 

104 

68 

h 

Lowercase h 

105 

69 

i 

Lowercase i 

106 

6A 

j 

Lowercase j 

107 

6B 

k 

Lowercase k 

108 

6C 

l 

Lowercase l 

109 

6D 

m 

Lowercase m 

110 

6E 

n 

Lowercase n 

111 

6F 

o 

Lowercase o 

112 

70 

p 

Lowercase p 

113 

71 

q 

Lowercase q 

114 

72 

r 

Lowercase r 

115 

73 

s 

Lowercase s 

116 

74 

t 

Lowercase t 

117 

75 

u 

Lowercase u 

118 

76 

v 

Lowercase v 

119 

77 

w 

Lowercase w 

120 

78 

x 

Lowercase x 

121 

79 

y 

Lowercase y 

122 

7A 

z 

Lowercase z 

123 

7B 

{ 

Open brace 

124 

7C 

| 

Pipe 

125 

7D 

} 

Close brace 

126 

7E 

~ 

Tilde 

127 

7F 

DEL 

Delete