0% found this document useful (0 votes)
28 views47 pages

6-1 Lab Manual - Visual Programmming

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
28 views47 pages

6-1 Lab Manual - Visual Programmming

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 47

LAB MANUAL

Visual Programming
Course Code: CSVP-368

DEPARTMENT OF COMPUTER SCIENCE


FACULTY OF ENGINEERING & COMPUTER SCIENCES

NATIONAL UNIVERSITY OF MODERN LANGUAGES


H-9, ISLAMABAD
PAKISTAN
Preface
The purpose of this course to provide the foundational knowledge of visual programming and skills
for event driven application building. Introduce the students to Graphical User Interfaces and
applications in a Windows as well as in Web environment. To enable them to plan, design,
construct, and integrate applications by using C#, ASP.Net and their frameworks.

Objective
• To acquaint students with better understanding of Visual Programing
• To familiarize students with C#, Asp.net Framework and MVC
• To equip students with hands-on experience of implementing Industrial Level projects in the field
of Desktop and Web.

Tools/ Technologies
Following tools and technologies will be used for implementing software programs in lab:

• Visual Studio IDE


• MySql
• SQL Server
• Xampp Server

Effectiveness
• Studetns analyzed fundamental concepts of visual programming for their mapping to real
life scenarios in Software Development.
• Read, write, execute, and debug C# Console and Windows Form applications
• Understand variables and data types
• Code decision and control structures (if, if/else, switch, while, do/while, for) and use
primitive data types and non-primitive data types. Write user-defined methods
• Manipulate Arrays from collection framework
• Write programs using object-oriented programming techniques including classes, objects,
inheritance, and polymorphism
• Use graphical user interface (GUI) components
• Understand C#’s Event Handling Model
• Write code to access and manipulate database
• Understaning of Web Developent in .net framework
• Modern echniques used with Asp.net code and Various databases
• Student designed solutions for implementing given problem in terms of an underlying
design pattern with associated visual tools for windows and web app development using dot
net framework.
• Students developed complete software solutions using learned techniques and tools that may
be deployed in the relevant organizations for routine operations.

2
WEEKLY BREAKDOWN

Task # Lab Work Description

• Create a child class and parent class for calculator and scientific Calc,
1 Create windows forms with Menus, buttons, etc.

• Create Account class with public and private variables and props,
2 Design Windows to get values and store in props and pass

• Develop an employee page to perform Insert and Search the records,


3 Design database in SQL server

• Develop properties, presentation layer in C sharp to get data from text


4 boxes and save in properties object for Employee.

• Develop a BLL and DAL using class library, Return from DAL to
5 presentation layer, Add references for namespaces
• Call functions in Application with Employee Form.
• Dynamic link libraries, Building Class Libraries, Using References
6 Using Data Set, Data Table and Data Adapter

• Designing Centralized Database operations using DbConn class


• Develop a MasterPage in ASP.net, Apply AJAX and provide the data to
7 web pages. Add pages in different Master Pages

• CREATE A STORED PROCEDURE AND EXECUTE IT IN SQL SERVER TO


PROOF RESULTS OF EXECUTION
8
• WRITE CODE BEHIND INSERT BUTTON TO CALL STORED PROCEDURE

• CREATE AN RDLC FILE, ADD TABLE AND SELECT COLUMNS, DESIGN


HEADER AND FOOTER OF REPORT.
9 • WRITE CODE BEHIND VIEW REPORT BUTTON TO DISPLAY LIST OF ALL
EMPLOYEES AND PRINT IT.

• Using Data Readers using Connection Oriented Approach


10 • Add functionality for Shopping Cart along with Add to Cart, View cart
and delete item
11
• Login and Signup using Web Form development

3
• Mange the User Access Level and design appropriate Master page and
webpages.
• Session Management and State Management
• CREATE A WCF SERVICE TO PROVIDE CURRECY CONVERSION AND
12 CALLING IT ON A WEB APPLICATION

• CREATE A LIST OF PROPERTIES AND FUNCTIONS IN MODEL, CREATE A


VIEW CLASS TO SHOW THE RESULTS
13 • CREATE CONTROLLER CLASS TO UTILISE MODEL AND VIEW, FINALLY
CREATE A WEB FORM TO UTILIZE MVC.

• CREATE TEXT FIELDS FOR MSG, CELL NUMBER AND A BUTTON TO


14 SEND SMS USING AT COMMANDS

• LINQ to Objects, LINQ to SQL, LINQ to DataSet


15 • LINQ to XML, JSON to connect with XML and JSON based Data, like in
Mongo DB etc.
• Entity Framework and its applicability,
16 • Introduction to Object relational mapping
• Model View Controller based web app development

4
Lab Task 1

Description:

Create a child class and parent class for calculator and scientific Calc, Create windows forms with Menus,
buttons, etc.

Solution:

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 CalculatorProject

public partial class frmCalculatort : Form

double val1, val2, result = 0, m =0;

int opt;

SimpleCalculator calc = new SimpleCalculator();

public Form1(){

InitializeComponent();

5
}

private void C_Click(object sender, EventArgs e){

txt.Text = "";

val1 = 0;

private void btnOne_Click(object sender, EventArgs e){

txt.Text = (txt.Text + 1);

private void btnTwo_Click(object sender, EventArgs e){

txt.Text = (txt.Text + 2);

// Same for 3 to 9 buttons

private void Equal_Click(object sender, EventArgs e)

val2 = Convert.ToDouble(txt.Text);

switch(opt)

case 1: result = calc.divide(val1,val2); break;

case 2: result = calc.multiplay(val1,val2); break;

case 3: result = calc.minus(val1,val2); break;

case 4: result = calc.add(val1,val2); break;

txt.Text = "" + result;

private void Back_Click(object sender, EventArgs e)

6
txt.Text = (txt.Text.Substring(0, txt.TextLength - 1));

private void Divide_Click(object sender, EventArgs e){

val1 = Convert.ToDouble(txt.Text);

opt = 1;

txt.Text = "";

private void Minus_Click(object sender, EventArgs e){

val1 = Convert.ToDouble(txt.Text);

opt = 3;

txt.Text = "";

private void Plus_Click(object sender, EventArgs e){

val1 = Convert.ToDouble(txt.Text);

opt = 4;

txt.Text = "";

private void Multiply_Click(object sender, EventArgs e){

val1 = Convert.ToDouble(txt.Text);

opt = 2;

txt.Text = "";

private void CE_Click(object sender, EventArgs e)

txt.Text = "";

7
}

private void Mplus_Click(object sender, EventArgs e)

m = m+Convert.ToDouble(txt.Text);

private void MR_Click(object sender, EventArgs e){

txt.Text = "" + m;

private void Mminis_Click(object sender, EventArgs e){

m = m - Convert.ToDouble(txt.Text);

txt.Text = "" + m;

private void MC_Click(object sender, EventArgs e){

m = 0;

private void PlusMin_Click(object sender, EventArgs e)

val1 = Convert.ToDouble(txt.Text );

val1 = val1*-1;

txt.Text = ""+val1;

8
Lab Task 2

Description:

Create Account class with public and private variables and props, Design Windows to get values and
store in props and pass

Solution:

// Done using visual features of tool

9
Lab Task 3

Description:

Develop an employee page to perform Insert and Search the records, Design database in SQL
server 2012.

Solution:

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

namespace ManagementSystem
{
public partial class Employee : Form
{
public Employee()
{
InitializeComponent();
}

10
private void Insert_Click(object sender, EventArgs e)
{
SqlConnection conn = new SqlConnection(@"Data
Source=(localdb)\v11.0;Initial Catalog=OfficeRecord;Integrated
Security=True");
SqlCommand cmd = new SqlCommand("Insert INTO
Employee VALUES(" + txtID.Text + ", '" + txtName.Text + "','" +
txtAddress.Text + "'," + txtCell.Text + ")", conn);
conn.Open();
cmd.ExecuteNonQuery();
conn.Close();
MessageBox.Show("Inserted Successfully");
}

private void Search_Click(object sender, EventArgs e)


{
SqlConnection sqlConn = new SqlConnection(@"Data
Source=(localdb)\v11.0;Initial Catalog= OfficeRecord;Integrated
Security=True");
String query = "select * from Employee where
empID='" + id.Text + "'";
SqlDataAdapter da = new SqlDataAdapter(query,
sqlConn);
DataSet ds = new DataSet();
da.Fill(ds, "Employee");
if (ds.Tables[0].Rows.Count > 0)
{
txtName.Text =
ds.Tables[0].Rows[0]["empName"].ToString();
txtAddress.Text =
ds.Tables[0].Rows[0]["empAddress"].ToString();
cell.Text =
ds.Tables[0].Rows[0]["Cell"].ToString();
}

11
else
{
MessageBox.Show("Record not found");
}

12
Lab Task 4

Description:

Develop properties, presentation layer in C sharp to get data from text boxes and save in
properties object.

Solution:

Properties Class

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Props
{
public class EmpProps
{

public EmpProps(){}
private int code;
public int Code
{
get { return code; }

13
set { code = value; }
}
private String name;
public String Name
{
get { return name; }
set { name = value; }
}
private String cellno;
public String Cellno
{
get { return cellno; }
set { cellno = value; }
}
private String address;
public String Address
{
get { return address; }
set { address = value; }
}
}}

Application Code

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;

14
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Props;
using Bll;

namespace Multilayermngmntsys
{
public partial class Employee : Form
{
public Employee()
{
InitializeComponent();
}

private void btnInsert_Click(object sender,


EventArgs e)
{
EmpProps p = new EmpProps();
p.Code = Convert.ToInt32(txtCode.Text);
p.Name = txtName.Text;
p.Cellno = txtCell.Text;
p.Address = txtAdrs.Text;

}
}
}

15
Lab Task 5

Description:

Develop a BLL and DAL using class library, Return from DAL to presentation layer, Add references
for namespaces

Solution:

Business Logic Layer(BLL)

using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Props;
using Dal;
using System.Data;

namespace Bll
{
public class EmpBll
{
public EmpBll(){ }

public bool insertBLL (EmpProps p1)


{

16
EmpDal Edal = new EmpDal();
return Edal.insertDAL(p1);
}
}
}

Data Access Layer (DAL)

using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Props;

namespace Dal
{
public class EmpDal
{
public EmpDal (){ }

public bool insertDAL(EmpProps p)


{
SqlConnection sqlConn = new
SqlConnection(@"Data Source=(localdb)\v11.0;Initial
Catalog=MyRecords;Integrated Security=True");
SqlCommand sqlComm = new SqlCommand("INSERT
INTO Employee VALUES (" + p.Code + ",'" + p.Name +
"','" + p.Cellno + "','" + p.Address + "')",
sqlConn);

17
sqlConn.Open();
int c1 = sqlComm.ExecuteNonQuery();
sqlConn.Close();
if ( c1 > 0 )
return true;
else
return false;
}
}
}

Application Code

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;
using Props;
using Bll;

namespace Multilayermngmntsys
{
public partial class Employee : Form
{
public Employee()

18
{
InitializeComponent();
}

private void btnInsert_Click(object sender,


EventArgs e)
{
EmpProps p = new EmpProps();
p.Code = Convert.ToInt32(txtCode.Text);
p.Name = txtName.Text;
p.Cellno = txtCell.Text;
p.Address = txtAdrs.Text;

EmpBll ebl = new EmpBll();


bool b = ebl.insertBLL(p);

if (b)
MessageBox.Show("Inserted
Successfully");
else
MessageBox.Show("Not inserted");
}
}
}

//Lab Task 6 is design based using Visual Studio 2013.

19
Lab Task 7
Description:

CREATE A STORED PROCEDURE AND EXECUTE IT IN SQL SERVER TO PROOF RESULTS OF


EXECUTION

WRITE CODE BEHIND INSERT BUTTON TO CALL STORED PROCEDURE

Solution:

private void btnInsert_Click(object sender, EventArgs e)


{
SqlConnection Conn = new SqlConnection(@"Data
Source=(localdb)\v11.0;Initial Catalog= OfficeRecords;Integrated
Security=True");
Conn.Open();
SqlCommand Cmd = new SqlCommand("dbo.empInsert",
Conn);
Cmd.CommandType = CommandType.StoredProcedure;

Cmd.Parameters.Add(new SqlParameter("@id",
txtID.Text));
Cmd.Parameters.Add(new
SqlParameter("@name",txtName.Text));
Cmd.Parameters.Add(new
SqlParameter("@address",txtAdrs.Text));
Cmd.Parameters.Add(new
SqlParameter("@cell",txtCell.Text));
Cmd.Parameters.Add(new
SqlParameter("@email",txtEmail.Text));

Cmd.ExecuteNonQuery();
MessageBox.Show("Inserted Successfully");

20
}

Stored Procedure at SQL Server

CREATE Procedure [dbo].[SP_empInsert]

@empCode int,
@empName VARCHAR(50),
@empCellNum VARCHAR(50),
@empAddress VARCHAR(50),
AS
INSERT INTO Employee values
(@empCode,@empName,@empCellNum,@empAddress)
return 0 //END

21
Lab Task 8

Description:

CREATE AN RDLC FILE, ADD TABLE AND SELECT COLUMNS, DESIGN HEADER AND FOOTER OF
REPORT. WRITE CODE BEHIND VIEW REPORT BUTTON TO DISPLAY LIST OF ALL EMPLOYEES AND
PRINT IT.

Solution:

public static string connectionString= @"Data Source=(localdb)\v11.0;Initial


Catalog=OfficeRecords;Integrated Security=True";

private SqlDataAdapter dataAdapter;

private DataSet dataSet;

private DataTable dataTable;

private static string id;

private static string name;

private static string address;

private static string cell;

private static string email;

public ViewReport()

InitializeComponent();

string commandstring = "select * from customer";

dataSet = new DataSet();

22
dataSet.CaseSensitive = true;

dataAdapter.Fill(dataSet, "customer");

dataTable = dataSet.Tables[0];

reportViewer1.Visible = true;

reportViewer1.LocalReport.ReportPath = "Report2.rdlc";

reportViewer1.LocalReport.DataSources.Clear();

reportViewer1.LocalReport.DataSources.Add(new ReportDataSource("DataSet1",
dataTable));

private void reportViewer1_Load(object sender, EventArgs e)

this.reportViewer1.RefreshReport();

23
Lab Task 9

Description:

Develop a Calculator Application for Windows 8 Desktop and mobile using XAML.

Solution:

<Page

x:Class="firstXamlApp.MainPage"

xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"

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

xmlns:local="using:firstXamlApp"

xmlns:d="http://schemas.microsoft.com/expression/blend/2008"

xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"

mc:Ignorable="d">

<Grid>

<Grid.Background>

<LinearGradientBrush EndPoint="0.5,1" StartPoint="0.5,0">

<GradientStop Color="Black" Offset="0"/>

<GradientStop Color="#FFDC6F6F" Offset="1"/>

</LinearGradientBrush>

</Grid.Background>

<Grid.RowDefinitions>

<RowDefinition Height="200"/>

<RowDefinition Height="Auto"/>

24
<RowDefinition Height="Auto"/>

<RowDefinition Height="*"/>

<RowDefinition Height="2*"/>

</Grid.RowDefinitions>

<Grid.ColumnDefinitions>

<ColumnDefinition Width="200"/>

<ColumnDefinition Width="200"/>

<ColumnDefinition Width="200"/>

<ColumnDefinition Width="200"/>

<ColumnDefinition Width="Auto"/>

<ColumnDefinition Width="*"/>

</Grid.ColumnDefinitions>

<TextBlock FontSize="22" HorizontalAlignment="Center" Margin="20,41,0,67" Width="180"


Foreground="#FF33B940">

<Run Text="hello"/>

<Run Text=" "/>

<Run Text=" world"/>

<Run Text=" "/>

<Run Text=" "/>

<Run Text="Application"/>

</TextBlock>

<Grid Grid.Row="2" Grid.Column="2" Height="250" Grid.ColumnSpan="2"


Margin="160,0,40,0">

<Grid.RowDefinitions>

<RowDefinition Height="50"/>

<RowDefinition Height="*"/>

25
</Grid.RowDefinitions>

<Grid.ColumnDefinitions>

<ColumnDefinition Width="100"/>

<ColumnDefinition Width="*"/>

</Grid.ColumnDefinitions>

<TextBlock FontSize="22" Margin="166,-179,-254,29" Grid.Column="1">

<Run Text="this is inner grid....."/>

<LineBreak/>

<Run Text="nested grid"/>

</TextBlock>

<TextBox PlaceholderText="Enter Second Value" Margin="-427,236,80,-94" Grid.Row="1"


Grid.ColumnSpan="2" Foreground="#FFA15AA4" FontSize="36" x:Name="txt22"
TextWrapping="Wrap" />

</Grid>

<StackPanel Margin="102,56,98,237" Grid.Column="1" Grid.ColumnSpan="2"


Grid.RowSpan="3">

<Image Source="Assets/aapng.png" Margin="206,0,-285,0"/>

<TextBlock HorizontalAlignment="Center" FontSize="22" Margin="50,0,47,0"


SelectionChanged="TextBlock_SelectionChanged" Height="89">

<Run Text="stackpanel"/>

<LineBreak/>

<Run/>

<LineBreak/>

<Run Text="Calculator"/>

<LineBreak/>

<Run/>

</TextBlock>

</StackPanel>

<Ellipse Grid.Column="1" Margin="5,28,0,130" Grid.ColumnSpan="2" Grid.Row="2">

<Ellipse.Fill>

26
<LinearGradientBrush EndPoint="1.0,0.5" StartPoint="2.0,0.5">

<GradientStop Color="#FFAC732F"></GradientStop>

</LinearGradientBrush>

</Ellipse.Fill>

</Ellipse>

<TextBlock FontSize="22" HorizontalAlignment="Center" Margin="10,32,10,76" Name="txt"


Width="180" Foreground="#FF33B940"/>

<TextBlock Name="txt2" ></TextBlock>

<Button Content="/" Height="50" Width="100" VerticalAlignment="Bottom"


Margin="49,0,0,98" Click="Button_ClickDIV" RenderTransformOrigin="0.97,2.78" Grid.Column="3"
Grid.Row="4" Background="#FF42538F" FontSize="24"/>

<Button Content="*" Height="50" Width="100" VerticalAlignment="Bottom"


Margin="47,0,0,98" Click="Button_ClickMUL" RenderTransformOrigin="0.97,2.78"
Grid.Column="2" Grid.Row="4" Background="#FF4C5E9C" FontSize="24"/>

<Button Content="-" Height="50" Width="100" VerticalAlignment="Bottom"


Margin="48,0,0,98" Click="Button_ClickMIN" RenderTransformOrigin="0.97,2.78"
Grid.Column="1" Grid.Row="4" Background="#FF3D5091" FontSize="24"/>

<Button Content="+" Height="50" Width="100" VerticalAlignment="Bottom"


Margin="68,0,0,98" Click="Button_ClickPUL" RenderTransformOrigin="0.97,2.78" Grid.Row="4"
Background="#FF44599E" FontSize="24"/>

<TextBox PlaceholderText="Enter First Value" Margin="131,166,122,34"


Grid.ColumnSpan="4" Grid.Row="2" Foreground="#FFBA71BD" FontSize="36" x:Name="txt11"/>

</Grid>

</Page>

27
Lab Task 10

Description:

SALES FORM, LOAD PRODUCT ON COMBO, BTN SHOW STOCK AND SELL PRODUCT.

Solution:

protected void btnShow (object sender, EventArgs e)

SqlConnection conn2 = new SqlConnection(@"Data Source=(localdb)\v11.0;Initial


Catalog=OfficeRecords;Integrated Security=True");

String query = "select * from Product WHERE id ='" + cmbProduct.SelectedItem.


Value.ToString()+"' ";

SqlDataAdapter dataAdapter = new SqlDataAdapter(query, conn2);

DataSet dataSet = new DataSet();

dataAdapter.Fill(dataSet, "Product");

if (dataSet.Tables[0].Rows.Count >= 0)

txtStock.Text = ""+Convert.ToInt32(dataSet.Tables[0].Rows[0]["prdStock"]);

txtPrice.Text = "" + Convert.ToInt32(dataSet.Tables[0].Rows[0]["prdPrice"]);

protected void btnSales_Click(object sender, EventArgs e)

28
int a = 0;

SqlConnection conn = new SqlConnection(@"Data Source=(localdb)\v11.0;Initial


Catalog=OfficRecords;Integrated Security=True");

double qty = Convert.ToDouble(txtQty.Text);

double stock = Convert.ToDouble(txtStock.Text);

double new_stock = stock – qty;

SqlCommand cmd = new SqlCommand("Update Product set prdStock=" + new_stock +


",total=" where id="+txtid.Text+" " , conn);

conn.Open();

cmd.ExecuteNonQuery();

SqlCommand cmd1 = new SqlCommand("Insert INTO Sales Values(" + txtid.Text + ",'" +


cmbProduct.Text + "'," + txtPrice.Text + "," + txtQty.Text + ")", conn);

cmd1.ExecuteNonQuery();

conn.Close();

29
Lab Task 11

Using LINQ to Objects in C#

A simple SELECT query in Linq

static void Main(string[] args)

string[] cars = { "VW Golf",

"Opel Astra",

"Audi A4",

"Ford Focus",

"Seat Leon",

"VW Passat",

"VW Polo",

"Mercedes C-Class" };

var list = from car in cars

select car;

StringBuilder sb = new StringBuilder();

foreach (string entry in list)

sb.Append(entry + "\n");

Console.WriteLine(sb.ToString());

30
Console.ReadLine();

In the example above, an array of strings (cars) is used as a collection of objects to be queried using LINQ.

In a LINQ query, the from clause comes first in order to introduce the data source (cars) and the range
variable (car).

When the query is executed, the range variable will serve as a reference to each successive element in cars.

Because the compiler can infer the type of car, you do not have to specify it explicitly

________________________________________________________________________________________
______________________

SELECT with a WHERE Clause

var list = from car in cars

where car.Contains("VW")

select car;

The WHERE clause is used to query the string array (cars) to find and return a subset of array which satisfies
the WHERE clause.

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

Generating an Ordered List

var list = from car in cars

orderby car ascending

select car;

Sometimes it is useful to sort the returned data.

The orderby clause will cause the elements to be sorted according to the default comparer for the type
being sorted.

31
-------------------------------------------------------------------------------------------

Working with a custom type

In this example, a typed list is created, populated, and then queried

public class Car

public String Name { get; private set; }

public int UnitsSold { get; private set; }

public Car(string name, int unitsSold)

Name = name;

UnitsSold = unitsSold;

class Program

static void Main(string[] args)

var car1 = new Car("VW Golf", 270952);

var car2 = new Car("Opel Astra", 56079);

var car3 = new Car("Audi A4", 52493);

var car4 = new Car("Ford Focus", 51677);

var car5 = new Car("Seat Leon", 42125);

var car6 = new Car("VW Passat", 97586);

32
var car7 = new Car("VW Polo", 69867);

var car8 = new Car("Mercedes C-Class", 67549);

var cars = new List<Car> {

car1, car2, car3, car4, car5, car6, car7, car8 };

var list = from car in cars

select car.Name;

foreach (var entry in list)

Console.WriteLine(entry);

Console.ReadLine();

33
Lab Task 12

USE [DBName]

GO

/****** Object: StoredProcedure [dbo].[EmpSearch] Script Date: 13-Mar-17 6:19:35 PM ******/

SET ANSI_NULLS ON

GO

SET QUOTED_IDENTIFIER ON

GO

-- =============================================

-- Author: Name

-- Create date:

-- Description:

-- =============================================

ALTER PROCEDURE [dbo].[EmpSearch]

-- Add the parameters for the stored procedure here

@EmpCode nvarchar = Null

AS

BEGIN

-- SET NOCOUNT ON added to prevent extra result sets from

-- interfering with SELECT statements.

SET NOCOUNT ON;

34
-- Insert statements for procedure here

SELECT Emp_id, Name, Cell_num, Address from Emp_detail where Emp_id=@EmpCode;

return;

END

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

USE [DBName]

GO

/****** Object: StoredProcedure [dbo].[SP_empInsert] Script Date: 13-Mar-17 6:20:46 PM ******/

SET ANSI_NULLS ON

GO

SET QUOTED_IDENTIFIER ON

GO

-- =============================================

-- Author: Fariha

-- Create date: 3-10-2015

-- Description: Returns Employee Data

-- =============================================

ALTER PROCEDURE [dbo].[SP_empInsert] (

-- Add the parameters for the stored procedure here

@empCode nvarchar(50) = Null,

@empName nvarchar(50) = Null,

@empCellNum VARCHAR(50)= Null,

@empAddress VARCHAR(50)= Null)

35
AS

BEGIN

-- SET NOCOUNT ON added to prevent extra result sets from

-- interfering with SELECT statements.

SET NOCOUNT OFF;

-- Insert statements for procedure here

INSERT INTO Emp_detail values (@empCode,@empName,@empCellNum,@empAddress)

return 0;

END

________________________________________________________________________________________
____________________________________________________________________________________

USE [DBName]

GO

/****** Object: StoredProcedure [dbo].[empDelete] Script Date: 13-Mar-17 6:21:30 PM ******/

SET ANSI_NULLS ON

GO

SET QUOTED_IDENTIFIER ON

GO

-- =============================================

-- Author: <Author,,Name>

-- Create date: <Create Date,,>

36
-- Description: <Description,,>

-- =============================================

ALTER PROCEDURE [dbo].[empDelete]

-- Add the parameters for the stored procedure here

@id nvarchar(50)=null

AS

BEGIN

-- SET NOCOUNT ON added to prevent extra result sets from

-- interfering with SELECT statements.

SET NOCOUNT off;

-- Insert statements for procedure here

Delete from Emp_detail where Emp_id=@id;

END

________________________________________________________________________________________
________________________________________________________________________________________
__

37
Lab Task 13

Develop a BLL and DAL using class library, Return from DAL to presentation layer, Add references for
namespaces

Solution:

Business Logic Layer(BLL)

using System;

using System.Collections.Generic;

using System.Data.SqlClient;

using System.Linq;

using System.Text;

using System.Threading.Tasks;

using Props;

using Dal;

using System.Data;

namespace Bll

public class EmpBll

public EmpBll(){ }

38
public bool insertBLL (EmpProps p1)

EmpDal Edal = new EmpDal();

return Edal.insertDAL(p1);

Data Access Layer (DAL)

using System;

using System.Collections.Generic;

using System.Data;

using System.Data.SqlClient;

using System.Linq;

using System.Text;

using System.Threading.Tasks;

using Props;

namespace Dal

public class EmpDal

public EmpDal (){ }

public bool insertDAL(EmpProps p)

SqlConnection sqlConn = new SqlConnection(@"Data Source=(localdb)\v11.0;Initial


Catalog=MyRecords;Integrated Security=True");

39
SqlCommand sqlComm = new SqlCommand("INSERT INTO Employee VALUES (" + p.Code + ",'" +
p.Name + "','" + p.Cellno + "','" + p.Address + "')", sqlConn);

sqlConn.Open();

int c1 = sqlComm.ExecuteNonQuery();

sqlConn.Close();

if ( c1 > 0 )

return true;

else

return false;

Application Code

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;

using Props;

using Bll;

namespace Multilayermngmntsys

40
public partial class Employee : Form

public Employee()

InitializeComponent();

private void btnInsert_Click(object sender, EventArgs e)

EmpProps p = new EmpProps();

p.Code = Convert.ToInt32(txtCode.Text);

p.Name = txtName.Text;

p.Cellno = txtCell.Text;

p.Address = txtAdrs.Text;

EmpBll ebl = new EmpBll();

bool b = ebl.insertBLL(p);

if (b)

MessageBox.Show("Inserted Successfully");

else

MessageBox.Show("Not inserted");

Lab Task 14

41
using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

using System.Web.UI;

using System.Web.UI.WebControls;

using System.Xml.Linq;

namespace LINQ

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

XDocument xml;

public void BindGrid()

// XDocument.Load(Server.MapPath("~XMLFile1.xml"));

xml = XDocument.Load(Server.MapPath("~/XMLFile1.xml"));

var bind = xml.Descendants("Employee").Select(p => new

ID = p.Element("id").Value,

Name = p.Element("name").Value,

Cell = p.Element("cell").Value,

Salary = p.Element("salary").Value

}).OrderBy(p => p.ID);

EmployeeGrid.DataSource = bind;

EmployeeGrid.DataBind();

42
protected void Page_Load(object sender, EventArgs e)

BindGrid();

protected void Button1_Click(object sender, EventArgs e)

XElement emp = new XElement("Employee",

new XElement("id", txtID.Text),

new XElement("name", txtName.Text),

new XElement("cell", txtCell.Text),

new XElement("salary", txtSalary.Text));

xml.Root.Add(emp);

xml.Save(Server.MapPath("~/XMLFile1.xml"));

BindGrid();

protected void btnEdit_Click(object sender, EventArgs e)

XElement emp = xml.Descendants("Employee").FirstOrDefault(p => p.Element("id").Value ==


txtID.Text);

if (emp != null)

emp.Element("name").Value = txtName.Text;

emp.Element("cell").Value = txtCell.Text;

emp.Element("salary").Value = txtSalary.Text;

xml.Save(Server.MapPath("~/XMLFile.xml"));

BindGrid();

43
}

protected void btnDelete_Click(object sender, EventArgs e)

XElement emp = xml.Descendants("Employee").FirstOrDefault(p => p.Element("id").Value ==


txtID.Text);

if (emp != null)

emp.Remove();

xml.Save(Server.MapPath("~/XMLFile.xml"));

BindGrid();

protected void btnSearch_Click(object sender, EventArgs e)

XElement emp = xml.Descendants("Employee").FirstOrDefault(p => p.Element("id").Value ==


txtID.Text);

if (emp != null)

txtName.Text = emp.Element("name").Value;

txtCell.Text = emp.Element("cell").Value;

txtSalary.Text = emp.Element("salary").Value;

protected void btnViewAll_Click(object sender, EventArgs e)

BindGrid();

44
}

protected void btnClear_Click(object sender, EventArgs e)

txtID.Text = "";

txtName.Text = "";

txtCell.Text = "";

txtSalary.Text = "";

Lab Task 16

public string ConvertDataTabletoString()

DataTable dt = new DataTable();

using (SqlConnection con = new SqlConnection("Data Source=SureshDasari;Initial


Catalog=master;Integrated Security=true"))

45
using (SqlCommand cmd = new SqlCommand("select title=City,lat=latitude,lng=longitude,description
from LocationDetails", con))

con.Open();

SqlDataAdapter da = new SqlDataAdapter(cmd);

da.Fill(dt);

System.Web.Script.Serialization.JavaScriptSerializer serializer = new


System.Web.Script.Serialization.JavaScriptSerializer();

List<Dictionary<string, object>> rows = new List<Dictionary<string, object>>();

Dictionary<string, object> row;

foreach (DataRow dr in dt.Rows)

row = new Dictionary<string, object>();

foreach (DataColumn col in dt.Columns)

row.Add(col.ColumnName, dr[col]);

rows.Add(row);

return serializer.Serialize(rows);

Using Newtonsoft Json.NET

46
string JSONresult;

JSONresult = JsonConvert.SerializeObject(dt);

Response.Write(JSONresult);

47

You might also like