354 50 5MB
English Pages [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: [email protected]
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 : [email protected] 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/OLevel/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 indepth 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, Webbased 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, objectoriented 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 Windowsbased 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. 2. 3. 4. 5.
The name of the assembly. Version information for the assembly. Security information for the assembly. A list of all files that are part of the assembly. 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 longrunning 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; number Char myletter = 'D';
// Character
Bool mybool = true;
// Boolean
String mytext = "Hello";
// Floating point
// 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; double
// Automatic casting: int to
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; to int
51
// Manual casting: double
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)); int to string
// convert
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()); WORLD"
// Outputs "HELLO
Console.writeline(txt.tolower()); world"
// Outputs "hello
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 concatenated.
are
added.
Strings
If you add two numbers, the result will be a number: Example: Int x = 10; 61
are
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 mathematics: • • • • • •
the
usual
logical
conditions
from
Less than: a < b Less than or equal to: 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 predefined 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: "Liam");
"John",
child1:
"Liam",
child2:
} // 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 objectoriented 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"; Int maxspeed = 200;
// field // 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; Int maxspeed;
// field // 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 threadstart(calltochildthread);
=
new
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:: wundervoll\")");
\"M+apw-nchen
ist
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 = streamwriter(Console.openstandardoutput()); 126
new
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 = streamwriter(Console.openstandardoutput());
new
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 /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
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:
id="Submit"
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: