Tuesday, July 28, 2009

HTML (Hypertext Markup Language)

Html is the language of web. Almost all the sites in the web is created using HTML.  It is a tag based language.

HTML can be created with plain Notepad or a there are a slew of editors like Visual Studio Code, Atom, Sublime, etc. I am using Notepad to start with.

 An HTML document contained two main section viz. Head section and Body section. Body section is where the contents of the page will appear. The Head section contains information like Title of the Page, Scripts, etc. 

<html>
 <body>
  Shalvin P D
 </body>
</html>

There are both opening and closing tags. Closing tag is denoted by /. Eg. </html>, </body>, etc. Notice that I have indented the tags so that it will be more readable. The relationship between tags can be better understood with indentation. Here HTML is the parent tag. 

I saved the document with .htm extension. Double clicking on the file will open the html document inside the default browser. 

 The Browser will interpret the HTML tags and produce the web site.

   

 

 

 

 

 

 

Title Title tag is used to produce a title for the document. The title appears in the title bar of Browser.  

<html>

 <head>
  <title>.Net and Angular Consultant and Trainer</title>
 <head>

 <body>
  Shalvin P D
 </body>
</html>



Br

 

Br tag is used for producing a break between contents Result

 

 

 

 

 

 

 

 

 

  

 

 

 

 

 

 

 

 

 

 

 

 

 H1 and H2 BgColor Attribute Unordered List Ordered List

ColorDialog and FontDialog in .Net Windows Forms

ColorDialog displays a list of colors and returns a property containing the selected color.
FontDialog enables the user to select a font and set its properties such as size, style, etc.























All the dialog boxes in .Net (ColorDialog, FontDialog, FolderBrowserDialog, FontDialog, PageSetupDialog and PrintDialog) inherit from System.Windows.Forms.CommonDialog class.

The ShowDialog method of CommonDialog class is used for running a dialog. We are also checking whether the Ok button is dialog is selected. If so we are changing the Back ground color of the form in the case of first button and the font the whole form in the case of second button.

private void btnColor_Click(object sender, EventArgs e)
{
if (colorDialog1.ShowDialog() == DialogResult.OK)
this.BackColor = colorDialog1.Color;
}

private void btnFont_Click(object sender, EventArgs e)
{
if (fontDialog1.ShowDialog() == DialogResult.OK)
this.Font = fontDialog1.Font;
}

Windows Forms Input Validation

ErrorProvider Control Validating Event

MaxLength property of TextBox can be used to restrict the input lenght of the textbox to specified number.
Validating Event is used to check for the validity of data in the event of loosing focus from the control.

In the following example the user can't navigate away from the control unless he enters some value in the text box.

Make sure you give a visual indication to the error stating the error. In this case I am using an ErrorProvider Control for this purpose.

private void txtName_Validating(object sender, CancelEventArgs e)
{
if (txtName.Text == "")
{
e.Cancel = true;
errorProvider1.SetError(txtName, "Name cannot be blank");
}
else
errorProvider1.SetError(txtName, "");
}














Checking for Float values using float.TryParse

private void textBox1_Validating(object sender, CancelEventArgs e)
{
float num1;
bool res = float.TryParse(textBox1.Text, out num1);
if (res == false)
{
errorProvider1.SetError(textBox1, "only float is accepted");
}
else
{
errorProvider1.SetError(textBox1, "");
}
}



KeyDown event to Check for special keys
private void textBox1_KeyDown(object sender, KeyEventArgs e)
{
if (e.Alt == true)
MessageBox.Show("Alt key pressed");
else if (e.Shift == true)
MessageBox.Show("Shift key pressed");
else if(e.Control == true)
MessageBox.Show("Contol key pressed");
else if (e.KeyCode == Keys.F1)
MessageBox.Show("F1 pressed");
}

WPF TextBox KeyDown Event
private void textBox1_KeyDown(object sender, KeyEventArgs e)
{
if (e.Key == Key.LeftShift)
MessageBox.Show("Left shift key");
else if (e.Key == Key.RightShift)
MessageBox.Show("Right shift key");
else if (e.Key == Key.RightCtrl)
MessageBox.Show("Right Ctrl key");
else if (e.Key == Key.F1)
MessageBox.Show("F1 Key pressed");
}

KeyPress Event to Discern Character Keys

private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
MessageBox.Show(e.KeyChar.ToString());
}

KeyPress Event to Discard Non numeric input

private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
if (! char.IsNumber(e.KeyChar))
e.Handled = true;
}

Discarding Lower Case Character
private void txtGrade_KeyPress(object sender, KeyPressEventArgs e)
{
if (char.IsLower(e.KeyChar))
e.Handled = true;
}

Windows Forms ListView



ListView is a very important control in Windows Forms. ListView can be used to display complex data list employee information, file information and the like.
You can see a list view in action in the Windows Explorer's right hand side.
Listview comes with various Views like SmallIcon, LargeIcon, Tile, List and Detail.

In this blog I am going to concentrate on DetailsView.

private void Form1_Load(object sender, EventArgs e)
{
listView1.View = View.Details;









//Adding Columns
listView1.Columns.Add("Blogs", 170);
listView1.Columns.Add("Blogger" , 100);












//Adding a ListView Item
ListViewItem item1 = new ListViewItem("shalvin.com", 0);
item1.SubItems.Add("Shalvin P D");
listView1.Items.Add(item1);
ListViewItem item2 = new ListViewItem("shalvinpd.blogspot.com", 0);
item2.SubItems.Add("Shalvin P D");
listView1.Items.Add(item2);
}








First I am adding Header to ListBox using Columns.Add method passing in the HeaderName and width.
Then I am adding items to ListView using ListViewItem Class which represents an item in ListView and then adding the SubItem to ListView using Items.Add.






























It is possible to change the look of in item in ListView using the ListViewItem class :

Font f = new Font(FontFamily.GenericSerif, 10, FontStyle.Bold ^ FontStyle.Italic);
item1.BackColor = Color.LightBlue;
item1.Font = f;
listView1.Items.Add(item1);

























Working with ListView Visually



Oracle Connectivity from C# Windows Forms

Inserting Values from Front End

System.Data.OleDb namespace contains classes required for interacting with any RDBMS including Oracle.

OleDbConnection class is used for establishing a live session between front end and back end. In this example we are connecting to Oracle with scott as username, tiger as password and hostname is Shalvin.

using System.Data.OleDb;



OleDbConnection cnn;
OleDbCommand cmd;
private void Form1_Load(object sender, EventArgs e)
{
cnn = new OleDbConnection("provider=msdaora.1;user id=scott;password=tiger;Data Source=Cargomar");
cnn.Open();
}
private void btnInsert_Click(object sender, EventArgs e)
{
cmd = new OleDbCommand("insert into Categories values (5, 'Mouse', 'Computer Mouse')", cnn);
cmd.ExecuteNonQuery();
MessageBox.Show("Record Saved");
}




Filling TextBox based on Selection from ComboBox

A common programming task is obtaining the details of a record based on a selection. Here Initially I am filling a combo box with Category Names. Based on a selection from Combo Box the the details of the Category will be displayed on the text boxes.










using System.Data.OleDb;

OleDbConnection cnn;
OleDbDataAdapter da;
DataSet ds = new DataSet();

bool b = false;

OleDbCommand cmd;
OleDbDataReader dr;

private void Form1_Load(object sender, EventArgs e)
{
cnn = new OleDbConnection("Provider=msdaora;Data Source=Cargomar;user id=scott;password=tiger");

cnn.Open();
da = new OleDbDataAdapter("select * from Categories", cnn);
da.Fill(ds, "Cat");
cboCategoryName.DataSource = ds.Tables["Cat"];
cboCategoryName.DisplayMember = "CategoryName";
cboCategoryName.ValueMember = "CategoryId";
b = true;
}

private void cboCategoryName_SelectedIndexChanged(object sender, EventArgs e)
{
if (b)
{
cmd = new OleDbCommand("select * from Categories where categoryId = " + cboCategoryName.SelectedValue, cnn);
dr = cmd.ExecuteReader();
while (dr.Read())
{
txtCategoryId.Text = dr["CategoryId"].ToString();
txtDescription.Text = dr["Description"].ToString();
}
}

Deleting Record
private void btnDelete_Click(object sender, EventArgs e)
{
cmd = new OleDbCommand("delete from Categories where CategoryId = " + cboCategoryName.SelectedValue, cnn);
cmd.ExecuteReader();
MessageBox.Show("Record Deleted");
}

Editing Record

private void btnEdit_Click(object sender, EventArgs e)
{
txtCategoryId.Enabled = false;
cmd = new OleDbCommand("Update Categories set Description = '" + txtDescription.Text + "' where CategoryId = " + cboCategoryName.SelectedValue, cnn);
cmd.ExecuteNonQuery();
MessageBox.Show("Record Edited successfully");
}

VB.Net

Imports System.Data.SqlClient

Dim cnn As SqlConnection
Dim da As SqlDataAdapter
Dim ds As New DataSet

Dim b As Boolean = False
Dim cmd As SqlCommand
Dim dr As SqlDataReader

Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
cnn = New SqlConnection("Integrated Security=sspi;Initial Catalog=Northwind")
cnn.Open()
da = New SqlDataAdapter("select * from Categories", cnn)
da.Fill(ds, "Cat")
cboCategories.DataSource = ds.Tables("Cat")
cboCategories.DisplayMember = "CategoryName"


cboCategories.ValueMember = "CategoryId"

b = True
End Sub

Private Sub cboCategories_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cboCategories.SelectedIndexChanged
If b = True Then

Dim strSql As String
strSql = "select * from Categories where CategoryId = " + cboCategories.SelectedValue.ToString()
cmd = New SqlCommand(strSql, cnn)
dr = cmd.ExecuteReader
While (dr.Read())
txtCategoryId.Text = dr("CategoryId")
txtDescription.Text = dr("description")
End While
dr.Close()
End If

End Sub

Enumerations in C#

Enumerations are the mechanism to group related constants. System.Enum class provides the base class for enumerations, it is a value type.
The following example demonstrates using WindowState enum in WPF. In the case of WindowState enumerator there are three constants viz., Maximized, Minimized and Normal.









Creating Enumerations
In the following example I am creating an enum called Tech with three constants Wpf, Silverlight and Xbap and later on I am using using it. Extensive use of enums makes your code more consistent.

enum TEch
{
Wpf, Silverligh, Xbap
}
private void Window_Loaded(object sender, RoutedEventArgs e)
{
MessageBox.Show(TEch.Silverligh.ToString());
}

The default underlying type of the enumeration elements is int. By default, the first enumerator has the value 0, and the value of each successive enumerator is increased by 1.

In the following example I am extracting the value of the element Wpf.


private void Window_Loaded(object sender, RoutedEventArgs e)
{
int i = (int)TEch.Wpf;
MessageBox.Show(i.ToString());
}


When you run the application you will get 0. If you substitute Wpf with Silverlight or Xbap you will get 1 or 2 respectively.


It is possible to alter the default underlying value by assigning another values.

enum TEch
{
Wpf = 2, Silverligh = 4, Xbap = 6
}









Enum.GetValues() method
Enum.GetValues() method to extract the constants in an Enumeration.
using System.Drawing;
private void Window_Loaded(object sender, RoutedEventArgs e)
{
KnownColor [] color = (KnownColor[])Enum.GetValues(typeof(KnownColor));
foreach (KnownColor colorName in color)
{
listBox1.Items.Add(colorName);
}
}



For this example to work in WPF you should set reference to System.Drawing

WPF Colors

The Brushes class provides 141 colors.

private void btnColor_Click(object sender, RoutedEventArgs e)
{
this.Background = Brushes.Red;
}


You can also have a wide ranging colors using the combination of Red, Green and Blue.

private void btnGreen_Click(object sender, RoutedEventArgs e)
{
this.Background = new SolidColorBrush(Color.FromRgb(0, 255, 0));
}

In the previous I am creating Green color by assigning 255, the maximum value to Green component, ie. the second parameter


private void btnWhite_Click(object sender, RoutedEventArgs e)
{
this.Background = new SolidColorBrush(Color.FromRgb(255, 255, 255));
}

private void btnYellow_Click(object sender, RoutedEventArgs e)
{
this.Background = new SolidColorBrush(Color.FromRgb(255, 255, 0));
}

Grey Scale
private void btnWhite_Click(object sender, RoutedEventArgs e)
{
this.Background = new SolidColorBrush(Color.FromArgb(255, 255, 255, 255));
}

private void btnBlack_Click(object sender, RoutedEventArgs e)
{
this.Background = new SolidColorBrush(Color.FromArgb(255, 0, 0, 0));
}

private void btnDarkGrey_Click(object sender, RoutedEventArgs e)
{
this.Background = new SolidColorBrush(Color.FromArgb(255, 50, 50, 50));
}

private void btnMGrey_Click(object sender, RoutedEventArgs e)
{
this.Background = new SolidColorBrush(Color.FromArgb(255, 150,150, 150));
}

private void slider1_ValueChanged(object sender,

RoutedPropertyChangedEventArgs e)
{
this.Background = new SolidColorBrush(Color.FromArgb(255,

(byte)slider1.Value, (byte)slider1.Value, (byte)slider1.Value));
}


LinearGradientBrush
LinearGradientBrush displays a gradualy changing mix of two or more color schemes.
The surface where you are planning to draw the linear gradient is considered to he unit 1 wide and 1 unit high.


private void Window_Loaded(object sender, RoutedEventArgs e)
{
this.Background = new LinearGradientBrush(Colors.Red, Colors.Blue, new Point(0, 0), new Point(1, 1));
}


LinearGradientBrush the Coded way


using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;
namespace WPFBrush
{
class Class1 : Window
{
[STAThread]
public static void Main()
{
Application app = new Application();
app.Run(new Class1 { Title = "Shalvin - Colors" });
}
public Class1()
{
Grid LayoutRoot = new Grid();
this.Content = LayoutRoot;
LayoutRoot.Background = new LinearGradientBrush(Colors.Red, Colors.Blue, 0);
}
}
}


RadialGradientBrush

Grid LayoutRoot = new Grid();
this.Content = LayoutRoot;
LayoutRoot.Background = new RadialGradientBrush (Colors.Red, Colors.Blue);


RadialGradientBrush and GradientStops


RadialGradientBrush brush = new RadialGradientBrush();
Background = brush;
brush.GradientStops.Add(new GradientStop(Colors.Red, 0));
brush.GradientStops.Add(new GradientStop(Colors.Green, .33));
brush.GradientStops.Add(new GradientStop(Colors.Blue, .66));

WPF (Windows Presentation Foundation)

This is a beginner level blog on WPF.


Nesting Controls
Styles
Exploring WPF the Code Way

Majority of examples presented in this blog will work with Silverlight also.
Windows Presentation Foundation (WPF) is the Microsoft's presentation technology for creating compelling user interface including graphics and media.
It is based on Vector Graphics
Create a new project in Visual Studio 2008 by selecting File, New Project.
Starting a WPF Application Project

















The WPF editor contains two view the visual representation of the form as well as the XAML implementation of the window.

A WPF Form is in fact a class that inherits from System.Windows.Window. The Window class which in turn inherits from ContentControl class.A ContentControl class can have only a single element as its Content Property.
Inside the Windows is a Grid Control that can hold multiple child controls.









As you set the propeties of an element both the windows designer as well as the xaml gets updated.







Here I am settting the Title for the form.






























You can also edit the xaml and the changes will be immediately apparent in the windows designer.





















Setting the window title at Runtime

private void Window_Loaded(object sender, RoutedEventArgs e)
{
this.Title = "shalvinpd.blogspot.com";
}




WPF do have a collection of common control which you would expect in a presentation technology.

















Button

Drag and drop a button on to the windows design surface.




























On clicking the button you will be taken to the event handler.


private void button1_Click(object sender, RoutedEventArgs e)
{
MessageBox.Show("Hello welcome to WPF", "Shalvin.com");
}

Run the application. Click on the button and you will receice a welcome message.


















MessageBox.Show Method's Overloads

MessageBox's Show method has 21 overloads, following are a few examples.

private void btnHello_Click(object sender, RoutedEventArgs e)
{
MessageBox.Show("Hello");
}

private void btnHelloCaption_Click(object sender, RoutedEventArgs e)
{
MessageBox.Show("Hello", "shalvin");
}

private void btnYesNo_Click(object sender, RoutedEventArgs e)
{
MessageBox.Show("Hello", "Shalvin", MessageBoxButton.YesNo);
}

private void btnExclamation_Click(object sender, RoutedEventArgs e)
{
MessageBox.Show("Hello", "Shalvin", MessageBoxButton.YesNo, MessageBoxImage.Exclamation);
}

MessageBoxResult
private void btnClose_Click(object sender, RoutedEventArgs e)
{
if (MessageBox.Show("Do you want to quit ?", "Shalvin", MessageBoxButton.YesNo) == MessageBoxResult.Yes)
Close();
}

String Memory Variable

private void btnMemoryVariable_Click(object sender, RoutedEventArgs e)
{
string strName = "Shalvin";
MessageBox.Show("Hello " + strName);
strName = "Shalvin P D";
MessageBox.Show("Hello " + strName);
}


String Concatenation
In this example instread of simply displaying a Hello message the user will be greated with the name entered in text box.













private void button1_Click(object sender, RoutedEventArgs e)

{
MessageBox.Show("Hello " + txtName.Text);
}




















Integer Memory Variable and Simple Calculator




















int i, j, res;
private void btnAdd_Click(object sender, RoutedEventArgs e)
{
i = Int32.Parse(txtInt1.Text);
j = Int32.Parse(txtInt2.Text);
res = i + j;
lblResult.Content = res.ToString();
}

Here I am defining three integer memory variables i, j and res. Int32.Parse() method is used to convert the textbox data to integer.

<Window x:Class="WpfApplication1.Calc"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="Calc" Height="300" Width="300" Loaded="Window_Loaded">
    <Grid>
        <Label Content="Integer 1" Height="28" HorizontalAlignment="Left" Margin="44,33,0,0" Name="label1" VerticalAlignment="Top" />
        <TextBox Height="23" HorizontalAlignment="Left" Margin="120,33,0,0" Name="txtInt1" VerticalAlignment="Top" Width="120" />
        <Label Content="Integer 2" Height="28" HorizontalAlignment="Left" Margin="53,88,0,0" Name="label2" VerticalAlignment="Top" />
        <TextBox Height="23" HorizontalAlignment="Left" Margin="120,80,0,0" Name="txtInt2" VerticalAlignment="Top" Width="120" />
        <Label Content="Result" Height="28" HorizontalAlignment="Left" Margin="63,132,0,0" Name="label3" VerticalAlignment="Top" />
        <Label Height="28" HorizontalAlignment="Left" Margin="120,132,0,0" Name="lblResult" VerticalAlignment="Top" Width="112" BorderBrush="Black" BorderThickness="1" />
        <Button Content="+" Height="23" HorizontalAlignment="Left" Margin="98,196,0,0" Name="btnAdd" VerticalAlignment="Top" Width="75" Click="btnAdd_Click" />
    </Grid>
</Window>

ListBox

ListBox is used for displaying a number of items at the same time. Place a ListBox on to the form and select the Items collection from the properties window. The Collection Editor dialog will appear. You can add additional items to the ListBox by clicking the Add button and specifying a Content.






Behing the scene it will create ListBoxItems tags inside the ListBox tag.







It is possible to add items to ListBox at runtime. Double click on the title of the form and you will be taken to the Loaded event of the Window.
private void Window_Loaded(object sender, RoutedEventArgs e)
{
lstInterests.Items.Add("Guitar");
}





ComboBox
ComboBox contains similar functionality that of ListBox. Above mentioned functionality also works with ComboBox

RadioButton and If else











private void btnGender_Click(object sender, RoutedEventArgs e)
{
if (rbMale.IsChecked == true)
MessageBox.Show("Male candidate");
else
MessageBox.Show("Female candidate");
}













DatePicker Control
private void btnDate_Click(object sender, RoutedEventArgs e)
{
DateTime dt = DateTime.Parse(datePicker1.SelectedDate.ToString());
MessageBox.Show(dt.ToString());
MessageBox.Show(dt.ToString("d"));
MessageBox.Show(dt.ToString("D"));
}

Nesting Controls

































As usual you can have event handlers of the controls. In this case I am extracting the value of Inner TextBox, concatenating it with a Hello and MessageBoxing it.

private void btnHello_Click(object sender, RoutedEventArgs e)
{
MessageBox.Show("Hello " + txtName.Text);
}























































Styles
Styles as WPF equivalent of CSS in Html.


















Working with Styles at Runtime




private void btnBold_Click(object sender, RoutedEventArgs e)
{
btnBold .Style = (Style)FindResource("BoldStyle");
}








Filling Wpf ComboBox with the Contents of a SqlDataReader
using System.Data.SqlClient;
SqlConnection cnn = new SqlConnection(@"Integrated Security=sspi;Initial Catalog=Shalvin;Data Source=.\sqlexpress");
SqlCommand cmd;
SqlDataReader dr;
private void Window_Loaded(object sender, RoutedEventArgs e)
{
cnn.Open();
cmd = new SqlCommand("select * from Categories", cnn);
dr = cmd.ExecuteReader();
while (dr.Read())
{
cboCategories.Items.Add(dr["CategoryName"]);
}
}























Exploring WPF the Code Way
Having seen the fundamentals of working with IDE. Let's turn out attention to the internals of WPF in coded way, means without XAML.

using System;
using System.Windows;
using System.Windows.Controls;
namespace WpfApplication1
{
class Class1 : Window
{
[STAThread]
public static void Main()
{
Application app = new Application();
app.Run(new Class1{Title = "shalvin"});
}
public Class1()
{
Grid LayoutRoot = new Grid();
this.Content = LayoutRoot;
Button btn = new Button();
btn.Width = 75;
btn.Height = 50;
btn.Content = "Hello";
LayoutRoot.Children.Add(btn);
}
}
}