C++



Lesson 09: WPF Forms, , File Handling, Exception Handling

Windows Presentation Foundation (WPF)

C#Ch9WPF.avi

up to drawing ellipse.

o File, New Project.

[pic]

You may wish to immediately run the program:

Our main window form appears:

Close the window or click

to stop.

If your design window it is not showing…..

[pic]

o Note that in our design view the Window form was produced automatically.

xmlns="

Take care that you are not dragging the grid. The grid and the Main Window are close together.

Main Window Grid

Hint: If you click on their names respectively in the xaml then they will be selected in the design window.

We can also resize the Grid:

Take a look at the first line of the XAML.

Class specifies the name of the class which is automatically produced representing our window ie MainWindow. This class can be found in this file MainWindow.xaml.cs. Double-click on it to open it. See bottom of this page for the code.

namespace MyWPF

{

public partial class MainWindow : Window

{

public MainWindow()

{

InitializeComponent();

}

}

}

Controls

Make sure that your Toolbox is visible (View, Toolbox from the menu.)

Choose Common WPF Controls.

o Choose the MainWindow.xaml tab and drag a Button and a TextBox on the form.

With the text box selected,

from the menu choose View,

Properties. (Unfortunately

we don’t appear to be able

to right-click on the control

and choose properties but

you can just press F4.)

.

Add an Event Handler for the button as follows:

o Double-click on the button and type this into the button1_Click event:

.

private void button1_Click(object sender, RoutedEventArgs e)

{

textBox1.Text = "Hello";

}

o Build and Run.

We can also create a new event my going to the XAML

and typing in the Button XAML Click=

whereupon we are prompted for a etc.

Once again take note where our code was automatically produced – in the MainWindow.xml file – in our MainWindow class.

namespace myWPF

{

public partial class MainWindow : Window

{

public MainWindow()

{

InitializeComponent();

}

private void button1_Click(object sender, RoutedEventArgs e)

{

textBox1.Text = "Hello";

}

}

}

Reflect once again: We are drawing controls onto a form. The XAML is produced automatically and the corresponding code is produce automatically in the corresponding Main Window .cs file!

Delete our button and text box controls. The XAML will be conveniently automatically deleted as well. (We could just as well have deleted the XAML instead!) but note that we must delete the event code manually!

private void button1_Click(object sender, RoutedEventArgs e)

{

textBox1.Text = "Hello";

}

Containers:

Our XAML produced so far has an opening and closing Grid elements by default:

< Grid>

The grid is a type of container which can hold controls.

There are other containers that our main window can have:

(Actually we can place one control (only) directly onto our main window.)

We can also have a StackPanel, Canvas etc.

They all have different behaviours when the Window is resized etc.

XAML page 1154 Troelsen.

ie in the form:

Element Attribute = value

The above could alternatively be written as

In both of these cases note that the value is written in quotes ie "200".

Equivalently to the above we could write:

200

In all cases the height of our grid will be 200.

Try them

The Grid properties: A grid consists of cells. A 1 x 1 grid is created by default.

o With the grid selected view the Properties. (Press F4)

We get 3 rows:

and corresponding XML:

To make a row fixed width:

and corresponding xaml:

As well as drawing them using the ToolBox as we have just done we can simply cut and paste code for them! For example we may cut and paste from this site:

Visit

WPF Controls using C#

Accordion in WPF Toolkit

AutoCompleteTextBox in WPF

AutoComplete Folder TextBox in WPF

Area Chart in WPF

Bar Chart in WPF

Button Control in WPF

Border in WPF

Canvas in WPF

CheckBox in WPF

Calendar in WPF

Closable Tab Control in WPF

Column Chart in WPF

ComboBox in WPF

DatePicker in WPF

DockPanel in WPF

Drawing Brush in WPF

Ellipse in WPF

Expander Control in WPF

Focus Manager in WPF

GridView in WPF

Grid in WPF

Hyperlink in WPF

Icon in WPF

ImageBrush in WPF

Image Viewer in WPF

Label in WPF

Line Chart in WPF

Line in WPF eg Choose Line in WPF

ListBox in WPF

Place the Line code with this (Between the tags.) as shown:

Using Code to Add Controls

We can achieve exactly the same thing with code! First delete the above XAML that you just added. Copy this code from the previous web page (or copy it from here.) and paste it as shown below in MainWindow.xaml.cs.

public partial class MainWindow : Window

{

public MainWindow()

{

InitializeComponent();

CreateALine();

}

public void CreateALine()

{

// Create a Line

Line redLine = new Line();

redLine.X1 = 50;

redLine.Y1 = 50;

redLine.X2 = 200;

redLine.Y2 = 200;

// Create a red Brush

SolidColorBrush redBrush = new SolidColorBrush();

redBrush.Color = Colors.Red;

// Set Line's width and color

redLine.StrokeThickness = 4;

redLine.Stroke = redBrush;

// Add line to the Grid.

LayoutRoot.Children.Add(redLine);

}

Run the code. You should get a red line as previously.

}

1. Exercise. Follow the article ScrollBar in WPF

o Write some event code which will show the value of the scroll bar in a label as the scroll bar button is moved.

[pic]

Hint: First ascertain the Name of the scroll bar and then use its Value property as an indication of the scroll button's position horizontally…

…and create a Scroll event stub:

[pic]

• Change the Content property of the label ie change its "caption". (See over)

More XAML:

The Property-Value Syntax is the alternative when we have more complex ("nested") properties.

eg

Attached Property

When the property of an element is in the child element:

The Content property

Content replaces the “Caption“ property of the old Windows Forms.

But Content is more than just a caption….

… eg it could be an image or even a StackPanel of a command button as below:

Markup Extensions

Markup extensions are dynamic placeholders for attribute values in XAML. They resolve the value of a property at runtime. Markup extensions are surrounded by curly braces (Example: Background="{StaticResource NormalBackgroundBrush}"). WPF has some built-in markup extensions, but you can write your own, by deriving from MarkupExtension. These are the built-in markup extensions:

Binding

To bind the values of two properties together.

• StaticResource

One time lookup of a resource entry

An example when using Styles

Help

Binding: Our form below has a text box and a label.

The following example shows a label whose Content is bound to the Text of the textbox. When you type text into the text box, the text property changes and the binding markup extension automatically updates the content of the label. ie no code required.

Comments:

We can block out whole elements - not just one property. We need:

How does XAML Work?

The XAML is parsed to form corresponding classes and properties etc.

binary files

Sometimes we need to save our data onto disk. For example we might save some lines of text or perhaps a set of numbers or even a picture (bitmap).

output

write

input

read

Memory Hard disk

Text Files Writing:

using System;

using System.IO;

public class Writing

{

public static void Main()

{

StreamWriter myFile = File.CreateText("C:\\text.txt"); myFile.WriteLine("about time");

myFile.Close();

}

}

To View Our File

If you have full version Visual Studio: To view our hex executable file use:

File, Open, File… then

Beware: When we open a file for output, it will write over any data that was there before.

o Confirm this – save the same file but with different data.

Text Files Reading:

using System;

using System.IO;

class Test

{

public static void Main()

{

string path = @"c:\Text.txt";

StreamReader sr = new StreamReader(path);

{

while (sr.Peek() >= 0)

{

Console.WriteLine(sr.ReadLine());

}

}

Console.ReadLine();

}

}

Write and read

Binary Files

We saw for text files that letters eg a and b are written as their ascii equivalent – and so are the numbers eg 1 is written as 49 (or hex 31). But for a binary file 1 is written as 1.

Writing

o Run this:

using System;

using System.IO;

class MyStream

{

public static void Main()

{

FileStream myFile = new FileStream("C:\\binFile", FileMode.CreateNew);

BinaryWriter bwFile = new BinaryWriter(myFile);

// Write data

for (int i = 0; i < 10; i++)

{

bwFile.Write(i);

}

bwFile.Close();

myFile.Close();

}

}

To avoid an error if the file exists we could use:

string path = @"c:\binFile";

if (File.Exists(path))

{

File.Delete(path);

}

Reading Binary File

To read back our binary file:

using System;

using System.IO;

class MyStream

{

public static void Main()

{

string path = @"c:\binFile";

FileStream myFile = new FileStream(path, FileMode.Open);

BinaryReader br = new BinaryReader(myFile);

// Read data

for (int i = 0; i < (int)br.BaseStream.Length/sizeof(int); i++)

{

int b = br.ReadInt32();

Console.WriteLine(b);

}

Console.ReadLine();

br.Close();

}

}

Running Programs from the Command Line page 622

Make a simple program to print hello to the screen as below. (Make exp.sln). For convenience locate the solution in a convenient folder eg c:\temp.

using System;

namespace exp

{

class Program

{

static void Main(string[] args)

{

Console.WriteLine("hello");

Console.ReadLine();

}

}

}

(Since we will run it from the command line there is no need to run it now but you may to check that it works so far :)

o Use Windows Explorer if necessary locate your executable exp.exe. Our exp.exe is located in the exp folder. This folder is usually located in the Debug folder.

o Open the Command Prompt window (You may need to do type cmd in the Windows run box to find it) and navigate to the file as follows:.

We now wish to pass some arguments to our executable so that we can say hello to whoever we choose. Modify the code as shown and rebuild:

using System;

namespace exp

{

class Program

{

static void Main(string[] args)

{

Console.WriteLine("hello");

Console.ReadLine();

}

}}

To Set the Command Line Arguments from the IDE

Now if we run from Visual Studio (not from the command line) we get

XML Files

Serialization: Page 365 – 375 C# 2008 book. Page 309 PH is an excellent reference.



Serializing Objects

This program will write some data to an XML file.

o First Locate our file test.xml

o Double-click on the file when you locate it. It should open in Internet Explorer or whatever is the default program for opening XML files.

The xml file is of course stored as sequential bytes ie serialized.

If we use our hex editor to view our test.xml stored as ascii:

[pic]

Deserializing Objects

Exercise: Combining an XML Reader and WPF:

MyXamlPad project Troelsen page1168

[pic]

To Download an XML Document from the Internet

using System;

using System.IO;

using System.Xml.Linq;

// This is the class that will be serialized.

public class Test

{

public static void Main()

{

XDocument rss = XDocument rss = XDocument.Load(@"");

Console.WriteLine(rss.ToString());

Console.ReadLine() ;

}

}

.

.

.

Exception Handling PH page 155 Chapter 9 C#21 days

An Exception is a run-time error. ie an error which occurs when the program is running. It is not necessarily detected at compile-time.

o Try this – it has no errors.

using System;

class TryIt2

{

public static void Main()

{

string s = "ed";

Console.WriteLine(s.ToUpper());

Console.ReadLine();

}

}

o Build it. It builds just fine!

o Run it.

It’s only when we run it that we see the problem: ToUpper() will not operate on a null string.

This is not what the user of our program would want to see. We must trap potential errors.

try catch finally

This program causes a run-time error. We “trap” the error as follows: (Note the order below 1,2,3,4.)

using System;

class TryIt

{

public static void Main()

{

string s = null;

try

{

Console.WriteLine(s.ToUpper());

}

catch

{

Console.WriteLine("null string");

}

finally

{

Console.WriteLine("finally");

}

Console.ReadLine();

}

}

o 1. Change string s = null; to string s = "ed";

We note that the finally is always executed – error or not.

ie the purpose of a finally block is to ensure that a set of statements will always be executed - exception or not. Try it in both cases.

We can find more information about the particular error using an Exception object,

o Change this catch:

string s = null;

try

{

Console.WriteLine(s.ToUpper());

}

catch (Exception e)

{

Console.WriteLine(e);

}

The above message can be resolved into two parts:

Console.WriteLine(e.StackTrace); which indicates where the error occurred

and Console.WriteLine(e.Message); which indicates the actual error.

Tip: To view a list of exceptions

o Type: catch(N (sic)

we will get the Itellisense drop down:

Exercise:

This code causes an error when we try to format a null string: Try it.

1. Provide a catch which will handle this particular error.

Hint: Look at the exception type reported when it is first run with no try-catch.

using System;

public class Program

{

public static void Main()

{

string s = null;

try

{

string st = String.Format(s);

}

catch

{

Console.WriteLine("Error:");

}

Console.ReadLine();

}

}

Other Error Types:

Out of Bounds Error

using System;

class Program

{

public static void Main()

{

int[] arr = new int[3];

try

{

Console.WriteLine(arr[3]);

}

catch (Exception e)

{

Console.WriteLine(e.Message);

}

Console.ReadLine();

}

}

Divide By Zero Error

try

{

Console.WriteLine(3/arr[2]);

}

catch (DivideByZeroException e)

{

Console.WriteLine(e.Message);

}

Finally

For a more practical example of using finally see page 306 C# 21 Days. ie ALWAYS close the file - error or not. Do this after File Handling).

This shows the use of Close in the finally block ie the file must be closed whatever happens.

Multiple Catch with a Single Try

o Place both of these catch statements in your code.

using System;

class TryIt

{

public static void Main()

{

int[] arr = new int[3];

try

{

Console.WriteLine(3/arr[2]);

}

catch (DivideByZeroException e)

{

Console.WriteLine(e.Message);

}

catch (IndexOutOfRangeException e)

{

Console.WriteLine(e.Message);

}

catch (Exception e)

{

Console.WriteLine(e.Message);

}

Console.ReadLine();

}

}

If we have multiple errors Only ONE will respond:

o Try Console.WriteLine(3/arr[3]);

For a list of common Exceptions see page 311 C# in 21 Days.

throw

Throw your own error! This can be useful for debugging.

using System;

class Program

{

public static void Main()

{

try

{

throw (new DivideByZeroException());

}

catch (DivideByZeroException e)

{

Console.WriteLine(e.Message);

}

Console.ReadLine();

}

}



enables us to make a web page fit for uploading. It consists mainly of HTML (see later)

Before we upload a web page to our agent server we can test it on our computer.

We upload it to a “practice server” on our computer called localhost.

Web Pages Troelsen page 1379

For lots of tutorials see:

Follow this:



(Uses New, Web Site as below– it’s not Web Application - only a form)

[pic]

For Community 2017:

Project, Add New Item.

FirstWebPage.aspx should open. If not open it:

Build and Run: The browser opens.

Web Controls

Here is the XML code:

My Web

• Double-click on the button in design view,

using System;

using System.Web;

using System.Web.UI.WebControls;

namespace WebApplication1

{

public partial class FirstWebPage : System.Web.UI.Page

{

protected void Page_Load(object sender, EventArgs e)

{

}

protected void Button1_Click(object sender, EventArgs e)

{

Label1.Text = TextBox1.Text;

}

}

}

Build and Run.

If you wish to publish your web page to the net you must upload it to the agent server rather than our localhost. The agent will provide details of the server addresses, passwords etc.

Next Steps at the bottom of:

Introduction to AngularJS HelloWorld with MVC5

v good to get started



-----------------------

o WPF App(.NET Framework).

o Choose WPF Application. Call it MyWPF and click OK.

o Click Run.

o …double-click on MainWindow.xaml.

XAML (Extended Application Markup Language) is just a variant of XML. Like XML it is simply a text file. (Great for emailing your form to another developer!)

Like XML (and HTML) it consists of opening and closing tags

eg ................
................

In order to avoid copyright disputes, this page is only a partial summary.

Google Online Preview   Download