VPL LabManual

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 109

Laboratory Workbook

Visual Programming Language

Name _____________________
Roll No ____________________
Semester ____________________
Marks ____________________

Signature ____________________

Department of Computer Science

2018
0
Visual Programming Language Lab

Content

Lab
Lab Objective
No.

1 Introduction to Windows Forms


2 Using Controls on Windows Forms
3 Using Timer, Picture Box, and ImageList components
4 Form Validations using Exception Handling and Regex
6 ADO .NET – Using Connected Architecture
7 ADO .NET – Using Disconnected Architecture
8 Introduction to Windows presentation Forms
9 WPF – Custom XAML Editor
10 Using LINQ & Lambda Expression
11 Entity Framework – Model First Approach
Entity Framework – Database First Approach
12 Working with Crystal Reports
13 Parallel Programming using PLINQ, task parallel library
Building Universal Windows Platform Apps Using XAML (UWP)
14
Objective
15 Building cross-platform apps on the .NET platform with Xamarin

1
Department of Computer Science - Iqra University
Visual Programming Language Lab

Lab Details

Lab Marks
Lab Objective Signature
No. Obtained

Introduction to Windows Forms


1 Objective:To create a Login Form which takes username and password to
login the user using Windows Form.

Using Controls on Windows Form


Objective: To explore the different controls like CheckBox, RadioButton
2
with a GroupBox, NumericUpDown, DateTimePicker, ComboBox, and
ListBox on Windows Forms.

Using Timer, PictureBox, and ImageList components


3 Objective: To create a stopwatch application using Timer component. Also,
to explore the handling of images using PictureBox and ImageList.

Form Validations using Exception Handling and Regex


4 Objective: To get familiar with Exception handling and regex expression to
perform form validation with the use of Error provider.

ADO .NET – Using Connected Architecture


5 Objective: To understand the concept of connected Architecture of ADO
.Net Framework

ADO .NET – Using Disconnected Architecture


6 Objective: To understand the concept of Disconnected Architecture of ADO
.Net Framework

Introduction to Windows presentation Forms


8
Objective: To create a Paint Application using WPF.
WPF – Custom XAML Editor
9
Objective: To create a custom XAML Editor using WPF

2
Department of Computer Science - Iqra University
Visual Programming Language Lab

Using LINQ & Lambda Expression


10 Objective: To understand the concept of LINQ and Lambda Expression to
handle the database for windows application.

Entity Framework – Model First Approach


11 Objective: Designing an application using Entity Framework Model First
approach
Entity Framework – Database First Approach
Objective: Designing an application using Entity Framework Database First
approach
Working with Crystal Reports
12 Objective: To generate report for the windows application with crystal
Reports.
Parallel Programming using PLINQ, task parallel library
13 Objective: To understand the Parallel Programming using PLINQ, task
parallel library
Building Universal Windows Platform Apps Using XAML (UWP)
Objective: To understand how to create Universal Windows Platform Apps
14
(UWP)
Using XAML.
Building cross-platform apps on the .NET platform with Xamarin
Objective: To understand how to use Xamarin to share code across multiple
15
platforms.

3
Department of Computer Science - Iqra University
Visual Programming Language Lab

Introduction to Windows Forms Lab 1

Objective:To create a Login Form which takes username and password to login the user using
Windows Form.

Step 1: Open Visual Studio and select File option then click New Project. After clicking the
following window appears.

Step 2: Select Windows Form application and in Name bar type the name of the project and then
click Ok. The following window appears.

Step 3: This Form1 is our Form and by clicking into this form the actual code appears in next
window which is Form1.cs.

Step 4: On the right side of screen (In Visual Studio 2013) there is a Solution Explorer and
properties window.

The Property window

4
Department of Computer Science - Iqra University
Visual Programming Language Lab

Step 5: If property window not appear right click on the form and then click the option properties
so that properties window appears.

 The properties windows has many options by which we set many properties of our form
or the components in the form.
 For example by the property BackColor we set the background color of our form.
 The property Size we set the size of our form.
 By using property Text we set the name of our Form. By default the name of form is
Form1.
 By changing BackColor to green, set Size to 400,300 and changing the Text to Login
Form our form is look like this:

5
Department of Computer Science - Iqra University
Visual Programming Language Lab

Step 6: At the left of the screen (In Visual Studio 2013) there is a bar Toolbox. By clicking it the
tool box appears , In the tool box select option All Windows Form. After it the list of
components appear.

 We place these components into our form.


 Some of the common use components are:
o Button , Label , TextBox etc.

6
Department of Computer Science - Iqra University
Visual Programming Language Lab

Step 7: We are making a Login Form application, for this, we first select a component label and
place it into the Form. By right clicking to the label the box appear where we select Properties
and now the properties box of the component Label appears in the right side of the screen.

Step 8: We set Size of our first label the Text of our first label which is LoginForm , we set Font
size of our Label which is 15.25.

7
Department of Computer Science - Iqra University
Visual Programming Language Lab

 Then we place two more Labels and give them Text Name and Password respectively and
also set their properties like Font size etc.
 We set each component property by right clicking it and click properties so the properties
box of the component appears.
 Then we place Button component and set it’s properties like Text which is “Login”.
 And we place two TextBox components in front of our Labels.
Step 9: The second TextBox component which is in front of our Label which we give Text
“Password”. In property of TextBox there is a property “PasswordChar” . We set the value of
this property is ‘ * ’

 Because as we know in most Login forms the password is hidden and the characters * , +
etc appears in the screen instead of a real password.
 After doing all above steps our Form is like this.

Step 10: We have completed our ‘Designing Form ‘phase and now we are move towards the
code.

 By clicking on the component Button the code file appears and look like this:

8
Department of Computer Science - Iqra University
Visual Programming Language Lab

Step 11: In the method void button1_Click we write the Logic that if the Name and Password
both are “IQRA” then user Log In.

 So when user enter Name and Password “IQRA” and then click the button Login the Text
Box appears with the Message “Welcome to Iqra University”.

 The Code for above we write is as follows:


private void button1_Click(object sender, EventArgs e)
{
string a,b;
a = textBox1.Text;
b = textBox2.Text;

if(a=="IQRA" && b =="IQRA")


MessageBox.Show("Welcome to Iqra Univerity", "IQRA University");

else
MessageBox.Show("Sorry Invalid enrty", "Error");

 Note : If the user enter wrong password or Name the Message appears “Invalid enrty”. In
pictures when we run our application:

9
Department of Computer Science - Iqra University
Visual Programming Language Lab

Picture 1:

Picture 2 after clicking Login Button :

10
Department of Computer Science - Iqra University
Visual Programming Language Lab

Picture 3 if the user enter wrong name or password:

11
Department of Computer Science - Iqra University
Visual Programming Language Lab

Reference:
Visual C# 2012, How to program fifth Edition
14.2 windows form
14.5 Label , TextBoxes and Button

Practice Exercise:
Design a windows form having four labels, four textboxes and two buttons namely submit and
clear. The user will enter his information in the textboxes. On submit button click display the
entered information in a messagebox and on clear button click clear the textboxes.

12
Department of Computer Science - Iqra University
Visual Programming Language Lab

Using Controls on Windows Form Lab 2

Objective: To explore the different controls like CheckBox, RadioButton with a GroupBox,
NumericUpDown, DateTimePicker, ComboBox, and ListBox on Windows Forms.

Task: Create a Employee registration form using windows forms.

1. Go to File-> New -> Project-> Visual C#->Windows Form application-> Entry


Application Name-> OK.

2. Drag Label, textBox, CheckBox, RadioButton, GroupBox, NumericupDown,


DateTimePicker, ComboBox, and ListBox from toolbox.
 Set Name property of each control i.e. txtUsername, txtEmail, cmbCountry,
lstCities, chkPhysical, rbtnMale, btnSubmit and so on.
 Add items in ListBox by setting items property of ListBox.

13
Department of Computer Science - Iqra University
Visual Programming Language Lab

3. Add RadioButtons to the GroupBox.

14
Department of Computer Science - Iqra University
Visual Programming Language Lab

4. Now move towards the code.


 By clicking on the component Button the code file appears and look like this:

5. Add the following code to get the values from the windows components and display to
the user.

15
Department of Computer Science - Iqra University
Visual Programming Language Lab

6. Now Employee registration is completed. Next we will be working on form validation to


restrict user from bad inputs.

16
Department of Computer Science - Iqra University
Visual Programming Language Lab

Task: Create Interest Calculator using NumberUpDown Component.

17
Department of Computer Science - Iqra University
Visual Programming Language Lab

Code Behind:

using System; using System.Windows.Forms;


namespace NumericUpDownTest
{
publicpartialclassInterestCalculatorForm : Form
{
public InterestCalculatorForm()
{
InitializeComponent();
}
privatevoid calculateButton_Click(object sender, EventArgs e)
{

decimal principal;
double rate;
int year;
decimal amount;
string output;

principal = Convert.ToDecimal(principalTextBox.Text);
rate = Convert.ToDouble(interestTextBox.Text);
year = Convert.ToInt32(yearUpDown.Value);

output = "Year\tAmount on Deposit\r\n";

for (int yearCounter = 1; yearCounter <= year; yearCounter++)


{
amount = principal * ((decimal)
Math.Pow((1 + rate / 100), yearCounter));
output += (yearCounter + "\t" +
string.Format("{0:C}", amount) + "\r\n");
}
displayTextBox.Text = output;
}
}}

18
Department of Computer Science - Iqra University
Visual Programming Language Lab

Reference:
Visual C# 2012, How to program fifth Edition
14.7 Checkboxes and radio buttons
14.5 Label , TextBoxes and Button
14.7 CheckBoxes and RadioButton
15.4 DateTimePicker Control
15.6 ListBox Control
15.7 CheckedListBox Control

Practice Exercise:

Design a student Registration form take student id, student name, gender, email address,
nationality, semester, and department as an input.User appropriate controls in windows form to
take input from the user. On submit button click display the input details in another form.

19
Department of Computer Science - Iqra University
Visual Programming Language Lab

Using Timer, Picture Box, and Image List components Lab 3


Objective: To create a stopwatch application uisng Timer component. Also, to explore the
handling of images using PictureBox and ImageList.

Task: Create a stopwatch application using Timer component.

Design:

Steps:

1. Drag timer component from the Toolbox.


2. Set Interval property of timer to 1000 (milliseconds) for 1 second.
3. Add tick event to the timer component.

4. Add the following code the timer event, btnStart, btnStop and btnPause.

publicpartialclassForm1 : Form
{
public Form1()

20
Department of Computer Science - Iqra University
Visual Programming Language Lab

{
InitializeComponent();
}
int sec = 0;
int min = 0;
int hrs = 0;
privatevoid timer1_Tick(object sender, EventArgs e)
{
sec++;
lblsec.Text = sec.ToString();
if (sec == 59)
{
min++;
sec = 0;
lblmin.Text = min.ToString();

}
elseif (min == 59)
{
hrs++;
min = 0;
lblhrs.Text = hrs.ToString();

privatevoid btnStop_Click(object sender, EventArgs e)


{
timer1.Stop();
lblhrs.Text = "0";
lblmin.Text = "0";
lblsec.Text = "0";
sec = 0;
}

privatevoid btnPause_Click(object sender, EventArgs e)


{
timer1.Stop();
}

privatevoid btnStart_Click(object sender, EventArgs e)


{
timer1.Start();
}

21
Department of Computer Science - Iqra University
Visual Programming Language Lab

Task: Create a windows application to show the product detail on the selection of picture from
the given list.

Design:

Steps:

1. Drag PictureBox and ImageList to the Windows Form


2. First click to the properties->Resource->Add Resources->Add Existing File to add all
images to project.

3. Or Add images to ImageList.

22
Department of Computer Science - Iqra University
Visual Programming Language Lab

4. Add items to the comboBox by setting item property.

Code Behind:

publicpartialclassForm1 : Form
{

public Form1()
{
InitializeComponent();

privatevoid comboBox1_SelectedValueChanged(object sender, EventArgs e)


{
if (comboBox1.Text == "Bristol")
{
//pictureBox1.Image = Image.FromFile("D:\\Iqra university\\VPL lab\\images\\rolax.jpg");
pictureBox1.Image = Properties.Resources._1;
}
elseif (comboBox1.Text == "Thirteen")
{
pictureBox1.Image = imageWatchList.Images[1];
}
elseif (comboBox1.Text == "BlackTan")
{
pictureBox1.Image = imageWatchList.Images[2];
}
elseif (comboBox1.Text == "Gotham")
{

23
Department of Computer Science - Iqra University
Visual Programming Language Lab

pictureBox1.Image = imageWatchList.Images[3];
}

}
// using open file dialogbox
privatevoid btnPicture_Click(object sender, EventArgs e)
{
OpenFileDialog openFileDialog = new OpenFileDialog();
openFileDialog.InitialDirectory = "D:\\Iqra university\\VPL lab\\images";
openFileDialog.Filter = "Image File(*.jpg)|*.jpg|(*.png)|*.png|All Files(*.*)|*.*";
openFileDialog.ShowDialog();
if (openFileDialog.ShowDialog() == DialogResult.OK)
{
string path = openFileDialog.FileName;
pictureBox1.Image = Image.FromFile(path);
}
}

privatevoid btnColor_Click(object sender, EventArgs e)


{
ColorDialog clg = new ColorDialog();
clg.ShowDialog();
this.BackColor = clg.Color;
}

privatevoid btnFont_Click(object sender, EventArgs e)


{
FontDialog flg = new FontDialog();
flg.ShowDialog();

lblnmae.Font = flg.Font;
}
Reference:
Visual C# 2012, How to program fifth Edition
14.8 PictureBoxes
14.10 NumericUpDown Control
https://www.c-sharpcorner.com/article/deigning-a-digital-clock-using-wind/

Practice Exercise:

Design an application for a firm who wants to check their internee general knowledge skills.
The manager’s requirement is to display some pictures to the internee and ask questions related

24
Department of Computer Science - Iqra University
Visual Programming Language Lab

to it. Use textbox to take input from user and use a picture box and image list to display the
pictures.
The manager also wishes to check the typing speed of the internee therefore he requires to give
only 60 seconds to type the answer. Display the next question after 60 seconds.
Hint: use timer.

Form Validations using Exception Handling and Regex Lab 4

Objective: To get familiar with Exception handling and regex expression to perform form
validation with the use of Error provider.

Task: Add form validation to Employee registration form created in Lab 3 using regex, exception
handling, and error provider component.

Design:

1. Drag error provider to windows form

25
Department of Computer Science - Iqra University
Visual Programming Language Lab

2. Use Validating event of the control to verify the user input e.g.
txtEmail_Validating(object sender, CancelEventArgs e ).

3. Use errorProvider1.SetError(txtEmail, "Invalid Email Address") method to display error


message to the user.
4. Set regular expression for email to validate email address i.e.
System.Text.RegularExpressions.Regex rEMail = new
System.Text.RegularExpressions.Regex(@"\w+(-+.]\w+)*@\w+(-.]\w+)*\.\w+(-
.]\w+)*");
5. Repeat steps for all the controls in form.

Code Behind:

publicpartialclassForm1 : Form
{
public Form1()
{
InitializeComponent();
}

//store whether DOB validated or not


bool isDOBValidated = false;

privatevoid txtEmail_Validating(object sender, CancelEventArgs e)


{
System.Text.RegularExpressions.Regex rEMail = new
System.Text.RegularExpressions.Regex(@"\w+(-+.]\w+)*@\w+(-.]\w+)*\.\w+(-.]\w+)*");
if (txtEmail.Text.Length > 0)
{
if (!rEMail.IsMatch(txtEmail.Text))
{
// MessageBox.Show("Valid E-Mail expected", "Error", MessageBoxButtons.OK,
MessageBoxIcon.Error);
errorProvider1.SetError(txtEmail, "Invalid Email Address");
txtEmail.SelectAll();
txtEmail.Focus();
e.Cancel = true;
}
else
{
errorProvider1.Clear();

26
Department of Computer Science - Iqra University
Visual Programming Language Lab

}
}
else
{
errorProvider1.Clear();
}
}

/// country combobox selected event

privatevoid cmbCountry_SelectedIndexChanged(object sender, EventArgs e)


{
// MessageBox.Show(cmbCountry.SelectedItem.ToString());
if (cmbCountry.SelectedItem.ToString().ToLower() == "india")
{
grpAddress.Enabled = true;
}
else
{
grpAddress.Enabled = false;
}
}

/// Handles Validating event for Confirm Password

privatevoid txtCnfrmPwd_Validating(object sender, CancelEventArgs e)


{
if (txtCnfrmPwd.Text.Length > 0) //if cheking textlenth
{
if (txtPassword.Text != txtCnfrmPwd.Text)
{
errorProvider1.SetError(txtCnfrmPwd, "Passwords mis-match");
txtCnfrmPwd.SelectAll();
txtCnfrmPwd.Focus();
}
else
{
errorProvider1.Clear();
}
}
else//else of if cheking textlenth
{
errorProvider1.Clear();
}
}

27
Department of Computer Science - Iqra University
Visual Programming Language Lab

/// Handles keypress for txtName

privatevoid txtName_KeyPress(object sender, KeyPressEventArgs e)


{
if (!char.IsLetter(e.KeyChar) && Convert.ToInt32(e.KeyChar) != 8 &&
Convert.ToInt32(e.KeyChar) != 32)
{
errorProvider1.SetError(txtUserName, "Only letters allowed");
e.Handled = true;
txtUserName.Focus();
}
else
{
errorProvider1.Clear();
e.KeyChar = char.ToUpper(e.KeyChar);
}
}

privatevoid txtMobile_KeyPress(object sender, KeyPressEventArgs e)


{
if (!char.IsDigit(e.KeyChar) && Convert.ToInt32(e.KeyChar) != 8)
{
errorProvider1.SetError(txtMobile, "Only Numbers Allowed");
e.Handled = true;
txtMobile.Focus();
}
else
{
errorProvider1.Clear();
}
}

privatevoid dtpDOB_ValueChanged(object sender, EventArgs e)


{
if (System.DateTime.Now < dtpDOB.Value.AddYears(18))
{
errorProvider1.SetError(dtpDOB, "Age should be 18yrs");
isDOBValidated = false;
dtpDOB.Focus();
}
else
{
errorProvider1.Clear();
isDOBValidated = true;
}

28
Department of Computer Science - Iqra University
Visual Programming Language Lab

/// Validating MobileNo textbox

privatevoid txtMobile_Validating(object sender, CancelEventArgs e)


{
System.Text.RegularExpressions.Regex rMob = new
System.Text.RegularExpressions.Regex(@"^[789]\d{9}$");
if (txtMobile.Text.Length > 0)
{
if (!rMob.IsMatch(txtMobile.Text))
{
// MessageBox.Show("Valid E-Mail expected", "Error", MessageBoxButtons.OK,
MessageBoxIcon.Error);
errorProvider1.SetError(txtMobile, "Invalid Mobile No");
txtMobile.SelectAll();
txtMobile.Focus();
e.Cancel = true;
}
else
{
errorProvider1.Clear();

}
}
else
{
errorProvider1.Clear();
}
}

privatevoid btnSubmit_Click(object sender, EventArgs e)


{
try
{
if (lstCities.SelectedIndex == -1 || txtUserName.Text == "" || txtEmail.Text == ""
|| txtPassword.Text == "" || txtCnfrmPwd.Text == "" || txtMobile.Text == ""
|| txtStreet.Text == "" || (rbtnMale.Checked == false&& rbtnFemale.Checked ==
false) || !isDOBValidated)
{
lblMsg.ForeColor = Color.Red;
if (isDOBValidated == true)
{
lblMsg.Text = "All * marked fields are mandatory";
}
else
{

29
Department of Computer Science - Iqra University
Visual Programming Language Lab

lblMsg.Text = "All * marked fields are mandatory. Invalid DOB";

}
if (lstCities.SelectedIndex == -1)
{
lblMsg.Text = "Select City";
}

return;
}
else
{
//database insertion operation here
lblMsg.Text = "";
String data = "";

data += txtUserName.Text;
data += "\n";
data += txtEmail.Text; data += "\n";
data += txtPassword.Text; data += "\n";
if (rbtnMale.Checked == true)
{
data += "Male"; data += "\n";
}
else
{
data += "Female"; data += "\n";
}
data += dtpDOB.Value.ToString("dd/MM/yyyy"); data += "\n";
data += txtMobile.Text; data += "\n";

if (chkPhysical.Checked == true)
{
data += "YesForPhysicallyChallenged"; data += "\n";
}
else
{
data += "NoForPhysicallyChallenged"; data += "\n";
}

data += cmbCountry.SelectedItem.ToString(); data += "\n";


data += lstCities.SelectedItem.ToString(); data += "\n";
data += txtStreet.Text; data += "\n";

MessageBox.Show(data);

30
Department of Computer Science - Iqra University
Visual Programming Language Lab

MessageBox.Show("Registered Successfully", "Registration Form",


MessageBoxButtons.OK, MessageBoxIcon.Information);

}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);} }

Reference:
https://www.c-sharpcorner.com/article/validating-user-input-using-regular-expression-with-c-sharp/

Practice Exercise:
Add form validation to the student registration form created in Lab 2 practice exercise using
regex, exception handling, and error provider component

31
Department of Computer Science - Iqra University
Visual Programming Language Lab

ADO .NET – Using Connected Architecture Lab 5

Objective: To understand the concept of connected Architecture of ADO .Net Framework

Steps:

1. Establish SQL server connection by entering your server name and authentication.

32
Department of Computer Science - Iqra University
Visual Programming Language Lab

2. Create database and name it.

33
Department of Computer Science - Iqra University
Visual Programming Language Lab

3. Create a table named Student.

34
Department of Computer Science - Iqra University
Visual Programming Language Lab

35
Department of Computer Science - Iqra University
Visual Programming Language Lab

36
Department of Computer Science - Iqra University
Visual Programming Language Lab

4. Create a Windows Form Application.

37
Department of Computer Science - Iqra University
Visual Programming Language Lab

5. Design Student Registration Form.

38
Department of Computer Science - Iqra University
Visual Programming Language Lab

6. Set a click event on the button by double click on the button.

39
Department of Computer Science - Iqra University
Visual Programming Language Lab

7. Add Server Connection to your application

40
Department of Computer Science - Iqra University
Visual Programming Language Lab

41
Department of Computer Science - Iqra University
Visual Programming Language Lab

8. Copy connection string from the properties section of the data source.

42
Department of Computer Science - Iqra University
Visual Programming Language Lab

43
Department of Computer Science - Iqra University
Visual Programming Language Lab

Code behind Clear Button

44
Department of Computer Science - Iqra University
Visual Programming Language Lab

Code Behind Submit Buttons

45
Department of Computer Science - Iqra University
Visual Programming Language Lab

46
Department of Computer Science - Iqra University
Visual Programming Language Lab

References:
http://csharp.net-informations.com/ado.net/ado.net-data-access-architecture.htm

https://krify.co/ado-net-connection-architecture-in-web-and-windows-application-development/

Practice Exercise:

Perform crud operations on the Employee Registration form created in lab 2 using connected
architecture in ADO.NET

47
Department of Computer Science - Iqra University
Visual Programming Language Lab

ADO .NET – Using Disconnected Architecture Lab 6

Objective: To understand the concept of Disconnected Architecture of ADO .Net Framework

Introduction

The architecture of ADO.net in which data retrieved from database can be accessed even when
connection to database was closed is called as disconnected architecture. Disconnected
architecture of ADO.net was built on classes connection, dataadapter, commandbuilder and
dataset and dataview.

Task: Add Book record to the database using windows form application by using disconnected
Architecture.

Design

48
Department of Computer Science - Iqra University
Visual Programming Language Lab

Steps:

1. Establish SQL server connection by entering your server name and authentication.
2. Create Database and name it.
3. Create table name it BookDetail

Code Behind

1. Create SqlConnection class with value of connection string.

49
Department of Computer Science - Iqra University
Visual Programming Language Lab

2. Load table data in datagridview

3. Set an event for the AddNew button to insert new record in the database.

4. Set an event for the Edit button to Update existing record in the database

50
Department of Computer Science - Iqra University
Visual Programming Language Lab

5. Set an event for the delete button to delete a record from the database.

Output

51
Department of Computer Science - Iqra University
Visual Programming Language Lab

Now, new row inserted in the database.

References:
http://csharp.net-informations.com/ado.net/ado.net-data-access-architecture.htm

https://krify.co/ado-net-connection-architecture-in-web-and-windows-application-development/

Practice Exercise:

Using disconnected architecture in ADO.NET perform crud operations on the Student


Registration form you created in lab 2 practice exercise.

52
Department of Computer Science - Iqra University
Visual Programming Language Lab

Introduction to Windows presentation Forms Lab 7

Objective: To create a Paint Application using WPF.

Design view

53
Department of Computer Science - Iqra University
Visual Programming Language Lab

XAML Code

C# Code

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace MyLittlePaint
{
///<summary>
/// Interaction logic for MainWindow.xaml

54
Department of Computer Science - Iqra University
Visual Programming Language Lab

///</summary>
publicpartialclassMainWindow : Window
{
privateint diameter = (int)Sizes.MEDIUM; // set diameter of circle
private Brush brushColor = Brushes.Black; // set the drawing color
privatebool shouldErase = false; // specify whether to erase
privatebool shouldPaint = false; // specify whether to paint

privateenumSizes// size constants for diameter of the circle


{
SMALL = 4,
MEDIUM = 15,
LARGE = 30
} // en
public MainWindow()
{
InitializeComponent();
}

privatevoid PaintCircle(Brush circleColor, Point position)


{
Ellipse newEllipse = new Ellipse(); // create an Ellipse
newEllipse.Fill = circleColor; // set Ellipse's color
newEllipse.Width = diameter; // set its horizontal diameter
newEllipse.Height = diameter; // set its vertical diameter
// set the Ellipse's position
Canvas.SetTop(newEllipse, position.Y);
Canvas.SetLeft(newEllipse, position.X);
paintCanvas.Children.Add(newEllipse);
} // end method

privatevoid paintCanvas_MouseMove(object sender, MouseEventArgs e)


{
if (shouldPaint)
{
Point mousePosition = e.GetPosition(paintCanvas);
PaintCircle(brushColor, mousePosition);
}

if (shouldErase)
{
Point mousePosition = e.GetPosition(paintCanvas);
PaintCircle(paintCanvas.Background, mousePosition);
}
}

55
Department of Computer Science - Iqra University
Visual Programming Language Lab

privatevoid paintCanvas_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)


{
shouldPaint = true;
}

privatevoid paintCanvas_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)


{
shouldPaint = false;
}

privatevoid paintCanvas_MouseRightButtonDown(object sender, MouseButtonEventArgs e)


{
shouldErase = true;
}

privatevoid paintCanvas_MouseRightButtonUp(object sender, MouseButtonEventArgs e)


{
shouldErase = false;
}

privatevoid redRadioButton_Checked(object sender, RoutedEventArgs e)


{
brushColor = Brushes.Red;
}

privatevoid blueRadioButton_Checked(object sender, RoutedEventArgs e)


{
brushColor = Brushes.Blue;
}

privatevoid greenRadioButton_Checked(object sender, RoutedEventArgs e)


{
brushColor = Brushes.Green;
}

privatevoid blackRadioButton_Checked(object sender, RoutedEventArgs e)


{
brushColor = Brushes.Black;
}

privatevoid smallRadioButton_Checked(object sender, RoutedEventArgs e)


{
diameter = (int)Sizes.SMALL;
}

56
Department of Computer Science - Iqra University
Visual Programming Language Lab

privatevoid MediumRadioButton_Checked(object sender, RoutedEventArgs e)


{
diameter = (int)Sizes.MEDIUM;
}

privatevoid largelRadioButton_Checked(object sender, RoutedEventArgs e)


{
diameter = (int)Sizes.LARGE;
}

privatevoid undoButton_Click(object sender, RoutedEventArgs e)


{
int count = paintCanvas.Children.Count;
// if there are any shapes on Canvas remove the last one added
if (count > 0)
paintCanvas.Children.RemoveAt(count - 1);
}

privatevoid clearButton_Click(object sender, RoutedEventArgs e)


{
paintCanvas.Children.Clear();
}
}
}

References:
https://www.tutorialspoint.com/wpf/wpf_quick_guide.htm

Practice Exercise:
Design a notepad application in WPF.

57
Department of Computer Science - Iqra University
Visual Programming Language Lab

WPF – Custom XAML Editor Lab 8

Objective: To create a custom XAML Editor using WPF

Steps:

1. Open Visual Studio


2. Select File – New Project - WPF Aplication
3. Name your project “XAML Editor” and Press OK

4. Update the initial XAML definition of your <Window> as shown next


<Window x:Class="WpfApplication2.MainWindow"

xmlns="http://schemas.microsoft.com/winfx/2006/xaml/pres
entation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="My Custom XAML Editor" Height="338"
Width="1041"
Loaded="Window_Loaded" Closed="Window_Closed"
WindowStartupLocation="CenterScreen">

<DockPanel LastChildFill="True" >


<Button DockPanel.Dock="Top" Name = "btnViewXaml" Width="100" Height="40"
Content ="View Xaml" Click="btnViewXaml_Click" />

58
Department of Computer Science - Iqra University
Visual Programming Language Lab

<TextBox AcceptsReturn ="True" Name ="txtXamlData" FontSize ="14"


Background="Black"
Foreground="Yellow" BorderBrush ="Blue" VerticalScrollBarVisibility="Auto"
AcceptsTab="True"/></DockPanel>
</Window>

5. You should find the following code in your MainWindow.xaml.cs file


privatevoid btnViewXaml_Click(object sender, RoutedEventArgs e)

}
privatevoid Window_Closed(object sender,
EventArgs e) { }
privatevoid Window_Loaded(object sender, RoutedEventArgs e)
{
}
6. Before continuing, be sure to import the following namespaces into your
MainWindow.xaml.cs file:

using System.IO; using System.Windows.Markup; you will fill the


TextBox with an initial default XAML description of an empty window

59
Department of Computer Science - Iqra University
Visual Programming Language Lab

privatevoid Window_Loaded(object sender,


RoutedEventArgs e) {
if (File.Exists("YourXaml.xaml"))
{
txtXamlData.Text = File.ReadAllText("YourXaml.xaml");
} else {
txtXamlData.Text =
"<Window xmlns=\"http://schemas.microsoft.com/winfx/2006/xaml/presentation\"\n"
+ "xmlns:x=\"http://schemas.microsoft.com/winfx/2006/xaml\"\n"
+ "Height =\"400\" Width =\"500\" WindowStartupLocation=\"CenterScreen\">\n"
+ "<StackPanel>\n"
+ "</StackPanel>\n"
+ "</Window>";
}
}
At this point, you should be able to run your program and find the display shown in
Figure

7. Change the method btnViewXaml_Click as given below

privatevoid btnViewXaml_Click(object sender, RoutedEventArgs e)


{
File.WriteAllText("YourXaml.xaml", txtXamlData.Text);
Window
myWindo
w = null;
try {
using (Stream sr = File.Open("YourXaml.xaml",
FileMode.Open)) {

myWindow = (Window)XamlReader.Load(sr);

60
Department of Computer Science - Iqra University
Visual Programming Language Lab

myWindow.ShowDial
og();
myWindow.Close();
myWindow = null;

}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}

8. Change the Window_Closed method as given below


privatevoid Window_Closed(object sender, EventArgs e)
{
File.WriteAllText("YourXaml.xaml", txtXamlData.Text);
Application.Current.Shutdown();
}

9. Now fire up your program and enter some XAML into your text area, As a first test, enter
the following XAML within your <StackPanel> scope
<Button Height = "100" Width = "100" Content = "Click Me!">
<Button.Background>
<LinearGradientBrush StartPoint = "0,0" EndPoint = "1,1">
<GradientStop Color = "Blue" Offset = "0" />
<GradientStop Color = "Yellow" Offset = "0.25" />
<GradientStop Color = "Green" Offset = "0.75" />
<GradientStop Color = "Pink" Offset = "0.50" />
</LinearGradientBrush>

61
Department of Computer Science - Iqra University
Visual Programming Language Lab

</Button.Background>
</Button>

10. Now, enter the following XAML markup directly after the current <Button> definition:
<Label Content = "Interesting...">
<Label.Triggers>
<EventTrigger RoutedEvent = "Label.Loaded">
<EventTrigger.Actions>
<BeginStoryboard>
<Storyboard TargetProperty = "FontSize">
<DoubleAnimation From = "12" To = "100" Duration = "0:0:4"
RepeatBehavior = "Forever"/>
</Storyboard>
</BeginStoryboard>
</EventTrigger.Actions>
</EventTrigger>
</Label.Triggers>
</Label>

62
Department of Computer Science - Iqra University
Visual Programming Language Lab

References:

https://docs.microsoft.com/en-us/archive/msdn-magazine/2019/may/xaml-custom-xaml-controls

63
Department of Computer Science - Iqra University
Visual Programming Language Lab

Using LINQ & Lambda Expression Lab 9

Objective: To understand the concept of LINQ and Lambda Expression for handling the
database for the windows application.

Introduction

LINQ to SQL provides a runtime infrastructure for managing relational data as objects without
losing the ability to query. Your application is free to manipulate the objects while LINQ to SQL
stays in the background tracking your changes automatically.

You can access the LINQ to SQL visual designer by adding a new or opening an existing “LINQ
to SQL Classes” item (*.dbml file) to the project, which opens the designer. This helps you to
build out the DataContext and entity classes for your database, which can then be used with
LINQ (or other programming constructs if you wish). A DataContext is analogous to an
ADO.NET Connection and Command object rolled into one. You use it to establish your
connection, execute queries, or access tables directly via entity classes.

Design

Steps:

1. Create a database having two table named “Student” and “course”. Add data connection
to your application.

64
Department of Computer Science - Iqra University
Visual Programming Language Lab

2. Create a “SMS.dbml” file and add database tables from server explorer into it. This will
create the SMSDataContext class and maps tables into the classes.

Code Behind

Load data from student and course table using LINQ and Lambda Expression

65
Department of Computer Science - Iqra University
Visual Programming Language Lab

On the click of insert button a studentRegistration form will be displayed to add new student
record.

Code behind Student registration form

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace WindowsFormsApp9
{
publicpartialclassstudDetail : Form
{
public studDetail()
{
InitializeComponent();
}

smsDataContext db;

privatevoid studDetail_Load(object sender, EventArgs e)


{
db = new smsDataContext();

var courseinfo = from c in db.courses


select c;

cmbocourse.DataSource = courseinfo.ToList();
cmbocourse.DisplayMember = "coursename";
cmbocourse.ValueMember = "Id";

// insert record into student table

privatevoid btnSave_Click(object sender, EventArgs e)


{
if (txtid.ReadOnly == false)
{
Student s = new Student()
{

66
Department of Computer Science - Iqra University
Visual Programming Language Lab

Id = Convert.ToInt32(txtid.Text.ToString()),
sname = txtname.Text,
email = txtname.Text,
phoneno = Convert.ToInt32(txtphoneno.Text.ToString()),
courseid = (int)cmbocourse.SelectedValue

};

db.Students.InsertOnSubmit(s);
db.SubmitChanges();
MessageBox.Show("record inserted");

}
else
{
// update record of the student

Student s = db.Students.First(E => E.Id == Convert.ToInt32(txtid.Text.ToString()));


s.sname = txtname.Text;
s.email = txtemail.Text;
s.phoneno = Convert.ToInt32(txtphoneno.Text.ToString());
s.courseid = (int)cmbocourse.SelectedValue;
db.SubmitChanges();
}

}
}
}

Code to delete selected record from the table.

Add event handler on the delete button to delete record form the student table.

privatevoid button3_Click(object sender, EventArgs e)


{
Student s = db.Students.First(E => E.Id ==
Convert.ToInt32(dataGridView1.SelectedRows[0].Cells[0].Value));
db.Students.DeleteOnSubmit(s);
db.SubmitChanges();
MessageBox.Show("Deleted success fully");
LoadData();
}

67
Department of Computer Science - Iqra University
Visual Programming Language Lab

References:

Visual C# 2012, How to program fifth Edition


22.5 Querying a database with LINQ

https://www.tutorialspoint.com/linq/linq_lambda_expressions.htm

Practice Exercise:
Design a windows form application and Insert, update and delete data of patients visiting a
private clinic using LINQ TO SQL queries.
Consider the following patient’s properties:
Name
Age
Bloodgroup
Symptoms
Prescribes medicines

68
Department of Computer Science - Iqra University
Visual Programming Language Lab

Entity Framework Lab 10

Objective: Designing an application using Entity Framework.

Introduction

Entity framework (EF) is the framework ORM (object-relational mapping) that Microsoft makes
available as part of the .NET development (version 3.5 SP1 and later). Its purpose is to abstract
the ties to a relational database, in such a way that the developer can relate to the database entity
as to a set of objects and then to classes in addition to their properties.

The Model First Approach provides the option to create entities and relationships directly on the
design interface of the EDMX and then we can execute it.

Task: You need to design a school management system using Entity framework model first
approach.

Steps:

1. Create a Windows application that uses model first approach to perform data access.
2. Create a model. Go to project->Add->New item -> Data -> ADO.NET Entity Data
Model.
3. Enter SchoolModel as the name and click OK, this launches the Entity Data Model
Wizard.
4. Select Empty Model and click Finish.

The Entity Framework Designer is opened with a blank model. Now we can start adding
entities, properties and associations to the model.
• Right-click on the design surface and select Properties

69
Department of Computer Science - Iqra University
Visual Programming Language Lab

• In the Properties window change the Entity Container Name to


SchoolModelDBContext
This is the name of the derived context that will be generated for you, the context
represents a session with the database, allowing us to query and save data
• Right-click on the design surface and select Add New -> Entity…
• Enter Studentas the entity name and StudId as the key name and click OK

70
Department of Computer Science - Iqra University
Visual Programming Language Lab

After creating the required entities, associations, and inheritance on the design surface of the
empty model, you can use the designer's context menu option 'Generate database from model' to
generate the DDL script.

71
Department of Computer Science - Iqra University
Visual Programming Language Lab

This will open the Generate Database Wizard. You can select the existing database or create a
new connection by clicking on New Connection... Select database server, enter the name of the
database to create and then click OK. It will ask you for the confirmation for creating a new
database. Click Yes to create a database.

Click Next to generate the DDL for the DB model as shown below.

72
Department of Computer Science - Iqra University
Visual Programming Language Lab

This will add the schoolmodel.edmx.sql file in the project. You can execute DDL scripts in
Visual Studio by opening the .sql file -> right click -> Execute.

Now, you can generate the context class and entities by right clicking on the designer and
selecting Add Code Generation Item…

References:

entityframeworktutorial.net/model-first-with-entity-framework.aspx

Practice Exercise:
Create Product Detail form and perform CRUD using Entity framework model first approach.

Database Colum’s.

-ProductId

-ProductCatagory

-ProductName

-ProductPrice

-ProductQuantity

73
Department of Computer Science - Iqra University
Visual Programming Language Lab

Entity Framework – Database First Approach Lab 11

Objective: Designing an application using Entity Framework database first approach

Steps: Referencing the Entity Framework in the project

 Open the Nuget package manager and look for the Entity Framework package , and
simply add it to our solution by pressing the "Install" button. At the end of the operation,
we will see how those related to EF will have been included among the project
References.

74
Department of Computer Science - Iqra University
Visual Programming Language Lab

Step: Prepare the database


 A database named TECHNET was created, inside which there are two tables: "Articles"
and "Families".

75
Department of Computer Science - Iqra University
Visual Programming Language Lab

Step: Model the classes with EF


 We add a new element to the solution, going to call, from the Visual C # Items »Data
menu, an object of type ADO.NET Entity Data Model, which we will call«
TechnetModello

 In this case, will be "EF Designer from database", which realizes the Database-First
paradigm.

76
Department of Computer Science - Iqra University
Visual Programming Language Lab

 Establish a connection to our database.

 Press "New Connection" and go to set the connection parameters.

77
Department of Computer Science - Iqra University
Visual Programming Language Lab

 In our case, we select the two tables created, leaving the rest of the settings as proposed.

78
Department of Computer Science - Iqra University
Visual Programming Language Lab

The Wizard will complete the operations of the case, going to generate a data model
composed of the classes representing the database entities, and showing a graphical
representation.

Extract from the table items the record having Codart = 'ART001'.Since our data context
has been transformed into classes, we can use the handy LINQ syntax, applied to the
entities of the daughters TECHNETEntities data context.

79
Department of Computer Science - Iqra University
Visual Programming Language Lab

 The query just mentions it, as follows:


using (TECHNETEntities db = new TECHNETEntities())
{
Articoli art = db.Articoli.Where((x) => x.CodArt ==
"ART001").FirstOrDefault();

MessageBox.Show(art.DesArt);
}

 Insert items in the table, a Foreign Key that establishes the relationship between Articles
and Families Using SQL Management Studio.

80
Department of Computer Science - Iqra University
Visual Programming Language Lab

 Once you save the changes to the database, Visual Studio side will have to regenerate the
data model. TechnetModello.edmx will simply open the file, which graphically shows
our data model, and using right click to select "Update Model from Database", the
screenshot shown below, appears:

 upgraded by establishing a relationship between the two tables.

81
Department of Computer Science - Iqra University
Visual Programming Language Lab

 modify the classes

 Class definition

1. namespace ArticoloEF.Model
2. {
3. using System;
4. using System.Data.Entity;
5. using System.ComponentModel.DataAnnotations.Schema;
6. using System.Linq;
7.
8. public partial class TechnetModelloCF : DbContext
9. {
10. public TechnetModelloCF()
11. : base("name=TechnetModelloCF")
12. {
13. }
14.

82
Department of Computer Science - Iqra University
Visual Programming Language Lab

15. public virtual DbSet<Articoli> Articoli { get; set; }


16. public virtual DbSet<Famiglie> Famiglie { get; set; }
17.
18. protected override void OnModelCreating(DbModelBuilder modelBuilder)
19. {
20. modelBuilder.Entity<Famiglie>()
21. .HasMany(e => e.Articoli)
22. .WithRequired(e => e.Famiglie)
23. .WillCascadeOnDelete(false);
24. }
25. }
26. }

1. namespace ArticoloEF.Model
2. {
3. using System;
4. using System.Collections.Generic;
5. using System.ComponentModel.DataAnnotations;
6. using System.ComponentModel.DataAnnotations.Schema;
7. using System.Data.Entity.Spatial;
8.
9. [Table("Articoli")]
10. public partial class Articoli
11. {
12. [Key]
13. public int IdArticolo { get; set; }
14.
15. [Required]
16. [StringLength(25)]
17. public string CodArt { get; set; }
18.
19. [Required]
20. [StringLength(50)]
21. public string DesArt { get; set; }
22.
23. [Required]
24. [StringLength(6)]
25. public string CodFamiglia { get; set; }
26.
27. public virtual Famiglie Famiglie { get; set; }
28. }
29. }
30. namespace ArticoloEF.Model

83
Department of Computer Science - Iqra University
Visual Programming Language Lab

31. {
32. using System;
33. using System.Collections.Generic;
34. using System.ComponentModel.DataAnnotations;
35. using System.ComponentModel.DataAnnotations.Schema;
36. using System.Data.Entity.Spatial;
37.
38. [Table("Famiglie")]
39. public partial class Famiglie
40. {
41. [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:
DoNotCallOverridableMethodsInConstructors")]
42. public Famiglie()
43. {
44. Articoli = new HashSet<Articoli>();
45. }
46.
47. [Key]
48. [StringLength(6)]
49. public string CodFamiglia { get; set; }
50.
51. [Required]
52. [StringLength(50)]
53. public string DesFamiglia { get; set; }
54.
55. [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:
CollectionPropertiesShouldBeReadOnly")]
56. public virtual ICollection<Articoli> Articoli { get; set; }
57. }
58. }

 Add a field to the Items table inserts a field named CostoStandard, Decimal type.

 enable the project to migrate type Enable-Migrations

84
Department of Computer Science - Iqra University
Visual Programming Language Lab

 Migrations can be created with the command


Add-Migration <NOME_MIGRAZIONE>
Add-Migration InitialCreate –IgnoreChanges
 This allows you to move fully into field Code-First control of the data modeling

85
Department of Computer Science - Iqra University
Visual Programming Language Lab

References:

https://www.aspsnippets.com/Articles/Entity-Framework-Database-First-Approach-in-
Windows-Forms-WinForms-Application-using-C-and-VBNet.aspx
Practice Exercise:
Create Signup form using Entity Framework – Database First Approach
Database Table Contain following columns
-UserName
-Email
-Contact
-Password

86
Department of Computer Science - Iqra University
Visual Programming Language Lab

Creating Crystal Report Lab 12

Objective: To generate report for the windows application with crystal Reports.

Crystal Report is a Reporting Application that can generate reports from various Data Sources
like Databases , XML files etc.. The Visual Studio.NET Integrated Development Environment
comes with Crystal Reports tools. The Crystal Reports makes it easy to create simple reports,
and also has comprehensive tools that you need to produce complex or specialized reports in
csharp and other programming languages.

We will create Crystal Report for Employee Data information

1. Create a database name “EmployeeDB”


2. Now create an Employee Table
create table Employee
(
Emp_ID int identity(1,1) constraint PK_Emp primary key,
Emp_Name varchar(30),
Emp_Contact nchar(15),
Emp_Salary decimal(7,2)
)
3. Insert Data into the table
insert into Employee values ('Rakesh','9924194054','15000.22');
insert into Employee values ('Amit','9824194555','17000');
insert into Employee values ('Ketan','9824198245','14000');
insert into Employee values ('Ketan','9994198245','12000');
insert into Employee values ('Chirag','9824398245','10000');
insert into Employee values ('Naren','9824398005','10000');
4. To display employee data information create a VIEW in your database
create view vw_Employee
as
Select Emp_ID,Emp_Name,Emp_Contact,Emp_Salary
from Employee
GO
5. Go to Visual Studio and create a windows Form

87
Department of Computer Science - Iqra University
Visual Programming Language Lab

6. Add crystal report into your project

7. Go to crystal report gallery and select using the report wizard

8. Choose the data source

88
Department of Computer Science - Iqra University
Visual Programming Language Lab

9. Select the data with OLEDB (ADO)


10. In OLEDB(ADO) window select locale identifier
11. Now select the VIEW Employee
12. Select the report format

13. Select fields to display in the report.

89
Department of Computer Science - Iqra University
Visual Programming Language Lab

14. The next step is to show the crystal report in the windows form. To do this, you need to
add Crystal Report Viewer control to the form.

15. Open the form


16. Locate Reporting tab in the toolbox
17. Select the crystalReportViewer drag and drop it unto the form.
18. Bind Report to Crystal Report Viewer Control
private void frmCrystalReport_Load(object sender, EventArgs e)
{
EmployeeList rpt = new EmployeeList();
crystalReportViewer1.ReportSource = rpt;
}

RUN YOUR FIRST REPORT!

References:
http://csharp.net-informations.com/crystal-reports/csharp-crystal-reports-stepbystep.htm

Practice Exercise:
Design a Student Result Application in Windows form With Crystal Report
Also Export it to Pdf format.

90
Department of Computer Science - Iqra University
Visual Programming Language Lab

Parallel Programming using PLINQ, task parallel library Lab 13

Objective: To understand the Parallel Programming using PLINQ, task parallel library

The Parallel API divides into two parts:

1. Task Parallel Library (TPL)


2. Parallel LINQ (PLINQ).

Both features help developers use processors more fully. You can think of the Task Parallel
Library as a generic set of parallel capabilities, whereas PLINQ focuses on database (or object)
manipulation.

Let’s get started

1. Go to VS and create a form name “PLINQ data processing with cancellation”.


2. The simple form will need only two buttons Execute and Cancel

3. On the click of execute button fire a new task which executes a LINQ query that investigates
a large number of integers looking for only the items where x is completely divisible by 2.
Here is a non-parallel version of the query.

91
Department of Computer Science - Iqra University
Visual Programming Language Lab

4. To inform the TPL to use execute this query in parallel use the AsParallel() extension
method. This method will attempt to pass the workload off to an available CPU.

5. Use a CancellationTokenSource object to inform a PLINQ query to stop processing under


the correct conditions(Typically because of user invention)

6. Implement the click handler for the btnCancel to call the Cancel() method on this object.

92
Department of Computer Science - Iqra University
Visual Programming Language Lab

7. Run the code

93
Department of Computer Science - Iqra University
Visual Programming Language Lab

8. Wrap PLINQ query in a proper try/catch block to deal with any exception.

References:

C# 6.0 and the .NET 4.6 Framework


By ANDREW TROELSEN, Philip Japikse
Parallel LINQ Quries (PLINQ)
Pages: 738 - 740

Practice Exercise:
Upgrade progress bar using TPL in windows forms.

94
Department of Computer Science - Iqra University
Visual Programming Language Lab

Building Universal Windows Platform Apps Using XAML (UWP) Lab 14

Objective: To understand how to create Universal Windows Platform Apps (UWP) Using
XAML.

UWP apps declare in their manifest the device capabilities they need such as access to the
microphone, location, Webcam, USB devices, files, and so on. The user must acknowledge and
authorize that access before the app is granted the capability.Windows 10 introduces the
Universal Windows Platform (UWP), which provides a common app platform on every device
that runs Windows 10. The UWP core APIs are the same on all Windows devices. If your app
only uses the core APIs, it will run on any Windows 10 device no matter whether you are
targeting a desktop PC, Xbox, Mixed-reality headset, and so on.

A UWP app written in C++ /WinRT or C++ /CX has access to the Win32 APIs that are part of
the UWP. These Win32 APIs are implemented by all Windows 10 devices.

95
Department of Computer Science - Iqra University
Visual Programming Language Lab

Lets get started with Universal Windows Platform Apps (UWP) Using XAML.

1. Go VS and create a new project. Select the target Version and Minimum Version

2. From windows universal select blank app and name it AnalogClock

96
Department of Computer Science - Iqra University
Visual Programming Language Lab

3. Use an ellipse and rectangle control to draw the clock. Go to MainPage.Xaml page and
write the following xaml code

4. We need 3 lines (rectangle) to show the hour, seconds, and minute hand on an analog
clock. Set the angle zero (0) to transform the line from the center of the circle.
For seconds and minutes multiply the value by 6 to get the angle for the clock hand to
transform. For hours multiply the hour by 30 to get the angle.

5. Using dispatcher time update the angle every second, code this in the MainPage class

97
Department of Computer Science - Iqra University
Visual Programming Language Lab

Run your code!

References:
https://docs.microsoft.com/en-us/visualstudio/get-started/csharp/tutorial-uwp?view=vs-2019

Practice Exercise:
Create a stop watch in UWP.

98
Department of Computer Science - Iqra University
Visual Programming Language Lab

Building cross-platform apps on the .NET platform with Xamarin Lab 15

Objective: To understand how to use Xamarin to share code across multiple platforms.

Xamarin is a cross-platform mobile development framework that now ships with Visual Studio
2019 for Windows and Visual Studio for Mac.

The first step is to set up Xamarin.

1. In installation window under Mobile and gaming category check mobile development with
.net

99
Department of Computer Science - Iqra University
Visual Programming Language Lab

2. To develop UWP Apps in Xamarin check the following box

3. Visual Studio includes an Android emulator and Windows 10 Emulator that can be used to
test and debug an Xamarin.Android and Xamarin Forms apps. The Android emulator uses
the Hyper-V capabilities of development machine which results in faster launch and
execution times than the default android emulator that comes with the Android SDK. To
install both the emulators just navigate to individual components option and check the
options in the following.

100
Department of Computer Science - Iqra University
Visual Programming Language Lab

Now lets build our first Xamarin.Forms App

1. Go to VS and create a new project


2. Search for "Xamarin" or choose Mobile from the Project type menu. Select the Mobile
App (Xamarin.Forms) project type:

3. Choose a project name – the example uses "AwesomeApp"

4. Click on the Blank project type and ensure Android and iOS are selected:

5. Wait until the NuGet packages are restored (a "Restore completed" message will appear
in the status bar).

101
Department of Computer Science - Iqra University
Visual Programming Language Lab

6. Click the dropdown arrow on the Debug button and choose Create Android Emulator to
launch the emulator creation screen.

7. In the emulator creation screen, use the default settings and click the Create button:

8. Creating an emulator will return you to the Device Manager window. Click the Start
button to launch the new emulator:

9. Visual Studio 2019 should now show the name of the new emulator on the Debug button:
10. Click the Debug button to build and deploy the application to the Android emulator:

102
Department of Computer Science - Iqra University
Visual Programming Language Lab

Lets create our First WeatherApp project:


1. Replace the template code with the following
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace WeatherApp
{
public class Weather
{
public string Title { get; set; }
public string Temperature { get; set; }
public string Wind { get; set; }
public string Humidity { get; set; }
public string Visibility { get; set; }
public string Sunrise { get; set; }
public string Sunset { get; set; }

public Weather()
{
//Because labels bind to these values, set them to an empty string
to
//ensure that the label appears on all platforms by default.
this.Title = " ";
this.Temperature = " ";
this.Wind = " ";
this.Humidity = " ";
this.Visibility = " ";
this.Sunrise = " ";
this.Sunset = " ";
}
}
}

103
Department of Computer Science - Iqra University
Visual Programming Language Lab

2. This is a simple class that will hold the data returned from the Open Weather Map
website. The constructor sets all variables to be blank strings by default.
3. Next we need a class to pass our request to the Open Weather Map website and return
the response for our application to use.
Right click on the WeatherApp project, then select Add, then Class. Name the class
DataService.cs and click on Add
using Newtonsoft.Json;
using System.Threading.Tasks;
using System.Net.Http;

namespace WeatherApp
{
public class DataService
{
public static async Task<dynamic> getDataFromService(string
pQueryString)
{
HttpClient client = new HttpClient();
var response = await client.GetAsync(pQueryString);

dynamic data = null;


if (response != null)
{
string json = response.Content.ReadAsStringAsync().Result;
data = JsonConvert.DeserializeObject(json);
}

return data;
}
}
}
4. Right click on the WeatherApp project, then select Add, then Class. Name the class
Core.cs and click on Add.
using System;

104
Department of Computer Science - Iqra University
Visual Programming Language Lab

using System.Threading.Tasks;
using WeatherApp;

namespace WeatherApp
{
public class Core
{
public static async Task<Weather> GetWeather(string pZipCode)
{
//Sign up for a free API key at http://openweathermap.org/appid
string key = "YOUR KEY HERE";
string queryString =
"http://api.openweathermap.org/data/2.5/weather?zip="
+ pZipCode + ",us&appid=" + key + "&units=imperial";

//Make sure developers running this sample replaced the API key
if (key != "YOUR API KEY HERE")
{
throw new ArgumentException("You must obtain an API key
from openweathermap.org/appid and save it in the 'key' variable.");
}

dynamic results = await


DataService.getDataFromService(queryString).ConfigureAwait(false);

if (results["weather"] != null)
{
Weather weather = new Weather();
weather.Title = (string)results["name"];
weather.Temperature = (string)results["main"]["temp"] + " F";
weather.Wind = (string)results["wind"]["speed"] + " mph";
weather.Humidity = (string)results["main"]["humidity"] + " %";
weather.Visibility = (string)results["weather"][0]["main"];

DateTime time = new System.DateTime(1970, 1, 1, 0, 0, 0, 0);


DateTime sunrise =
time.AddSeconds((double)results["sys"]["sunrise"]);
DateTime sunset =
time.AddSeconds((double)results["sys"]["sunset"]);
weather.Sunrise = sunrise.ToString() + " UTC";

105
Department of Computer Science - Iqra University
Visual Programming Language Lab

weather.Sunset = sunset.ToString() + " UTC";


return weather;
}
else
{
return null;
}
}
}
}

5. Open the WeatherApp MainPage.xaml and replace the XAML with:


<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"

xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"

xmlns:local="clr-namespace:WeatherApp"

x:Class="WeatherApp.MainPage">

<StackLayout>
<StackLayout Margin="10,0,0,0" VerticalOptions="Start"
HorizontalOptions="Start" WidthRequest="400"
BackgroundColor="#545454">
<Label Text="Weather App" x:Name="lblTitle"/>

<StackLayout HorizontalOptions="Start" Margin="10,10,0,0"


VerticalOptions="Start" WidthRequest="400">
<Label Text="Search by Zip Code" FontAttributes="Bold"
TextColor="White" Margin="10" x:Name="lblSearchCriteria"
VerticalOptions="Start"/>
<Label Text="Zip Code" TextColor="White" Margin="10"
x:Name="lblZipCode"/>
<StackLayout Orientation="Horizontal" VerticalOptions="Start">
<Entry WidthRequest="100" x:Name="edtZipCode"
VerticalOptions="Start"/>
<Button Text="Get Weather" x:Name="btnGetWeather"
VerticalOptions="Start"/>

106
Department of Computer Science - Iqra University
Visual Programming Language Lab

</StackLayout>
</StackLayout>
</StackLayout>

<StackLayout VerticalOptions="StartAndExpand">
<Label Text ="Location" TextColor="#FFA8A8A8" FontSize="14"/>
<Label Text ="" Margin="10,0,0,10" x:Name="txtLocation"/>
<Label Text ="Temperature" TextColor="#FFA8A8A8" FontSize="14"/>
<Label Text ="" Margin="10,0,0,10" x:Name="txtTemperature"/>
<Label Text ="Wind Speed" TextColor="#FFA8A8A8" FontSize="14"/>
<Label Text ="" Margin="10,0,0,10" x:Name="txtWind"/>
<Label Text ="Humidity" TextColor="#FFA8A8A8" FontSize="14"/>
<Label Text ="" Margin="10,0,0,10" x:Name="txtHumidity"/>
<Label Text ="Visibility" TextColor="#FFA8A8A8" FontSize="14"/>
<Label Text ="" Margin="10,0,0,10" x:Name="txtVisibility"/>
<Label Text ="Sunrise" TextColor="#FFA8A8A8" FontSize="14"/>
<Label Text ="" Margin="10,0,0,10" x:Name="txtSunrise"/>
<Label Text ="Sunset" TextColor="#FFA8A8A8" FontSize="14"/>
<Label Text ="" Margin="10,0,0,10" x:Name="txtSunset"/>
</StackLayout>
</StackLayout>
</ContentPage>

6. Now open the MainPage.xaml.cs, in the MainPage() constructor add the following
code to link a procedure to the button being pushed:
public MainPage()
{
InitializeComponent();

btnGetWeather.Clicked += btnGetWeather_Click;
}
7. Then add the button push code:
private async void btnGetWeather_Click(object sender, EventArgs e)
{
if (!String.IsNullOrEmpty(edtZipCode.Text))
{
Weather weather = await Core.GetWeather(edtZipCode.Text);

if (weather != null)
{

107
Department of Computer Science - Iqra University
Visual Programming Language Lab

txtLocation.Text = weather.Title;
txtTemperature.Text = weather.Temperature;
txtWind.Text = weather.Wind;
txtVisibility.Text = weather.Visibility;
txtHumidity.Text = weather.Humidity;
txtSunrise.Text = weather.Sunrise;
txtSunset.Text = weather.Sunset;

btnGetWeather.Text = "Search Again";


}
}
}

References:
https://riptutorial.com/xamarin-forms

Practice Exercise:
Create tic-tac-toe game in Xamarin form

108
Department of Computer Science - Iqra University

You might also like