Professional Documents
Culture Documents
VPL LabManual
VPL LabManual
VPL LabManual
Name _____________________
Roll No ____________________
Semester ____________________
Marks ____________________
Signature ____________________
2018
0
Visual Programming Language Lab
Content
Lab
Lab Objective
No.
1
Department of Computer Science - Iqra University
Visual Programming Language Lab
Lab Details
Lab Marks
Lab Objective Signature
No. Obtained
2
Department of Computer Science - Iqra University
Visual Programming Language Lab
3
Department of Computer Science - Iqra University
Visual Programming Language Lab
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.
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.
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”.
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:
10
Department of Computer Science - Iqra University
Visual Programming Language Lab
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
Objective: To explore the different controls like CheckBox, RadioButton with a GroupBox,
NumericUpDown, DateTimePicker, ComboBox, and ListBox on Windows Forms.
13
Department of Computer Science - Iqra University
Visual Programming Language Lab
14
Department of Computer Science - Iqra University
Visual Programming Language Lab
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
16
Department of Computer Science - Iqra University
Visual Programming Language Lab
17
Department of Computer Science - Iqra University
Visual Programming Language Lab
Code Behind:
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);
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
Design:
Steps:
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();
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:
22
Department of Computer Science - Iqra University
Visual Programming Language Lab
Code Behind:
publicpartialclassForm1 : Form
{
public Form1()
{
InitializeComponent();
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);
}
}
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.
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:
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 ).
Code Behind:
publicpartialclassForm1 : Form
{
public Form1()
{
InitializeComponent();
}
26
Department of Computer Science - Iqra University
Visual Programming Language Lab
}
}
else
{
errorProvider1.Clear();
}
}
27
Department of Computer Science - Iqra University
Visual Programming Language Lab
28
Department of Computer Science - Iqra University
Visual Programming Language Lab
}
}
else
{
errorProvider1.Clear();
}
}
29
Department of Computer Science - Iqra University
Visual Programming Language Lab
}
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";
}
MessageBox.Show(data);
30
Department of Computer Science - Iqra University
Visual Programming Language Lab
}
}
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
Steps:
1. Establish SQL server connection by entering your server name and authentication.
32
Department of Computer Science - Iqra University
Visual Programming Language Lab
33
Department of Computer Science - Iqra University
Visual Programming Language Lab
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
37
Department of Computer Science - Iqra University
Visual Programming Language Lab
38
Department of Computer Science - Iqra University
Visual Programming Language Lab
39
Department of Computer Science - Iqra University
Visual Programming Language Lab
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
44
Department of Computer Science - Iqra University
Visual Programming Language Lab
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
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
49
Department of Computer Science - Iqra University
Visual Programming Language Lab
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
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:
52
Department of Computer Science - Iqra University
Visual Programming Language Lab
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
if (shouldErase)
{
Point mousePosition = e.GetPosition(paintCanvas);
PaintCircle(paintCanvas.Background, mousePosition);
}
}
55
Department of Computer Science - Iqra University
Visual Programming Language Lab
56
Department of Computer Science - Iqra University
Visual Programming Language Lab
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
Steps:
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">
58
Department of Computer Science - Iqra University
Visual Programming Language Lab
}
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:
59
Department of Computer Science - Iqra University
Visual Programming Language Lab
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);
}
}
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
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.
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;
cmbocourse.DataSource = courseinfo.ToList();
cmbocourse.DisplayMember = "coursename";
cmbocourse.ValueMember = "Id";
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
}
}
}
Add event handler on the delete button to delete record form the student table.
67
Department of Computer Science - Iqra University
Visual Programming Language Lab
References:
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
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
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
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
75
Department of Computer Science - Iqra University
Visual Programming Language Lab
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
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
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:
81
Department of Computer Science - Iqra University
Visual Programming Language Lab
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
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.
84
Department of Computer Science - Iqra University
Visual Programming Language Lab
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
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.
87
Department of Computer Science - Iqra University
Visual Programming Language Lab
88
Department of Computer Science - Iqra University
Visual Programming Language Lab
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.
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
Objective: To understand the Parallel Programming using PLINQ, task parallel library
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.
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.
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
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:
Practice Exercise:
Upgrade progress bar using TPL in windows forms.
94
Department of Computer Science - Iqra University
Visual Programming Language Lab
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
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
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
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.
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
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
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
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);
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.");
}
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"];
105
Department of Computer Science - Iqra University
Visual Programming Language Lab
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"/>
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;
References:
https://riptutorial.com/xamarin-forms
Practice Exercise:
Create tic-tac-toe game in Xamarin form
108
Department of Computer Science - Iqra University