You are on page 1of 377

LEARN .

NET WITH
PROGRAMMING
( 3-in-1 )
Covers .NET using C#, Visual Basic
ASP.NET

For B.Tech, B.Sc and M.Sc. CS, BCA, MCA, Diploma


and other computer related professional courses
for latest syllabus of all Universities.
LEARN .NET WITH
PROGRAMMING

DR. S.H. ABBAS


ER. RAHUL RANJAN

SHRIHIND PUBLICATIONS
SHRIHIND PUBLICATIONS
Registered Office
310, 3rd Floor, Patidar Tower, Freeganj
Ujjain (M.P.) 456010
Phone No. 0734 3554812
Corporate Office
310, 3rd Floor, Patidar Tower, Freeganj
Ujjain (M.P.) 456010
Distribution Center
Ahmedabad, Hyderabad, Bengaluru, Pune, Jabalpur,
Badodara, Bhopal, Indore, Chennai, Kolkata, Mumbai.
website : www.shrihindpublications.com
Email: shrihindpublications@gmail.com
Copyright Dr. S.H.Abbas
Er. Rahul Ranjan
1st Edition published in English as Learn .Net With
Programming by Dr. S.H.Abbas and Er. Rahul Ranjan
Out in the year 2022 by SHRIHIND PUBLICATIONS.
ISBN - 978-93-92759-74-1
Printed & Bound in India
All rights reserved. No part of this publication may be
reproduced in any form or by any means without the prior
written permission of the publishers
ABOUT PUBLISHER

SHRIHIND PUBLICATIONS PVT. LTD. is an ambitious


publishing firm as well as an association of various newly
emerging writers. we believe in giving a chance to those
writers who have great literary skills, but due to some or
other reasons, couldn’t get their “Piece of Art” published.
Through our different projects we encourage a writer to let
his/her intellectual hidden treasure be expressed in the form
of writing and gets the required appreciation for his/her writing
expertise.
Be it a book or a poem or a short story or a drama or even
an article, which is of immense proficiency, is always being
applauded by SHRIHIND PUBLICATIONS and we get it
published, as one of our motive is to bring in the limelight
the commendable literary work of those concealed talents,
who have the capability to be wonderful authors and so they
must be cherished for their praise worthy flair for literature
and writing.
So, “ Let your Creativity Thrives With Excellence” by being a
part of SHRIHIND PUBLICATIONS.
Email : shrihindpublications@gmail.com
Web: www.shrihindpublications.com
PREFACE

The present book entitled “Learn .NET with


Programming, ( 3-in-1 ) has been designed so as to cover
the chapter-wise syllabus of Diploma/O-
Level/btech/BCA/MCA of all Indian Universities. The
book is dedicated to the description of the latest trends
and happening in .NET. This book covers the basic
programming fundamentals, professional programming
logics and deep concepts of programming in .NET such as
the flow control statements in C# and Visual Basic, the
basic programming techniques, procedures and
procedural programming concepts. This book provides
fresh and relevant content to .NET Core in a succinct
format that is enjoyable to read. It also delivers concepts,
along with the implications, design decisions, and
potential pitfalls.

This book is divided into four chapters.

Chapter 1: Which provides an overview of the language


and the .NET platform. The first chapters deals with .
NET basics.

Chapte 2: Introduces you to the C# language and the


.NET platform.

Chapter 3: Describes that Libraries and .Net Advance


Features also.

1
Chapter 4: Covers Windows and Website Development.
ASP.NET is the successor to “classic” ASP technology, the
world’s leading web development tool. ASP.NET solves
many of the problems associated with ASP and provides
an integrated and consistent approach to software
development that builds on the libraries and languages
of the .NET platform.

In this book concepts, command and syntax are


explained in a simple language with a lot of Example:s.
This will enable the students to gain basic as well as in-
depth knowledge about the subject. The chapters have
been written by various experts in the field. We believe
that this book is well suited to self-learning. The concise
and sequential nature of the book makes it easier to
learn. Although we have made all efforts to make the text
error free, yet errors may remain in the text. We shall be
thankful to the students and teachers alike if they point
these out to us. Any further comments and suggestions
for future improvement are welcome and will be most
gratefully acknowledged.

By the end of the book, you will have built five solid
projects using all the tools and support provided by the
.NET Core 2.0 framework.

Authors

2
CONTENTS
INTRODUCTION TO .NET FRAMEWORK
1.1 Common Language Runtime (CLR) .............................. 9
1.2 .NET Components............................................................... 13
1.3 .Net Framework Design Principle ............................... 17
1.4 Features of .NET Framework ........................................ 20
1.5 Architecture of .NET Framework ................................ 25
1.6 Garbage collection ............................................................. 31

C# BASICS
2.1 What is C#? ........................................................................... 33
2.1.1 Why Use C#? ................................................................ 33
2.1.2 C# Install ....................................................................... 34
2.2 Example: explained ........................................................... 38
2.3 writeline or Write .............................................................. 39
2.4 C# Comments...................................................................... 40
2.4.1 Single-line Comments .............................................. 40
2.4.2 C# Multi-line Comments ......................................... 41
2.5 C# Variables ......................................................................... 41
2.6 Constants ............................................................................... 43
2.7 Declare Many Variables ................................................... 44
2.8 C# Identifiers ....................................................................... 45
3
2.9 C# Data Types ...................................................................... 46
2.10 C# Type Casting ............................................................... 50
2.11 Type Conversion Methods ........................................... 52
2.12 C# Operators ..................................................................... 55
2.13 C# Conditions and If Statements ............................... 64
2.13.1 The if Statement....................................................... 65
2.13.2 The else Statement ................................................ 66
2.13.3 The else if Statement ............................................. 67
2.14 Loops .................................................................................... 72
2.14.1 C# While Loop .......................................................... 72
2.14.2 The Do/While Loop ................................................ 73
2.14.3 C# For Loop ............................................................... 74
2.14.4 The foreach Loop .................................................... 75
2.15 C# Break .............................................................................. 76
2.16 C# Continue ....................................................................... 77
2.17 Break and Continue in While Loop .......................... 77
2.18 C# Arrays ............................................................................ 78
2.18.1 Loop Through an Array ........................................ 80
2.19 C# Methods ........................................................................ 83
2.20 Parameters and Arguments ........................................ 85
2.21 Method Overloading ....................................................... 89
2.22 C# - What is OOP?............................................................ 91
2.22 Access Modifiers ........................................................... 100
4
2.23 Properties and Encapsulation ................................. 102
2.24 Inheritance (Derived and Base Class) .................. 104
2.25 Abstract Classes and Methods................................. 106
2.26 Interfaces ......................................................................... 108

C# LIBRARIES AND .NET ADVANCE FEATURES


3.1 Input output (Streams Classes) ................................. 113
3.2 C# - Multithreading ........................................................ 116
3.3 Thread Life Cycle ............................................................. 116
3.4 Creating Threads ............................................................. 119
3.5 Managing Console I/O Operations ........................... 122
3.6 .NET Assemblies .............................................................. 134
3.7 Global ASAX Files ............................................................ 138
3.8 State management: Session Object .......................... 140
3.9 Cookie .................................................................................. 145
3.10 Hidden Field ................................................................... 146
3.11 What is viewstate C#?................................................. 154
3.12 ASP.NET Cookie............................................................. 155
3.13 Cross Page Posting In ASP.NET ............................... 162
3.14 Web Configuration and Machine Configuration
Files .............................................................................................. 165

WINDOWS AND WEBSITE DEVELOPMENT


4.1 Windows Forms Basics in C# ..................................... 166

5
4.1.1 C# Hello World ........................................................ 167
4.1.2 Adding Controls to a form ................................... 175
4.1.3 Group Box .................................................................. 175
4.1.4 Label Control ............................................................ 178
4.1.5 Textbox ....................................................................... 181
4.1.6 List box ........................................................................ 183
4.1.7 radiobutton ............................................................... 185
4.1.8 Checkbox .................................................................... 188
4.1.9 Button .......................................................................... 190
4.2 C# Event Handling for Controls ................................ 192
4.3 Tree and picturebox Control ...................................... 197
4.3.1 picturebox Control ................................................. 201
4.4 Web Services ..................................................................... 203
4.5 ADO.NET Architecture .................................................. 204
4.5.1 C# Database Connection: How to connect SQL
Server (Example:) .............................................................. 208
4.6 SQL Command in c# ....................................................... 210
4.7 Distributed Applications .............................................. 250
4.7.1 Evolution of Distributed Applications............ 251
4.8 What is Globalization?................................................... 254
4.9 Authentication in ASP.NET.......................................... 258

6
PROGRAMS/PROJECTS
PROGRAM 1 .............................................................................. 274
PROGRAM 2 .............................................................................. 277
PROGRAM 3 .............................................................................. 279
PROGRAM 4 .............................................................................. 281
PROGRAM 5 .............................................................................. 283
PROGRAM 6 .............................................................................. 286
PROGRAM 7 .............................................................................. 292
PROGRAM 8 .............................................................................. 295
PROGRAM 9 .............................................................................. 298
PROGRAM 10 ............................................................................ 309
PROGRAM 11 ............................................................................ 312
PROGRAM 12 ............................................................................ 317
PROGRAM 13 ............................................................................ 330

7
CHAPTER 1

INTRODUCTION TO .NET
FRAMEWORK
.NET is a software framework which is designed and
developed by Microsoft. The first version of the .Net
framework was 1.0 which came in the year 2002. In easy
words, it is a virtual machine for compiling and executing
programs written in different languages like C#, VB.Net
etc. It is used to develop Form-based applications, Web-
based applications, and Web services. There is a variety
of programming languages available on the .Net platform,
VB.Net and C# being the most common ones. It is used to
build applications for Windows, phone, web, etc. It
provides a lot of functionalities and also supports
industry standards..NET Framework supports more than
60 programming languages in which 11 programming
languages are designed and developed by Microsoft. The
remaining Non-Microsoft Languages which are
supported by .NET Framework but not designed and
developed by Microsoft.

1.1 Common Language Runtime (CLR): CLR is the basic


and Virtual Machine component of the NET Framework.
It is the run-time environment in the .NET Framework
that runs the codes and helps in making the development
process easier by providing the various services such as

9
remoting, thread management, type-safety, memory
management, robustness, etc. Basically, it is responsible
for managing the execution of .NET programs regardless
of any .NET programming language. It also helps in the
management of code, as code that targets the runtime is
known as the Managed Code and code doesn’t target to
runtime is known as Unmanaged code. Framework Class
Library(FCL): It is the collection of reusable, object-
oriented class libraries and methods, etc that can be
integrated with CLR. Also called the Assemblies. It is just
like the header files in C/C++ and packages in the java.
Installing .NET framework basically is the installation of
CLR and FCL into the system. Below is the overview of
.NET Framework.

Is .NET application platform dependent or platform


independent?

10
Figure 1.1 Framework

The combination of Operating System Architecture and


CPU Architecture is known as the platform. Platform
dependent means the programming language code will
run only on particular Operating System. A .NET
application is platform dependent because of the .NET
framework which is only able to run on the Windows-
based operating system. The .Net application is platform
independent also because of Mono framework. Using
Mono framework the .Net application can run on any
Operating System including windows. Mono framework
is a third party software developed by Novell Company
which is now a part of Micro Focus Company. It is a paid
framework. Event-driven programming focuses on
events. Eventually, the flow of program depends upon
events. Until now, we were dealing with either sequential
or parallel execution model but the model having the
concept of event-driven programming is called
asynchronous model. Event- driven programming
depends upon an event loop that is always listening for
the new incoming events. The working of event-driven
programming is dependent upon events. Once an event
loops, then events decide what to execute and in what
order. Following flowchart will help you understand how
this works:

11
Figure 1.2. .Net Architecture

The basic architecture of the .Net framework is as shown


below:

12
1.2 .NET Components

The architecture of the .Net framework is based on the


following key components;

1. Common Language Runtime

The "Common Language Infrastructure" or CLI is a


platform on which the .Net programs are executed.

The CLR has the following key features:

Exception Handling - Exceptions are errors which occur


when the application is executed. Example:s of
exceptions are:

 If an application tries to open a file on the local


machine, but the file is not present.

 If the application tries to fetch some records from


a database, but the connection to the database is
not valid.

 Garbage Collection - Garbage collection is the


process of removing unwanted resources when
they are no longer required.

 Example:s of garbage collection are A File handle


which is no longer required. If the application has
finished all operations on a file, then the file
handle may no longer be required.

13
 The database connection is no longer required. If
the application has finished all operations on a
database, then the database connection may no
longer be required.

Working with Various programming languages –

As noted in an earlier section, a developer can develop an


application in a variety of .Net programming languages.

Language - The first level is the programming language


itself, the most common ones are VB.Net and C#.

Compiler – There is a compiler which will be separate


for each programming language. So underlying the
VB.Net language, there will be a separate VB.Net
compiler. Similarly, for C#, you will have another
compiler.

Common Language Interpreter – This is the final layer


in .Net which would be used to run a .net program
developed in any programming language. So the
subsequent compiler will send the program to the CLI
layer to run the .Net application.

14
1. Class Library

The .NET Framework includes a set of standard class


libraries. A class library is a collection of methods and
functions that can be used for the core purpose. For
Example:, there is a class library with methods to handle
all file-level operations. So there is a method which can
be used to read the text from a file. Similarly, there is a
method to write text to a file.

Most of the methods are split into either the System.* or


Microsoft.* namespaces. (The asterisk * just means a
reference to all of the methods that fall under the System
or Microsoft namespace). A namespace is a logical
separation of methods. We will learn these namespaces
more in detail in the subsequent chapters.
15
2. Languages

The types of applications that can be built in the .Net


framework is classified broadly into the following
categories.

Winforms – This is used for developing Forms-based


applications, which would run on an end user machine.
Notepad is an Example: of a client-based application.

ASP.Net – This is used for developing web-based


applications, which are made to run on any browser such
as Internet Explorer, Chrome or Firefox.

The Web application would be processed on a server,


which would have Internet Information Services
Installed.

Internet Information Services or IIS is a Microsoft


component which is used to execute an Asp.Net
application.The result of the execution is then sent to the
client machines, and the output is shown in the browse
ADO.Net – This technology is used to develop
applications to interact with Databases such as Oracle or
Microsoft SQL Server.

Microsoft always ensures that .Net frameworks are in


compliance with all the supported Windows operating
systems.

16
1.3 .Net Framework Design Principle

The following design principles of the .Net framework


are what make it very relevant to create .Net based
applications:

Interoperability - The .Net framework provides a lot of


backward support. Suppose if you had an application
built on an older version of the .Net framework, say 2.0.
And if you tried to run the same application on a machine
which had the higher version of the .Net framework, say
3.5. The application would still work. This is because
with every release, Microsoft ensures that older
framework versions gel well with the latest version.

Portability- Applications built on the .Net framework


can be made to work on any Windows platform. And now
in recent times, Microsoft is also envisioning to make
Microsoft products work on other platforms, such as ios
and Linux.

Security - The .NET Framework has a good security


mechanism. The inbuilt security mechanism helps in
both validation and verification of applications. Every
application can explicitly define their security
mechanism. Each security mechanism is used to grant
the user access to the code or to the running program.

Memory management - The Common Language


runtime does all the work or memory management. The
.Net framework has all the capability to see those
resources, which are not used by a running program. It
17
would then release those resources accordingly. This is
done via a program called the "Garbage Collector" which
runs as part of the .Net framework.

The garbage collector runs at regular intervals and keeps


on checking which system resources are not utilized, and
frees them accordingly.

Simplified deployment - The .Net framework also have


tools, which can be used to package applications built on
the .Net framework. These packages can then be
distributed to client machines. The packages would then
automatically install the application.

In this chapter, we will understand the execution process


of .NET Core and compare it with the .NET Framework.
The managed execution process includes the following
steps.

• Choosing a compiler
• Compiling your code to MSIL
• Compiling MSIL to native code
• Running code

18
Figure 1.3 FCL

Choosing a Compiler

• It is a multi-language execution environment, the


runtime supports a wide variety of data types and
language features.
• To obtain the benefits provided by the common
language runtime, you must use one or more
language compilers that target the runtime.

Compiling your code to MSIL

• Compiling translates your source code into


Microsoft Intermediate Language (MSIL) and
generates the required metadata.
• Metadata describes the types in your code,
including the definition of each type, the signatures
of each type's members, the members that your

19
code references, and other data that the runtime
uses at execution time.
• The runtime locates and extracts the metadata
from the file as well as from framework class
libraries (FCL) as needed during execution.

Compiling MSIL to Native Code

At execution time, a just-in-time (JIT) compiler translates


the MSIL into native code. During this compilation, code
must pass a verification process that examines the MSIL
and metadata to find out whether the code can be
determined to be type safe.

Running Code

The common language runtime provides the


infrastructure that enables the execution to take place
and services that can be used during execution. During
execution, managed code receives services such as
garbage collection, security, interoperability with
unmanaged code, cross-language debugging support, and
enhanced deployment.

1.4 Features of .NET Framework

• Common Language Runtime (CLR)


• .NET Framework Class Library (FCL)
• Interoperability
• Common Type System (CTS)
• Asynchronous Programming
• Portability
20
• High Performance
• Memory Management
• Security
• IDE (integrated Development Environment)

It is a software application that provides comprehensive


facilities to computer programmers for software
development.In general IDE is a graphical user interface
based workbench which helps the developer in building
software applications by providing tools like a source
code editor; build automation tools, a debugger etc. In
the context of .NET based applications, visual studio is
the most commonly used IDE.

VS.Net is just an editor, provided by Microsoft to help


developers to write .NET programs easily.VS.Net
provides:

1. Editor which automatically generate lot of code.


2. Allow developers to drag and drop control to a
form.
3. Provide shortcuts to compile and build the
application etc.

Event driven programming

• Changing the state of an object is known as an


event. For Example: click on button, dragging
mouse etc. Event handling is the mechanism that
controls the event and decides what should happen
if an event occurs.

21
• Event driven programming is a paradigm in which
the flow of the program is determined by events
(mouse clicks, key presses), sensor outputs, or
messages from other programs/threads.

• In in fig a simple event driven programming


paradigm where each and every event go through a
scheduler. Scheduler passes the code written
inside the events to a particular event handler.

VB.net support event driven programming by following


ways:

• A Visual studio IDE provides toolbox which is a


window that gives us access to all controls,
components, etc. User can easily drag and drop
controls or tools on forms.

• A Visual studio IDE also provides editor which


automatically generates codes for different events
like click or press events. The programmer
therefore concentrate on issues such as interface
design, which involves adding controls such as
command buttons, text boxes, and labels to
standard forms

• Once the user interface is substantially complete,


the programmer can add event-handling code to
each control as required.

• Each event-handler is usually bound to a specific


object or control on a form. Any additional
22
subroutines, methods, or function procedures
required are usually placed in a separate code
module, and can be called from other parts of the
program as and when needed.

An assembly is a collection of types and resources that


are built to work together and form a logical unit of
functionality.

Manifest:

Manifest is the most important part of an Assembly.


Manifest contains useful information, about an assembly
which makes an assembly: self-describing,

The specifications in an assembly are collectively


referred to as the assembly’s the manifest contains:

1. The name of the assembly.


2. Version information for the assembly.
3. Security information for the assembly.
4. A list of all files that are part of the assembly.
5. Type reference information for the types specified
in the assembly.
6. A list of other assemblies that are referenced by
the assembly.

System Namespaces:

• Namespace plays a fundamental role in the .Net


framework. You cannot build a vb.net application

23
without using classes from the .net system
namespace.
• The .net framework class library consists of several
thousand classes and other types, (such as
interfaces, structures and enumerations) that are
divided into several namespaces

Most commonly used namespaces are as follows:

System.Data:

• System.Data and its nested namespaces, notably


system.Data.oledb and system.data.sqlclient
provide data access using ADO.NET
• The oledb and sqlclient namespaces are
responsible for defining data providers that can
connect to a data source retrieve data from a data
source, write data back to a data source and
execute commands against the data source.
• ADO.net is an entirely new model for data access
that is based on the disconnected dataset.

System.IO:

The system.IO namespace contains classes that provide a


variety of input/output functionality, such as

• Manipulating directories and files


• Monitoring changes in directories and files
• Reading and writing single bytes, multi byte blocks
or characters to and from streams.
• Reading and writing characters to and from strings
24
System.Text.regularexpressions:

• The system.Text.regularexpressions namespace


contains classes that provide access to the .NET
frameworks regular expression engine.
• In its simplest form a regular expression is a text
string that represents a pattern that other strings
may or may not match.

System.windows.forms:

• This namespace is the mother of all namespaces


and is used for creating windows applications.
• The system.Window.Forms namesqace contains
classes for creating windows based applications
that take full advantage of the rich user interface
features available in the Microsoft windows
operating system.
• In this namespace you will find the form class and
many other controls that can be added to forms to
create user interfaces.
• In fact each new form added to a vb.net Project
contains the following line: Imports
System.Window.Forms
• Fortunately visual studio provides the functionality
of the system.window.forms namespace to us as vb
programmers, so we do not need to program
directly against this namespace.

1.5 Architecture of .NET Framework

25
Microsoft .NET (pronounced “dot net”) is a software
component that runs on the Windows operating
system...NET provides tools and libraries that enable
developers to create Windows software much faster and
easier.The .NET Framework must be installed on a user’s
PC to run .NET applications

.Net Framework

.NET is a framework to develop software applications. It


is designed and developed by Microsoft and the first beta
version released in 2000.

It is used to develop applications for web, Windows,


phone. Moreover, it provides a broad range of
functionalities and support. This framework contains a
large number of class libraries known as Framework
Class Library (FCL). The software programs written in
.NET are executed in the execution environment, which is
called CLR (Common Language Runtime). These are the
core and essential parts of the .NET framework.

This framework provides various services like memory


management, networking, security, memory
management, and type-safety. The .Net Framework
supports more than 60 programming languages such as
C#, F#, VB.NET, J#, VC++, jscript.NET, APL, COBOL, Perl,
Oberon, ML, Pascal, Eiffel, Smalltalk, Python, Cobra, ADA,
etc.

26
Following is the .NET framework Stack that shows the
modules and components of the Framework.

The .NET Framework is composed of four main


components:

Common Language Runtime (CLR) Framework Class


Library (FCL), Core Languages (winforms, ASP.NET, and
ADO.NET), and Other Modules (WCF, WPF, WF, Card
Space, LINQ, Entity Framework, Parallel LINQ, Task
Parallel Library, etc.)

27
Figure 1.3: Architecture of .NET Framework

CLR (Common Language Runtime)

It is a program execution engine that loads and executes


the program. It converts the program into native code. It
acts as an interface between the framework and
operating system. It does exception handling, memory
management, and garbage collection. Moreover, it
provides security, type-safety, interoperability, and
portablility. A list of CLR components are given below:

28
Figure 1.4 FCL (Framework Class Library)

It is a standard library that is a collection of thousands of


classes and used to build an application. The BCL (Base
Class Library) is the core of the FCL and provides basic
functionalities.

Figure 1.4 BCL

Winforms

Windows Forms is a smart client technology for the .NET


Framework, a set of managed libraries that simplify

29
common application tasks such as reading and writing to
the file system.

ASP.NET

ASP.NET is a web framework designed and developed by


Microsoft. It is used to develop websites, web
applications, and web services. It provides a fantastic
integration of HTML, CSS, and javascript. It was first
released in January 2002.

ADO.NET

ADO.NET is a module of .Net Framework, which is used


to establish a connection between application and data
sources. Data sources can be such as SQL Server and
XML. ADO .NET consists of classes that can be used to
connect, retrieve, insert, and delete data.

WPF (Windows Presentation Foundation)

Windows Presentation Foundation (WPF) is a graphical


subsystem by Microsoft for rendering user interfaces in
Windows-based applications. WPF, previously known as
"Avalon", was initially released as part of .NET
Framework 3.0 in 2006. WPF uses directx.

WCF (Windows Communication Foundation)

It is a framework for building service-oriented


applications. Using WCF, you can send data as
asynchronous messages from one service endpoint to
another.
30
WF (Workflow Foundation)

Windows Workflow Foundation (WF) is a Microsoft


technology that provides an API, an in- process workflow
engine, and a rehostable designer to implement long-
running processes as workflows within .NET
applications.

LINQ (Language Integrated Query)

It is a query language, introduced in .NET 3.5 framework.


It is used to make the query for data sources with C# or
Visual Basics programming languages.

Entity Framework

It is an ORM based open source framework which is used


to work with a database using .NET objects. It eliminates
a lot of developers effort to handle the database. It is
Microsoft's recommended technology to deal with the
database.

1.6 Garbage collection

• The garbage collector (GC) manages the allocation


and release of memory. The garbage collector
serves as an automatic memory manager.

• You do not need to know how to allocate and


release memory or manage the lifetime of the
objects that use that memory.

31
• An allocation is made any time you declare an
object with a “new” keyword or a value type is
boxed. Allocations are typically very fast.

• When there isn’t enough memory to allocate an


object, the GC must collect and dispose of garbage
memory to make memory available for new
allocations.

This process is known as garbage collection.

Garbage Collection in C# has the following advantages:

• You don’t need to free memory manually while


developing your application.

• It also allocates objects on the managed heap


efficiently.

• When objects are no longer used then it will


reclaim those objects by clearing their memory,
and keeps the memory available for future
allocations.

• Managed objects automatically get clean content to


start with, so their constructors do not have to
initialize every data field.

32
CHAPTER 2

C# BASICS
2.1 What is C#?

C# is pronounced "C-Sharp".

It is an object-oriented programming language created


by Microsoft that runs on the .NET Framework.C# has
roots from the C family, and the language is close to other
popular languages like C++ and Java.

The first version was released in year 2002. The latest


version, C# 8, was released in September 2019.

C# is used for:

• Mobile applications
• Desktop applications
• Web applications
• Web services
• Web sites
• Games
• VR
• Database applications

2.1.1 Why Use C#?

• It is one of the most popular programming


language in the world
33
• It is easy to learn and simple to use
• It has a huge community support
• C# is an object oriented language which gives a
clear structure to programs and allows code to be
reused, lowering development costs.
• As C# is close to C, C++ and Java, it makes it easy
for programmers to switch to C# or vice versa

2.1.2 C# Install

Once the Visual Studio Installer is downloaded and


installed, choose the .NET workload and click on the
Modify/Install button:

After the installation is complete, click on the Launch


button to get started with Visual Studio.On the start
window, choose Create a new project:

34
Then click on the "Install more tools and features"
button:

35
Choose "Console App (.NET Core)" from the list and click
on the Next button:

Enter a name for your project, and click on the Create


button:

36
Visual Studio will automatically generate some code for
your project:

The code should look something like this:

Program.cs
Using System;
Namespace helloworld
{
Class Program
{
Static void Main(string[] args)
{
Console.writeline("Hello World!");
}
}
}

Run the program by pressing the F5 button on your


keyboard (or click on "Debug" -> "Start Debugging"). This
will compile and execute your code. The result will look
something to this:

37
2.2 Example: explained

Line 1: using System means that we can use classes from


the System namespace.

Line 2: A blank line. C# ignores white space. However,


multiple lines makes the code more readable.

Line 3: namespace is used to organize your code, and it


is a container for classes and other namespaces.

Line 4: The curly braces {} marks the beginning and the


end of a block of code.

Line 5: class is a container for data and methods, which


brings functionality to your program. Every line of code
that runs in C# must be inside a class. In our Example:,
we named the class Program.

38
Line 7: Another thing that always appear in a C#
program, is the Main method. Any code inside its curly
brackets {} will be executed. You don't have to
understand the keywords before and after Main. You will
get to know them bit by bit while reading this tutorial.

Line 9: Console is a class of the System namespace,


which has a writeline() method that is used to
output/print text. In our Example: it will output "Hello
World!”

If you omit the using System line, you would have to


write System.Console.writeline() to print/output text.

Note: Every C# statement ends with a semicolon ;

Note: C# is case-sensitive: "myclass" and "myclass" has


different meaning.

Note: Unlike Java, the name of the C# file does not have
to match the class name, but they often do (for better
organization). When saving the file, save it using a proper
name and add ".cs" to the end of the filename. To run the
Example: above on your computer, make sure that C# is
properly installed

2.3 writeline or Write

The most common method to output something in C# is


writeline(), but you can also use Write().

The difference is that writeline() prints the output on a


new line each time, while Write() prints on the same line
39
(note that you should remember to add spaces when
needed, for better readability):

Example:

Console.writeline("Hello World!");

Console.writeline("I will print on a new line.");

Console.Write("Hello World! ");

Console.Write("I will print on the same line.");

Result:

2.4 C# Comments

Comments can be used to explain C# code, and to make it


more readable. It can also be used to prevent execution
when testing alternative code.

2.4.1 Single-line Comments

Single-line comments start with two forward slashes


(//).

40
Any text between // and the end of the line is ignored by
C# (will not be executed).

This Example: uses a single-line comment before a line of


code:

Example::

// This is a comment

Console.writeline("Hello World!");

2.4.2 C# Multi-line Comments

Multi-line comments start with /* and ends with */.

Any text between /* and */ will be ignored by C#.

This Example: uses a multi-line comment (a comment


block) to explain the code:

Example::

/* The code below will print the words Hello World

To the screen, and it is amazing */

Console.writeline("Hello World!");

2.5 C# Variables

Variables are containers for storing data values.

In C#, there are different types of variables (defined with


different keywords), for Example::
41
• int - stores integers (whole numbers), without
decimals, such as 123 or -123
• double - stores floating point numbers, with
decimals, such as 19.99 or -19.99
• char - stores single characters, such as 'a' or 'B'.
Char values are surrounded by single quotes
• string - stores text, such as "Hello World". String
values are surrounded by double quotes
• bool - stores values with two states: true or false

Declaring (Creating) Variables

To create a variable, you must specify the type and assign


it a value:

Syntax

Type variablename = value;

Where type is a C# type (such as int or string), and


variablename is the name of the variable (such as x or
name). The equal sign is used to assign values to the
variable.

To create a variable that should store text, look at the


following Example::

Example::

Create a variable called name of type string and assign it


the value "John":

42
String name = "John";

Console.writeline(name);

To create a variable that should store a number, look at


the following Example::

Example::

Create a variable called mynum of type int and assign it


the value 15:

Int mynum = 15;

Console.writeline(mynum);

2.6 Constants

However, you can add the const keyword if you don't


want others (or yourself) to overwrite existing values
(this will declare the variable as "constant", which means
unchangeable and read-only):

Example::

Const int mynum = 15;

Mynum = 20; // error

The const keyword is useful when you want a variable to


always store the same value, so that others (or yourself)
won't mess up your code. An Example: that is often
referred to as a constant, is PI (3.14159...).

43
Note: You cannot declare a constant variable without
assigning the value. If you do, an error will occur: A const
field requires a value to be provided.

Example::

String firstname = "John ";

String lastname = "Doe";

String fullname = firstname + lastname;

Console.writeline(fullname);

For numeric values, the + character works as a


mathematical operator (notice that we use int (integer)
variables here):

Example::

Int x = 5;

Int y = 6;

Console.writeline(x + y); // Print the value of x + y

2.7 Declare Many Variables

To declare more than one variable of the same type, use a


comma-separated list:

Example::

Int x = 5, y = 6, z = 50;

44
Console.writeline(x + y + z);

Example::

Int x, y, z;

X = y = z = 50;

Console.writeline(x + y + z);

2.8 C# Identifiers

All C# variables must be identified with unique names.

These unique names are called identifiers.

Identifiers can be short names (like x and y) or more


descriptive names (age, sum, total Volume).

Note: It is recommended to use descriptive names in


order to create understandable and maintainable code:

Example::

// Good

Int minutes Per Hour = 60;

// OK, but not so easy to understand what m actually is

Int m = 60;

45
2.9 C# Data Types

As explained in the variables chapter, a variable in C#


must be a specified data type:

Example::

Int mynum = 5; // Integer (whole number)

Double mydoublenum = 5.99D; // Floating point


number

Char myletter = 'D'; // Character

Bool mybool = true; // Boolean

String mytext = "Hello"; // String

A data type specifies the size and type of variable values.


It is important to use the correct data type for the
corresponding variable; to avoid errors, to save time and
memory, but it will also make your code more
maintainable and readable. The most common data types
are:

46
Numbers

Number types are divided into two groups:

Integer types stores whole numbers, positive or negative


(such as 123 or -456), without decimals. Valid types are
int and long. Which type you should use, depends on the
numeric value.

Floating point types represents numbers with a


fractional part, containing one or more decimals. Valid
types are float and double.

Integer Types

Int

The int data type can store whole numbers from -


2147483648 to 2147483647. In general, and in our
tutorial, the int data type is the preferred data type when
we create variables with a numeric value.

Example::

Int mynum = 100000;

Console.writeline(mynum);

Long

The long data type can store whole numbers from -


9223372036854775808 to 9223372036854775807.
This is used when int is not large enough to store the
value. Note that you should end the value with an "L":
47
Example::

Long mynum = 15000000000L;

Console.writeline(mynum);

Floating Point Types

You should use a floating point type whenever you need


a number with a decimal, such as 9.99 or 3.14515.

Float

The float data type can store fractional numbers from


3.4e−038 to 3.4e+038. Note that you should end the
value with an "F":

Example::

Float mynum = 5.75F;

Console.writeline(mynum);

Double

The double data type can store fractional numbers from


1.7e−308 to 1.7e+308. Note that you can end the value
with a "D" (although not required):

Example::

Double mynum = 19.99D;

Console.writeline(mynum);

48
Scientific Numbers

A floating point number can also be a scientific number


with an "e" to indicate the power of 10:

Example::

Float f1 = 35e3f;

Double d1 = 12E4D;

Console.writeline(f1);

Console.writeline(d1);

Booleans

A boolean data type is declared with the bool keyword


and can only take the values true or false:

Example::

Bool iscsharpfun = true;

Bool isfishtasty = false;

Console.writeline(iscsharpfun); // Outputs True

Console.writeline(isfishtasty); // Outputs False

Boolean values are mostly used for conditional testing,


which you will learn more about in a later chapter.

Characters

49
The char data type is used to store a single character. The
character must be surrounded by single quotes, like 'A'
or 'c':

Example::

Char mygrade = 'B';

Console.writeline(mygrade);

Strings

The string data type is used to store a sequence of


characters (text). String values must be surrounded by
double quotes:

Example::

String greeting = "Hello World";

Console.writeline(greeting);

2.10 C# Type Casting

Type casting is when you assign a value of one data type


to another type.

In C#, there are two types of casting:

Implicit Casting (automatically) - converting a smaller


type to a larger type size

Char -> int -> long -> float -> double

50
Explicit Casting (manually) - converting a larger type to
a smaller size type

Double -> float -> long -> int -> char

Implicit Casting

Implicit casting is done automatically when passing a


smaller size type to a larger size type:

Example::

Int myint = 9;

Double mydouble = myint; // Automatic casting: int to


double

Console.writeline(myint); // Outputs 9

Console.writeline(mydouble); // Outputs 9

Explicit Casting

Explicit casting must be done manually by placing the


type in parentheses in front of the value:

Example::

Double mydouble = 9.78;

Int myint = (int) mydouble; // Manual casting: double


to int

51
Console.writeline(mydouble); // Outputs 9.78

Console.writeline(myint); // Outputs 9

2.11 Type Conversion Methods

It is also possible to convert data types explicitly by using


built-in methods, such as Convert.toboolean,
Convert.todouble, Convert.tostring, Convert.toint32 (int)
and Convert.toint64 (long):

Example::

Int myint = 10;

Double mydouble = 5.25;

Bool mybool = true;

Console.writeline(Convert.tostring(myint)); // convert
int to string

Console.writeline(Convert.todouble(myint)); //
convert int to double

Console.writeline(Convert.toint32(mydouble)); //
convert double to int

Console.writeline(Convert.tostring(mybool)); //
convert bool to string

Get User Input

52
You have already learned that Console.writeline() is used
to output (print) values. Now we will use
Console.readline() to get user input.

In the following Example:, the user can input his or hers


username, which is stored in the variable user Name.
Then we print the value of user Name:

Example::

// Type your username and press enter

Console.writeline("Enter username:");

// Create a string variable and get user input from the


keyboard and store it in the variable

String username = Console.readline();

// Print the value of the variable (username), which will


display the input value

Console.writeline("Username is: " + username);

53
User Input and Numbers

The Console.readline() method returns a string.


Therefore, you cannot get information from another data
type, such as int. The following program will cause an
error:

Example::

Console.writeline("Enter your age:");

Int age = Console.readline();

Console.writeline("Your age is: " + age);

The error message will be something like this:

Cannot implicitly convert type 'string' to 'int'

Like the error message says, you cannot implicitly


convert type 'string' to 'int'.

Luckily, for you, you just learned from the previous


chapter (Type Casting), that you can convert any type
explicitly, by using one of the Convert.To methods:

54
2.12 C# Operators

Operators are used to perform operations on variables


and values.In the Example: below, we use the + operator
to add together two values:

Example::

Int x = 100 + 50;

Arithmetic Operators

Arithmetic operators are used to perform common


mathematical operations:

C# Assignment Operators

Assignment operators are used to assign values to


variables.

In the Example: below, we use the assignment operator


(=) to assign the value 10 to a variable called x:

55
Example::

Int x = 10;

The addition assignment operator (+=) adds a value to a


variable:

Example::

Int x = 10;

X += 5;

C# Comparison Operators

56
Comparison operators are used to compare two values:

C# Logical Operators

Logical operators are used to determine the logic


between variables or values:

Math.Max(x,y)

The Math.Max(x,y) method can be used to find the


highest value of x and y:

Example::
57
Math.Max(5, 10);

Math.Min(x,y)

The Math.Min(x,y) method can be used to find the lowest


value of of x and y:

Example::

Math.Min(5, 10);

Math.Sqrt(x)

The Math.Sqrt(x) method returns the square root of x:

Example::

Math.Sqrt(64);

Math.Abs(x)

The Math.Abs(x) method returns the absolute (positive)


value of x:

Example::

Math.Abs(-4.7);

Math.Round()

Math.Round() rounds a number to the nearest whole


number:

Example::

58
Math.Round(9.99);

C# Strings

Strings are used for storing text.

A string variable contains a collection of characters


surrounded by double quotes:

Example::

Create a variable of type string and assign it a value:

String greeting = "Hello";

String Length

A string in C# is actually an object, which contain


properties and methods that can perform certain
operations on strings. For Example:, the length of a string
can be found with the Length property:

Example::

String txt = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";

Console.writeline("The length of the txt string is: " +


txt.Length);

Other Methods

There are many string methods available, for Example:


toupper() and tolower(), which returns a copy of the
string converted to uppercase or lowercase:

59
Example::

String txt = "Hello World";

Console.writeline(txt.toupper()); // Outputs "HELLO


WORLD"

Console.writeline(txt.tolower()); // Outputs "hello


world"

String Concatenation

The + operator can be used between strings to combine


them. This is called concatenation:

Example::

String firstname = "John ";

String lastname = "Doe";

String name = firstname + lastname;

Console.writeline(name);

String Interpolation

Another option of string concatenation, is string


interpolation, which substitutes values of variables into
placeholders in a string. Note that you do not have to
worry about spaces, like with concatenation:

Example:

String firstname = "John";


60
String lastname = "Doe";

String name = $"My full name is: {firstname} {lastname}";

Console.writeline(name);

You can access the characters in a string by referring to


its index number Access Strings

Inside square brackets [].

This Example: prints the first character in mystring:

Example:

String mystring = "Hello";

Console.writeline(mystring[0]); // Outputs "H"

Adding Numbers and Strings

WARNING!

C# uses the + operator for both addition and


concatenation.

Remember: Numbers are added. Strings are


concatenated.

If you add two numbers, the result will be a number:

Example:

Int x = 10;

61
Int y = 20;

Int z = x + y; // z will be 30 (an integer/number)

C# Booleans

Very often, in programming, you will need a data type


that can only have one of two values, like:

YES / NO

ON / OFF

TRUE / FALSE

For this, C# has a bool data type, which can take the
values true or false.

Boolean Values
62
A boolean type is declared with the bool keyword and
can only take the values true or false:

Example:

Bool iscsharpfun = true;

Bool isfishtasty = false;

Console.writeline(iscsharpfun); // Outputs True

Console.writeline(isfishtasty); // Outputs False

Boolean Expression

A Boolean expression is a C# expression that returns a


Boolean value: True or False.

You can use a comparison operator, such as the greater


than (>) operator to find out if an expression (or a
variable) is true:

Example:

Int x = 10;

Int y = 9;

Console.writeline(x > y); // returns True, because 10 is


higher than 9

63
2.13 C# Conditions and If Statements

C# supports the usual logical conditions from


mathematics:

• Less than: a < b


• Less than or equal to: a <= b
• Greater than: a > b
• Greater than or equal to: a >= b
• Equal to a == b
• Not Equal to: a != b

You can use these conditions to perform different actions


for different decisions.

C# has the following conditional statements:

• Use if to specify a block of code to be executed, if a


specified condition is true
• Use else to specify a block of code to be executed, if
the same condition is false

64
• Use else if to specify a new condition to test, if the
first condition is false
• Use switch to specify many alternative blocks of
code to be executed

2.13.1 The if Statement

Use the if statement to specify a block of C# code to be


executed if a condition is True.

Syntax

If (condition)

// block of code to be executed if the condition is True

In the Example: below, we test two values to find out if


20 is greater than 18. If the condition is True, print some
text:

65
2.13.2 The else Statement

Use the else statement to specify a block of code to be


executed if the condition is False.

Syntax

If (condition)

// block of code to be executed if the condition is True

}
66
Else

// block of code to be executed if the condition is False }

Example: explained

In the Example: above, time (20) is greater than 18, so


the condition is False. Because of this, we move on to the
else condition and print to the screen "Good evening". If
the time was less than 18, the program would print
"Good day".

2.13.3 The else if Statement

Use the else if statement to specify a new condition if the


first condition is False.

Syntax

If (condition1)

67
{

// block of code to be executed if condition1 is True

Else if (condition2)

// block of code to be executed if the condition1 is false


and condition2 is True

Else

// block of code to be executed if the condition1 is false


and condition2 is False

68
Example: explained

In the Example: above, time (22) is greater than 10, so


the first condition is False. The next condition, in the else
if statement, is also False, so we move on to the else
condition since condition1 and condition2 is both False -
and print to the screen "Good evening".

However, if the time was 14, our program would print


"Good day."

C# Switch Statements

Use the switch statement to select one of many code


blocks to be executed.

Syntax

Switch(expression)

Case x:

// code block

Break;

Case y:

// code block

Break;
69
Default:

// code block

Break;

The Example: below uses the weekday number to


calculate the weekday name:

Using System;

Namespace myapplication

Class Program

Static void Main(string[] args)

Int day = 4;

Switch (day)

Case 1:

Console.writeline("Monday");

Break;
70
Case 2:

Console.writeline("Tuesday");

Break;

Case 3:

Console.writeline("Wednesday");

Break;

Case 4:

Console.writeline("Thursday");

Break;

Case 5:

Console.writeline("Friday");

Break;

Case 6:

Console.writeline("Saturday");

Break;

Case 7:

Console.writeline("Sunday");

Break;

71
}

2.14 Loops

Loops can execute a block of code as long as a specified


condition is reached.Loops are handy because they save
time, reduce errors, and they make code more readable.

2.14.1 C# While Loop

The while loop loops through a block of code as long as a


specified condition is True:

Syntax

72
While (condition)

// code block to be executed

In the Example: below, the code in the loop will run, over
and over again, as long as a variable (i) is less than 5:

2.14.2 The Do/While Loop

The do/while loop is a variant of the while loop. This


loop will execute the code block once, before checking if
the condition is true, then it will repeat the loop as long
as the condition is true.

Syntax

Do

{
73
// code block to be executed

While (condition);

The Example: below uses a do/while loop. The loop will


always be executed at least once, even if the condition is
false, because the code block is executed before the
condition is tested:

2.14.3 C# For Loop

When you know exactly how many times you want to


loop through a block of code, use the for loop instead of a
while loop:

Syntax

For (statement 1; statement 2; statement 3)

// code block to be executed

74
Statement 1 is executed (one time) before the execution
of the code block.

Statement 2 defines the condition for executing the code


block.

Statement 3 is executed (every time) after the code block


has been executed.

The Example: below will print the numbers 0 to 4:

2.14.4 The foreach Loop

There is also a foreach loop, which is used exclusively to


loop through elements in an array:

Syntax

Foreach (type variablename in arrayname) {

// code block to be executed}

75
The following Example: outputs all elements in the cars
array, using a foreach loop:

2.15 C# Break

You have already seen the break statement used in an


earlier chapter of this tutorial. It was used to "jump out"
of a switch statement.

The break statement can also be used to jump out of a


loop.

This Example: jumps out of the loop when i is equal to 4:

76
2.16 C# Continue

The continue statement breaks one iteration (in the


loop), if a specified condition occurs, and continues with
the next iteration in the loop.

This Example: skips the value of 4:

2.17 Break and Continue in While Loop

You can also use break and continue in while loops:

Continue Example:
77
2.18 C# Arrays

Create an Array

Arrays are used to store multiple values in a single


variable, instead of declaring separate variables for each
value.

To declare an array, define the variable type with square


brackets:

String[] cars;

We have now declared a variable that holds an array of


strings.

To insert values to it, we can use an array literal - place


the values in a comma-separated list, inside curly braces:

String[] cars = {"Volvo", "BMW", "Ford", "Mazda"};

To create an array of integers, you could write:

78
Int[] mynum = {10, 20, 30, 40};

Access the Elements of an Array

You access an array element by referring to the index


number.

This statement accesses the value of the first element in


cars:

Example:

String[] cars = {"Volvo", "BMW", "Ford", "Mazda"};

Console.writeline(cars[0]);// Outputs Volvo

Change an Array Element

To change the value of a specific element, refer to the


index number:

Example:

Cars[0] = "Opel";

Example:

String[] cars = {"Volvo", "BMW", "Ford", "Mazda"};

Cars[0] = "Opel";

Console.writeline(cars[0]);

// Now outputs Opel instead of Volvo

79
Array Length

To find out how many elements an array has, use the


Length property:

Example:

String[] cars = {"Volvo", "BMW", "Ford", "Mazda"};

Console.writeline(cars.Length);

// Outputs 4

2.18.1 Loop Through an Array

You can loop through the array elements with the for
loop, and use the Length property to specify how many
times the loop should run.

The following Example: outputs all elements in the cars


array:

Example:

String[] cars = {"Volvo", "BMW", "Ford", "Mazda"};

For (int i = 0; i < cars.Length; i++)

Console.writeline(cars[i]);

Sort Arrays
80
There are many array methods available, for Example:
Sort(), which sorts an array alphabetically or in an
ascending order:

Example:

// Sort a string

String[] cars = {"Volvo", "BMW", "Ford", "Mazda"};

Array.Sort(cars);

Foreach (string i in cars)

Console.writeline(i);

// Sort an int

Int[] mynumbers = {5, 1, 8, 9};

Array.Sort(mynumbers);

Foreach (int i in mynumbers)

Console.writeline(i);

System.Linq Namespace

81
Other useful array methods, such as Min, Max, and Sum,
can be found in the System.Linq namespace:

Example:

Using System;

Using System.Linq;

Namespace myapplication

Class Program

Static void Main(string[] args)

Int[] mynumbers = {5, 1, 8, 9};

Console.writeline(mynumbers.Max()); // returns the


largest value

Console.writeline(mynumbers.Min()); // returns the


smallest value

Console.writeline(mynumbers.Sum()); // returns the


sum of elements

}
82
}

2.19 C# Methods

A method is a block of code which only runs when it is


called.You can pass data, known as parameters, into a
method.Methods are used to perform certain actions, and
they are also known as functions.Why use methods? To
reuse code: define the code once, and use it many times.

Create a Method

A method is defined with the name of the method,


followed by parentheses (). C# provides some pre-
defined methods, which you already are familiar with,
such as Main(), but you can also create your own
methods to perform certain actions:

Example:

Create a method inside the Program class:

Class Program

Static void mymethod()

// code to be executed

83
}

Call a Method

To call (execute) a method, write the method's name


followed by two parentheses () and a semicolon;

In the following Example:, mymethod() is used to print a


text (the action), when it is called:

Example:

Inside Main(), call the mymethod() method:

Static void mymethod()

Console.writeline("I just got executed!");

Static void Main(string[] args)

Mymethod();

// Outputs "I just got executed!"

84
2.20 Parameters and Arguments

Information can be passed to methods as parameter.


Parameters act as variables inside the method. They are
specified after the method name, inside the parentheses.
You can add as many parameters as you want, just
separate them with a comma.

The following Example: has a method that takes a string


called fname as parameter. When the method is called,
we pass along a first name, which is used inside the
method to print the full name:

Example:

Static void mymethod(string fname)

Console.writeline(fname + " Refsnes");

Static void Main(string[] args)

Mymethod("Liam");

Mymethod("Jenny");

Mymethod("Anja");

85
// Liam Refsnes

// Jenny Refsnes

// Anja Refsnes

When a parameter is passed to the method, it is called an


argument. So, from the Example: above: fname is a
parameter, while Liam, Jenny and Anja are arguments.

Default Parameter Value

You can also use a default parameter value, by using the


equals sign (=). If we call the method without an
argument, it uses the default value ("Norway"):

Example:

Static void mymethod(string country = "Norway")

Console.writeline(country);

Static void Main(string[] args)

Mymethod("Sweden");

Mymethod("India");

Mymethod();
86
Mymethod("USA");

// Sweden

// India

// Norway

// USA

Multiple Parameters

You can have as many parameters as you like:

Example:

Static void mymethod(string fname, int age)

Console.writeline(fname + " is " + age);

Static void Main(string[] args)

Mymethod("Liam", 5);

Mymethod("Jenny", 8);

Mymethod("Anja", 31);

87
}

// Liam is 5

// Jenny is 8

// Anja is 31

Return Values

The void keyword, used in the Example:s above,


indicates that the method should not return a value. If
you want the method to return a value, you can use a
primitive data type (such as int or double) instead of
void, and use the return keyword inside the method:

Example:

Static int mymethod(int x)

Return 5 + x;

Static void Main(string[] args)

Console.writeline(mymethod(3));

// Outputs 8 (5 + 3)
88
Named Arguments

It is also possible to send arguments with the key: value


syntax.That way, the order of the arguments does not
matter:

Example:

Static void mymethod(string child1, string child2, string


child3)

Console.writeline("The youngest child is: " + child3);

Static void Main(string[] args)

Mymethod(child3: "John", child1: "Liam", child2:


"Liam");

// The youngest child is: John

2.21 Method Overloading

With method overloading, multiple methods can have the


same name with different parameters:

Example:

89
Int mymethod(int x)

Float mymethod(float x)

Double mymethod(double x, double y)

Consider the following Example:, which have two


methods that add numbers of different type:

Example:

Static int plusmethodint(int x, int y)

Return x + y;

Static double plusmethoddouble(double x, double y)

Return x + y;

Static void Main(string[] args)

Int mynum1 = plusmethodint(8, 5);

Double mynum2 = plusmethoddouble(4.3, 6.26);

Console.writeline("Int: " + mynum1);


90
Console.writeline("Double: " + mynum2);

2.22 C# - What is OOP?

OOP stands for Object-Oriented Programming.


Procedural programming is about writing procedures or
methods that perform operations on the data, while
object-oriented programming is about creating objects
that contain both data and methods.

Object-oriented programming has several advantages


over procedural programming:

• OOP is faster and easier to execute.


• OOP provides a clear structure for the programs.
• OOP helps to keep the C# code DRY "Don't Repeat
Yourself", and makes the code easier to maintain,
modify and debug
• OOP makes it possible to create full reusable
applications with less code and shorter
development time

C# - What are Classes and Objects?

Classes and objects are the two main aspects of object-


oriented programming.

Look at the following illustration to see the difference


between class and objects:
91
Classes and Objects

You learned from the previous chapter that C# is an


object-oriented programming language. Everything in C#
is associated with classes and objects, along with its
attributes and methods. For Example:: in real life, a car is
an object. The car has attributes, such as weight and
color, and methods, such as drive and brake.

A Class is like an object constructor, or a "blueprint" for


creating objects.

Create a Class

To create a class, use the class keyword:

Create a class named "Car" with a variable color:

Class Car

String color = "red";

Create an Object

An object is created from a class. We have already


created the class named Car, so now we can use this to
create objects.To create an object of Car, specify the class
name, followed by the object name, and use the keyword
new:

92
Example:

Create an object called "myobj" and use it to print the


value of color:

Class Car

String color = "red";

Static void Main(string[] args)

Car myobj = new Car();

Console.writeline(myobj.color);

Multiple Objects

You can create multiple objects of one class:

Example:

Create two objects of Car:

Class Car

{
93
String color = "red";

Static void Main(string[] args)

Car myobj1 = new Car();

Car myobj2 = new Car();

Console.writeline(myobj1.color);

Console.writeline(myobj2.color);

Using Multiple Classes

You can also create an object of a class and access it in


another class. This is often used for better organization
of classes (one class has all the fields and methods, while
the other class holds the Main() method (code to be
executed)).

Prog2.cs

Prog.cs

Prog2.cs

Class Car
94
{

Public string color = "red";

Class Members

Fields and methods inside classes are often referred to as


"Class Members":

Example:

Create a Car class with three class members: two fields


and one method.

// The class

Class myclass

// Class members

String color = "red"; // field

Int maxspeed = 200; // field

Public void fullthrottle() // method

Console.writeline("The car is going as fast as it can!");

95
}

Class Car

String color;

Int maxspeed;

Static void Main(string[] args)

Car myobj = new Car();

Myobj.color = "red";

Myobj.maxspeed = 200;

Console.writeline(myobj.color);

Console.writeline(myobj.maxspeed);

Object Methods

You learned from the C# Methods chapter that methods


are used to perform certain actions. Methods normally
belongs to a class, and they define how an object of a
class behaves. Just like with fields, you can access
methods with the dot syntax. However, note that the
96
method must be public. And remember that we use the
name of the method followed by two parantheses () and
a semicolon ; to call (execute) the method:

Example:

Class Car

String color; // field

Int maxspeed; // field

Public void fullthrottle() // method

Console.writeline("The car is going as fast as it can!");

Static void Main(string[] args)

Car myobj = new Car();

Myobj.fullthrottle(); // Call the method

Constructors

97
A constructor is a special method that is used to initialize
objects. The advantage of a constructor, is that it is called
when an object of a class is created. It can be used to set
initial values for fields:

Example:

Create a constructor:

// Create a Car class

Class Car

Public string model; // Create a field

// Create a class constructor for the Car class

Public Car()

Model = "Mustang"; // Set the initial value for model

Static void Main(string[] args)

Car Ford = new Car(); // Create an object of the Car


Class (this will call the constructor)

98
Console.writeline(Ford.model); // Print the value of
model

// Outputs "Mustang"

Constructor Parameters

Constructors can also take parameters, which is used to


initialize fields.

The following Example: adds a string modelname


parameter to the constructor. Inside the constructor we
set model to modelname (model=modelname). When we
call the constructor, we pass a parameter to the
constructor ("Mustang"), which will set the value of
model to "Mustang":

Example:

Class Car

Public string model;

// Create a class constructor with a parameter

Public Car(string modelname)

99
{

Model = modelname;

Static void Main(string[] args)

Car Ford = new Car("Mustang");

Console.writeline(Ford.model);

// Outputs "Mustang"

2.22 Access Modifiers

By now, you are quite familiar with the public keyword


that appears in many of our Example:s:

Public string color

The public keyword is an access modifier, which is used


to set the access level/visibility for classes, fields,
methods and properties.

Private Modifier

If you declare a field with a private access modifier, it can


only be accessed within the same class:
100
Example:

Class Car

Private string model = "Mustang";

Static void Main(string[] args)

Car myobj = new Car();

Console.writeline(myobj.model);

The output will be:

Mustang

Public Modifier

If you declare a field with a public access modifier, it is


accessible for all classes:

Example:

Class Car

Public string model = "Mustang";


101
}

Class Program

Static void Main(string[] args)

Car myobj = new Car();

Console.writeline(myobj.model);

The output will be:

Mustang

2.23 Properties and Encapsulation

Before we start to explain properties, you should have a


basic understanding of "Encapsulation".

The meaning of Encapsulation, is to make sure that


"sensitive" data is hidden from users. To achieve this, you
must:

Declare fields/variables as private

Provide public get and set methods, through properties,


to access and update the value of a private field
102
Properties

You learned from the previous chapter that private


variables can only be accessed within the same class (an
outside class has no access to it). However, sometimes
we need to access them - and it can be done with
properties.

A property is like a combination of a variable and a


method, and it has two methods: a get and a set method:

Example:

Class Person

Private string name; // field

Public string Name // property

Get { return name; } // get method

Set { name = value; } // set method

103
2.24 Inheritance (Derived and Base Class)

In C#, it is possible to inherit fields and methods from


one class to another. We group the "inheritance concept"
into two categories:

• Derived Class (child) - the class that inherits from


another class
• Base Class (parent) - the class being inherited
from

To inherit from a class, use the : symbol.

In the Example: below, the Car class (child) inherits the


fields and methods from the Vehicle class (parent):

Polymorphism and Overriding Methods

Polymorphism means "many forms", and it occurs when


we have many classes that are related to each other by
inheritance.

Like we specified in the previous chapter; Inheritance


lets us inherit fields and methods from another class.
Polymorphism uses those methods to perform different
tasks. This allows us to perform a single action in
different ways.

For Example:, think of a base class called Animal that has


a method called animalsound(). Derived classes of
Animals could be Pigs, Cats, Dogs, Birds - And they also

104
have their own implementation of an animal sound (the
pig oinks, and the cat meows, etc.):

Example:

Class Animal // Base class (parent)

Public void animalsound()

Console.writeline("The animal makes a sound");

Class Pig : Animal // Derived class (child)

Public void animalsound()

Console.writeline("The pig says: wee wee");

Class Dog : Animal // Derived class (child)

{
105
Public void animalsound()

Console.writeline("The dog says: bow wow");

2.25 Abstract Classes and Methods

Data abstraction is the process of hiding certain details


and showing only essential information to the user.

Abstraction can be achieved with either abstract classes


or interfaces (which you will learn more about in the
next chapter).

The abstract keyword is used for classes and methods:

• Abstract class: is a restricted class that cannot be


used to create objects (to access it, it must be
inherited from another class).
• Abstract method: can only be used in an abstract
class, and it does not have a body. The body is
provided by the derived class (inherited from).

An abstract class can have both abstract and regular


methods:

// Abstract class

Abstract class Animal


106
{

// Abstract method (does not have a body)

Public abstract void animal Sound();

// Regular method

Public void sleep()

Console.writeline("Zzz");

// Derived class (inherit from Animal)

Class Pig : Animal

Public override void animalsound()

// The body of animalsound() is provided here

Console.writeline("The pig says: wee wee");

107
Class Program

Static void Main(string[] args)

Pig mypig = new Pig(); // Create a Pig object

Mypig.animalsound(); // Call the abstract method

Mypig.sleep(); // Call the regular method

2.26 Interfaces

Another way to achieve abstraction in C#, is with


interfaces. An interface is a completely "abstract class",
which can only contain abstract methods and properties
(with empty bodies):

Example:

// interface

Interface Animal

Void animalsound(); // interface method (does not have


a body)
108
Void run(); // interface method (does not have a body)

Multiple Interfaces

To implement multiple interfaces, separate them with a


comma:

Example:

Interface ifirstinterface

Void mymethod(); // interface method

Interface isecondinterface

Void myothermethod(); // interface method

// Implement multiple interfaces

Class democlass : ifirstinterface, isecondinterface

Public void mymethod()

{
109
Console.writeline("Some text..");

Public void myothermethod()

Console.writeline("Some other text...");

Class Program

Static void Main(string[] args)

Democlass myobj = new democlass();

Myobj.mymethod();

Myobj.myothermethod();

C# Enums

An enum is a special "class" that represents a group of


constants (unchangeable/read-only variables).To create
110
an enum, use the enum keyword (instead of class or
interface), and separate the enum items with a comma:

Example:

Enum Level

Low,

Medium,

High

Enum inside a Class

You can also have an enum inside a class:

Example:

Class Program

Enum Level

Low,

Medium,

High
111
}

Static void Main(string[] args)

Level myvar = Level.Medium;

Console.writeline(myvar);

The output will be:

Medium

112
CHAPTER 3

C# LIBRARIES AND .NET


ADVANCE FEATURES
3.1 Input output (Streams Classes)

C# - Stream

C# includes following standard IO (Input/Output) classes


to read/write from different sources like files, memory,
network, isolated storage, etc.

Stream: System.IO.Stream is an abstract class that


provides standard methods to transfer bytes (read, write,
etc.) To the source. It is like a wrapper class to transfer
bytes. Classes that need to read/write bytes from a
particular source must implement the Stream class. The
following classes inherit Stream class to provide the
functionality to Read/Write bytes from a particular
source:

Filestream: Reads or writes bytes from/to a physical


file, whether it is a .txt, .exe, .jpg, or any other file.
Filestream is derived from the Stream class.

Memorystream: memorystream reads or writes bytes


that are stored in memory.

113
Bufferedstream: bufferedstream reads or writes bytes
from other Streams to improve certain I/O operations'
performance.

Networkstream: networkstream reads or writes bytes


from a network socket.

Pipestream: pipestream reads or writes bytes from


different processes.

Cryptostream: cryptostream is for linking data streams


to cryptographic transformations. The following diagram
shows the hierarchy of stream classes:

Figure 3.1 Stream Classes Hierarchy

Stream Readers and Writers

Streamreader: streamreader is a helper class for


reading characters from a Stream by converting bytes
into characters using an encoded value. It can be used to

114
read strings (characters) from different Streams like
filestream, memorystream, etc.

Streamwriter: streamwriter is a helper class for writing


a string to a Stream by converting characters into bytes.
It can be used to write strings to different Streams such
as filestream, memorystream, etc.

Binaryreader: binaryreader is a helper class for reading


primitive datatype from bytes.

Binarywriter: binarywriter writes primitive types in


binary.

Figure 3.2 Stream IO

The above image shows that filestream reads bytes from


a physical file, and then streamreader reads strings by
converting those bytes to strings. In the same way, the
streamwriter takes a string and converts it into bytes and
writes to the filestream, and then the filestream writes
the bytes to a physical file. So, the filestream deals with
bytes, where as streamreader and streamwriter deals
with strings.

115
3.2 C# - Multithreading

A thread is defined as the execution path of a program.


Each thread defines a unique flow of control. If your
application involves complicated and time consuming
operations, then it is often helpful to set different
execution paths or threads, with each thread performing
a particular job.

Threads are lightweight processes. One common


Example: of use of thread is implementation of
concurrent programming by modern operating systems.
Use of threads saves wastage of CPU cycle and increase
efficiency of an application.

So far we wrote the programs where a single thread runs


as a single process which is the running instance of the
application. However, this way the application can
perform one job at a time. To make it execute more than
one task at a time, it could be divided into smaller
threads.

3.3 Thread Life Cycle

The life cycle of a thread starts when an object of the


System.Threading.Thread class is created and ends when
the thread is terminated or completes execution.

Following are the various states in the life cycle of a


thread:

116
The Unstarted State − It is the situation when the
instance of the thread is created but the Start method is
not called.

The Ready State − It is the situation when the thread is


ready to run and waiting CPU cycle.

The Not Runnable State − A thread is not executable,


when:

• Sleep method has been called


• Wait method has been called
• Blocked by I/O operations

The Dead State − It is the situation when the thread


completes execution or is aborted.

The Main Thread

In C#, the System.Threading.Thread class is used for


working with threads. It allows creating and accessing
individual threads in a multithreaded application. The
first thread to be executed in a process is called the main
thread.

When a C# program starts execution, the main thread is


automatically created. The threads created using the
Thread class are called the child threads of the main
thread. You can access a thread using the currentthread
property of the Thread class.

The following program demonstrates main thread


execution −
117
Example:

Using System;

Using System.Threading;

Namespace multithreadingapplication {

Class mainthreadprogram {

Static void Main(string[] args) {

Thread th = Thread.currentthread;

Th.Name = "mainthread";

Console.writeline("This is {0}", th.Name);

Console.readkey();

When the above code is compiled and executed, it


produces the following result −

This is mainthread

118
3.4 Creating Threads

Threads are created by extending the Thread class. The


extended Thread class then calls the Start() method to
begin the child thread execution.

The following program demonstrates the concept −

Using System;

Using System.Threading;

Namespace multithreadingapplication {

Class threadcreationprogram {

Public static void calltochildthread() {

Console.writeline("Child thread starts");

Static void Main(string[] args) {

Threadstart childref = new


threadstart(calltochildthread);

Console.writeline("In Main: Creating the Child


thread");

Thread childthread = new Thread(childref);

Childthread.Start();

Console.readkey();
119
}

When the above code is compiled and executed, it


produces the following result −

In Main: Creating the Child thread

Child thread starts

Console is the set of devices throught which a user


communicates with a system using interactive set of
commands. GUI is not considered as console in this
respect. The primary input device in most of the
computer systems is a keyboard and the primary output
is the monitor. The pair forms the user's console in most
of the caseds

Contents

The Console Class

Managing Console I/O Operations

Console.openstandardinput Method()

Console.openstandardoutput Method()

Console.Read Method()

Console.readline Method()

120
Console.Write Method(Boolean)

Console.Write Method(String)

The Console Class

To allow console input/output operations, C# provides,


C# provides a console class. The Console class provides
basic input and output support for applications that read
from and write characters to the console. The standard
input, output, and error streams are represented by
properties, and are automatically associated with the
console when the application starts. Application can
redirected these properties to other streams; for
Example:, streams associated with fies instead of the
console.By default, the read methods in console class use
the standard input stream (keyboard) and the write
methods use the standard output (monitor) stream.

The write methods support writing data with or without


automatically appending carriage return and linefeed
characters. This enables the writing of string, formatted
strings, arrays of characters, instances of primitive types,
and arbitrary objects without first having to convert
them to strings.

The following Example: demonstrates the use of basic


Console input and output functions.

/* Console Input/Ouput */

Using System;

121
Class consoletest

Public static void Main()

Console.Write("Hello");

Console.writeline("World");

Console.Write("What is Your Name");

String name = Console.readline();

Console.Write("Hello, ");

Console.Write(name);

Console.writeline(" ! ");

3.5 Managing Console I/O Operations

Console input/ouput operations are carried out by the


Console class which is inside system namespace and is
stored in Mscorlib (in Mscorlib.dll) assembly.

122
Data from the console is read from the standard input
stream; normal data to the console is written to the
standard output stream; and error data to the console is
written to the standard error output stream. These
streams are automatically associated with the console
when your application start, and are presented to you as
the In, Out, and Error properties.

By default, the value of the In property is a


System.IO.textreader, while the values of the Out and
Error properties are System.IO.textwriter objects.
However, you can associate these properties with
streams that do not represent the console. This class
synchronized textreader and textwriter instances.
Multiple threads can concurrently read from or write to
an instance of this type.

Console.openstandardinput Method()

This method acquires the standard input stream. The


code given below shows this. This method can be used to
reacquire the standard input stream after it has been
changed by the setin method. Consider the following
code snippet for illustration.

The following code sample illustrates the user of


openstandardinput:

Public class Decoder

123
Public static void Main()

Stream inputstream = Console.openstandardinput();

Byte [] bytes = new byte[100];

Console.writeline("To decode, type or paste the UTF7


encoded string and press enter:");

Console.writeline("(Example:: \"M+apw-nchen ist


wundervoll\")");

Int outputlength = inputstream.Read(bytes, 0 ,100);

Char [] chars = Encoding.UTF7.getchars(bytes, 0 ,


outputlenght);

Console.writeline("Decoded String:");

Console.writeline(new string(chars));

Console.openstandardoutput Method()

The method acquires the standard output stream. This


method can be used to reqcquire the standard output
stream after it has been changed by the setout method.
Consider the following code snippet for illustration.

Public class inserttabs


124
{

Private const int tabsize = 4;

Private const string usagetext = "Usage: INSERTTABS


inputfile.txt outputfile.txt";

Public static int Main(String[] args)

Streamwriter writer = null;

If (args.Length < 2)

Console.writeline(usagetextt);

Return 1;

Try

Write = new stramwriter(args[1]);

Console.setout(writer);

Console.setin(new streamreader(args[0]));

}
125
Catch(ioexception e)

Textwriter errorwriter = Console.Error;

Errorwriter.writeline(e.Message);

Errorwriter.writeline(usagetext);

Return 1;

String line;

While((line = Console.readline())!= null)

String newline =
line.Replace(("").padright(tabsize,'),"\t");

Console.writeline(newline);

Writer.Close();

//Recover the standard output stream so that a

// Completion message can be displayed.

Streamwriter standardoutput = new


streamwriter(Console.openstandardoutput());

126
Standardoutput.autoflush = true;

Console.setout(standardoutput);

Console.writeline("INSERTTABS has completed the


processing of (0).", args[0]);

Return 0;

Console.Read Method()

This method reads the next character from the standard


input stream. It returns the next character from the input
stream, or negative one (-1) if no more characters are
available. This method will not return until the read
operation is terminated; for Example: by the user
pressing the enter key. If data is available, the input
stream contains what the user entered, suffixed with the
environment dependent newline character. Consider the
following for illustration.

Int i;

Char c;

While(true)

I = Console.Read();
127
If (i == 1)

Break;

C = (char) l;

Console.writeline("Echo: )0)",c);

Console.writeline("Done");

Return 0;

Console.readline Method()

This method reads the next line of characters from the


standard input stream. It returns the next line from the
input stream, or a null reference if no more charcters are
available. A line is defined as a sequence of characters
followed by a carriage return (hexadecimal 0x000d), a
line feed (hexadecimal 0x000a). The returned string does
not contain the termination character(s). Consider the
following code for illustration.

Public class inserttabs

Private const int tabsize = 4;

Private const string usagetext = "Usage: INSERTTABS


inputfile.txt outputfile.txt";

128
Public static int Main(String[] args)

Streamwriter writer = null;

If (args.Length < 2)

Console.writeline(usagetextt);

Return 1;

Try

Write = new stramwriter(args[1]);

Console.setout(writer);

Console.setin(new streamreader(args[0]));

Catch(ioexception e)

Textwriter errorwriter = Console.Error;

Errorwriter.writeline(e.Message);

129
Errorwriter.writeline(usagetext);

Return 1;

String line;

While((line = Console.readline())!= null)

String newline =
line.Replace(("").padright(tabsize,'),"\t");

Console.writeline(newline);

Writer.Close();

//Recover the standard output stream so that a

// Completion message can be displayed.

Streamwriter standardoutput = new


streamwriter(Console.openstandardoutput());

Standardoutput.autoflush = true;

Console.setout(standardoutput);

Console.writeline("INSERTTABS has completed the


processing of (0).", args[0]);

130
Return 0;

Console.Write Method(Boolean)

This method writes the text representation of the


specified Boolean value to the standard output stream.
The text representation of value is produced by calling
Boolean.Tostring. Consdier the following code for
illustration.

Public class formatconverter

Public static void Main(string[] args)

String lineinput;

While((lineinput = Console.readline()) != null)

Bool isfirstfield = true;

Foreach(string item in fields)

If (isfirstfield)
131
Isfirstfield = false;

Else

Console.Write(',');

Try

{
Console.Write(Convert.tobyte(Convert.toboolean(item)))
;

Catch(formatexception)

Console.Write(item);

Console.writeline();

Console.Write Method(String)

132
This method writes the specified string value to the
standard output stream. If value is a null reference,
nothing is written to the standard output stream.
Consider the following code for illustration.

Public class formatconverter

Public static void Main(string[] args)

String lineinput;

While((lineinput = Console.readline()) != null)

Bool isfirstfield = true;

Foreach(string item in fields)

If (isfirstfield)

Isfirstfield = false;

Else

Console.Write(',');

133
Try

{
Console.Write(Convert.tobyte(Convert.toboolean(item)))
;

Catch(formatexception)

Console.Write(item);

Console.writeline();

3.6 .NET Assemblies

An Assembly is a basic building block of .Net Framework


applications. It is basically a compiled code that can be
executed by the CLR. An assembly is a collection of types
and resources that are built to work together and form a
logical unit of functionality. An Assembly can be a DLL or
exe depending upon the project that we choose.
134
Assemblies are basically the following two types:

1. Private Assembly
2. Shared Assembly

1. Private Assembly

It is an assembly that is being used by a single application


only. Suppose we have a project in which we refer to a
DLL so when we build that project that DLL will be
copied to the bin folder of our project. That DLL becomes
a private assembly within our project. Generally, the dlls
that are meant for a specific project are private
assemblies.

2. Shared Assembly

Assemblies that can be used in more than one project are


known to be a shared assembly. Shared assemblies are
generally installed in the GAC. Assemblies that are
installed in the GAC are made available to all the .Net
applications on that machine.

However, there are two more types of assemblies in .Net,


Satellite Assembly, and Shared Assembly.

3.7 GAC (Global Assembly Cache)

Using Global Assembly Cache (GAC) Deployment

Installing application components into the the Global


Assembly Cache (GAC) can be useful if you are installing
components that will be used by multiple applications on
135
the same machine, or if you need to run multiple versions
of the same assembly on a single computer. By default
when you install the Ultimate UI for ASP.NET toolset the
control assemblies are installed into the GAC. If you
would like to deploy the Infragistics components that are
part of your application into the GAC of the client
computer there are three primary methods.

Using Gacutil.exe to add components to the GAC

The Gacutil.exe tool is a command line utility installed as


part of the base .NET framework which can be used to
add and remove application components to/from the
GAC. The Gacutil.exe tool is located in the .NET
Framework installation directory. The default location
for this is:

C:\Windows\Microsoft.NET\Framework\v4.0.30319.

To use the Gacutil.exe tool:

Open a Visual Studio command prompt

( Start > Programs > Microsoft Visual Studio .NET 2005 >
Visual Studio .NET Tools > Visual Studio .NET 2005
Command Prompt )

Enter the Gacutil.exe command. The following line


demonstrates adding the Infragistics webchart
component to the GAC from an application’s folder called
myapplication. Gacutil -i

136
C:\Projects\myapplication\Infragistics4.webui.ultraweb
chart.v21.2.dll

Gacutil.exe command line include a number of


commands that allow you spe specify the operation you
want the tool to perform. The list below explain the
available commands:

/i - Installs an assembly to the GAC

/il - Installs one or more assemblies to the GAC

/u - Uninstalls an assembly from the GAC

/ul - Uninstalls one or more assemblies from the GAC

/ungen - Uninstalls a native images installed via the


NGEN utility

/l - List the GAC filtered by <assembly_name>

/lr - List the GAC with all traced references

/cdl - Deletes the contents of the download cache

/ldl - Lists the contents of the download cache

Gacutil.exe also allows for several options to be specified


on the command line:

/r - Specifies a traced reference to install or uninstall

/f - Forces reinstall of an assembly

/nologo - Suppresses the display of the logo banner


137
/silent - Suppressed the display f all output.

3.7 Global ASAX Files

What is global.asax

Ispostback

Global.asax is an optional file which is used to handling


higher level application events such as Application_Start,
Application_End, Session_Start, Session_End etc. It is also
popularly known as ASP.NET Application File. This file
resides in the root directory of an ASP.NET-based
application. Global.asax contains a Class representing
your application as a whole. At run time, this file is
parsed and compiled into a dynamically generated .NET
Framework class derived from the httpapplication base
class. You can deploy this file as an assembly in the \bin
directory of an ASP.NET application. The Global.asax file
itself is configured so that if a user requests the file, the
request is rejected. External users cannot download or
view the code written within it.

How to create a Global.asax file

Global.asax file don't create normally; you need to


add it by yourself.

How to ?

Create-global

Your Global.asax file look like this


138
<%@ Application Language="C#" %>

<script runat="server">

Void Application_Start(object sender, eventargs e)

// Code that runs on application startup

Void Application_End(object sender, eventargs e)

// Code that runs on application shutdown

Void Application_Error(object sender, eventargs e)

// Code that runs when an unhandled error occurs

Void Session_Start(object sender, eventargs e)

// Code that runs when a new session is started

139
Void Session_End(object sender, eventargs e)

// Code that runs when a session ends.

// Note: The Session_End event is raised only when


the sessionstate mode

// is set to inproc in the Web.config file. If session


mode is set to stateserver

// or sqlserver, the event is not raised.

</script>

After that you need to add a class in your project.

Inherit the newly generated by


System.Web.httpapplication and copy all the method
created Global.asax to Global.cs and also add an inherit
attribute to the Global.asax file

3.8 State management: Session Object

State management is very important and useful in


ASP.NET. It is also asked in many interviews to fresher
and experienced developers.ASP.NET State management
is a preserve state control and object in an application
because ASP.NET web applications are stateless. A new
instance of the Web page class is created each time the

140
page is posted to the server. If a user enters information
into a web application, that information would be lost in
the round trip from the browser (MSDN).

In a single line, State management maintains and stores


the information of any user till the end of the user
session.Two types of State Management techniques are
available in ASP.NET as in the ,State Management
Concept In ASP.NET.

Server side Session

Session is a very important technique to maintain state.


Normally session is used to store information and
identity. The server stores information using Sessionid.

Set User Session

Protected void btnsubmit_Click(object sender, eventargs


e)

Session["username"] = txtname.Text;

Response.Redirect("Home.aspx");

Session Event

Session event can be seen in project Global.asax file.

Two types of Session Events:


141
Session_Start

The Session_start event is raised every time a new user


requests without a session ID.

Void Session_Start(object sender, eventargs e)

Session["master"] = "~/Master.master";

Session_End

The Session_End event is raised when session is ended


by a user or a time out using Session end method.

Void Session_End(object sender, eventargs e)

Response.Write("Session_End");

The session is stored in the following for ways in


ASP.NET.

Inprocmode

It is a default session mode and a value store in web


server memory (IIS). In this the session value stored with
server start and it ends when the server is restarted.

142
State Server Mode

In this mode session data is stored in separate server.

SQL Server Mode

In this session is stored in the database. It is a secure


mode.

Custom Mode

Generally under session data is stored in inproc, Sql


Server, State server, etc. If you store session data with
other new techniques then provide ASP.NET.

Application

Application State is a server side management state. It is


also called application level state management. In this
mainly store user activity in server memory and
application event shown in Global.asax file.

Their are three types of applications in ASP.NET.

Application_Start

This event begins with domain start.

Void Application_Start(object sender, eventargs e)

Application["appstartmessage"] = "Welcome to csharp


Corner Developer Communtiy";

143
}

Application_Error

In this section manage unhandled exception error.

Void Application_Error(object sender, eventargs e)

// Write an unhandled error code exception

Application_ End

This ends with domain or restarts IIS.

Void Application_End(object sender, eventargs e)

Application["appendmessage"] = "Application Closed";

Cache

Cache is stored on server side. It implements Page


Caching and data caching. Cache is use to set expiration
polices

Response.Cache.setexpirestime(datetime.Now.adddays(1
));

144
Client Side

Now here I am explaining client side state management


one by one:

Also state management has the following four important


parts available on the client side,

3.9 Cookie

Cookie is a small and an important part of ASP.NET. In


this store user information, session and application. It
can be created constant and temporary and they work
with browser request. Cookies are store on client side.
The server can read cookies and abstract data.

Two types of cookies are available:

Persistence

This type of cookie works with Date and time.

Response.Cookies["cookiename"].Value = "Test Cookies";

//set expire time

Response.Cookies["cookiename"].Expires =
datetime.Today.addhours(1);

Non-Persistence

This is a temporary cookie. It is created with access


application and discards the close application.

145
Response.Cookies["cookiename"].Value = "Test Cookies";

Control state

Control state technique is developed to maintain data


work properly in order. We can use view state but
suppose view state is disabled by the user, the control
will not work as expected. For expected results of the
control we have to use Control State. In application, the
Viewstate is by default true. Sometimes we need to use
custom control to manage application properly.

If (!Ispostback)

Lblmsg1.Text = "Welcome to C# corner";

Lblmsg2.Text = "Welcome to C# corner community";

When two messages are displayed on a Postback event,


then control which one is displayed by using customized
control state.

3.10 Hidden Field

Hidden fields are used to store value to client side.


Hidden field is not displayed on the browser, but it works
on a request.

If (hiddenfield1.Value != null)

146
{

Int val = Convert.toint32(hiddenfield1.Value) + 1;

Hiddenfield1.Value = val.tostring();

Label1.Text = val.tostring();

Viewstate

Viewstate is a very useful client side property. It is used


for page level state management. Viewstate stores any
type of data and used for sending and receiving
information,

Example: 1 - Count.

Viewstate Demo Count: <asp:Label runat="server"


id="lblcount" />

<asp:Button runat="server" id="Submit"


onclick="Submit_Click" text="show" />

Protected void Page_Load(object sender, eventargs e)

If (ispostback)

If (viewstate["count"] != null)

147
{

Int viewstateval =
Convert.toint32(viewstate["count"]) + 1;

Lblcount.Text = viewstateval.tostring();

Viewstate["count"] = viewstateval.tostring();

Else

Viewstate["count"] = "1";

Protected void Submit_Click(object sender, eventargs e)

Lblcount.Text = viewstate["count"].tostring();

Example: 2 - Set/Get user.

If (viewstate["username"] != null)

Lblname.Text = viewstate["username"].tostring();

OR,
148
Viewstate["username"] = txtusername.Text;

Viewstate is easy to apply and does not need access to


any server resources. In a Viewstate, do not store big
data, only store small values. Viewstate enables and
disables on page level control. It also supports
Encryption and Decryption and data/value is stored in
hashed format. So we are not storing important data such
as password, account information, etc. When more data
is stored in this, then the page becomes heavy.

Hidden Fields

Hiddenfield Control

Hidden fields are a common trick of the HTML web


developer’s trade for carrying information within a page
when you do not want that information to be visible to
the user—that is, the hidden field provides a way to store
state information in the page. For Example:, you might
want to keep track of whether a form on the page has
been completed, has been saved as a draft, or is being
edited for the first time.

Often, an easier and more elegant way to accomplish this


task is to use one of the state mechanisms provided by
the .NET Framework (see Chapter 6 for a complete
discussion of state). However, sometimes this is
impossible, perhaps for performance, bandwidth, or
security reasons. (Performance and bandwidth are
mostly two sides of the same coin.)

149
In HTML pages, you might use something such as the
following code snippet to implement a hidden field:

<input type="hidden" id="formstatus" value="Draft


Saved">

Indeed, ASP.NET uses a hidden field to implement view


state. You can see this by examining the source that is
rendered to the browser, via the View → Source menu
command in Internet Explorer. (Other browsers have
analogous commands.) You will see something similar to
the following, where the value attribute encodes all the
information saved in view state:

<input type="hidden" name="_ _VIEWSTATE"

Value="/wepdwujl0chlbr...yfl+BDX7xhMw=" />

To reap the benefits of server-side processing, you can


use an ASP.NET hiddenfield control to generate these
hidden fields for use both by the browser and on the
server.

In addition to accessing the hidden value through the


control’s Value property, ASP.NET also defines an event
called valuechanged for the hiddenfield control. This
fires on postback when the Value property of the control
is different from the previous posting. The event does not
cause a postback itself, and unlike most nonpostback
controls, the hiddenfield does not expose an
autopostback property to force an instantaneous
postback. As with all nonpostback controls (explained in
150
Chapter 3), notification of the event will be cached until
the form is posted back by some other control, at which
point the event will be raised in server code.

These features are demonstrated in Example: 4-8, in a


file called hiddenfielddemo.aspx. The file contains a
textbox (txtsecretvalue) for entering a new value for the
hiddenfield control (hdnsecretvalue), an HTML button
(used to execute a client-side function without causing a
postback to the server), and an ASP.NET Button called
btnpost (to force a postback to the server). A Label
(lblsecretvalue) displays the contents of the hidden field.

Example: 4-8. Hiddenfielddemo.aspx

<%@ Page Language="C#" autoeventwireup="true"

Codefile="hiddenfielddemo.aspx.cs"
Inherits="hiddenfielddemo" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0


Transitional//EN"

"http://www.w3.org/TR/xhtml1/DTD/xhtml1-
transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">

<head runat="server">

<title>hiddenfield Control Demo</title>

</head>

151
<body>

<script type="text/javascript" language="javascript">

Function changehiddenvalue()

Alert("Entering changehiddenvalue");

Var hdnid = "<%=hdnsecretvalue.clientid%>";

Var hdn = document.getelementbyid(hdnid);

Var txt =
document.getelementbyid("txtsecretvalue");

Hdn.value = txt.value;

Alert("Value changed");

</script>

<form id="form1" runat="server">

<div>

<asp:hiddenfield ID="hdnsecretvalue" runat="server"

Onvaluechanged="hdnsecretvalue_valuechanged"
/>

Enter secret value:

152
<asp:textbox ID="txtsecretvalue" runat="server" />

<br />

<br />

<input id="Button1" type="button" value="button"

Onclick="changehiddenvalue()" />

<asp:Button ID="btnpost" runat="server" Text="Post"


/>

<br />

<br />

<asp:Label ID="lblsecretvalue" runat="server" />

</div>

</form>

</body>

</html>

The HTML button calls the changehiddenvalue function,


highlighted in the code listing. This function has two alert
methods that are helpful in debugging; they can be
omitted or commented out.

Changehiddenvalue demonstrates two equivalent ways


of getting a reference to a control on the page, both using
the javascript getelementbyid method. This method
153
returns a reference to the first object it finds on the page
with the specified ID attribute.

In the first technique, a reference is obtained to the


hiddenfield control via the clientid property, which
returns the actual ID of the <input type="hidden">
element as rendered on the page by ASP.NET:

Var hdnid = "<%=hdnsecretvalue.clientid%>";

Enclosing the server-side code in <% %> tags tells


ASP.NET to evaluate that code and place the results there
in place of the tags and their contents.

In the second technique, the ID attribute of the textbox


control is passed directly to the getelementbyid method
in the script rather than by injecting it:

Var txt = document.getelementbyid("txtsecretvalue");

The hiddenfield valuechanged event is handled by a


server-side method, hdnsecretvalue_valuechanged, as
indicated by the hiddenfield’s onvaluechanged attribute
in Example: 4-8.

3.11 What is viewstate C#?

View State is the method to preserve the Value of the


Page and Controls between round trips. It is a Page-Level
State Management technique. View State is turned on by
default and normally serializes the data in every control
154
on the page regardless of whether it is actually used
during a post-back.

3.12 ASP.NET Cookie

ASP.NET Cookie is a small bit of text that is used to store


user-specific information. This information can be read
by the web application whenever user visits the site.

When a user requests for a web page, web server sends


not just a page, but also a cookie containing the date and
time. This cookie stores in a folder on the user's hard
disk.

When the user requests for the web page again, browser
looks on the hard drive for the cookie associated with the
web page. Browser stores separate cookie for each
different sites user visited.

There are two ways to store cookies in ASP.NET


application.

 Cookies collection
 httpcookie

We can add Cookie either to Cookies collection or by


creating instance of httpcookie class. Both work same
except that httpcookie require Cookie name as part of the
constructor.

Httpcookie Example:

155
In the following Example:, we are creating and adding
cookie with the help of httpcookie class.

// cookieExample:.aspx

1. <%@ Page Language="C#"


autoeventwireup="true"
2. Codebehind="cookieExample:.aspx.cs"
Inherits="coockieExample:.cookieExample:" %>
3. <!DOCTYPE html>
4. <html xmlns="http://www.w3.org/1999/xhtml">
5. <head runat="server">
6. <title></title>
7. </head>
8. <body>
9. <form id="form1" runat="server">
10. <div>
11. <asp:Label ID="Label1" runat="server"
Text="Label"></asp:Label>
12. </div>
13. </form>
14. </body>
15. </html>

Code

// cookieExample:.aspx.cs

1. Using System;
2. Using System.Web;
3. Namespace webformscontrolls
4. {
156
5. Public partial class cookieExample: :
System.Web.UI.Page
6. {
7. Protected void Page_Load(object sender, eventargs
e)
8. {
9. //-------------- Creating Cookie --------------------------
//
10. // Creating httpcookie instance by specifying name
"student"
11. Httpcookie cokie = new httpcookie("student");
12. // Assigning value to the created cookie
13. Cokie.Value = "Rahul Kumar";
14. // Adding Cookie to the response instance
15. Response.Cookies.Add(cokie);
16. //--------------- Fetching Cookie -------------------------
//
17. Var co_val = Response.Cookies["student"].Value;
18. Label1.Text = co_val;
19. }
20. }
21. }

Cookie Collection Example:

In the following Example:, we are adding cookie directly


to the Cookies collection.

// Default.aspx

157
1. <%@ Page Title="Home Page" Language="C#"
autoeventwireup="true"
codebehind="Default.aspx.cs"
2. Inherits="coockieExample:._Default" %>
3. <form id="form1" runat="server">
4. <asp:Label ID="Label1" runat="server"
Text="Select Brand Preferences"></asp:Label>
5. <br />
6. <br />
7. <asp:checkbox ID="apple" runat="server"
Text="Apple" />
8. <br />
9. <asp:checkbox ID="dell" runat="server"
Text="Dell" />
10. <br />
11. <asp:checkbox ID="lenevo" runat="server"
Text="Lenevo" />
12. <br />
13. <asp:checkbox ID="acer" runat="server"
Text="Acer" />
14. <br />
15. <asp:checkbox ID="sony" runat="server"
Text="Sony" />
16. <br />
17. <asp:checkbox ID="wipro" runat="server"
Text="Wipro" />
18. <br />
19. <br />
20. <asp:Button ID="Button1" runat="server"
onclick="Button1_Click" Text="Submit" />
158
21. <p>
22. <asp:Label ID="Label2"
runat="server"></asp:Label>
23. </p>
24. </form>

Codebehind

// Default.aspx.cs

1. Using System;
2. Using System.Web.UI;
3. Namespace coockieExample:
4. {
5. Public partial class _Default : Page
6. {
7. Protected void Page_Load(object sender, eventargs
e)
8. {
9. // Setting expiring date and time of the cookies
10. Response.Cookies["computer"].Expires =
datetime.Now.adddays(-1);
11. }
12. Protected void Button1_Click(object sender,
eventargs e)
13. {
14. Label2.Text = "";
15. // --------------- Adding Coockies ---------------------//
16. If (apple.Checked)
17. Response.Cookies["computer"]["apple"] = "apple";
18. If (dell.Checked)
159
1. 19.
Response.Cookies["computer"]["dell"] = "dell";
19. If (lenevo.Checked)
20. Response.Cookies["computer"]["lenevo"] =
"lenevo";
21. If (acer.Checked)
22. Response.Cookies["computer"]["acer"] = "acer";
23. If (sony.Checked)
24. Response.Cookies["computer"]["sony"] = "sony";
25. If (wipro.Checked)
26. Response.Cookies["computer"]["wipro"] =
"wipro";
27. // --------------- Fetching Cookies -----------------------
//
28. If (Request.Cookies["computer"].Values.tostring()
!= null)
29. {
30. If (Request.Cookies["computer"]["apple"] != null)
31. Label2.Text +=
Request.Cookies["computer"]["apple"] + " ";
32. If (Request.Cookies["computer"]["dell"] != null)
33. Label2.Text +=
Request.Cookies["computer"]["dell"] + " ";
34. If (Request.Cookies["computer"]["lenevo"] != null)
35. Label2.Text +=
Request.Cookies["computer"]["lenevo"] + " ";
36. If (Request.Cookies["computer"]["acer"] != null)
37. Label2.Text +=
Request.Cookies["computer"]["acer"] + " ";
38. If (Request.Cookies["computer"]["sony"] != null)
160
39. Label2.Text +=
Request.Cookies["computer"]["sony"] + " ";
40. If (Request.Cookies["computer"]["wipro"] != null)
41. Label2.Text +=
Request.Cookies["computer"]["wipro"] + " ";
42. }else Label2.Text = "Please select your choice";
43. Response.Cookies["computer"].Expires =
datetime.Now.adddays(-1);
44. }
45. }
46. }

Output:

This Example: will store selected values as cookie.

161
3.13 Cross Page Posting In ASP.NET

ASP.NET by default, submits the form to the same page.


Cross page posting is submitting the form to a different
page. This is usually required when you are creating a
multi page form to collect information from the user on
each page. When moving from the source to the target
page, the values of controls in the source page can be
accessed in the target page.

To use cross-page posting, you have to use the


postbackurl attribute to specify the page you want to
post to.

Follow these steps :

Step 1: Create a new ASP.NET website called


crosspageposting. By default, the website is created with
162
a single webpage, Default.aspx. Right click the project in
the Solution Explorer > Add New Item >Web Form. Keep
the original name Default2.aspx and click ‘Add’. The
website will now contain two pages, Default.aspx and
Default2.aspx.

Step 2: On the source page, Default.aspx, drop a button


on the form. Set the text of the button as ‘targetbutton’.
Set the ‘postbackurl’ property of a Button to the URL of
the target page, Default2.aspx.

<asp:Button ID="Button1" runat="server"


postbackurl="~/Default2.aspx" Text="targetbutton"
/></div>

Step 3: In the target page Default2.aspx, drop a label on


the page from the toolbox.

Step 4: In the Page_Load() of Default2.aspx, you can then


access the ‘previouspage’ property to check if the page is
being accessed as Cross Page postback.

Protected void Page_Load(object sender, eventargs e)

If (Page.previouspage != null)

163
Step 5: To retrieve values from the source page, you
must access controls using the ‘findcontrol()’ method of
the ‘previouspage’. We will be accessing the Text
property of the Button control placed in Default.aspx.

Protected void Page_Load(object sender, eventargs e)

If (Page.previouspage != null)

Button btn =
(Button)(Page.previouspage.findcontrol("button1"));

Label1.Text = btn.Text;

Step 6: In the Solution Explorer, right click Default.aspx >


‘Set as Start Page’. Run the application and click on the
button. As you can observe, the page is posted to
Default2.aspx and the value containing the name of the
button control gets displayed in the label.

164
3.14 Web Configuration and Machine
Configuration Files

There are two types of configuration files supported by


ASP.Net. Configuration files are used to control and
manage the behavior of a web application.

1. Machine.config
2. Web.config

Difference between Machine.Config and Web.Config

Machine.Config

1. This is automatically installed when you install


Visual Studio. Net.
2. This is also called machine level configuration file.
3. Only one machine.config file exists on a server.
4. This file is at the highest level in the configuration
hierarchy.

Web.Config

1. This is automatically created when you create an


ASP.Net web application project.
2. This is also called application level configuration
file.
3. This file inherits setting from the machine.config

165
CHAPTER 4

WINDOWS AND WEBSITE


DEVELOPMENT
4.1 Windows Forms Basics in C#

A Windows forms application is one that runs on the


desktop computer. A Windows forms application will
normally have a collection of controls such as labels,
textboxes, list boxes, etc.

Below is an Example: of a simple Windows form


application C#. It shows a simple Login screen, which is
accessible by the user. The user will enter the required
credentials and then will click the Login button to
proceed.

166
So an Example: of the controls available in the above
application

1. This is a collection of label controls which are


normally used to describe adjacent controls. So in
our case, we have 2 textboxes, and the labels are
used to tell the user that one textbox is for entering
the user name and the other for the password.

2. The 2 textboxes are used to hold the username and


password which will be entered by the user.

3. Finally, we have the button control. The button


control will normally have some code attached to
perform a certain set of actions. So for Example: in
the above case, we could have the button perform
an action of validating the user name and
password which is entered by the user.

4.1.1 C# Hello World

Now let’s look at an Example: of how we can implement a


simple ‘hello world’ application in Visual Studio. For this,
we would need to implement the below-mentioned steps

Step 1) The first step involves the creation of a new


project in Visual Studio. After launching Visual Studio,
you need to choose the menu option New->Project.

167
Step 2) The next step is to choose the project type as a
Windows Forms application. Here we also need to
mention the name and location of our project.

168
1. In the project dialog box, we can see various
options for creating different types of projects in
Visual Studio. Click the Windows option on the left-
hand side.
2. When we click the Windows options in the
previous step, we will be able to see an option for
Windows Forms Application. Click this option.
3. We will give a name for the application. In our case,
it is demoapplication. We will also provide a
location to store our application.
4. Finally, we click the ‘OK’ button to let Visual Studio
create our project.

If the above steps are followed, you will get the below
output in Visual Studio.

Output:-

169
You will see a Form Designer displayed in Visual Studio.
It’s in this Form Designer that you will start building
your Windows Forms application.

In the Solution Explorer, you will also be able to see the


demoapplication Solution. This solution will contain the
below 2 project files

1. A Form application called Forms1.cs. This file will


contain all of the code for the Windows Form
application.
2. The Main program called Program.cs is default
code file which is created when a new application
is created in Visual Studio. This code will contain
the startup code for the application as a whole.

On the left-hand side of Visual Studio, you will also see a


toolbox. The toolbox contains all the controls which can
170
be added to a Windows Forms. Controls like a text box or
a label are just some of the controls which can be added
to a Windows Forms.

Below is a screenshot of how the Toolbox looks like.

Step 3) In this step, we will now add a label to the Form


which will display “Hello World.” From the toolbox, you
will need to choose the Label control and simply drag it
onto the Form.

171
Once you drag the label to the form, you can see the label
embedded on the form as shown below.

172
Step 4) The next step is to go to the properties of the
control and Change the text to ‘Hello World’.

To go to the properties of a control, you need to right-


click the control and choose the Properties menu option

• The properties panel also shows up in Visual


Studio. So for the label control, in the properties
control, go to the Text section and enter “Hello
World”.
• Each Control has a set of properties which describe
the control.

173
If you follow all of the above steps and run your program
in Visual Studio, you will get the following output

Output:-

174
4.1.2 Adding Controls to a form

We had already seen how to add a control to a form


when we added the label control in the earlier section to
display “Hello World.”

Let’s look at the other controls available for Windows


forms and see some of their common properties.In our
Windows form application in C# Example:s, we will
create one form which will have the following
functionality.

1. The ability for the user to enter name and address.


2. An option to choose the city in which the user
resides in
3. The ability for the user to enter an option for the
gender.
4. An option to choose a course which the user wants
to learn. There will make choices for both C# and
ASP.Net

So let’s look at each control in detail and add them to


build the form with the above-mentioned functionality.

4.1.3 Group Box

A group box is used for logical grouping controls into a


section. Let’s take an Example: if you had a collection of
controls for entering details such as name and address of
a person. Ideally, these are details of a person, so you
would want to have these details in a separate section on
the Form. For this purpose, you can have a group box.
175
Let’s see how we can implement this with an Example:
shown below

Step 1) The first step is to drag the Groupbox control


onto the Windows Form from the toolbox as shown
below

Step 2) Once the groupbox has been added, go to the


properties window by clicking on the groupbox control.
In the properties window, go to the Text property and
change it to “User Details”.

176
Once you make the above changes, you will see the
following output

Output:-

177
In the output, you can clearly see that the Groupbox was
added to the form. You can also see that the text of the
groupbox was changed to “User Details.”

4.1.4 Label Control

Next comes the Label Control. The label control is used to


display a text or a message to the user on the form. The
label control is normally used along with other controls.
Common Examples are wherein a label is added along
with the textbox control. The label indicates to the user
on what is expected to fill up in the textbox. Let’s see how
we can implement this with an Example: shown below.
We will add 2 labels, one which will be called ‘name’ and
the other called ‘address.’ They will be used in
conjunction with the textbox controls which will be
added in the later section.

Step 1) The first step is to drag the label control on to the


Windows Form from the toolbox as shown below. Make
sure you drag the label control 2 times so that you can
have one for the ‘name’ and the other for the ‘address’.

178
Step 2) Once the label has been added, go to the
properties window by clicking on the label control. In the
properties window, go to the Text property of each label
control.

179
Once you make the above changes, you will see the
following output

Output:-

180
You can see the label controls added to the form.

4.1.5 Textbox

A textbox is used for allowing a user to enter some text


on the Windows application in C#. Let’s see how we can
implement this with an Example: shown below. We will
add 2 textboxes to the form, one for the Name and the
other for the address to be entered for the user

Step 1) The first step is to drag the textbox control onto


the Windows Form from the toolbox as shown below

181
Step 2) Once the text boxes have been added, go to the
properties window by clicking on the textbox control. In
the properties window, go to the Name property and add
a meaningful name to each textbox. For Example:, name
the textbox for the user as txtname and that for the
address as txtaddress. A naming convention and
standard should be made for controls because it becomes
easier to add extra functionality to these controls, which
we will see later on.

182
In the output, you can clearly see that the Textboxes was
added to the form.

4.1.6 List box

A Listbox is used to showcase a list of items on the


Windows form. Let’s see how we can implement this
with an Example: shown below. We will add a list box to
the form to store some city locations.

Step 1) The first step is to drag the list box control onto
the Windows Form from the toolbox as shown below

183
Step 2) Once the list box has been added, go to the
properties window by clicking on the list box control.

1. First, change the property of the Listbox box


control, in our case, we have changed this to lstcity
2. Click on the Items property. This will allow you to
add different items which can show up in the list

184
box. In our case, we have selected items
“collection”.
3. In the String Collection Editor, which pops up,
enter the city names. In our case, we have entered
“Mumbai”, “Bangalore” and “Hyderabad”.
4. Finally, click on the ‘OK’ button.

Once you make the above changes, you will see the
following output

Output:

4.1.7 radiobutton

A Radiobutton is used to showcase a list of items out of


which the user can choose one. Let’s see how we can
implement this with an Example: shown below. We will
add a radio button for a male/female option.

185
Step 1) The first step is to drag the ‘radiobutton’ control
onto the Windows Form from the toolbox as shown
below.

Step 2) Once the Radiobutton has been added, go to the


properties window by clicking on the Radiobutton
control.

186
1. First, you need to change the text property of both
Radio controls. Go the properties windows and
change the text to a male of one radiobutton and
the text of the other to female.

2. Similarly, change the name property of both Radio


controls. Go the properties windows and change
the name to ‘rdmale’ of one radiobutton and to
‘rdfemale’ for the other one.

One you make the above changes, you will see the
following output

Output:-
187
4.1.8 Checkbox

A checkbox is used to provide a list of options in which


the user can choose multiple choices. Let’s see how we
can implement this with an Example: shown below. We
will add 2 checkboxes to our Windows forms. These
checkboxes will provide an option to the user on
whether they want to learn C# or ASP.Net.

Step 1) The first step is to drag the checkbox control


onto the Windows Form from the toolbox as shown
below

188
Step 2) Once the checkbox has been added, go to the
properties window by clicking on the Checkbox control.

In the properties window,

1. First, you need to change the text property of both


checkbox controls. Go the properties windows and
change the text to C# and ASP.Net.

2. Similarly, change the name property of both Radio


controls. Go the properties windows and change
the name to chkc of one checkbox and to chkasp for
the other one.

Once you make the above changes, you will see the
following output

189
Output:-

4.1.9 Button

A button is used to allow the user to click on a button


which would then start the processing of the form. Let’s
see how we can implement this with an Example: shown
below. We will add a simple button called ‘Submit’ which
will be used to submit all the information on the form.

Step 1) The first step is to drag the button control onto


the Windows Form from the toolbox as shown below

190
Step 2) Once the Button has been added, go to the
properties window by clicking on the Button control.

1. First, you need to change the text property of the


button control. Go the properties windows and
change the text to ‘submit’.
2. Similarly, change the name property of the control.
Go the properties windows and change the name to
‘btnsubmit’.

Once you make the above changes, you will see the
following output
191
Output:-

Congrats, you now have your first basic Windows Form


in place. Let’s now go to the next topic to see how we can
do Event handling for Controls.

4.2 C# Event Handling for Controls

When working with windows form, you can add events


to controls. An event is something that happens when an
action is performed. Probably the most common action is
the clicking of a button on a form. In C# Windows Forms,
you can add code which can be used to perform certain
actions when a button is pressed on the form.

Normally when a button is pressed on a form, it means


that some processing should take place.

192
Let’s take a look at one of the event and how it can be
handled before we go to the button event scenario.

The below Example: will showcase an event for the


Listbox control. So whenever an item is selected in the
listbox control, a message box should pop up which
shows the item selected. Let’s perform the following
steps to achieve this.

Step 1) Double click on the Listbox in the form designer.


By doing this, Visual Studio will automatically open up
the code file for the form. And it will automatically add an
event method to the code. This event method will be
triggered, whenever any item in the listbox is selected.

Above is the snippet of code which is automatically


added by Visual Studio, when you double-click the List
box control on the form. Now let’s add the below section
of code to this snippet of code, to add the required
functionality to the listbox event.

193
1. This is the event handler method which is
automatically created by Visual Studio when you
double-click the List box control. You don’t need to
worry about the complexity of the method name or
the parameters passed to the method.

2. Here we are getting the selecteditem through the


lstcity.selecteditem property. Remember that
lstcity is the name of our Listbox control. We then
use the getitemtext method to get the actual value
of the selected item. We then assign this value to
the text variable.

3. Finally, we use the messagebox method to display


the text variable value to the user.

One you make the above changes, and run the program in
Visual Studio you will see the following output

Output:-

194
From the output, you can see that when any item from
the list box is selected, a message box will pops up. This
will show the selected item from the listbox.

Now let’s look at the final control which is the button


click Method. Again this follows the same philosophy.
Just double click the button in the Forms Designer and it
will automatically add the method for the button event
handler. Then you just need to add the below code.

1. This is the event handler method which is


automatically created by Visual Studio when you
double click the button control. You don’t need to
worry on the complexity of the method name or
the parameters passed to the method.

2. Here we are getting values entered in the name


and address textbox. The values can be taken from
the text property of the textbox. We then assign the
values to 2 variables, name, and address
accordingly.

195
3. Finally, we use the messagebox method to display
the name and address values to the user.

One you make the above changes, and run the program in
Visual Studio you will see the following output

Output:-

1. First, enter a value in the name and address field.


2. Then click on the Submit button

Once you click the Submit button, a message box will


pop, and it will correctly show you what you entered in
the user details section.

196
4.3 Tree and picturebox Control

There are 2 further controls we can look at, one is the


‘Tree Control’ and the other is the ‘Image control’. Let’s
look at Example:s of how we can implement these
controls

Tree Control

The tree control is used to list down items in a tree like


fashion. Probably the best Example: is when we see the
Windows Explorer itself. The folder structure in
Windows Explorer is like a tree-like structure.

Let’s see how we can implement this with an Example:


shown below.

Step 1) The first step is to drag the Tree control onto the
Windows Form from the toolbox as shown below

197
Step 2) The next step is to start adding nodes to the tree
collection so that it can come up in the tree accordingly.
First, let’s follow the below sub-steps to add a root node
to the tree collection.

198
1. Go to the properties toolbox for the tree view
control. Click on the Node’s property. This will
bring up the treenode Editor

2. In the treenode Editor click on the Add Root button


to add a root node to the tree collection.

3. Next, change the text of the Root node and provide


the text as Root and click ‘OK’ button. This will add
Root node.

Step 3) The next step is to start adding the child nodes to


the tree collection. Let’s follow the below sub-steps to
add child root node to the tree collection.

199
1. First, click on the Add child button. This will allow
you to add child nodes to the Tree collection.
2. For each child node, change the text property. Keep
on repeating the previous step and this step and
add 2 additional nodes. In the end, you will have 3
nodes as shown above, with the text as Label,
Button, and Checkbox respectively.
3. Click on the OK button

Once you have made the above changes, you will see the
following output.

Output:-

200
You will be able to see the Tree view added to the form.
When you run the Windows form application, you can
expand the root node and see the child nodes in the list.

4.3.1 picturebox Control

This control is used to add images to the Winforms C#.


Let’s see how we can implement this with an Example:
shown below.

Step 1) The first step is to drag the picturebox control


onto the C# Windows Form from the toolbox as shown
below

201
Step 2) The next step is to actually attach an image to the
picture box control. This can be done by following the
below steps.

1. First, click on the Image property for the


picturebox control. A new window will pops out.

2. In this window, click on the Import button. This


will be used to attach an image to the picturebox
control.

3. A dialog box will pop up in which you will be able


to choose the image to attach the picturebox

4. Click on the OK button

One you make the above changes, you will see the
following output

Output:-
202
From the output, you can see that an image is displayed
on the form.

4.4 Web Services

UDDI: UDDI stands for Universal Description, Discovery


and Integration and built in to Microsoft .NET platform. It
works as a directory which is used to publish and
discover public web services. It communicates via SOAP
(SOAP is a simple XML-based protocol that allows
applications to exchange information over HTTP).

WSDL: WSDL stands for Web Service Description


Language and is a W3C specification which defines XML
grammar for describing Web Services. Means it is written
in XML and also specifies the location of the service and
the operations (or methods) the service exposes.XML
grammar describes details such as:-

1. Where we can find the Web Service (its URI)?


2. What are the methods and properties that service
supports?
3. Data type support.
4. Supported protocols
203
DISCO: DISCO is the abbreviated form of Discovery; it is
the file that helps .NET discovers local

Services. Basically it is used to club or group common


services together on a server and provides

Links to the schema documents of the services it


describes may require. It contains WSDL (Web

Service Description Language) when one searches for the


Web Services; it will go to the DISCO which gives actual
information about the particular Webservices.

4.5 ADO.NET Architecture

In this article, I am going to discuss ADO.NET


Architecture. Please read our previous article where we
discussed ADO.NET Connection Pooling with Example:s.

What is ADO.NET?

ADO stands for Active Data Objects. ADO is nothing but a


component in .NET Framework that helps us to fetch
data from different data sources to our C# and VB.NET
code and probably you can send data from your C# or
VB.NET code to different data sources.

204
The architecture of ADO.NET:

The ADO.NET Architecture is comprising of 6 important


components. They are as follows:

1. Connection
2. Command
3. Datareader
4. Dataadapter
5. Dataset
6. Dataview

From the above components, two components are


compulsory. One is the command object and the other
one is the connection object. Irrespective of the
operations like Insert, Update, Delete and Select, the
command and connection object you always need. For
better understanding, please have a look at the
following image.

205
Let us understand each of the components in detail.

Connection:

The first important component is the connection object.


The connection object is required to connect with your
backend database which can be SQL Server, Oracle,
mysql, etc. To create a connection object, you need at
least two things. The first one is where is your database
located i.e. The Machine name or IP Address or
someplace where your database is located. And the
second thing is the security credentials i.e. Whether it is a
windows authentication or user name and password-
based authentication. So, the first is to create the
connection object and the connection is required to
connect to the backend data source.
206
Command:

The second important component is the command object.


When we talk about databases like SQL Server, Oracle,
mysql, then understand SQL. The command object is the
component where you go and write your SQL queries.
Later you take the command object and execute it over
the connection. Then you can fetch data or send data to
the database using the command object and SQL queries.

Datareader:

Datareader is a read-only connected recordset that helps


us to read the records only in the forward mode. Here,
you need to understand three things i.e. Read-only,
connected, and forward mode.

Dataset:

It is a disconnected recordset that can be browsed in


both i.e. Forward and backward. It is also possible to
update via dataset. Dataset gets filled by somebody called
dataadapter.

Dataadapter:

The dataadapter acts as a bridge between the command


object and the dataset. What the dataadapter does, it
takes the data from the command object and fills the data
set.

Dataview Class

207
A dataview enables you to create different views of the
data stored in a datatable, a capability that is often used
in data-binding applications. Using a dataview, you can
expose the data in a table with different sort orders, and
you can filter the data by row state or based on a filter
expression.

4.5.1 C# Database Connection: How to connect SQL


Server (Example:)

Accessing Data from a database is one of the important


aspects of any programming language. It is an absolute
necessity for any programming language to have the
ability to work with databases. C# is no different.

It can work with different types of databases. It can work


with the most common databases such as Oracle and
Microsoft SQL Server.

It also can work with new forms of databases such as


mongodb and mysql.

Fundamentals of Database connectivity

C# and .Net can work with a majority of databases, the


most common being Oracle and Microsoft SQL Server.
But with every database, the logic behind working with
all of them is mostly the same.

In our Example:s, we will look at working the Microsoft


SQL Server as our database. For learning purposes, one
can download and use the Microsoft SQL Server Express

208
Edition, which is a free database software provided by
Microsoft.

In working with databases, the following are the


concepts which are common to all databases.

1. Connection – To work with the data in a database,


the first obvious step is the connection. The
connection to a database normally consists of the
below-mentioned parameters.

2. Database name or Data Source – The first


important parameter is the database name to
which the connection needs to be established. Each
connection can only work with one database at a
time.

3. Credentials – The next important aspect is the


username and password which needs to be used to
establish a connection to the database. It ensures
that the username and password have the
necessary privileges to connect to the database.

4. Optional parameters – For each database type,


you can specify optional parameters to provide
more information on how .net should handle the
connection to the database. For Example:, one can
specify a parameter for how long the connection
should stay active. If no operation is performed for
a specific period of time, then the parameter would
determine if the connection has to be closed.

209
1. Selecting data from the database – Once the
connection has been established, the next
important aspect is to fetch the data from the
database. C# can execute ‘SQL’ select command
against the database. The ‘SQL’ statement can be
used to fetch data from a specific table in the
database.

2. Inserting data into the database – C# can also be


used to insert records into the database. Values
can be specified in C# for each row that needs to
be inserted into the database.

3. Updating data into the database – C# can also be


used to update existing records into the database.
New values can be specified in C# for each row
that needs to be updated into the database.

4. Deleting data from a database – C# can also be


used to delete records into the database. Select
commands to specify which rows need to be
deleted can be specified in C#.

Ok, now that we have seen the theory of each operation,


let’s jump into the further sections to look at how we can
perform database operations in C#.

4.6 SQL Command in c#

Sqlcommand in C# allow the user to query and send the


commands to the database. SQL command is specified by
the SQL connection object. Two methods are used,
210
executereader method for results of query and
executenonquery for insert, Update, and delete
commands. It is the method that is best for the different
commands.

How to connect C# to Database

Let’s now look at the code, which needs to be kept in


place to create a connection to a database. In our
Example:, we will connect to a database which has the
name of Demodb. The credentials used to connect to the
database are given below

• Username – sa
• Password – demo123

We will see a simple Windows forms application to work


with databases. We will have a simple button called
“Connect” which will be used to connect to the database.

So let’s follow the below steps to achieve this

Step 1) The first step involves the creation of a new


project in Visual Studio. After launching Visual Studio,
you need to choose the menu option New->Project.

211
Step 2) The next step is to choose the project type as a
Windows Forms application. Here, we also need to
mention the name and location of our project.

212
• In the project dialog box, we can see various
options for creating different types of projects in
Visual Studio. Click the Windows option on the left-
hand side.

• When we click the Windows options in the


previous step, we will be able to see an option for
Windows Forms Application. Click this option.

• We then give a name for the application which in


our case is “demoapplication”. We also need to
provide a location to store our application.

• Finally, we click the ‘OK’ button to let Visual Studio


to create our project.

Step 3) Now add a button from the toolbox to the


Windows form. Put the text property of the Button as
Connect. This is how it will look like

213
Step 4) Now double click the form so that an event
handler is added to the code for the button click event. In
the event handler, add the below code.

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 demoapplication1
{
Public partial class Form1 : Form
{
Public Form1()
{

214
Initializecomponent();
}

Private void button1_Click(object sender, eventargs e)


{
String connetionstring;
Sqlconnection cnn;
Connetionstring = @"Data Source=WIN-
50GP30FGO75;Initial Catalog=Demodb;User
ID=sa;Password=demol23";
Cnn = new sqlconnection(connetionstring);
Cnn.Open();
Messagebox.Show("Connection Open !");
Cnn.Close();
}
}
}

Code Explanation:-

• The first step is to create variables, which will be


used to create the connection string and the
connection to the SQL Server database.
• The next step is to create the connection string.
The connecting string needs to be specified
correctly for C# to understand the connection
string. The connection string consists of the
following parts
1. Data Source – This is the name of the server on
which the database resides. In our case, it resides
on a machine called WIN- 50GP30FGO75.
215
2. The Initial Catalog is used to specify the name of
the database

3. The userid and Password are the credentials


required to connect to the database.

• Next, we assign the connecting string to the


variable cnn. The variable cnn, which is of type
sqlconnection is used to establish the connection to
the database.
• Next, we use the Open method of the cnn variable
to open a connection to the database. We then just
display a message to the user that the connection is
established.
• Once the operation is completed successfully, we
then close the connection to the database. It is
always a good practice to close the connection to
the database if nothing else is required to be done
on the database.

When the above code is set, and the project is executed


using Visual Studio, you will get the below output. Once
the form is displayed, click the Connect button.

Output:-

216
When you click on “connect” button, from the output, you
can see that the database connection was established.
Hence, the message box was displayed.

Access data with the sqldatareader

To showcase how data can be accessed using C#, let us


assume that we have the following artifacts in our
database.

• A table called demotb. This table will be used to


store the ID and names of various Tutorials.
• The table will have 2 columns, one called
“tutorialid” and the other called “tutorialname.”
• For the moment, the table will have 2 rows as
shown below.

217
TutorialID TutorialName

1 C#

2 ASP.Net

Let’s change the code in our form, so that we can query


for this data and display the information via a
Messagebox. Note that all the code entered below is a
continuation of the code written for the data connection
in the previous section.

Step 1) Let’s split the code into 2 parts so that it will be


easy to understand for the user.

• The first will be to construct our “select” statement,


which will be used to read the data from the
database.
• We will then execute the “select” statement against
the database and fetch all the table rows
accordingly.

218
Code Explanation:-

• The first step is to create the following variables

1. Sqlcommand – The ‘sqlcommand’ is a class


defined within C#. This class is used to perform
operations of reading and writing into the
database. Hence, the first step is to make sure
that we create a variable type of this class. This
variable will then be used in subsequent steps of
reading data from our database.

2. The datareader object is used to get all the data


specified by the SQL query. We can then read all
the table rows one by one using the data reader.

3. We then define 2 string variables, one is “SQL” to


hold our SQL command string. The next is the
“Output” which will contain all the table values.

219
• The next step is to define the SQL statement, which
will be used against our database. In our case, it is
“Select tutorialid, tutorialname from demotb”. This
will fetch all the rows from the table demotb.

• Next, we create the command object which is used


to execute the SQL statement against the database.
In the SQL command, you have to pass the
connection object and the SQL string.

• Next, we will execute the data reader command,


which will fetch all the rows from the demotb
table.

• Now that we have all the rows of the table with us,
we need a mechanism to access the row one by
one. For this, we will use the while statement. The
while statement will be used to access the rows
from the data reader one at a time. We then use the
getvalue method to get the value of tutorialid and
tutorialname.

Step 2) In the final step, we will just display the output to


the user and close all the objects related to the database
operation.

220
Code Explanation:-

• We will continue our code by displaying the value


of the Output variable using the messagebox. The
Output variable will contain all the values from the
demotb table.
• We finally close all the objects related to our
database operation. Remember this is always a
good practice.

When the above code is set, and the project is run using
Visual Studio, you will get the below output. Once the
form is displayed, click the Connect button.

Output:-

From the output, you can clearly see that the program
was able to get the values from the database. The data is
then displayed in the message box.

C# Insert Into Database

221
Just like Accessing data, C# has the ability to insert
records into the database as well. To showcase how to
insert records into our database, let’s take the same table
structure which was used above.

TutorialID TutorialName

1 C#

2 ASP.Net

Let’s change the code in our form, so that we can insert


the following row into the table

TutorialID TutorialName

3 VB.Net

So let’s add the following code to our program. The


below code snippet will be used to insert an existing
record in our database.

222
Code Explanation:-

• The first step is to create the following variables

1. Sqlcommand – This data type is used to define


objects which are used to perform SQL operations
against a database. This object will hold the SQL
command which will run against our SQL Server
database.

2. The dataadapter object is used to perform specific


SQL operations such as insert, delete and update
commands.
3. We then define a string variable, which is “SQL” to
hold our SQL command string.

• The next step is to actually define the SQL


statement which will be used against our database.
In our case, we are issuing an insert statement,
which will insert the record of tutorialid=1 and
tutorialname=VB.Net

223
• Next, we create the command object which is used
to execute the SQL statement against the database.
In the SQL command, you have to pass the
connection object and the SQL string

• In our data adapter command, we now associate


the insert SQL command to our adapter. We also
then issue the executenonquery method which is
used to execute the Insert statement against our
database. The ‘executenonquery’ method is used in
C# to issue any DML statements against the
database. By DML statements, we mean the insert,
delete, and update operation. In C# , if you want to
issue any of these statements against a table, you
need to use the executenonquery method.

• We finally close all the objects related to our


database operation. Remember this is always a
good practice.

When the above code is set, and the project is executed


using Visual Studio, you will get the below output. Once
the form is displayed, click the Connect button.

Output:-

224
If you go to SQL Server Express and see the rows in the
demotb table, you will see the row inserted as shown
below

C# Update Database

Just like Accessing data, C# has the ability to update


existing records from the database as well. To showcase
how to update records into our database, let’s take the
same table structure which was used above.

225
TutorialID TutorialName

1 C#

2 ASP.Net

3 VB.Net

Let’s change the code in our form, so that we can update


the following row. The old row value is tutorialid as “3”
and Tutorial Name as “VB.Net”. Which we will update it
to “VB.Net complete” while the row value for Tutorial ID
will remain same.

Old Row

TutorialID TutorialName

3 VB.Net

New row

TutorialID TutorialName

3 VB.Net Complete

226
So let’s add the following code to our program. The
below code snippet will be used to update an existing
record in our database.

C# sqlcommand Example: With Code Explanation:-

• The first step is to create the following variables

1. Sqlcommand – This data type is used to define


objects which are used to perform SQL operations
against a database. This object will hold the SQL
command which will run against our SQL Server
database.

2. The dataadapter object is used to perform specific


SQL operations such as insert, delete and update
commands.

3. We then define a string variable, which is SQL to hold


our SQL command string.

227
• The next step is to define the SQL statement which
will be used against our database. In our case we
are issuing an update statement, this will update
the Tutorial name to “VB.Net Complete” while the
tutorialid is unchanged and kept as 3.

• Next, we will create the command object, which is


used to execute the SQL statement against the
database. In the SQL command, you have passed
the connection object and the SQL string.

• In our data adapter command, we now associate


the insert SQL command to our adapter. We also
then issue the executenonquery method which is
used to execute the Update statement against our
database.

• We finally close all the objects related to our


database operation. Remember this is always a
good practice.

When the above code is set, and the project is executed


using Visual Studio, you will get the below output. Once
the form is displayed, click the Connect button.

Output:-

228
If you actually go to SQL Server Express and see the rows
in the demotb table, you will see the row was
successfully updated as shown below.

229
Deleting Records

Just like Accessing data, C# has the ability to delete


existing records from the database as well. To showcase
how to delete records into our database, let’s take the
same table structure which was used above.

TutorialID TutorialName

1 C#

2 ASP.Net

3 VB.Net Complete

Let’s change the code in our form, so that we can delete


the following row

TutorialID TutorialName

3 VB.Net Complete

So let’s add the following code to our program. The


below code snippet will be used to delete an existing
record in our database.

230
Code Explanation:-

• The Key difference in this code is that we are now


issuing the delete SQL statement. The delete
statement is used to delete the row in the demotb
table in which the tutorialid has a value of 3.

• In our data adapter command, we now associate


the insert SQL command to our adapter. We also
then issue the executenonquery method which is
used to execute the Delete statement against our
database.

When the above code is set, and the project is executed


using Visual Studio, you will get the below output. Once
the form is displayed, click the Connect button.

Output:-

231
If you actually go to SQL Server Express and see the rows
in the demotb table, you will see the row was
successfully deleted as shown below.

Connecting Controls to Data

232
In the earlier sections, we have seen how to we can use
C# commands such as sqlcommand and sqlreader to
fetch data from a database. We also saw how we read
each row of the table and use a messagebox to display
the contents of a table to the user.

But obviously, users don’t want to see data sent via


message boxes and would want better controls to display
the data. Let’s take the below data structure in a table

TutorialID TutorialName

1 C#

2 ASP.Net

3 VB.Net Complete

From the above data structure, the user would ideally


want to see the tutorialid and Tutorial Name displayed in
a textbox. Secondly, they might want to have some sort of
button control which could allow them to go to the next
record or to the previous record in the table. This would
require a bit of extra coding from the developer’s end.

The good news is that C# can reduce the additional


coding effort by allowing binding of controls to data.

233
What this means is that C# can automatically populate
the value of the textbox as per a particular field of the
table.

So, you can have 2 textboxes in a windows form. You can


then link one text box to the tutorialid field and another
textbox to the tutorialname field. This linking is done in
the Visual Studio designer itself, and you don’t need to
write extra code for this.

Visual Studio will ensure that it writes the code for you to
ensure the linkage works. Then when you run your
application, the textbox controls will automatically
connect to the database, fetch the data and display it in
the textbox controls. No coding is required from the
developer’s end to achieve this.

Let’s look at a code Example: of how we can achieve


binding of controls.

In our Example:, we are going to create 2 textboxes on


the windows form. They are going to represent the
Tutorial ID and Tutorial Name respectively. They will be
bound to the Tutorial ID and tutorialname fields of the
database accordingly.

Let’s follow the below-mentioned steps to achieve this.

Step 1) Construct the basic form. In the form drag and


drop 2 components- labels and textboxes. Then carry out
the following substeps

234
• Put the text value of the first label as tutorialid
• Put the text value of the second label as
tutorialname
• Put the name property of the first textbox as txtid
• Put the name property of the second textbox as
txtname

Below is the how the form would look like once the
above-mentioned steps are performed.

Step 2) The next step is to add a binding Navigator to the


form. The binding Navigator control can automatically
navigate through each row of the table. To add the
binding navigator, just go to the toolbox and drag it to
the form.

235
Step 3) The next step is to add a binding to our database.
This can be done by going to any of the Textbox control
and clicking on the databindings->Text property. The
Binding Navigator is used to establish a link from your
application to a database.

When you perform this step, Visual Studio will


automatically add the required code to the application to
make sure the application is linked to the database.
Normally the database in Visual Studio is referred to as a
Project Data Source. So to ensure the connection is
established between the application and the database,
the first step is to create a project data source.

The following screen will show up. Click on the link- “Add
Project Data Source”. When you click on the project data
source, you will be presented with a wizard; this will
allow you to define the database connection.

236
Step 4) Once you click on the Add Project Data Source
link, you will be presented with a wizard which will be
used to create a connection to the demotb database. The
following steps show in detail what needs to be
configured during each step of the wizard.

• In the screen which pops up , choose the Data


Source type as Database and then click on next
button.

• In the next screen, you need to start the creation of


the connection string to the database. The
connection string is required for the application to
establish a connection to the database. It contains

237
the parameters such as server name, database
name, and the name of the driver.

1. Click on the New connection button


2. Choose the Data Source as Microsoft SQL Server
3. Click the Continue button.

• Next, you need to add the credentials to connect to


the database

1. Choose the server name on which the SQL


Server resides
2. Enter the user id and password to connect to
the database
3. Choose the database as demotb
4. Click the ‘ok’ button.

238
• In this screen, we will confirm all the settings
which were carried on the previous screens.

1. Choose the option “Yes” to include sensitive data in


the connection string

2. Click on the “Next” button.

239
• In the next screen, click on the “Next” button to
confirm the creation of the connection string

240
• In this step,
• Choose the tables of Demotb, which will be shown
in the next screen.
• This table will now become an available data
source in the C# project

241
When you click the Finish button, Visual Studio will now
ensure that the application can query all the rows in the
table Demotb.

Step 5) Now that the data source is defined, we now


need to connect the tutorialid and tutorialname textbox
to the demotb table. When you click on the Text property
of either the tutorialid or tutorialname textbox, you will
now see that the binding source to Demotb is available.

For the first text box choose the Tutorial ID. Repeat this
step for the second textbox and choose the field as
tutorialname. The below steps shows how we can
navigate to each control and change the binding
accordingly.
242
• Click on the Tutorial ID control.

• In the Properties window, you will see the


properties of the tutorialid textbox. Go to the text
property and click on the down arrow button.

243
• When you click the down arrow button, you will
see the demotbbinding Source option. And under
this, you will see the options of tutorialname and
tutorialid. Choose the Tutorial ID one.

Repeat the above 3 steps for the Tutorial Name text box.

• So click on the Tutorial Name text box


• Go to the properties window
• Choose the Text property
• Choose the tutorialname option under
demotbbindingsource

Step 6) Next we need to change the Binding Source


property of the bindingnavigator to point to our Demotb
data source. The reason we do this is that the Binding
Navigator also needs to know which table it needs to
refer to.
244
The Binding Navigator is used to select the next or
previous record in the table. So even though the data
source is added to the project as a whole and to the text
box control, we still need to ensure the Binding
Navigator also has a link to our data source. In order to
do this, we need to click the Binding navigator object, go
to the Binding Source property and choose the one that is
available

Next, we need to go to the Properties window so that we


can make the change to Binding Source property.

245
When all of the above steps are executed successfully,
you will get the below-mentioned output.

Output:-

Now when the project is launched, you can see that the
textboxes automatically get the values from the table.

246
When you click the Next button on the Navigator, it
automatically goes to the next record in the table. And
the values of the next record automatically come in the
text boxes

C# datagridview

Data Grids are used to display data from a table in a grid-


like format. When a user sees’s table data, they normally
prefer seeing all the table rows in one shot. This can be
achieved if we can display the data in a grid on the form.

C# and Visual Studio have inbuilt data grids, this can be


used to display data. Let’s take a look at an Example: of
this. In our Example:, we will have a data grid, which will
be used to display the Tutorial ID and Tutorial Name
values from the demotb table.

Step 1) Drag the datagridview control from the toolbox


to the Form in Visual Studio. The datagridview control is
used in Visual Studio to display the rows of a table in a
grid-like format.

247
Step 2) In the next step, we need to connect our data grid
to the database. In the last section, we had created a
project data source. Let’s use the same data source in our
Example:.

• First, you need to choose the grid and click on the


arrow in the grid. This will bring up the grid
configuration options.
• In the configuration options, just choose the data
source as demotbbinding Source which was the
data source created in the earlier section.

If all the above steps are executed as shown, you will get
the below-mentioned output.

Output:-

248
From the output, you can see that the grid was populated
by the values from the database.

Summary

• C# SQL can work with databases such as Oracle


and Microsoft SQL Server.
• This C# database tutorial has all the commands
which are required to work with databases. This
involves establishing a connection to the database.
You can perform operations such as select, update,
insert and delete using the commands in C#.
• The datareader object in C# is used to hold all the
data returned by the database. The While loop in
C# can be used to read the data rows one at a time.

249
• The data adapter object is used to perform SQL
operations such as insert, delete, and update
against the database.
• C# can bind controls to the various fields in a table.
They are bound by defining a data source in C#.
The data source is used to pull the data from the
database and populate them in the controls.
• The binding navigator is used to automatically
navigate through the rows in a table.
• The data grid in C# can connect to the database
and display all the values from the table in a grid-
like format.

4.7 Distributed Applications

As described in the previous sections, processes as well


as application domains provide a close, protected
environment. As a result, objects in a process or an
application domain cannot talk directly to objects in
another process or another application domain.

However, in the increasingly connected world,


enterprises and users demand distributed applications.
Distributed applications allow objects to talk across
process boundaries. Often, distributed applications also
meet the following objectives:

• Establish communication between objects that run


in different application domains and processes,
whether on the same computer or across the
Internet.
250
• Enable enterprise application integration by
establishing communication between objects that
run on heterogeneous architectures.

• Enable application availability by making sure that


portions of an application run even if some
components are busy or have failed.

• Provide increased security and scalability by


dividing the application into several layers (or
tiers).

4.7.1 Evolution of Distributed Applications

A well-designed distributed application has the potential


to be more connected, more available, more scalable, and
more robust than an application where all components
run on a single computer. This is a desirable model for an
enterprise application.

Traditionally, there have been several efforts to design


frameworks for developing distributed applications. A
few well-known frameworks are Distributed Computing
Environment/Remote Procedure Calls (DEC/RPC),
Microsoft Distributed Component Object Model (DCOM),
Common Object Request Broker Architecture (CORBA),
and Java Remote Method Invocation (RMI). Some of these
implementations are widely deployed in enterprises.

However, modern business requirements are different


from those of earlier days. Today, businesses seek
solutions that can be developed rapidly, that integrate
251
well with their legacy applications, and that interoperate
well with their business partners. Each of the
technologies already mentioned failed to satisfy one or
more of these requirements.

In 2000, Microsoft introduced the .NET Framework for


designing next-generation distributed applications. As
you'll explore more in this book, the .NET Framework is
specifically targeted to meet the needs of modern
business, whether the need is rapid development or
integration or interoperability.

The .NET Framework provides various mechanisms to


support distributed application development. Most of
this functionality is present in the following three
namespaces of the Framework Class Library (FCL):

• The System.Net Namespace—This namespace


includes classes to create standalone listeners and
custom protocol handlers to start from scratch and
create your own framework for developing a
distributed application. Working with the
System.Net namespace directly requires a good
understanding of network programming.

• The System.Runtime.Remoting Namespace—This


namespace includes the classes that constitute the
.NET remoting framework. The .NET remoting
framework allows communication between objects
living in different application domains, whether or
not they are on the same computer. Remoting

252
provides an abstraction over the complex network
programming and exposes a simple mechanism for
inter-application domain communication. The key
objectives of .NET remoting are flexibility and
extensibility.

• The System.Web.Services Namespace—This


namespace includes the classes that constitutes the
ASP.NET Web services framework. ASP.NET Web
services allow objects living in different application
domains to exchange messages through standard
protocols such as HTTP and SOAP. ASP.NET Web
services, when compared to remoting, provide a
much higher level of abstraction and simplicity.
The key objectives of ASP.NET Web services are
the ease of use and interoperability with other
systems.

• Both .NET remoting and ASP.NET Web services


provide a complete framework for designing
distributed applications. Most programmers will
use either .NET remoting or ASP.NET Web services
rather than build a distributed programming
framework from scratch with the System.Net
namespace classes.

• The functionality offered by .NET remoting and


ASP.NET Web services appears very similar. In fact,
ASP.NET Web services are actually built on the
.NET remoting infrastructure. It is also possible to
use .NET remoting to design Web services. Given
253
the amount of similarity, how do you choose one
over the other in your project? Simply put, the
decision depends on the type of application you
want to create. You'll use.NET Remoting when both
the end points (client and server) of a distributed
application are in your control. This might be a
case when an application has been designed for
use within a corporate network.

• ASP.NET Web services when one end point of a


distributed application is not in your control. This
might be a case when your application is
interoperating with your business partner's
application.

4.8 What is Globalization?

Globalization refers to any activity that brings the people,


cultures and economies of different countries closer
together. In business, "globalization" refers to practices
by which organizations become better connected to their
customers around the world. This includes any aspect of
operating in different national markets, from product
design to marketing.

Globalization Examples

If that’s still a bit vague for you, here are a few Example:s
of globalization in the world of business:

Online marketplaces like ebay and Amazon make it easy


to buy products from businesses or individuals on the
254
other side of the planet. Even products sold in traditional
brick-and-mortar stores like Target often make stops in
several different countries before reaching their final
destinations. Consumer electronics, for Example:, are
commonly sourced from raw materials in India, made in
China, then sold in America.

Many large restaurant chains, like mcdonald's, operate in


dozens of countries. Mcdonald's specifically has
franchises in upwards of one hundred countries, and
diners around the world recognize its brand and logo.

Netflix operates in more than 190 countries and


customizes content offerings for individual markets with
subtitles and programming in local languages.

The instantly recognizable "swoosh" logo of Nike


transcends different cultures and languages. Nike has
formed partnerships with athletes who play a variety of
sports in many different countries and uses these
endorsements to support its worldwide expansion.

There are many benefits of globalization for both


companies and consumers. The impact of global inter-
connectivity has been a boon for the world economy in
recent decades and has increased global GDP from $89.6
trillion in 2010 to a projected $149 trillion in 2021.
Globalization has come hand-in-hand with the most
transformation advances of the 20th century, such as
international air travel and the Internet.

255
The rise of globalization also means that there has
arguably never been a better time to build a business
into a global company. There are a huge range of
opportunities available to companies looking to expand,
from access to a global talent pool to an increased
volume of information that can be used to position a
business. As it gets easier to enter new markets, there
are also more product niches to take advantage of—and
new customers to attract.

However, to truly go global takes a lot of preparation.


Two of the most important steps in this process are to
localize and internationalize your product. While both
localization and internationalization fall under the
banner of globalization, there are some differences
between the two. We’ll explore these further in the
following sections.

What is Internationalization?

Internationalization is a corporate strategy that involves


making products and services as adaptable as possible,
so they can easily enter different national markets. This
often requires the assistance of subject matter experts.
Internationalization is sometimes shortened to "i18n",
where 18 represents the number of characters in the
word.

Products intended for use by speakers of multiple


languages typically undergo an internationalization
process. For Example:, IKEA internationalizes the

256
assembly instructions for its furniture by using only
diagrams and illustrations, without including any text
that would need to be translated. Products with
instructions that do require translation are still often
written with the goal of being as culturally-neutral as
possible. This, of course, is easier said than done.

In the case of software products and electronics,


internationalization involves a number of different
concerns:

Data encoding: The ASCII character encoding is sufficient


for texts in most Western European languages. However,
languages that use non-Latin alphabets, such as Russian,
Chinese, Hindi and Korean, require larger character
encodings like Unicode.

Hardware support: Software designers must consider


that certain hardware devices may not be available in all
countries.

User interface: If a software application will be translated


into multiple languages, the user interface needs to
include enough space for the text in all of these
languages.

According to most definitions, companies must first


internationalize before they can localize a product. In the
next section, we'll discuss the difference between
internationalization and localization.

What is Localization?
257
Localization is the process of adapting a product to a
specific target market. This usually happens after
internationalization has taken place. Where
internationalization develops a product that’s easy to
adapt for many audiences in many different countries,
localization takes that product and makes it highly
relevant for one specific market.

As mentioned, mcdonald's operates over 30,000


restaurants in 100 countries. Its worldwide expansion is
an Example: of globalization. By design, the corporation
creates a menu adaptable to various local tastes and
customs. This policy is an Example: of
internationalization.

Many of the mcdonald's restaurants in Israel serve


kosher food and drink and close during the Sabbath and
Jewish holidays. Mcdonald's has also opened a meat-free
restaurant in India, a country in which much of the
population does not eat beef or pork. In both cases,
mcdonald's has maintained its global brand identity but
tailored its products and services for local markets.
These cases exemplify localization.

4.9 Authentication in ASP.NET

There are two closely interlinked concepts at the heart of


security for distributed applications - authentication and
authorization. Authentication is the process of obtaining
some sort of credentials from the users and using those
credentials to verify the user's identity. Authorization is
258
the process of allowing an authenticated user access to
resources. Authentication is always precedes to
Authorization; even if your application lets anonymous
users connect and use the application, it still
authenticates them as being anonymous.

ASP.net provides flexible set of alternatives for


authentication. You can perform authentication yourself
in code or delegate authentication to other authorities
(such as Microsoft Passport). In fact sometimes it seems
ASP.net authentication is a bit too flexible; it can be
difficult for a new developer to know just where to start.
In this article, we review the settings in ASP.net and
Internet Information Services (IIS) that control
authentication and authorization in ASP.net applications.

An ASP.net application has two separate authentication


layers. That is because ASP.net is not a standalone
product. Rather it is a layer on top of IIS. All requests
flow through IIS before they are handed to ASP.net. As a
result, IIS can decide to deny access without the ASP.net
process even knowing that someone requested a
particular page. Here is an overview of the steps in the
joint IIS and ASP.net authentication process.

IIS first checks to make sure the incoming request comes


from an IP address that is allowed access to the domain.
If not it denies the request.

Next IIS performs its own user authentication if it


configured to do so. By default IIS allows anonymous

259
access, so requests are automatically authenticated, but
you can change this default on a per - application basis
with in IIS.

If the request is passed to ASP.net with an authenticated


user, ASP.net checks to see whether impersonation is
enabled. If impersonation is enabled, ASP.net acts as
though it were the authenticated user. If not ASP.net acts
with its own configured account.

Finally the identity from step 3 is used to request


resources from the operating system. If ASP.net
authentication can obtain all the necessary resources it
grants the users request otherwise it is denied.
Resources can include much more than just the ASP.net
page itself you can also use .Net's code access security
features to extend this authorization step to disk files,
Registry keys and other resources.

As you can see several security authorities interact when


the user requests and ASP.net page. If things are not
behaving the way you think they should, it can be helpful
to review this list and make sure you have considered all
the factors involved

Authentication Providers

Assuming IIS passes a request to ASP.net, what happens


next? The answer depends on the configuration of
ASP.net itself. The ASP.net architecture includes the
concept of and authentication provider a piece of code
whose job is to verify credentials and decide whether a
260
particular request should be considered authenticated.
Out of the box ASP.net gives you a choice of three
different authentication providers.

The windows Authentication provider lets you


authenticates users based on their windows accounts.
This provider uses IIS to perform the authentication and
then passes the authenticated identity to your code. This
is the default provided for ASP.net.

The passport authentication provider uses Microsoft's


passport service to authenticate users.

The forms authentication provider uses custom HTML


forms to collect authentication information and lets you
use your own logic to authenticate users. The user's
credentials are stored in a cookie for use during the
session.

Introduction

Extensible Markup Language (XML) strores and


transports data. If we use a XML file to store the data
then we can do operations with the XML file directly
without using the database. The XML format is supported
for all applications. It is independent of all software
applications and it is accessible by all applications. Here
is an Example: that shows how to insert the data into the
XML file and how to retrieve the data from the XML file;
also how to bind the data into tha datalist using ASP.NET.
For this the following procedure can be used.

261
Step 1: First start Visual Studio 2010 by clicking "File" ->
"New" -> "Web Site..." then click on "ASP.NET Web Site".
Now write the following inline code that will design your
web page.

<html xmlns="http://www.w3.org/1999/xhtml">

<head runat="server">

<title></title>

<style type="text/css">

.style1

Width: 40%;

Border-style: solid;

Border-width: 1px;

Background-color:Silver;

Height: 152px;

.style2

262
{

Width: 295px;

.style3

Width: 754px;

</style>

</head>

<body>

<form id="form1" runat="server">

<div>

<table class="style1">

<tr>

<td class="style2">

263
&nbsp;</td>

<td class="style3">

&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
&nbsp; Employee_Information</td>

</tr>

<tr>

<td class="style2">

Name:</td>

<td class="style3">

<asp:textbox ID="textbox1"
runat="server"></asp:textbox>

</td>

</tr>

<tr>

<td class="style2">

Emp_Id:</td>

264
<td class="style3">

<asp:textbox
ID="textbox2"runat="server"></asp:textbox>

</td>

</tr>

<tr>

<td class="style2">

Qualification:</td>

<td class="style3">

<asp:dropdownlist ID="dropdownlist1"
runat="server" Height="22px" Width="132px">

<asp:listitem>--SELECT--</asp:listitem>

<asp:listitem>MCA</asp:listitem>

<asp:listitem>BCA</asp:listitem>

<asp:listitem>MBA</asp:listitem>

<asp:listitem>BBA</asp:listitem>

265
<asp:listitem>btech</asp:listitem>

<asp:listitem>mtech</asp:listitem>

</asp:dropdownlist>

</td>

</tr>

<tr>

<td class="style2">

&nbsp;</td>

<td class="style3">

<asp:Button ID="Button1" runat="server"


Text="Submit" onclick="Button1_Click"/>

<asp:Button ID="Button2" runat="server"


onclick="Button2_Click" Text="Show"/>

</td>

</tr>

</table>

266
<asp:datalist ID="datalist1" runat="server"
backcolor="#DEBA84" bordercolor="#DEBA84"

Borderstyle="None" borderwidth="1px" cellpadding="3"


cellspacing="2" gridlines="Both"
repeatdirection="Horizontal"

Style="margin-right: 32px">

<footerstyle backcolor="#F7DFB5"
forecolor="#8C4510"/>

<headerstyle backcolor="#A55129" Font-


Bold="True"forecolor="White"/>

<itemstyle backcolor="#FFF7E7"
forecolor="#8C4510"/>

<selecteditemstyle backcolor="#738A9C" Font-


Bold="True" forecolor="White"/>

<itemtemplate>

<hrsize=0 />

Name:<%#databinder.Eval(Container.dataitem,"name")
%><br/>

267
Emp_id:<%#databinder.Eval(Container.dataitem,"Emp_i
d")%></a><br/>

Qualification:<%#databinder.Eval(Container.dataitem,"Q
ualification")%><br/>

</itemtemplate>

</asp:datalist>

<br />

</div>

</form>

</body>

</html>

The design will look as in the following image:

Designing.jpg

Step 2: Add a XML file by clicking "File" -> "Add new


item" then click on "XML file". Name this XML file
Sample.xml. Put the following code in the XML file:

<?Xml version="1.0"encoding="utf-8"?>

268
<employeeinformation>

</employeeinformation>

Step 3: After that add the following namespaces in the


code behind:

Using System.Data;

Using System.Xml;

Step 4: Now write the following code in the code behind


file:

Public partial classdefault2 : System.Web.UI.Page

Protected void Page_Load(object sender, eventargs e)

If (!Ispostback)

//Bind xml data to datalist

Binddatalist();

269
}

Private void binddatalist()

Xmltextreader xmlreader =new


xmltextreader(Server.mappath("Employee.xml"));

Dataset ds = newdataset();

Ds.readxml(xmlreader);

Xmlreader.Close();

If (ds.Tables.Count != 0)

Datalist1.datasource = ds;

Datalist1.databind();

Else

Datalist1.datasource = null;

Datalist1.databind();

}
270
}

Step 5: Write the following code in the click event of the


submit button, so that the data that is entered is stored in
the XML File:

Protected void Button1_Click(object sender, eventargs e)

Xmldocument xmldoc =new xmldocument();

Xmldoc.Load(Server.mappath("Employee.xml"));

Binddatalist();

Step 6: Write the following code in the click event of the


show button. Now the data stored in the XML file can be
shown.

Protected void Button2_Click(object sender, eventargs e)

Xmldocument xmldoc =new xmldocument();

Xmldoc.Load(Server.mappath("Employee.xml"));

Xmlelement parentelement =
xmldoc.createelement("Details");

271
Xmlelement name = xmldoc.createelement("Name");

Name.innertext = textbox1.Text;

Xmlelement Emp_id =
xmldoc.createelement("Emp_id");

Emp_id.innertext = textbox2.Text;

Xmlelement Qualification =
xmldoc.createelement("Qualification");

Qualification.innertext =
dropdownlist1.selecteditem.Text;

Parentelement.appendchild(name);

Parentelement.appendchild(Emp_id);

Parentelement.appendchild(Qualification);

Xmldoc.documentelement.appendchild(parentelement);

Xmldoc.Save(Server.mappath("Employee.xml"));

Binddatalist();

Step 7: Run your application by pressing F5. The output


is:

Save.jpg

272
Step 8 : See your sample.xml file, it will include the data
that I entered at the run time like this:

<?Xmlversion="1.0"encoding="utf-8"?>

<employeeinformation>

<Details>

<Name>Richa</Name>

<Emp_id>1</Emp_id>

<Qualification>MCA</Qualification>

</Details>

</employeeinformation>

273
PROGRAMS/PROJECTS
PROGRAM 1

C# program to print Even and Odd numbers from 1 to


30.

Even numbers are those numbers they are divisible by 2.


And odd numbers are those numbers they are not
divisible by 2. 0 is an even number.

Using System;

Using System.Collections.Generic;

Using System.Linq;

Using System.Text;

Namespace consoleapplication1

Class Program

Static void Main(string[] args)

Int i = 0;

274
Console.writeline("Even Numbers :");

For (i = 1; i <= 50; i++)

If( i%2 == 0 )

Console.Write(i + " ");

Console.writeline("\nodd Numbers :");

For (i = 1; i <= 50; i++)

If (i % 2 != 0)

Console.Write(i + " ");

Console.writeline();

275
}

Output

Even Numbers :

2 4 6 8 10 12 14 16 18 20 22 24 26 28 30 32 34 36 38 40
42 44 46 48 50

Odd Numbers :

1 3 5 7 9 11 13 15 17 19 21 23 25 27 29 31 33 35 37 39
41 43 45 47 49

276
PROGRAM 2

Write a c# program to print fibonacci series without


using recursion and using recursion.

Using System;

Public class fibonacciExample:

Public static void Main(string[] args)

Int n1=0,n2=1,n3,i,number;

Console.Write("Enter the number of elements: ");

Number = int.Parse(Console.readline());

Console.Write(n1+" "+n2+" "); //printing 0 and 1

For(i=2;i<number;++i) //loop starts from 2 because


0 and 1 are already printed

N3=n1+n2;

Console.Write(n3+" ");

N1=n2;

N2=n3;
277
}

Output:

Enter the number of elements: 15

0 1 1 2 3 5 8 13 21 34 55 89 144 233 377

278
PROGRAM 3

Write a c# program to print factorial of a number.

Using System;

Public class factorialExample:

Public static void Main(string[] args)

Int i,fact=1,number;

Console.Write("Enter any Number: ");

Number= int.Parse(Console.readline());

For(i=1;i<=number;i++){

Fact=fact*i;

Console.Write("Factorial of " +number+" is: "+fact);

279
Output:

Enter any Number: 6

Factorial of 6 is: 720

280
PROGRAM 4

Write a c# program to print alphabet triangle

Using System;

Public class printExample:

Public static void Main(string[] args)

Char ch='A';

Int i, j, k, m;

For(i=1; i<=5; i++)

For(j=5; j>=i; j--)

Console.Write(" ");

For(k=1;k<=i;k++)

Console.Write(ch++);

Ch--;

For(m=1;m<i;m++)

Console.Write(--ch);

281
Console.Write("\n");

Ch='A';

Output:

ABA

ABCBA

ABCDCBA

ABCDEDCBA

282
PROGRAM 5

Write a Vb.net program to design following screen,


accept the details from the user. Clicking on Submit
button Net Salary should be calculated and displayed
into the textbox. Display the messagebox informing
the Name and Net Salary of employee.

283
Program:-

Public Class slip7

Private Sub Button1_Click(sender As Object, e As


eventargs) Handles Button1.Click

Dim cal, tax, bs, da, hra, ma, pf, pt, it As Integer

Bs = cint(textbox2.Text)

Da = cint(textbox3.Text)

Hra = cint(textbox4.Text)

Ma = cint(textbox5.Text)

Pf = cint(textbox6.Text)

Pt = cint(textbox7.Text)

It = cint(textbox8.Text)

Cal = bs + ((da * bs) / 100) + ((hra * bs) / 100) +


((ma * bs) / 100)

Tax = ((pt * bs) / 100) + ((it * bs) / 100) + ((pf * bs) /


100)

Cal = cal - tax

Textbox9.Text = cal

Msgbox("Name: " + textbox1.Text + " Net salary: " +


textbox9.Text)
284
End Sub

End Class

Output:-

285
PROGRAM 6

Write a Vb.net program to design the following form,


select the question number from combo box that
question will be displayed into textbox and the
options for that question will be displayed on four
radio buttons, select option and click on submit
button result should be displayed in another textbox.

Program:-

Public Class slip14

Private Sub slip14_Load(sender As Object, e As


eventargs) Handles mybase.Load

Combobox1.Items.Add("Question1")
286
Combobox1.Items.Add("Question2")

Combobox1.Items.Add("Question3")

Radiobutton1.Visible = False

Radiobutton2.Visible = False

Radiobutton3.Visible = False

Radiobutton4.Visible = False

End Sub

Private Sub Button1_Click(sender As Object, e As


eventargs) Handles Button1.Click

If combobox1.selecteditem() = "Question1" Then

If radiobutton1.Checked = True Then

Textbox2.Text = "Answer is Correct."

Else

Textbox2.Text = "Answer is Wrong."

End If

End If

If combobox1.selecteditem() = "Question2" Then

If radiobutton2.Checked = True Then

Textbox2.Text = "Answer is Correct."


287
Else

Textbox2.Text = "Answer is Wrong."

End If

End If

If combobox1.selecteditem() = "Question3" Then

If radiobutton4.Checked = True Then

Textbox2.Text = "Answer is Correct."

Else

Textbox2.Text = "Answer is Wrong."

End If

End If

End Sub

Private Sub combobox1_selectedindexchanged(sender


As Object, e As eventargs) Handles
combobox1.selectedindexchanged

Radiobutton1.Visible = True

Radiobutton2.Visible = True

Radiobutton3.Visible = True

288
Radiobutton4.Visible = True

If combobox1.selecteditem() = "Question1" Then

Textbox1.Text = "What is capital of India?"

Textbox2.Text = ""

Radiobutton1.Checked = False

Radiobutton2.Checked = False

Radiobutton3.Checked = False

Radiobutton4.Checked = False

Radiobutton1.Text = "New Delhi"

Radiobutton2.Text = "Mumbai"

Radiobutton3.Text = "Pune"

Radiobutton4.Text = "Chennai"

Elseif combobox1.selecteditem() = "Question2" Then

Textbox1.Text = "What is Capital of USA?"

Textbox2.Text = ""

Radiobutton1.Checked = False

Radiobutton2.Checked = False

Radiobutton3.Checked = False

289
Radiobutton4.Checked = False

Radiobutton1.Text = "New York"

Radiobutton2.Text = "Washington DC"

Radiobutton3.Text = "California"

Radiobutton4.Text = "Georgia"

Elseif combobox1.selecteditem() = "Question3" Then

Textbox1.Text = "what is capital of Germany?"

Textbox2.Text = ""

Radiobutton1.Checked = False

Radiobutton2.Checked = False

Radiobutton3.Checked = False

Radiobutton4.Checked = False

Radiobutton1.Text = "Frankfurt"

Radiobutton2.Text = "Washington DC"

Radiobutton3.Text = "Hamburg"

Radiobutton4.Text = "Berlin"

End If

End Sub

290
End Class

Output:-

291
PROGRAM 7

Write a Vb.net program to design the following form,


this program shows the details of students in the
form of form (use split container or Groupbox
control to separate the input and output session).

Program:-

Public Class slip17

Private Sub slip17_Load(sender As Object, e As


eventargs) Handles mybase.Load

Combobox1.Items.Add("BCA")

Combobox1.Items.Add("BSC")

Combobox1.Items.Add("MCA")

Splitcontainer1.Panel2.Hide()
292
End Sub

Private Sub Button1_Click(sender As Object, e As


eventargs) Handles Button1.Click

Splitcontainer1.Panel2.Show()

Label26.Text = textbox1.Text

Label25.Text = textbox2.Text

Label24.Text = textbox3.Text

Label23.Text = combobox1.selecteditem()

If radiobutton1.Checked = True Then

Label22.Text = radiobutton1.Text

Elseif radiobutton2.Checked = True Then

Label22.Text = radiobutton2.Text

End If

Label21.Text = datetimepicker1.Value

Label20.Text = textbox4.Text

Label19.Text = textbox5.Text

End Sub

End Class

293
Output:-

294
PROGRAM 8

Write a Vb.net program to design the following form,


accept all details from user and display the details
through message box.

Program:-

Public Class slip18

Private Sub Button1_Click(sender As Object, e As


eventargs) Handles Button1.Click

Dim a, b As String

If checkbox1.Checked = True Then

A = checkbox1.Text

Elseif checkbox2.Checked = True Then

A = checkbox2.Text

295
Elseif checkbox3.Checked = True Then

A = checkbox3.Text

End If

If radiobutton1.Checked = True Then

B = radiobutton1.Text

Elseif radiobutton2.Checked = True Then

B = radiobutton2.Text

Elseif radiobutton3.Checked = True Then

B = radiobutton3.Text

End If

Msgbox("Name : " + textbox1.Text + " Qualification : "


+ a + " post: " + b)

End Sub

End Class

296
Output:-

297
PROGRAM 9

Students marksheet Result Program in VB.NET

Create one class student which stores information of


student’s Roll no, Name, Total marks, which can not be
used from outside the class. Student class must provide
properly methods to read and write this information. The
child class must provide function for calculating the total
which should be stored in Total Marks of base class. The
child classes must have the correct method for
calculating percentage according to no. Of subjects.
Demonstrate the use of these classes.

FYBCA.VB

Public Class FYBCA

Inherits student

Dim i As Integer = 0

Dim submark(4) As Integer

Public Property calculatemark As Integer

Set(byval value As Integer)

Submark(i) = value

I += 1

End Set

298
Get

Return submark.Sum

End Get

End Property

End Class

SYBCA.VB

Public Class SYBCA

Inherits student

Dim i As Integer = 0

Dim submark(4) As Integer

Public Property calculatemark As Integer

Set(byval value As Integer)

Submark(i) = value

I += 1

End Set

Get

Return submark.Sum

End Get

299
End Property

End Class

TYBCA.VB

Public Class TYBCA

Inherits student

Dim i As Integer = 0

Dim submark(4) As Integer

Public Property calculatemark As Integer

Set(byval value As Integer)

Submark(i) = value

I += 1

End Set

Get

Return submark.Sum

End Get

End Property

End Class

Student.vb

300
Public Class student

Dim rollno, totalmarks As Single

Dim studentname As String

Public Property roll As Integer

Set(byval value As Integer)

Rollno = value

End Set

Get

Return rollno

End Get

End Property

Public Property mark As Integer

Set(byval value As Integer)

Totalmarks = value

End Set

Get

Return totalmarks

End Get

301
End Property

Public Property name As String

Set(byval value As String)

Studentname = value

End Set

Get

Return studentname

End Get

End Property

Public Function percentage(byval i As Integer) As


Single

Totalmarks = i

Return totalmarks / 4

End Function

End Class

Form1.vb

Public Class Form1

Private i As Short

302
Private Sub Form1_Load(sender As Object, e As
eventargs) Handles mybase.Load

Sub1.Visible = False

Sub2.Visible = False

Sub3.Visible = False

Sub4.Visible = False

End Sub

Private Sub fybca_Click(sender As Object, e As


eventargs) Handles fybca.Click

Changeyear()

Fybca.forecolor = Color.Black

Sub1name.Text = "C Language"

Sub2name.Text = "HTML"

Sub3name.Text = "DHTML & XML"

Sub4name.Text = "DBMS-1"

I=1

End Sub

Private Sub sybca_Click(sender As Object, e As


eventargs) Handles sybca.Click

303
Changeyear()

Sybca.forecolor = Color.Black

Sub1name.Text = "C++ Language"

Sub2name.Text = "VB.NET"

Sub3name.Text = "DBMS-2"

Sub4name.Text = "Fundamental OS"

I=2

End Sub

Private Sub tybca_Click(sender As Object, e As


eventargs) Handles tybca.Click

Changeyear()

Tybca.forecolor = Color.Black

Sub1name.Text = "JAVA"

Sub2name.Text = "ASP.NET"

Sub3name.Text = "Advance JAVA"

Sub4name.Text = "Advance VB.NET"

I=3

End Sub

Sub changeyear()
304
Sub1.Clear()

Sub2.Clear()

Sub3.Clear()

Sub4.Clear()

Sub1.Visible = True

Sub2.Visible = True

Sub3.Visible = True

Sub4.Visible = True

Totaldisplay.Text = ""

Persdisplay.Text = ""

Fybca.forecolor = Color.White

Sybca.forecolor = Color.White

Tybca.forecolor = Color.White

End Sub

Private Sub Button1_Click(sender As Object, e As


eventargs) Handles

Dispresult.Click

If i = 1 Then

Dim fystudent As New FYBCA


305
Fystudent.calculatemark = Val(sub1.Text)

Fystudent.calculatemark = Val(sub2.Text)

Fystudent.calculatemark = Val(sub3.Text)

Fystudent.calculatemark = Val(sub4.Text)

Totaldisplay.Text = "Total Marks : " &


fystudent.calculatemark

Persdisplay.Text = "Percentage : " &


fystudent.percentage(fystudent.calculatemark)

Elseif i = 2 Then

Dim systudent As New SYBCA

Systudent.calculatemark = Val(sub1.Text)

Systudent.calculatemark = Val(sub2.Text)

Systudent.calculatemark = Val(sub3.Text)

Systudent.calculatemark = Val(sub4.Text)

Totaldisplay.Text = "Total Marks : " &


systudent.calculatemark

Persdisplay.Text = "Percentage : " &


systudent.percentage(systudent.calculatemark)

Elseif i = 3 Then

Dim tystudent As New TYBCA


306
Tystudent.calculatemark = Val(sub1.Text)

Tystudent.calculatemark = Val(sub2.Text)

Tystudent.calculatemark = Val(sub3.Text)

Tystudent.calculatemark = Val(sub4.Text)

Totaldisplay.Text = "Total Marks : " &


tystudent.calculatemark

Persdisplay.Text = "Percentage : " &


tystudent.percentage(tystudent.calculatemark)

Else

Msgbox("Select Year of BCA")

End If

End Sub

End Class

307
308
PROGRAM 10

Implementation of Server Side Controls in asp.net

Here, we are implementing an HTML server control in


the form.

// htmlcontrolsExample:.aspx

<%@ Page Language="C#" autoeventwireup="true"


codebehind="htmlcontrolsExample:.aspx.cs"

Inherits="asp.netExample:.htmlcontrolsExample:" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">

<head runat="server">

<title></title>

</head>

<body>

<form id="form1" runat="server">

<div>

<input id="Text1" type="text" runat="server"/>

<asp:Button ID="Button1" runat="server" Text="Button"


onclick="Button1_Click"/>

309
</div>

</form>

</body>

</html>

This application contains a code behind file.

// htmlcontrolsExample:.aspx.cs

Using System;

Namespace asp.netExample:

Public partial class htmlcontrolsExample: :


System.Web.UI.Page

Protected void Page_Load(object sender, eventargs e)

Protected void Button1_Click(object sender, eventargs e)

String a = Request.Form["Text1"];

Response.Write(a);
310
}

Output:

When we click the button after entering text, it responses


back to client.

311
PROGRAM 11

Registration Form In C# With SQL Database

This article will show you how you can create


registration form in c#.net with SQL database. So in this
article I have used Ms SQL server database. In this I will
save the user login detail into sql table by using c#.net

First we will create a windows application


registration form.

Above form is a custom design registration from and you


can check how to create a custom registration from in
windows application.

On submit button add the below code.

Private void btnsubmit_Click(object sender, eventargs e)


312
{

String connection = @"Server=LAPTOP-


EVJEKV38\SQLEXPRESS; Database=testdb;
Integrated Security=True";

Sqlconnection con = new


sqlconnection(connection);

Try

String query = "Insert into


userlogin(Name,emailid,loginid,Password) Values('"
+ txtname.Text + "','" + txtemailid.Text + "','" +
txtloginid.Text + "','" + txtpassword.Text + "')";

Sqldataadapter da = new sqldataadapter(query,


con);

Con.Open();

Da.selectcommand.executenonquery();

Messagebox.Show("Account created
successfully..");

Cleardata();

Catch

313
{

Messagebox.Show("Error occured...");

Finally

Con.Close();

//Clear data after submit

Private void cleardata()

Txtname.Text = "";

Txtemailid.Text = "";

Txtloginid.Text = "";

Txtpassword.Text = "";

Txtconpassword.Text = "";

314
Here is above code I have saved the data into the
database. After saving the record a message will show
and later all the records have been cleared. Now let’s run
the application and check the output. For this I have
created a table named as userlogin.

In above code u need to change the connection string


as per your server database and change the query as
per you need.

Now add the detail into form and click on submit.

315
316
PROGRAM 12

Creating User Registration Form In ASP.NET

After studying web server controls now let's create a


user registration form. This web form takes user input
and submits to the server. After submitting, it return
message of successfully registered. This whole process
takes the following steps.

1. Add a Web Form to the project

317
318
1. Adding Controls to the form

To add controls to the form either we can drag


components from the toolbox or write code manually to
create the components.

The following file contains the code for a user


registration form.

// webcontrols.aspx

1. <%@ Page Language="C#"


autoeventwireup="true"
codebehind="webcontrols.aspx.cs"
2. Inherits="webformscontrolls.webcontrols" %>
3. <!DOCTYPE html>
4. <html xmlns="http://www.w3.org/1999/xhtml">
5. <head runat="server">
6. <title></title>
7. <style type="text/css">
8. .auto-style1 {
9. Width: 100%;
10. }
11. .auto-style2 {
12. Width: 278px;
13. }

319
14. .auto-style3 {
15. Width: 278px;
16. Height: 23px;
17. }
18. .auto-style4 {
19. Height: 23px;
20. }
21. </style>
22. </head>
23. <body>
24. <form id="form1" runat="server">
25. <div>
26. <table class="auto-style1">
27. <tr>
28. <td>
29. <asp:Label ID="Label1" runat="server" Text="User
Name"></asp:Label>
30. </td>
31. <td>
32. <asp:textbox ID="username" runat="server"
required="true"></asp:textbox></td>
33. </tr>
34. <tr>
35. <td>
36. <asp:Label ID="Label6" runat="server"
Text="Email ID"></asp:Label>
37. </td>
38. <td>
39. <asp:textbox ID="emailid" runat="server"
textmode="Email"></asp:textbox></td>
320
40. </tr>
41. <tr>
42. <td>
43. <asp:Label ID="Label2" runat="server"
Text="Password"></asp:Label></td>
44. <td>
45. <asp:textbox ID="textbox2" runat="server"
textmode="Password"></asp:textbox></td>
46. </tr>
47. <tr>
48. <td>
49. <asp:Label ID="Label3" runat="server"
Text="Confirm Password"></asp:Label></td>
50. <td>
51. <asp:textbox ID="textbox3" runat="server"
textmode="Password"></asp:textbox></td>
52. </tr>
53. <tr>
54. <td>
55. <asp:Label ID="Label4" runat="server"
Text="Gender"></asp:Label></td>
56. <td>
57. <asp:radiobutton ID="radiobutton1"
runat="server" groupname="gender" Text="Male"
/>
58. <asp:radiobutton ID="radiobutton2"
runat="server" groupname="gender"
Text="Female" /></td>
59. </tr>
60. <tr>
321
61. <td>
62. <asp:Label ID="Label5" runat="server"
Text="Select Course"></asp:Label>s</td>
63. <td>
64. <asp:checkbox ID="checkbox1" runat="server"
Text="J2SEE" />
65. <asp:checkbox ID="checkbox2" runat="server"
Text="J2EE" />
66. <asp:checkbox ID="checkbox3" runat="server"
Text="Spring Framework" />
67. </td>
68. </tr>
69. <tr>
70. <td>
71. </td>
72. <td>
73. <br />
74. <asp:Button ID="Button1" runat="server"
Text="Register" cssclass="btn btn-primary"
onclick="Button1_Click"/>
75. </td>
76. </tr>
77. </table>
78. <asp:Label ID="message" runat="server" Font-
Size="Medium" forecolor="Red"></asp:Label>
79. </div>
80. </form>
81. <table class="auto-style1">
82. <tr>

322
83. <td class="auto-style2"><asp:Label
ID="showusernamelabel" runat="server"
></asp:Label></td>
84. <td>
85. <asp:Label ID="showusername" runat="server"
></asp:Label></td>
86. </tr>
87. <tr>
88. <td class="auto-style2"><asp:Label
ID="showemailidlabel" runat="server"
></asp:Label></td>
89. <td>
90. <asp:Label ID="showemail" runat="server"
></asp:Label></td>
91. </tr>
92. <tr>
93. <td class="auto-style3"><asp:Label
ID="showgenderlabel" runat="server"
></asp:Label></td>
94. <td class="auto-style4">
95. <asp:Label ID="showgender" runat="server"
></asp:Label></td>
96. </tr>
97. <tr>
98. <td class="auto-style2"><asp:Label
ID="showcourselabel" runat="server"
></asp:Label></td>
99. <td>
100. <asp:Label ID="showcourses" runat="server"
></asp:Label></td>
323
101. </tr>
102. </table>
103. </body>
104. </html>

Handling Submit Request

In code behind file, we are adding a message that trigger


only when user submit the registration form. This file
includes the following code.

// webcontrols.aspx.cs

1. Using System;
2. Using System.Collections.Generic;
3. Using System.Linq;
4. Using System.Web;
5. Using System.Web.UI;
6. Using System.Web.UI.webcontrols;
7. Namespace webformscontrolls
8. {
9. Public partial class webcontrols :
System.Web.UI.Page
10. {
11. Protected
System.Web.UI.htmlcontrols.htmlinputfile File1;
12. Protected
System.Web.UI.htmlcontrols.htmlinputbutton
Submit1;
13. Protected void Page_Load(object sender, eventargs
e)

324
14. {
15. }
16. Protected void Button1_Click(object sender,
eventargs e)
17. {
1. 18. Message.Text = "Hello " +
username.Text + " ! ";
2. 19. Message.Text = message.Text + "
<br/> You have successfuly Registered with the
following details.";
3. 20. Showusername.Text =
username.Text;
4. 21. Showemail.Text = emailid.Text;
22. If (radiobutton1.Checked)
23. {
24. Showgender.Text = radiobutton1.Text;
25. }
26. Else showgender.Text = radiobutton2.Text;
27. Var courses = "";
28. If (checkbox1.Checked)
29. {
30. Courses = checkbox1.Text + " ";
31. }
32. If (checkbox2.Checked)
33. {
34. Courses += checkbox2.Text + " ";
35. }
36. If (checkbox3.Checked)
37. {
38. Courses += checkbox3.Text;
325
39. }
40. Showcourses.Text = courses;
41. Showusernamelabel.Text = "User Name";
42. Showemailidlabel.Text = "Email ID";
43. Showgenderlabel.Text = "Gender";
44. Showcourselabel.Text = "Courses";
45. Username.Text = "";
46. Emailid.Text = "";
47. Radiobutton1.Checked = false;
48. Radiobutton2.Checked = false;
49. Checkbox1.Checked = false;
50. Checkbox2.Checked = false;
51. Checkbox3.Checked = false;
52. }
53. }
54. }

Run User Registration Form

To run this form, just right click and select view in


browser option. We did it in our Example:.

326
Output:

And it produces the following output.

327
After filling the form and registration, it shows a greeting
message to the user.

After submit the registration details.

328
329
PROGRAM 13

Create registration form with proper Validations -


ASP.NET Program.

This application is a simple student registration page


containing various web controls like radio buttons, check
box, combo box, calendar, image, File Upload etc. We also
use validation for different controls.

Studentregistratation.aspx

<!DOCTYPE html>

<script runat="server">

Protected Sub dob_selectionchanged(sender As


Object, e As eventargs)

End Sub

</script>

<head>

<title>Registration Page</title>

</head>

<body>

<form id="f1" method="post" runat="server">

330
<fieldset style="width:280px">

<legend>Registration Form</legend>

<table>

<tr>

<td>First Name:</td><td> <asp:textbox


id="txt1" runat="server" ></asp:textbox></td>

<td> <asp:requiredfieldvalidator
ID="validfname" runat="server" controltovalidate="txt1"
errormessage="Required!"
forecolor="Red"></asp:requiredfieldvalidator></td>

</tr>

<tr>

<td>Last Name:</td><td> <asp:textbox


id="txt2" runat="server" ></asp:textbox></td>

<td><asp:requiredfieldvalidator
ID="validlname" runat="server"

Controltovalidate="txt2" errormessage="Required!"
forecolor="Red"></asp:requiredfieldvalidator></td>

</tr>

<tr>

331
<td>User Name:</td><td> <asp:textbox
id="user" runat="server"></asp:textbox></td>

<td><asp:requiredfieldvalidator
ID="validuser" runat="server" controltovalidate="user"
errormessage="Required!"
forecolor="Red"></asp:requiredfieldvalidator></td>

</tr>

<tr>

<td>Password:</td><td><asp:textbox
ID="pwd" runat="server"
textmode="Password"></asp:textbox></td>

<td><asp:requiredfieldvalidator
ID="validpwd" runat="server" controltovalidate="pwd"
errormessage="Required!" forecolor="Red">

</asp:requiredfieldvalidator></td>

</tr>

<tr>

<td>Confirm
Password:</td><td><asp:textbox ID="Textbox1"
runat="server"
textmode="Password"></asp:textbox></td>

</tr>

<tr>
332
<td>Email:</td><td><asp:textbox ID="email"
runat="server" textmode="Email" ></asp:textbox></td>

<td><asp:requiredfieldvalidator
ID="validemail" runat="server"
controltovalidate="email" errormessage="required!"
forecolor="Red"></asp:requiredfieldvalidator></td>

</tr>

<tr>

<td>Mobile:</td><td><asp:textbox
ID="mobile" runat="server" textmode
="Phone"></asp:textbox></td>

</tr>

<tr>

<td>Gender:</td><td><asp:radiobuttonlist
ID="radiobuttonlist1" runat="server">

<asp:listitem Text="Male"
Value="0"></asp:listitem>

<asp:listitem Text="Female"
Value="1"></asp:listitem>

</asp:radiobuttonlist></td>

</tr>

<tr>
333
<td>DOB: </td><td><asp:textbox ID="dob"
runat="server" textmode="Date"
Width="168px"></asp:textbox> </td>

<td><asp:requiredfieldvalidator ID="validdob"
runat="server" controltovalidate="dob"
errormessage="Required"
forecolor="Red"></asp:requiredfieldvalidator></td>

</tr>

<tr>

<td>Course: </td><td><asp:dropdownlist
ID="ddlcourse" runat="server" datavaluefield="Course"
Width="173px">

<asp:listitem text="Select Course" Value="-


1"></asp:listitem>

<asp:listitem Text ="btech" Value


="0"></asp:listitem>

<asp:listitem Text ="MCA" Value


="1"></asp:listitem>

<asp:listitem Text ="MBA"


Value="2"></asp:listitem>

</asp:dropdownlist></td>

<td><asp:requiredfieldvalidator initialvalue="-
1" ID="validcourse" runat="server"

334
controltovalidate="ddlcourse"
errormessage="Required!"
forecolor="Red"></asp:requiredfieldvalidator></td>

</tr>

<tr>

<td>Nationality:</td><td><asp:checkbox
ID="check" Text="Indian"
runat="server"/><asp:checkbox id="checknat"
Text="Others" runat="server" /></td>

</tr>

<tr>

<td>Profile: </td><td><asp:Image id="img"


imageurl="images/new/new-member.png"
runat="server" /></td>

</tr>

<tr>

<td></td><td><asp:fileupload
ID="imgupload" runat="server" Enabled="true" /></td>

</tr>

<tr>

<td><asp:Button ID="btn1" runat="server"


Text="Submit"></asp:Button></td>
335
<td><asp:Button ID="btn2" runat="server"
Text="Reset"></asp:Button></td>

</tr>

</table>

</fieldset>

</form>

</body>

336
Output:

1. Registration page having various web controls

2. Validation: When we submit the page without


filling any record.

337
3. Filling the record

338
Implementation of Web Services in asp.Net Applications.

Create Web Service

A simple asmx page is known as Web Service. For the


creation of the web service, we will use the Visual Studio
2017, which is using the .NET Framework 4.8. For

339
creating the Web Service, we will follow the following
steps:

Step 1: Firstly, we will create a Web Application for


creating the Web Service.

For that, we will click on the File-> Select Project as


shown in the below screenshot:

After that the new window will open as shown in the


below screenshot:

From here, we will select the Web->Asp.Net Web


Application->Name of the Web Application-> Click on
OK.

340
After this a new window will be shown us like as shown
below:

For creating the Web Service, we will do the right click


on the project name-> Click on Add-> Add New Item.
As shown in the below screenshot:

341
After this, a new window will appear. From where we
have to click on the Web-> Select Web Service(.asmx
page)-> Give a name to the Web Service as shown in
the below screenshot:

342
After adding the Web Service to the application, a new
window will appear which is shown as below:

Directly method overloading is not supported by the web


service. To allow the method overloading in the Web
Service, we have to add the messagename property to
differentiate the one method used in the web service
from the other method, which is having the same name
and used parameter.

343
[webservicebinding(conformsto=
wsiprofiles.basicprofile1_1)] to [webservicebinding
(conformsto = wsiprofiles.None)].

1. [webmethod]
2. Public int sumofnums(int firstnumber, int
secondnumber)
3. {
4. Return firstnumber + secondnumber;
5. }
6.
7. //here we will use messagename property to do
the differentiation between both of the methods.
8. [webmethod(messagename = "sumoffloats")]
9. 9.
10. Public float sumofnums(float firstnumber, float
secondnumber)
11. {
12. Return firstnumber + secondnumber;
13. }

If we want to call the Web service from the Script, we will


use ASP.NET, AJAX and uncomment the below line.

[System.Web.Script.Services.scriptservice]

[webmethod]

This attribute is always used at the top of the method.


We write this attribute in the Web Service. [webmethod]
attribute is used to define that the method used this
attribute is exposed to the user/client access.
344
If we remove this attribute, in that case, the client will
not be able to see the details of the method; hence they
cannot implement it.

Mark-up

Now we will see the mark-up.

For the mark-up, we have to the right click on the


Service1.asmx in the window of the Solution Explorer
and select the view mark-up as shown in the below
screenshot:

345
In the Service1.asmx, we will see that the Service uses
the webservice directive with the attribute. From here,
this will show us that the application invokes the Service,
not by the end-user. Hence the asmx page has no mark-
up.

Service1.asmx

346
<%@ webservice Language="C#"
codebehind="Service1.asmx.cs"
Class="webapplication7.Service1" %

Here are some points about the Service1.asmx.

 "Web Service" directive: This directive shows that


the asmx page is a web service.
 "Language"="C#": This indicates that the C#
language is used for the Service.
 "codebehind": This property has not any role with
the ASP.NET or web service. Codebehind is the
property of the Visual Studio. This property is used
to map the asmx page with the code behind the
page.
 "Class" property contains the qualified name of the
class. This is the entry point of the Service, just like
the main () in C language.

Now we will run this application after pressing the


button F5. Vary). Here will find a link for the Service
Description as shown in the below screenshot:

347
There is also another link to the helloworld. After
clicking on this link, this will redirect us to the testing
page.

348
Implementation of web Service

Now we will implement the Service. Now we will rename


the file "Service1" in the Solution Explorer to
"myservice". Here we will change the class name to
myservice from Service1. Now we will open the mark-
up(.asmx) page.

From the above screenshot here, we will see that the


visual Studio is unable to resolve the "Service1" in the
class property. Here class shows the fully-qualified name
of the Service, and we renamed the Service1 class to
myservice, but Visual Studio is unable to resolve it.

Here we change the property of the class to "Web


application.myservice" and will change the "codebehind"
property from "Service1.asmx.cs" to "myservice.asmx.cs"
like as we name the file also.

Myservice.asmx

1. <%@ webservice Language="C#"


codebehind="myservice.asmx.cs"
Class="webapplication7.myservice

349
Myservice.asmx.cs

1. Using System;
2. Using System.Collections.Generic;
3. Using System.Linq;
4. Using System.Web;
5. Using System.Web.Services;
6. Using System.Web.Script.Serialization;
7.
8.
9. Namespace webapplication7
10. {
11. /// <summary>
12. /// Summary description for Service1
13. /// </summary>
14. [webservice(Namespace =
"http://tempuri.org/")]
15. [webservicebinding(conformsto =
wsiprofiles.basicprofile1_1)]
16. [System.componentmodel.toolboxitem(false)
]
17. // To allow this Web Service to be called
from script, using ASP.NET AJAX, uncomment
the following line.
18. [System.Web.Script.Services.scriptservice]
19. Public class myservice :
System.Web.Services.webservice
20. {
21.
22. [webmethod]

350
23. Public int sumofnums(int First, int Second)
24. {
25. Return First + Second;
26. }
27. }
28. }

After this, the Service is ready to use. Now we will


compile and run this application.

After the compilation a new window will open as shown


in the below screenshot:

Testing of a Web Service

Now we will run the application by clicking on the F5


button. The http://localhost:62639/myservice.asmx
page will open. The page will contain the link for the
Service Description (the WSDL document,
documentation of Web Service) and contains another
link of sumofnums. This page is the test page of the
sumofnums method as shown in the below screenshot:

351
Now we will use the OOP (Object Oriented Programming
Concept) concept method overloading. Now we add the
webmethod in the myservice class.

Myservice.asmx.cs

1. Using System;
2. Using System.Collections.Generic;
3. Using System. Linq;
4. Using System. Web;
5. Using System.Web.Services;
6. Using System.Web.Script.Serialization;
7.
8.
9. Namespace webapplication7
10. {
11. /// <summary>
12. /// Summary description for Service1
13. /// </summary>
14. [webservice(Namespace =
"http://tempuri.org/")]
15. [webservicebinding(conformsto =
wsiprofiles.basicprofile1_1)]
352
16. [System.componentmodel.toolboxitem(false)
]
17. // To allow this Web Service to be called
from script, using ASP.NET AJAX, uncomment
the following line.
18. [System.Web.Script.Services.scriptservice]
19. Public class myservice :
System.Web.Services.webservice
20. {
21.
22. [webmethod(messagename = "sumoffloats")]
23.
24. Public float sumofnums(float First, float
Second)
25. {
26. Return First + Second;
27. }
28.
29. }
30. }

Now we will run this application by pressing the button


F5. The http://localhost:62639/myservice.asmx page
will open which contains the link for the Service
Description(the WSDL document, documentation for the
web service). Here we have another link sumofnums
which is the test page of the sumofnums method as
shown in the below screenshot:

353
After entering the values in the first text box and second
text box, this will invoke the method as shown in the
below screenshot:

Method Overloading

Now we will use the overloading method in the Service.


Web service does not support method overloading. This
will throw an error in the case of the method

354
overloading. Here we are taking an Example: to show the
method overloading done in the Web Service and throw
an error because it does not support the overloading.

Myservice.asmx.cs

1. Using System;
2. Using System.Collections.Generic;
3. Using System. Linq;
4. Using System. Web;
5. Using System.Web.Services;
6. Using System.Web.Script.Serialization;
7.
8.
9. Namespace webapplication7
10. {
11. /// <summary>
12. /// Summary description for Service1
13. /// </summary>
14. [webservice(Namespace =
"http://tempuri.org/")]
15. [webservicebinding(conformsto =
wsiprofiles.basicprofile1_1)]
16. [System.componentmodel.toolboxitem(false)
]
17. // To allow this Web Service to be called
from script, using ASP.NET AJAX, uncomment
the following line.
18. [System.Web.Script.Services.scriptservice]
19. Public class myservice :
System.Web.Services.webservice
355
20. {
21.
22. [webmethod]
23. Public int sumofnums(int First, int Second)
24. {
25. Return First + Second;
26. }
27. [webmethod(messagename = "sumoffloats")]
28.
29. Public float sumofnums(float First, float
Second)
30. {
31. Return First + Second;
32. }
33.
34. }
35. }

In the above Example:, Web Service does not support the


method overloading and shows the error message that
the Service "webapplication7.myservice" does not
conform to WS-I Basic Profile v1.1. Now to support the
overloading method, we have to follow the following
356
steps either we have to remove the
"[webservicebinding(conformsto =
wsiprofiles.basicprofile1_1)]," or we have to make some
changes "[webservicebinding(conformsto =
wsiprofiles.None)]".

To support the overloading method, we have to make


some changes in the code, as shown in the box which is
highlighted:

1. Using System;
2. Using System.Collections.Generic;
3. Using System. Linq;
4. Using System. Web;
5. Using System.Web.Services;
6. Using System.Web.Script.Serialization;
7.
8.
9. Namespace webapplication7
10. {
11. /// <summary>
12. /// Summary description for Service1
13. /// </summary>
14. [webservice(Namespace =
"http://tempuri.org/")]
15. //make the wsiprofiles to None
16. [webservicebinding(conformsto =
wsiprofiles.None)]
17. [System.componentmodel.toolboxitem(false)
]

357
18. // To allow this Web Service to be called
from script, using ASP.NET AJAX, uncomment
the following line.
19. [System.Web.Script.Services.scriptservice]
20. Public class myservice :
System.Web.Services.webservice
21. {
22.
23. [webmethod]
24. Public int sumofnums(int First, int Second)
25. {
26. Return First + Second;
27. }
28.
29. //here we have to add the messagename
property to make the difference between
both of the methods.
30. [webmethod(messagename = "sumoffloats")]
31. 31.
32. Public float sumofnums(float First, float
Second)
33. {
34. Return First + Second;
35. }
36.
37. }
38. }

After all these changes the Web Service will looks like as
shown in the below screenshot:

358
Here web service supports the method with the same
name. By adding the message name property, we can
create the differences between both of the methods.

By using the above property, we can use the method


overloading in the Web Service.

Testing of the Page

After clicking on the sumoffloats, the page will redirect to


the
http://localhost:62639/myservice.asmx?Op=sumoffloats
here we will see that the "?Op=sumofnums" is appended
to the Service URL. This page contains the two text boxes
for the two input values (First, Second), where the
sumofnums value will take as an input parameter and a
"invoke" button. After clicking on this invoke button, we
will redirect to the

359
http://localhost:62639/myservice.asmx/sumoffloats,
which is having the value where the sumofnums method
returns the XML format.

After clicking on the invoke button, we will redirect to


http://localhost:62639/myservice.asmx/sumoffloats
page. This page contains the value in the XML format.

Similarly, after clicking on the "sumofnums


messagename="sumoffloats"". We will redirect to the
"http://localhost:62639/myservice.asmx?Op=sumoffloat
360
s" . So the "sumofnums messagename="sumoffloat""
method which is known as the "sumoffloats" for client
application.

Here a question is arising from where the test page came.


Because we didn't add the Mark-up, but still the page was
rendered.

Test Pages are not part of the Web Service. Test Page is
rendered by the ASP.NET by using the Web Page
c:\[windir]\Microsoft. NET\Framework\ [Version]
\Config\defaultwsdlhelpgenerator.aspx. "Reflection"
concept renders to the test page.

WSDL Document

Web Services are self-describing, which means ASP.Net


itself provides us all the information required for the
client to consume a web service in the form of the WSDL
document. WSDL document tells the client about the
methods which are present in the Web Service. And the
what parameter and return value used by the method
and how a client application can communicate with
them. WSDL is an XML standard.

Hosting of the Web Service

For the hosting of the web service, we will add the


reference to the Service and consume it from the
different applications. Here we suppose that the port
number can vary, so now we will host the Service on the
IIS (Internet Information Server) for getting the
361
particular address of the server. For this, we will open
the Internet Information Server-> Go to the default web
site-> Right-click on the application-> Add the
Application->browse to the physical location of our
Service for the physical path field-> Click "OK". Now we
will browse the application with the alias name
http://localhost/webservicedemo/ for the testing if the
application was correctly hosted. Here we will get an
error "HTTP Error 403.14-Forbidden". This error was
coming because there is not set any default document for
this application. Now we will add a page as a default
document "myservice.asmx". Now we can browse our
application by adding this URL in the browser
localhost/webservicedemo/myservice.asmx.

Consume the Web Service from the Client Script

We can use web service in any type of application. Here


we will create an application .Net web application. For
that, we will follow the following steps:

Step1: Right-click on the Solution explorer->Add->New


Project as shown in the below screenshot:

362
Step2: After clicking on the New Project a new window
will open as shown in the below screenshot:

Step 3. After this, to communicate with the web service,


we have to create a proxy class. To create the proxy class,
we have to follow the following steps:

Proxy Class

For creating the proxy class, we have to the right click on


the References->Select Add Service Reference as shown
in the below screenshot:

363
After clicking on the Add Service Reference, a new
window will appear as shown in the below screenshot:

364
Right-click on the project in the solution explorer->
select add->choose web form as shown in the below
screenshot:

After clicking on the Web Form, this will open a new


window where we have to provide the name of the web
form as shown in the below screenshot:

365
Here in the above screenshot, we gave the name of the
web form and then click on OK.

In the Web Form, we will create a table to use the


predefined method with the help of the Web Service.

In the webform1.aspx, we have done the following


coding as shown in the below code:

1. %@ Page Language="C#" autoeventwireup="true"


codebehind="webform1.aspx.cs"
Inherits="calculatorwebapplication.webform1" %>
2.
3. <!DOCTYPE html>
4.
5. <html xmlns="http://www.w3.org/1999/xhtml">
6. <head runat="server">
7. <title></title>
8. </head>
9. <body>
10. <form id="form1" runat="server">
11. <table style="font-family:Arial">
12. <tr>
13. <td>
14. <b>First Number</b>
15. </td>
16. <td>

366
17. <asp:textbox ID="txtfirstnumber"
runat="server"></asp:textbox>
18. </td>
19. </tr>
20. <tr>
21. <td>
22. <b>Second Number</b>
23. </td>
24. <td>
25. <asp:textbox ID="txtsecondnumber"
runat="server"></asp:textbox>
26. </td>
27. </tr>
28. <tr>
29. <td>
30. <b>Result</b>
31. </td>
32. <td>
33. <asp:Label ID="lblresult" runat="server"
Text="Label"></asp:Label>
34. </td>
35. </tr>
36. <tr>
37. <td>
38. <asp:Button ID="btnadd" runat="server"
Text="Add" onclick="btnadd_Click" />
39. </td>
40.
41.
42. </tr>
367
43. </table>
44. </form>
45. </body>
46. </html>

In the above code, create a table where we take the two


textboxes, textbox1, for entering the firstnumber and the
textbox2 for entering the secondnumber. Create a button
with the help of which we will add the two numbers.

The designing view of the above code is as shown in the


below screenshot:

Here we have taken two textboxes for entering the


firstnumber and secondnumber. The add button is used
to add the value of both the textbox.

After double-clicking on the Add button, this will switch


us to the coding page. The page is webform.aspx.cs.

To use the method of the Web Service, we will do the


following code on the button click.

368
Webform.aspx.cs

1. Using System;
2. Using System.Collections.Generic;
3. Using System. Linq;
4. Using System. Web;
5. Using System.Web.UI;
6. Using System.Web.UI.webcontrols;
7. 7.
8. Namespace calculatorwebapplication
9. {
10. Public partial class webform1 :
System.Web.UI.Page
11. {
12. Protected void Page_Load(object sender, eventargs
e)
13. {
14. 14.
15. }
16. 16.
17. Protected void btnadd_Click(object sender,
eventargs e)
18. {
19. Calculatorservice.calculatorwebservicesoapclient
client = new
calculatorservice.calculatorwebservicesoapclient()
;
20. Int result=
client.Add(Convert.toint32(txtfirstnumber.Text),
21. Convert.toint32(txtsecondnumber.Text));

369
22. Lblresult.Text = result.tostring();
23. }
24. }
25. }

Now we will press F5 to start the web service. The output


will look like as shown in the below screenshot:

370
371

You might also like