Professional Documents
Culture Documents
C# Unit1
C# Unit1
The third layer of the framework is ASP.NET and Windows Forms. ASP.NET should not be viewed as
the next version of Active Server Pages after ASP 3.0, but as a dramatically new shift in Web application
development. Using ASP.NET, it’s now possible to build robust Web applications that are even more
functional than Win32 applications of the past. This was always quite difficult to do in the stateless nature
of the Internet, but ASP.NET offers a number of different solutions to overcome the traditional limitations
on the types of applications that were possible. The ASP.NET section of the .NET Framework is also
where the XML Web services model resides.
The .Net framework applications are multi-platform applications. The framework has been designed in
such a way that it can be used from any of the following languages: C#, C++, Visual Basic, Jscript,
COBOL, etc. All these languages can access the framework as well as communicate with each other.
The .Net framework consists of an enormous library of codes used by the client languages such as C#.
5. Windows Services.
In short, developers just need to import the BCL in their language code and use its predefined methods
and properties to implement common and complex functions like reading and writing to file, graphic
rendering, database interaction, and XML document manipulation. The framework's Base Class Library
provides
User Interface
Data Access
Database Connectivity
Cryptography
Web Application Development
Numeric Algorithms
Network Communications
The class library is used by programmers, who combine it with their own code to produce applications.
type can be determined from values of self-describing types. Self-describing types are further split into
arrays and class types. The class types are user-defined classes, boxed value types, and delegates.
Assemblies
Assemblies are the building blocks of .NET Framework applications; they form the fundamental unit of
deployment, version control, reuse, activation scoping, and security permissions. An assembly is a
collection of types and resources that are built to work together and form a logical unit of functionality.
18MCA51 [Programming using C#] 2020 5
.NET assemblies may or may not be executable, i.e., they might exist as the executable (.exe) file or
dynamic link library (DLL) file.
When a *.dll or *.exe has been created using a .NET-aware compiler, the resulting module is bundled into
an assembly. An assembly contains CIL(Common Intermediate Language) code, which is conceptually
similar to Java bytecode in that is not compiled into platform specific instructions until absolutely
necessary such as CIL is referenced for use by the .NET runtime. The CIL code is housed in .NET
assemblies. As mandated by specification, assemblies are stored in the Portable Executable (PE) format,
common on the Windows platform for all dll and exe files.
Note: IL (Intermediate Language), CIL (Common Intermediate Language), and MSIL (Microsoft
Intermediate Language) are all describing the same thing.
It forms a security boundary. An assembly is the unit at which permissions are requested and
granted.
It forms a type boundary. Every type's identity includes the name of the assembly in which it
resides. A type called MyType loaded in the scope of one assembly is not the same as a type called
MyType loaded in the scope of another assembly.
It forms a reference scope boundary. The assembly's manifest contains assembly metadata that is
used for resolving types and satisfying resource requests. It specifies the types and resources that
are exposed outside the assembly. The manifest also enumerates other assemblies on which it
depends.
18MCA51 [Programming using C#] 2020 6
It forms a version boundary. The assembly is the smallest versionable unit in the common
language runtime; all types and resources in the same assembly are versioned as a unit. The
assembly's manifest describes the version dependencies you specify for any dependent assemblies.
When an application starts, only the assemblies that the application initially calls must be present.
Other assemblies, such as localization resources or assemblies containing utility classes can be
retrieved on demand. This allows applications to be kept simple and thin when first downloaded.
Private assemblies are simple and copied with each calling assemblies in the calling assemblies folder.
Shared assemblies (also called strong named assemblies) are copied to a single location (usually the
Global assembly cache). For all calling assemblies within the same application, the same copy of the
shared assembly is used from its original location. Hence, shared assemblies are not copied in the private
folders of each calling assembly. Each shared assembly has a four part name including its face name,
version, public key token and culture information. The public key token and
version information makes it almost impossible for two different assemblies
with the same name or for two similar assemblies with different version to
mix with each other.
An assembly can be a single file or it may consist of the multiple files. In case
of multi-file, there is one master module containing the manifest while other
assemblies exist as non-manifest modules. A module in .NET is a sub part of
a multi-file .NET assembly.
Metadata
Metadata is binary information describing your program that is stored either in a common language
runtime portable executable (PE) file or in memory. When we compile our code into a PE file, metadata is
inserted into one portion of the file, and our code is converted to Microsoft intermediate language (MSIL)
and inserted into another portion of the file. Every type and member that is defined and referenced in a
module or assembly is described within metadata. When code is executed, the runtime loads metadata into
memory and references it to discover information about our code's classes, members, inheritance, and so
on.
Metadata describes every type and member defined in our code in a language-neutral manner. Metadata
stores the following information:
Description of the assembly.
o Identity (name, version, culture, public key).
o The types that are exported.
o Other assemblies that this assembly depends on.
o Security permissions needed to run.s
Description of types.
o Name, visibility, base class, and interfaces implemented.
o Members (methods, fields, properties, events, nested types).
Attributes.
o Additional descriptive elements that modify types and members.
Benefits of Metadata
18MCA51 [Programming using C#] 2020 7
Metadata is the key to a simpler programming model, and eliminates the need for Interface Definition
Language (IDL) files, header files, or any external method of component reference. Metadata enables
.NET Framework languages to describe themselves automatically in a language-neutral manner, unseen
by both the developer and the user. Additionally, metadata is extensible through the use of attributes.
Metadata provides the following major benefits:
Self-describing files.
Common language runtime modules and assemblies are self-describing. A module's metadata
contains everything needed to interact with another module. Metadata automatically provides the
functionality of IDL in COM, so you can use one file for both definition and implementation.
Runtime modules and assemblies do not even require registration with the operating system. As a
result, the descriptions used by the runtime always reflect the actual code in your compiled file,
which increases application reliability.
Language interoperability and easier component-based design.
Metadata provides all the information required about compiled code for you to inherit a class from
a PE file written in a different language. We can create an instance of any class written in any
managed language without worrying about using custom interoperability code.
Attributes.
The .NET Framework lets us declare specific kinds of metadata, called attributes, in your compiled
file. Attributes can be found throughout the .NET Framework and are used to control in more
detail how your program behaves at run time. Additionally, we can emit our own custom metadata
into .NET Framework files through user-defined custom attributes.
Windows Forms
Windows Forms (WinForms) is the name given to a graphical (GUI) class library included as a part of
Microsoft .NET Framework, providing a platform to write rich client applications for desktop, laptop, and
tablet PCs. Windows Forms is the most commonly used feature of .NET. 'Windows' based applications
in .NET is called 'WinForms'. The .NET framework comes with a good number of classes to support
'Form' based application development.
A WinForm application will have at least one 'Form' (window), which would be used for the interaction
between the application and user. A Form can contain other controls like TextBox, Label, Button etc.
Large WinForms applications will have several 'Forms', some of them used to capture data from user and
some of them used to display data to user. By performing certain actions in each form, user can navigate
to other 'Forms' in the application.
Windows Forms application supports Event driven programming. Event Driven programming model is the
most commonly used feature in modern programming. In this model, we use to write appropriate code for
each event. Examples for events are
Button Click
Mouse Move
Mouse Click
Key Press
In Winforms application, users interact with the application using various actions in the window (like
clicking a button, moving mouse, pressing keys in keyboard etc). These actions will generate various
events. When an event is generated, the code written for that event will be executed.
For example, in a user registration screen, we may have several controls like text boxes where user can
enter their name, address, age etc. Once user enters all the information, he may press the 'Submit' button.
As a developer, we would have written code in the button click event, to save this user entered data into a
database. This is how typically a WinForms based application works in an event driven programming
model.
To create WinForms applications:
18MCA51 [Programming using C#] 2020 8
ASP.NET
ASP.NET is a web development platform, which provides a programming model, a comprehensive
software infrastructure and various services required to build up robust web applications for PC, as well as
mobile devices. ASP.NET works on top of the HTTP protocol, and uses the HTTP commands and policies
to set a browser-to-server bilateral communication and cooperation.
ASP.NET is a part of Microsoft .NET platform. ASP.NET applications are compiled codes, written using
the extensible and reusable components or objects present in .NET framework. These codes can use the
entire hierarchy of classes in .Net framework. The ASP.NET application codes can be written in any of
the following languages:
C#
Visual Basic.Net
Jscript
J#
ASP.NET is used to produce interactive, data-driven web applications over the internet. It consists of a
large number of controls such as text boxes, buttons, and labels for assembling, configuring, and
manipulating code to create HTML pages.
ASP.NET AJAX
ASP.NET AJAX extension is a part of ASP.NET that makes Ajax functionalities possible and effective.
ASP.NET Ajax, formerly known as Atlas, is an extension of ASP.NET 2.0. Ajax extension has developed
for both client side and server side. The core part of the Ajax extension client library is the networking
layer that manages the complexity of making asynchronous calls over XMLHttpRequest.
XMLHttpRequest is the core of making AJAX web applications. It acts as a communication layer between
the server and the client. XMLHttpRequest object is responsible for the partial updates of web pages by
using JavaScript to make requests to the web server and process the response without posting the full web
page back to the web server. XMLHTTP is a protocol that is designed to package data as XML and send it
via the network to the web server. XmlHttpRequest object is today fully supported by the majority of Web
browsers.
The most frequently used ASP.NET Ajax server controls are ScriptManager, UpdatePanel,
UpdateProgress and Timer. With the help of ScriptManager Control and UpdatePanel control, ASP.NET
Ajax can refresh selected parts of the web page instead of refreshing the whole page with a postback.
UpdateProgress provides status information for the progress of the download occurring in the UpdatePanel
and the Timer control enables you to perform postbacks at a specified interval.
ADO.NET
ADO.NET is an object-oriented set of libraries that allows you to interact with data sources. Commonly,
the data source is a database, but it could also be a text file, an Excel spreadsheet, or an XML file.
18MCA51 [Programming using C#] 2020 9
ADO.NET provides a bridge between the front end controls and the back end database. The ADO.NET
objects encapsulate all the data access operations and the controls interact with these objects to display
data, thus hiding the details of movement of data.
Data Providers
ADO.NET provides a relatively common way to interact with data sources, but comes in different sets of
libraries for each way we can talk to a data source. These libraries are called Data Providers and are
usually named for the protocol or data source type they allow you to interact with. ADO.NET Data
Providers are class libraries that allow a common way to interact with specific data sources or protocols.
The library APIs have prefixes that indicate which provider they support. Following Table lists some well
known data providers, the API prefix they use, and the type of data source they allow us to interact with.
API
Provider Name Data Source Description
prefix
ODBCData Provider Odbc Data Sources with an ODBC interface. Normally older data bases.
OleDb Data Provider OleDb Data Sources that expose an OleDb interface, i.e. Access or Excel.
Oracle Data Provider Oracle For Oracle Databases.
SQL Data Provider SqlClient For interacting with Microsoft SQL Server.
ADO.NET Objects
ADO.NET includes many objects which can be used to work with data. Following are few examples of
ADO.NET Objects:
The SqlConnection Object: To interact with a database, we must have a connection to it. The connection
helps identify the database server, the database name, user name, password, and other parameters that are
required for connecting to the data base. A connection object is used by command objects so they will
know which database to execute the command on.
The SqlCommand Object: The process of interacting with a database means that we must specify the
actions we want to occur. This is done with a command object. We use a command object to send SQL
18MCA51 [Programming using C#] 2020 10
statements to the database. A command object uses a connection object to figure out which database to
communicate with. We can use a command object alone, to execute a command directly, or assign a
reference to a command object to an SqlDataAdapter, which holds a set of commands that work on a
group of data as described below.
The SqlDataReader Object: Many data operations require that we only get a stream of data for reading.
The data reader object allows us to obtain the results of a SELECT statement from a command object. For
performance reasons, the data returned from a data reader is a fast forward-only stream of data. This
means that we can only pull the data from the stream in a sequential manner. This is good for speed, but if
we need to manipulate data, then a DataSet is a better object to work with.
The DataSet Object: DataSet objects are in-memory representations of data. They contain multiple
Datatable objects, which contain columns and rows, just like normal database tables. We can even define
relations between tables to create parent-child relationships. The DataSet is specifically designed to help
manage data in memory and to support disconnected operations on data, when such a scenario make
sense. The DataSet is an object that is used by all of the Data Providers, which is why it does not have a
Data Provider specific prefix.
The SqlDataAdapter Object: Sometimes the data we work with is primarily read-only and you rarely
need to make changes to the underlying data source Some situations also call for caching data in memory
to minimize the number of database calls for data that does not change. The data adapter makes it easy for
us to accomplish these things by helping to manage data in a disconnected mode. The data adapter fills a
DataSet object when reading the data and writes in a single batch when persisting changes back to the
database. A data adapter contains a reference to the connection object and opens and closes the connection
automatically when reading from or writing to the database. Additionally, the data adapter contains
command object references for SELECT, INSERT, UPDATE, and DELETE operations on the data. We
will have a data adapter defined for each table in a DataSet and it will take care of all communication with
the database for us. All you need to do is tell the data adapter when to load from or write to the database.
Windows Presentation Framework is a next generation UI framework to create applications with a rich
user experience. It is part of the .NET framework 3.0 and higher. WPF architecture is a layered
architecture which have Managed, Unmanaged and Core API layers as shown in below fig.
Managed layer has two main components – Presentation Framework and Presentation Core.
1. Presentation Framework provides the required functionalities that we need to build the WPF
applications such as controls, data bindings, styling, shapes, media, documents, annotations,
animation and more. PresentationFamework.dll is responsible for this purpose.
2. Presentation Core acts as a managed wrapper around MILCore and provides public interface for
MIL. Presentation Core is the home for WPF Visual System and provides classes for creating
application visual tree. The Visual System creates visual tree which contains applications Visual
Elements and rendering instructions. PresentationCore.dll is responsible for this purpose.
Unmanaged Layer
This layer is also called milcore or Media Integration Library Core. MilCore is written in unmanaged code
in order to enable tight integration with DirectX. DirectX engine is underlying technology used in WPF to
display all graphics, allowing for efficient hardware and software rendering. MIL has Composition System
that receives rendering instructions from Visual System and translates into data that can be understood by
DirectX to render user interface.
Core API Layer
This layer has OS core components like Kernel, User32, GDI, Device Drivers, Graphic cards etc. These
components are used by the application to access low level APIs. User32 manages memory and process
separation.
represented uniformly, WCF makes it possible to have a unified API irrespective of diverse transport
mechanisms.
WCF was released for the first time in 2006 as a part of the .NET framework with Windows Vista, and
then got updated several times. WCF 4.5 is the most recent version that is now widely used.
A WCF application consists of three components:
WCF service,
WCF service host, and
WCF service client.
Advantages of WCF
It is interoperable with respect to other services. This is in sharp contrast to .NET Remoting in
which both the client and the service must have .NET.
WCF services offer enhanced reliability as well as security in comparison to ASMX (Active
Server Methods) web services.
Implementing the security model and binding change in WCF do not require a major change in
coding. Just a few configuration changes is required to meet the constraints.
WCF has built-in logging mechanism whereas in other technologies, it is essential to do the
requisite coding.
WCF has integrated AJAX and support for JSON (JavaScript object notation).
WCF has a layered architecture that offers ample support for developing various distributed applications.
The architecture is explained below in detail.
18MCA51 [Programming using C#] 2020 13
Windows CardSpace
The Internet continues to be increasingly valuable, and yet also faces significant challenges. Online
identity theft, fraud, and privacy concerns are rising. Users must track a growing number of accounts and
passwords. This burden results in "password fatigue," and that results in insecure practices, such as
reusing the same account names and passwords at many sites. Many of these problems are rooted in the
lack of a widely adopted identity solution for the Internet.
CardSpace is Microsoft's implementation of an Identity Metasystem that enables users to choose from a
portfolio of identities that belong to them and use them in contexts where they are accepted, independent
of the underlying identity systems where the identities originate and are used.
It is the code name for an identity management component in Microsoft's upcoming WinFX product suite.
With InfoCard, end users create a digital file on their own computer that includes user-specific
information, like a work phone number, e-mail address or snail mail address. Users are able to save
several different profiles and use whichever profile is appropriate for a certain situation. CardSpace is a
potential successor to the Microsoft Passport information management system, which stores user
information on a database instead of individual machines.
Customer security is becoming an increasingly important part of Web application development. One key
to security, particularly in credit-card and other financial transactions, is safer customer identity
management.
18MCA51 [Programming using C#] 2020 14
There are two types of CardSpace information cards -- personal cards, which users create themselves, and
managed cards, which are issued by identity providers. The card itself does not actually contain any
personal data. Rather, the card indicates which identity provider must be contacted to obtain the claims to
this data. An application requests these claims by issuing a security token; once this happens, the entire
transaction is locked down, and no code at all will run.
LINQ
The acronym LINQ is for Language Integrated Query. Microsoft’s query language is fully integrated and
offers easy data access from in-memory objects, databases, XML documents and many more. It is through
a set of extensions, LINQ ably integrate queries in C# and Visual Basic.
Developers across the world have always encountered problems in querying data because of the lack of a
defined path and need to master a multiple of technologies like SQL, Web Services, XQuery, etc.
Introduced in Visual Studio 2008 and designed by Anders Hejlsberg, LINQ (Language Integrated Query)
allows writing queries even without the knowledge of query languages like SQL, XML etc. LINQ queries
can be written for diverse data types.
Example of a LINQ query: --C#
using System;
using System.Linq;
class Program
{
public static void Main(string[] args)
{
string[] words = {"hello", "wonderful", "LINQ", "beautiful", "world"};
//Get only short words
var shortWords = from word in words where word.Length <= 5 select word;
//Print each word out
foreach (var word in shortWords)
{
Console.WriteLine(word);
}
Console.ReadLine();
}
}
Syntax of LINQ
There are two syntaxes of LINQ. These are the following ones.
Lamda (Method) Syntax
Example
In C#: var longWords = words.Where( w => w.length > 10);
In VB.NET Dim longWords = words.Where(Function(w) w.length > 10)
Query (Comprehension) Syntax
Example
In C#: var longwords = from w in words where w.length > 10;
In VB.NET Dim longwords = from w in words where w.length > 10
Types of LINQ
The types of LINQ are mentioned below in brief.
LINQ to Objects
LINQ to XML(XLINQ)
LINQ to DataSet
LINQ to SQL (DLINQ)
LINQ to Entities
Apart from the above, there is also a LINQ type named PLINQ which is Microsoft’s parallel LINQ.
18MCA51 [Programming using C#] 2020 15
Advantages of LINQ
LINQ offers a host of advantages and among them the foremost is its powerful expressiveness which
enables developers to express declaratively. Some of the other advantages of LINQ are given below.
LINQ offers syntax highlighting that proves helpful to find out mistakes during design time.
LINQ offers IntelliSense which means writing more accurate queries easily.
Writing codes is quite faster in LINQ and thus development time also gets reduced significantly.
LINQ makes easy debugging due to its integration in the C# language.
Viewing relationship between two tables is easy with LINQ due to its hierarchical feature and this
enables composing queries joining multiple tables in less time.
LINQ allows usage of a single LINQ syntax while querying many diverse data sources and this is
mainly because of its unitive foundation.
LINQ is extensible that means it is possible to use knowledge of LINQ to querying new data
source types.
LINQ offers the facility of joining several data sources in a single query as well as breaking
complex problems into a set of short queries easy to debug.
18MCA51 [Programming using C#] 2020 16
LINQ offers easy transformation for conversion of one data type to another like transforming SQL
data to XML data.