Professional Documents
Culture Documents
ASP Papers Word File
ASP Papers Word File
IT Consist of a primarily of a gigantic library of code thet you use for your client
languages(Such as C#) using OOP techniques.
The Library is Categorized in to different modules you use the portion depending
on the results you want to achieve.
One Module contains the building block of Windows Application while another for
WEB-Development ,Network Programming
.Net Framework library defines some basic types, a types is the representation of
data and specified some of the most fundamentals of these(Such as 32bit signed
integer) facilities interoperability between languages using the .Net Framework.
This is called as the CTS.(Common Type System)
As well as supplying the library, the .Net Framework also includes the .Net
Common Language Runtime(CLR).
The CLR is responsible for maintaining the execution of all application
development using the .NET Framework.
In Order for C# code to execute It must be converted into a language that the
target OS usnderstands Known as Native Code.
This Conversions is called as compiling codes.
An Act that is performed by a compiler under the .NET Framework, this is a Two
Stage Process.
Q.2.CIL and JIT
When you compile code that uses the .NET Framework library, you don t
immediately create operating-system-specific native code.
Instead, you compile your code into Common Intermediate Language (CIL) code.
This code isnt specific to any operating system (OS) and isn t specific to C#.
Other .NET languages Visual Basic .NET, for example also compile to this
language as a first stage.
This compilation step is carried out by VS or VCE when you develop C#
applications.
Obviously, more work is necessary to execute an application. That is the job of a
just-in-time (JIT) compiler, which compiles CIL into native code that is specific to
the OS and machine architecture being targeted.
Only at this point can the OS execute the application.
In the past, it was often necessary to compile your code into several applications,
each of which targeted a specific operating system and CPU architecture.
Typically, this was a form of optimization (to get code to run faster on an AMD
chipset, for example), but at times it was critical (for applications to work in both
Win9x and WinNT/2000 environments, for example).
This is now unnecessary, because JIT compilers (as their name suggests) use
CIL code, which is independent of the machine, operating system, and CPU.
Several JIT compilers exist, each targeting a different architecture, and the
appropriate one is used to create the native code required.
The beauty of all this is that it requires a lot less work on your part in fact, you
can forget about system-dependent details and concentrate on the more
interesting functionality of your code.
Q.3.Explain Assemblies?
When you compile an application, the CIL code created is stored in an assembly.
Assemblies include both executable application files that you can run directly
from Windows without the need for any other programs (these have a .exe file
extension) and libraries (which have a .dll extension) for use by other
applications.
In addition to containing CIL, assemblies also include meta information (that is,
information about the information contained in the assembly, also known as
metadata) and optional resources
The meta information enables assemblies to be fully self-descriptive.
You need no other information to use an assembly, meaning you avoid situations
such as failing to add required data to the system registry and so on, which was
often a problem when developing with other platforms.
This means that deploying applications is often as simple as copying the files into
a directory on a remote computer.
Because no additional information is required on the target systems, you can just
run an executable file from this directory and (assuming the .NET CLR is
installed) youre good to go.
You might write some code that performs tasks required by multiple applications.
In situations like that, it is often useful to place the reusable code in a place
accessible to all applications.
In the .NET Framework, this is the global assembly cache (GAC). Placing code in
the GAC is simple you just place the assembly containing the code in the
directory containing this cache.
Q.4.Managed Code
The role of the CLR doesnt end after you have compiled your code to CIL and a
JIT compiler has compiled that to native code.
Code written using the .NET Framework is managed when it is executed (a stage
usually referred to as runtime).
This means that the CLR looks after your applications by managing memory,
handling security, allowing cross-language debugging, and so on.
By contrast, applications that do not run under the control of the CLR are said to
be unmanaged, and certain languages such as C++ can be used to write such
applications, which, for example, access low-level functions of the operating
system.
However, in C# you can write only code that runs in a managed environment.
You will make use of the managed features of the CLR and allow .NET itself to
handle any interaction with the operating system.
Q.B: Garbage Collection
One of the most important features of managed code is the concept of garbage
collection.
This is the .NET method of making sure that the memory used by an application
is freed up completely when the application is no longer in use.
Prior to .NET this was mostly the responsibility of programmers, and a few simple
errors in code could result in large blocks of memory mysteriously disappearing
as a result of being allocated to the wrong place in memory.
That usually meant a progressive slowdown of your computer followed by a
system crash.
.NET garbage collection works by periodically inspecting the memory of your
computer and removing anything from it that is no longer needed.
Q.5.Introduction to C#
C# is a relatively new language that was unveiled to the world when
Microsoft announced the first version of its .NET Framework in July 2000.
Since then its popularity has rocketed and it has arguably become the
language of choice for both Windows and Web developers who use the
.NET framework.
Part of the appeal of C# comes from its clear syntax, which derives from
C/C++ but simplifies some things that have previously discouraged some
programmers.
Fully object oriented language like java and first component oriented language
Designed to support key features of .NET framework
Its is simple, effective, productive, type-safe
Belongs to family of C/C++
It is designed to build robust, reliable and durable components to handle real
world applications
Linking
Note one additional point concerning this process. The C# code that
compiles into CIL in step 2 neednt be contained in a single file.
Its possible to split application code across multiple source code files,
which are then compiled together into a single assembly.
This extremely useful process is known as linking. It is required because it
is far easier to work with several smaller files than one enormous one.
You can separate out logically related code into an individual file so that it
can be worked on independently and then practically forgotten about when
completed.
This also makes it easy to locate specific pieces of code when you need
them and enables teams of developers to divide the programming burden
into manageable chunks
whereby individuals can check out pieces of code to work on without
risking damage to otherwise satisfactory sections or sections other people
are working on.
Q.6.LOOPING
Looping refers to the repeated execution of statements. This technique
comes in very handy because it means that you can repeat operations as
many times as you want (thousands, even millions, of times) without
having to write the same code each time.
The structure of a do loop is as follows, where <Test> evaluates to a
Boolean value:
do { <code to be looped> } while (<Test>);
Do while loop is also called as exit condition checking loop, means it will
check the condition while exiting loop.
Eg:
int i = 0;//initialization
do
{
System.Console.Write(" " +
i.ToString());
i++; //increment
} while (i != 10); //condition
while Loops
The Boolean test in a while loop takes place at the start of the loop cycle,
not at the end entry level checking
while (<Test>) { <code to be looped> }
Eg: int i = 1; //initialization while (i <= 10) // condition
{ Console.WriteLine(i); i++; // increment }
for Loops
This type of loop executes a set number of times and maintains its own
counter.
for (<initialization>; <condition>; <operation>) { <code to loop> }
Eg:
for (int i = 0; i <= 10; i++) { Console.Write(" " + i.ToString()); }
Interrupting Loops
breakCauses the loop to end immediately
continueCauses the current loop cycle to end immediately (execution
continues with the next loop cycle)
Compiler figures it out that which overloaded method should be called with given
parameters.
C#
string a = "String Value";
int b = 34;
Console.Write(a);
Console.Write(b);
VB.NET
Dim a As String = "String Value"
Dim b As Integer = 34
Console.Write(a)
Console.Write(b)
Write() method of Console class has overloaded versions. It can take string, integer,
decimal or char value. Same is the case with WriteLine() method of Console class.
We can write our own overloaded methods like methods given in ASP.NET
C#
public int Add(int x, int y)
{
return x + y;
}
public int Add(int x, int y, int z)
{
return x + y + z;
}
VB.NET
Public Function Add(ByVal x As Integer, ByVal y As Integer) As Integer
Return x + y
End Function
Public Function Add(ByVal x As Integer, ByVal y As Integer, ByVal z As Integer) As
Integer
Return x + y + z
End Function
I have created two functions with same name but different number of parameters. First
Add() function takes two arguments and second takes three. Now we can call
overloaded function as below.
C#
Add(1, 2);
Add(1, 2, 3);
VB.NET
Add(1, 2)
Add(1, 2, 3)
Compiler will find that first call is for first version of the Add() function and second call is
for second overloaded Add() function with three parameters.
Q.8.Method or Function Overriding
Overridden method cannot be in the same class. A method created in base class
can be overridden in derived class for different implementation
to override in inherited class and we have to write override keyword before overridden
method in derived class. In VB.NET Overridable keyword is used in place of virtual
and Overrides keyword is used for Override.
We can call this method as below
C#
A obj1 = new A();
obj1.showMessage();
B obj2 = new B();
obj2.showMessage();
VB.NET
Dim obj1 As New A()
obj1.showMessage()
Dim obj2 As New B()
obj2.showMessage()
Result will be as below.
class A
class B
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 multifile, 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.
Assembly is one of the most interesting and extremely useful areas of .NET architecture
along with reflections and attributes, but unfortunately very few people take interest in
learning such theoretical looking topics.
Q.10.Assembly Benefits
Assemblies are designed to simplify application deployment and to solve versioning
problems that can occur with component-based applications.
End users and developers are familiar with versioning and deployment issues that
arise from
today's component-based systems. Some end users have experienced the frustration of
installing a new application on their computer, only to find that an existing application
has
suddenly stopped working. Many developers have spent countless hours trying to keep
all
necessary registry entries consistent in order to activate a COM class.
Many deployment problems have been solved by the use of assemblies in the .NET
Framework. Because they are self-describing components that have no dependencies
on
registry entries, assemblies enable zero-impact application installation. They also
simplify
uninstalling and replicating applications.
Q.11.What are the basic components of .NET platform?
The basic components of .NET platform (framework) are:
.Net Applications
(Win Forms,Web Applications,Web Services)
Data(ADO.Net) and XML Library
FrameWork Class Library(FCL)
(IO,Streams,Sockets,Security,Reflection,UI)
Common Language Runtime(CLR)
(Debugger,Type Checker,JITer,GC)
Operating System
(Windows,Linux,UNIX,Macintosh,etc.,)
When we compile our .Net Program using any .Net compliant language like (C#,
VB.NET, C++.NET)
it does not get converted into the executable binary code but to an intermediate
code, called MSIL or IL in short, understandable by CLR.
When our CIL compiled code needs to be executed, CLR invokes JIT compilers
which compile the IL code to native executable code (.exe or .dll) for the specific
machine and OS.
JITers in many ways are different from traditional compilers as they, as their
name suggests, compile the IL to native code only when desired e.g., when a
function is called, IL of function's body is converted to native code;
just in time of need. So, the part of code that is not used by particular run is not
converted to native code.
If some IL code is converted to native code then the next time when its needed to
be used, the CLR uses the same copy without re-compiling.
So, if a program runs for sometime, then it won't have any just in time
performance penalty. As JITers are aware of processor and OS exactly at
runtime, they can optimize the code extremely efficiently resulting in very robust
applications.
Also, since JITer knows the exact current state of executable code, they can also
optimize the code by in-lining small function calls (like replacing body of small
function when its called in a loop, saving the function call time).
Although, Microsoft stated that C# and .Net are not competing with languages
like C++ in efficiency, speed of execution, JITers can make your code even faster
than C++ code in some cases when program is run over extended period of time
(like web-servers).
.NET Framework provides huge set of Framework (or Base) Class Library (FCL)
for common, usual tasks.
FCL contains thousands of classes to provide the access to Windows API and
common functions like String Manipulation, Common Data Structures, IO,
Streams, Threads, Security, Network Programming, Windows Programming,
Web Programming, Data Access, etc.
It is simply the largest standard library ever shipped with any development
environment or programming language.
The best part of this library is they follow extremely efficient OO design (design
patterns) making their access and use very simple and predictable.
You can use the classes in FCL in your program just as you use any other class
and can even apply inheritance and polymorphism on these.
.NET also defines a Common Type System (CTS). Like CLS, CTS is also a set of
standards. CTS defines the basic data types that IL understands.
Each .NET compliant language should map its data types to these standard data
types.
This makes it possible for the 2 languages to communicate with each other by
passing/receiving parameters to/from each other.
For example, CTS defines a type Int32, an integral data type of 32 bits (4 bytes)
which is mapped by C# through int and VB.Net through its Integer data type.
Q.16:Metadata Overview
Metadata is binary information describing program that is stored either in a
common language
runtime portable executable (PE) file or in memory. When code is complied into a
PE file,
metadata is inserted into one portion of the file, while code is converted to
Microsoft
intermediate language (MSIL) and inserted into another portion of the file. Every
type and
member 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 code's classes, members, inheritance, and so on.
Metadata describes every type and member defined in code in a languageneutral manner.
Metadata stores the following information:
Description of the assembly.
Identity (name, version, culture, public key).
The types that are exported.
Other assemblies that this assembly depends on.
Security permissions needed to run.
Description of types.
Name, visibility, base class, and interfaces implemented.
Members (methods, fields, properties, events, nested types).
Attributes.
Additional descriptive elements that modify types and members.
Q.17.Benefits of Metadata
Metadata is the key to a simpler programming model, eliminating the need for
Interface
Definition Language (IDL) files, header files, or any external method of
component reference.
Metadata allows .NET 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 selfdescribing. A module's
metadata contains everything needed to interact with another module. Metadata
automatically provides the functionality of IDL in COM, allowing to use one file for
both
At its simplest, an object holds a single value. At its most complex, it holds
references to
many other objects. The .NET Framework provides collectionsthese include
List and
Dictionary. They are often useful.
List
First, the List type provides an efficient and dynamically-allocated array. It does not
provide
fast lookup in the general casethe Dictionary is better for this. List is excellent when
used in
loops.
example::
using System;
using System.Collections.Generic;
class Program
{
static void Main()
{
// Use the List type.
List<string> list = new List<string>();
list.Add("cat");
list.Add("dog");
foreach (string element in list)
{
Console.WriteLine(element);
}
}
}
output::
cat
dog
Q.18.Dictionary
The Dictionary type in the base class library is an important one. It is an
implementation of a
hashtable, which is an extremely efficient way to store keys for lookup. The
Dictionary in .NET
is well-designed.
We try to reference items in a table directly by doing arithmetic operations to
transform keys
into table addresses.
code:
using System;
using System.Collections.Generic;
class Program
{
A unified pipeline receives the first request and the following events take place:
o
and events are available, which could be overridden according to the need of the
application. In other words, you can write your own code to override the default code.
The Page class creates a hierarchical tree of all the controls on the page. All the
components on the page, except the directives, are part of this control tree. You can
see the control tree by adding trace= "true" to the page directive. We will cover page
directives and tracing under 'directives' and 'event handling'.
The page life cycle phases are:
Initialization
Instantiation of the controls on the page
Restoration and maintenance of the state
Execution of the event handler codes
Page rendering
Understanding the page cycle helps in writing codes for making some specific thing
happen at any stage of the page life cycle. It also helps in writing custom controls and
initializing them at right time, populate their properties with view-state data and run
control behavior code.
Following are the different stages of an ASP.NET page:
Page request - When ASP.NET gets a page request, it decides whether to parse
and compile the page, or there would be a cached version of the page;
accordingly the response is sent.
Starting of page life cycle - At this stage, the Request and Response objects
are set. If the request is an old request or post back, the IsPostBack property of
the page is set to true. The UICulture property of the page is also set.
Page initialization - At this stage, the controls on the page are assigned unique
ID by setting the UniqueID property and the themes are applied. For a new
request, postback data is loaded and the control properties are restored to the
view-state values.
Page load - At this stage, control properties are set using the view state and
control state values.
Page rendering - At this stage, view state for the page and all controls are
saved. The page calls the Render method for each control and the output of
rendering is written to the OutputStream class of the Response property of page.
Unload - The rendered page is sent to the client and page properties, such as
Response and Request, are unloaded and all cleanup done.
PreInit - PreInit is the first event in page life cycle. It checks the IsPostBack
property and determines whether the page is a postback. It sets the themes and
master pages, creates dynamic controls, and gets and sets profile property
values. This event can be handled by overloading the OnPreInit method or
creating a Page_PreInit handler.
Init - Init event initializes the control property and the control tree is built. This
event can be handled by overloading the OnInit method or creating a Page_Init
handler.
InitComplete - InitComplete event allows tracking of view state. All the controls
turn on view-state tracking.
LoadPostData - During this phase, the contents of all the input fields are
defined with the <form> tag are processed.
PreLoad - PreLoad occurs before the post back data is loaded in the controls.
This event can be handled by overloading the OnPreLoad method or creating a
Page_PreLoad handler.
Load - The Load event is raised for the page first and then recursively for all
child controls. The controls in the control tree are created. This event can be
handled by overloading the OnLoad method or creating a Page_Load handler.
PreRender - The PreRender event occurs just before the output is rendered. By
handling this event, pages and controls can perform any updates before the
output is rendered.
UnLoad - The UnLoad phase is the last phase of the page life cycle. It raises the
UnLoad event for all controls recursively and lastly for the page itself. Final
cleanup is done and all resources and references, such as database
connections, are freed. This event can be handled by modifying the OnUnLoad
method or creating a Page_UnLoad handler.
Q.20.Web.config
The web.config file uses the predefined XML format.The Entire content of the file
is nested in a root<Configuration> elemnt.
Inside this element are several more subsections, some of which youll never
change, and others which are more important.
<?xml version=1.0 ?>
<configuration>
<configSections>.</configSections>
<appSettings>.</appSettings>
<connectionSettings>.</connectionSettings>
<system.web>.</system.web>
<system.codedom>.</system.codedom>
<system.webServer>.</system.webServer>
</cofiguration>
The web.config file is case-sensitive,like all XML documents, and starts every
setting with a lowercase letter.This means you cannot write <AppSetting> instead
of <appSettings>
There are three sections in the web.config file.
The <appSettings> section allows you to add your own miscellaneous pieces of
information.
The<connectionStrings> section allows you to define the connections information
for accessing a database.
Finally, the <system.web> section holds every ASP.NET setting youll need to
configure.
Inside the <system.web> element are separate elements for each aspect of
website configuration. You can incluse as few or as many of these as you want.
Q.21.Global.asax File
The Global.asax file allows you to write the code that responds to global
application events.
These events fire at various points during the lifetime of a web application,
including when the application domain is first created (When the first request is
received for a page in a website folder).
To add an Global.asax file to an application in visual studio, choose Website>Add
New Item, and Select the Global Application Class file type.Then, Click OK.
The Global.asax File looks similar to a normal .aspx file, expect it cant contain
any HTML or ASP.NET tags. Instead, it contains event handlers, This event
handler uses a Write() method of a Built-in Response object.
Each ASP.NET application can have one Global.asax file. Once you place it in the
appropriate website directory, ASP.NET recognizes it and uses it automatically.
Event-Handling Method
Application_Start()
Description
Occurs when the application starts,
which the first time it receives a
Application_End()
Application_BeginRequest()
Application_EndRequest()
Session_Start()
Session_End()
Application_Error()
Application_Disposed()
}
// ...
</script>
Q.22.DELEGATES
A delegate is a type that enables you to store references to functions. Although this
sounds
quite involved, the mechanism is surprisingly simple.
class Program
{
public delegate void ashok(string letter); // delegate declaration
static void Main(string[] args)
{
Program pp = new Program();
ashok a = new ashok(pp.soniya); // delegate instance
a("increase taxes"); // delegate invokation
}
public void soniya(string msg) // delegate method
{
Console.WriteLine("inside display");
}}
What is the use of Delegates?
Suppose if you have multiple methods with same signature (return type & number of
parameters) and want to call all the methods with single object then we can go for
delegates.
Delegates are two types
- Single Cast Delegates
- Multi Cast Delegates
Single Cast Delegates
Single cast delegate means which hold address of single method like as explained in
above example.
Multicast Delegates
Multi cast delegate is used to hold address of multiple methods in single delegate. To
hold multiple addresses with delegate we will use overloaded += operator and if you
want remove addresses from delegate we need to use overloaded operator -=
Multicast delegates will work only for the methods which have return type only void. If
we want to create a multicast delegate with return type we will get the return type of last
method in the invocation list
Check below sample code for delegate declaration and methods declaration
Syntax of Multicast Delegate & Method Declaration
Check below sample code for multicast delegate declaration and methods declaration
public delegate void MultiDelegate(int a,int b);
public class Sampleclass
{
public static void Add(int x, int y)
{
Console.WriteLine("Addition Value: "+(x + y));
}
public static void Sub(int x, int y)
{
Console.WriteLine("Subtraction Value: " + (x - y));
}
public static void Mul(int x, int y)
{
Console.WriteLine("Multiply Value: " + (x * y));
}
}
class Program
{
static void Main(string[] args)
{
Sampleclass sc=new Sampleclass();
MultiDelegate del = Sampleclass.Add;
del += Sampleclass.Sub;
del += Sampleclass.Mul;
del(10, 5);
Console.ReadLine();
}
}
Output
Whenever we run above code we will get output like as shown below
Addition Value : 15
Subtraction Value : 5
Multiply Value : 50
If you observe above code I declared MultiDelegate method with void return type.
foreach loop is a different kind of looping constructs in C# programming that doesnt
includes initialization, termination and increment/decrement characteristics. It uses
collection to take value one by one and then processes them.
Syntax:
foreach (string name in arr)
{}
Where, name is a string variable that takes value from collection as arr and then
processes them in the body area.
Example:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace foreach_loop
{
class Program
{
static void Main(string[] args)
{
string[] arr = new string[5]; // declaring array
//Storing value in array element
arr[0] = "Steven";
arr[1] = "Clark";
arr[2] = "Mark";
arr[3] = "Thompson";
arr[4] = "John";
//retrieving value using foreach loop
foreach (string name in arr)
{
Private members are accessible only within the body of the class or the struct in which
they are declared.
Accessibility:
Cannot be accessed by object
Cannot be accessed by derived classes
Example: In the following example num2 is not accessible outside the class.
using System;
namespace AccessModifiers
{
class Program
{
class AccessMod
{
public int num1;
int num2;
}
static void Main(string[] args)
{
AccessMod ob1 = new AccessMod();
//Direct access to public members
ob1.num1 = 100;
//Access to private member is not permitted
ob1.num2 = 20;
Console.WriteLine("Number one value in main {0}", ob1.num1);
Console.ReadLine();
}
}
}
protected
A protected member is accessible from within the class in which it is declared, and from
within any class derived from the class that declared this member.
A protected member of a base class is accessible in a derived class only if the access
takes place through the derived class type.
Accessibility:
Cannot be accessed by object
By derived classes
using System;
namespace AccessModifiers
{
class Program
{
class Base
{
protected int num1;
}
class Derived : Base
{
public int num2;
static void Main(string[] args)
{
Base ob1 = new Base();
Derived ob2 = new Derived();
ob2.num1 = 20;
// Access to protected member as it is inhertited by the Derived class
ob2.num2 = 90;
Console.WriteLine("Number2 value {0}", ob2.num2);
Console.WriteLine("Number1 value which is protected {0}", ob2.num1);
Console.ReadLine();
}
}
}
}
internal
The internal keyword is an access modifier for types and type members. We can
declare a class as internal or its member as internal. Internal members are accessible
only within files in the same assembly (.dll).
In other words, access is limited exclusively to classes defined within the current project
assembly.
Accessibility:
In same assembly (public)
Can be accessed by objects of the class
Can be accessed by derived classes
In other assembly (internal)
Description
AccessKey
fromWebControl.)
Adapter
AppendDataBoundItems
AppRelativeTemplateSourceDirector
y
Attributes
Q.25.B.LIST-BOX
Nam
e
Description
AccessibilityObject
AccessibleDefaultActionDescriptio
n
AccessibleDescription
AccessibleName
AccessibleRole
To give you an idea of what a LINQ query looks like, heres a quick example that
shows a list of
Wrox authors whose names contain the letter S:
LINQ has a great power of querying on any source of data, data source could be
the collections of
objects, database or XML files. We can easily retrieve data from any object that
implements the
IEnumerable<T> interface. Microsoft basically divides LINQ into three areas and
that are give below.
LINQ to Object {Queries performed against the in-memory data}
LINQ to ADO.Net
LINQ to SQL (formerly DLinq) {Queries performed against the
relation database
only Microsoft SQL Server Supported}
LINQ to DataSet {Supports queries by using ADO.NET data sets and
data tables}
LINQ to Entities {Microsoft ORM solution}
LINQ to XML (formerly XLinq) { Queries performed against the XML
so
This sample uses where to find all elements of an array less than 5.
Source Code
C#
public void Linq1()
{
int[] numbers = { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 };
var lowNums =
from n in numbers
where n < 5
select n;
Console.WriteLine("Numbers < 5:");
foreach (var x in lowNums)
{
Console.WriteLine(x);
}
}
Result
Numbers < 5:
4,0,2,3,1
Q.28.Explain standard query operators Select,From,Order BY,and Where in LINQ?
LINQ supports a large number of query operators keywords that enable you to
select, order, or
filter data that is to be returned from the query.
examples uses the object model and the ObjectContext object called myEntities
Select
var allReviews = from r in myEntities.Reviews
select r;
The r variable in this example is referred to as a range variable that is only available
within
the current query. You typically introduce the range variable in the From clause, and
then
use it again in the Where and Select clauses to filter the data, and to indicate the data
you
want to select. Although you can choose any name you like, you often see single letter
variables like the r (for Review) or you see the singular form of the collection you are
querying
From
Although not considered a standard query operator because it doesnt operate on
the data
but rather points to the data the From clause (from in C#) is an important element in
a LINQ
query, because it defines the collection or data source that the query must act upon.
Order By
With Order By (orderby in C#, without the space that VB.NET uses) you can sort the
items
in the result collection. Order By is followed by an optional Ascending or Descending
(ascending and descending in C#) keyword to specify sort order. You can specify
multiple
criteria by separating them with a comma. The following query returns a list of genres
first
sorted by SortOrder in descending order, then sorted on their Name in ascending order
(the
default):
var allGenres = from g in myEntities.Genres
orderby g.SortOrder descending, g.Name
select g;
Where
Just like the WHERE clause in SQL, the Where clause in LINQ (where in C#) enables
you
to filter the objects returned by the query.
var allReviews = from r in myEntities.Reviews
where r.Authorized == true
select r;
Sum, Min, Max, Average, and Count
These aggregation operators enable you to perform mathematical calculations on the
objects
in the result set. For example, to retrieve the number of reviews, you can execute this
query:
var numberOfReviews = (from r in myEntities.Reviews
select r).Count();
(Q.29.A)LINQ to Objects
it was vital to write long coding (foreach loops of much complexity) for retrieval of
data from a collection which is now replaced by writing declarative code which
clearly describes the desired data that is required to retrieve.
There are also many advantages of LINQ to Objects over traditional foreach
loops like more readability, powerful filtering, capability of grouping, enhanced
ordering with minimal application coding.
Such LINQ queries are also more compact in nature and are portable to any
other data sources without any modification or with just a little modification.
This is the purest form of language integration. With LINQ to Objects, you can
query collections in
your .NET applications as you saw in the previous example. Youre not limited to
arrays because
LINQ enables you to query almost any kind of collection that exists in the .NET
Framework.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace LINQtoObjects
{
class Program
{
static void Main(string[] args)
{
string[] tools = { "Tablesaw", "Bandsaw", "Planer", "Jointer", "Drill",
"Sander" };
serialize them.
It eliminates the need for a developer to learn the XML query language which is
somwhat complex.
LINQ to XML has its power in the System.Xml.Linq namespace. This has all the
19 necessary classes to work with XML. These classes are the following ones.
Xattribute,XCData,Xcomment,Xcontainer,Xdeclaration,Xdocument,XdocumentTy
pe,Xelement,Xname,Xnamespace,Xnode,XnodeDocumentOrderComparer,Xnod
eEqualityComparer,Xobject,XobjectChange,XobjectChangeEventArgs,XobjectEv
entHandler,XprocessingInstruction,XText
using System;
using System.Collections.Generic;
using System.Linq;
using System.Xml.Linq;
namespace LINQtoXML
{
class ExampleOfXML
{
static void Main(string[] args)
{
string myXML = @"<Departments>
<Department>Account</Department>
<Department>Sales</Department>
<Department>Pre-Sales</Department>
<Department>Marketing</Department>
</Departments>";
XDocument xdoc = new XDocument();
xdoc = XDocument.Parse(myXML);
var result = xdoc.Element("Departments").Descendants();
foreach (XElement item in result)
{
Console.WriteLine("Department Name - " + item.Value);
}
Console.WriteLine("\nPress any key to continue.");
Console.ReadKey();
}
}
}
LINQ to SQL enables you to write object-oriented queries in your .NET projects
that target
Microsoft SQL Server databases. The LINQ to SQL implementation translates
your queries into
SQL statements, which are then sent to the database to perform typical CRUD
operations.
For most ASP.NET developers, LINQ to SQL (also known as DLINQ) is an electrifying
part of Langauage Integrated Query as this allows quering data in SQL server database
by using usual LINQ expressions. It also allows to update, delete and insert data, but
the only drawback from which it suffers is its limitation to the SQL server database.
However, there are many benefits of LINQ to SQL over ADO.NET like reduced
complexity, few lines of coding and many more.
Below is a diagram showing the execution architecture of LINQ to SQL.
CSS saves time You can write CSS once and then reuse same sheet in
multiple HTML pages. You can define a style for each HTML element and apply it
to as many Web pages as you want.
Pages load faster If you are using CSS, you do not need to write HTML tag
attributes every time. Just write one CSS rule of a tag and apply it to all the
occurrences of that tag. So less code means faster download times.
Easy maintenance To make a global change, simply change the style, and all
elements in all the web pages will be updated automatically.
Superior styles to HTML CSS has a much wider array of attributes than
HTML, so you can give a far better look to your HTML page in comparison to
HTML attributes.
Global web standards Now HTML attributes are being deprecated and it is
being recommended to use CSS. So its a good idea to start using CSS in all the
HTML pages to make them compatible to future browsers.
Offline Browsing CSS can store web applications locally with the help of an
offline catche.Using of this, we can view offline websites.The cache also ensures
faster loading and better overall performance of the website.
Inline CSS
For Inline CSS every style content is in HTML elements. It is used for a limited section.
Whenever our requirements are very small we can use inline CSS.
It will affect only single elements. In HTML we require that various HTML tag's views are
different so then we use inline Cascading Style Sheets. There are disadvantage of inline
Cascading Style Sheets. It must be specified on every HTML tag. There is very much
time consumed by that and it is not the best practice for a good programmer and the
code will be quite large and very complex.
Inline CSS examples are given below:
Internal CSS
In internal CSS the style of CSS is specified in the <head> section. This is internal CSS,
it affects all the elements in the body section. Internal CSS is used in the condition when
we want a style to be used in the complete HTML body. For that we can use style in the
head tag.
This style performs an action in the entire HTML body.
External CSS
In External CSS we create a .css file and use it in our HTML page as per our
requirements. Generally external Cascading Style Sheets are used whenever we have
many of HTML attributes and we can use them as required; there is no need to rewrite
the CSS style again and again in a complete body of HTML that inherits the property of
the CSS file. There are two ways to create a CSS file. The first is to write the CSS code
in Notepad and save it as a .css file, the second one is to directly add the style sheet in
our Solution Explorer and direct Visual Studio to use it on our HTML page.
How to create and use an External CSS.
1.
2.
3.
4.
5.
(Q.1.1)ASP.NET CONTROLS
Controls are small building blocks of the graphical user interface, which include text
boxes, buttons, check boxes, list boxes, labels, and numerous other tools. Using these
tools, the users can enter data, make selections and indicate their preferences.
Controls are also used for structural jobs, like validation, data access, security, creating
master pages, and data manipulation.
ASP.NET uses five types of web controls, which are:
HTML controls
HTML Server controls
ASP.NET Server controls
ASP.NET Ajax Server controls
User controls and custom controls
ASP.NET server controls are the primary controls used in ASP.NET. These controls can
be grouped into the following categories:
Validation controls - These are used to validate user input and they work by
sources.
Data view controls - These are various lists and tables, which can bind to data
Pressing this key with the Alt key moves focus to the
control.
Attributes
BackColor
Background color.
BindingContainer
BorderColor
Border color.
BorderStyle
Border style.
BorderWidth
Border width.
CausesValidation
ChildControlCreate
d
ClientID
Context
Controls
ControlStyle
CssClass
CSS class
Description
AddAttributesToRender
AddedControl
AddParsedSubObject
ApplyStyleSheetSkin
ClearCachedClientID
ClearChildControlState
ClearChildState
ClearChildViewState
CreateChildControls
CreateControlCollection
CreateControlStyle
View State
Control State
Session State
Application State
View State
The view state is the state of the page and all its controls. It is automatically maintained
across posts by the ASP.NET framework.
When a page is sent back to the client, the changes in the properties of the page and
its controls are determined, and stored in the value of a hidden input field named
_VIEWSTATE. When the page is again posted back, the _VIEWSTATE field is sent to
the server with the HTTP request.
The view state could be enabled or disabled for:
It is implemented using a view state object defined by the StateBag class which defines
a collection of view state items. The state bag is a data structure containing attribute
value pairs, stored as strings associated with objects.
The StateBag class has the following properties:
Properties
Description
Item(name)
The value of the view state item with the specified name.
This is the default property of the StateBag class.
Count
Keys
Values
Description
Add(name, value)
Clear
Equals(Object)
current object.
Finalize
GetEnumerator
GetType
IsItemDirty
Remove(name)
SetDirty
SetItemDirty
ToString
Example
The following example demonstrates the concept of storing view state. Let us keep a
counter, which is incremented each time the page is posted back by clicking a button
on the page. A label control shows the value in the counter.
The markup file code is as follows:
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs"
Inherits="statedemo._Default" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>
Untitled Page
</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<h3>View State demo</h3>
Page Counter:
<asp:Label ID="lblCounter" runat="server" />
<asp:Button ID="btnIncrement" runat="server" Text="Add Count"
onclick="btnIncrement_Click" />
</div>
</form>
</body>
</html>
The code behind file for the example is shown here:
public partial class _Default : System.Web.UI.Page
{
public int counter
{
get
{
if (ViewState["pcounter"] != null)
{
return ((int)ViewState["pcounter"]);
}
else
{
return 0;
}
}
set
{
ViewState["pcounter"] = value;
}
}
protected void Page_Load(object sender, EventArgs e)
{
lblCounter.Text = counter.ToString();
counter++;
}
}
It would produce the following result:
Control State
Control state cannot be modified, accessed directly, or disabled.
Session State
When a user connects to an ASP.NET website, a new session object is created. When
session state is turned on, a new session state object is created for each new request.
This session state object becomes part of the context and it is available through the
page.
Session state is generally used for storing application data such as inventory, supplier
list, customer record, or shopping cart. It can also keep information about the user and
his preferences, and keep the track of pending operations.
Sessions are identified and tracked with a 120-bit SessionID, which is passed from
client to server and back as cookie or a modified URL. The SessionID is globally
unique and random.
The session state object is created from the HttpSessionState class, which defines a
collection of session state items.
The HttpSessionState class has the following properties:
Properties
Description
SessionID
Item(name)
Count
TimeOut
Description
Add(name, value)
Clear
Remove(name)
RemoveAll
RemoveAt
The session state object is a name-value pair to store and retrieve some information
from the session state object. You could use the following code for the same:
void StoreSessionInfo()
{
String fromuser = TextBox1.Text;
Session["fromuser"] = fromuser;
}
void RetrieveSessionInfo()
{
String fromuser = Session["fromuser"];
Label1.Text = fromuser;
}
The above code stores only strings in the Session dictionary object, however, it can
store all the primitive data types and arrays composed of primitive data types, as well
as the DataSet, DataTable, HashTable, and Image objects, as well as any user-defined
class that inherits from the ISerializable object.
Application State
The ASP.NET application is the collection of all web pages, code and other files within
a single virtual directory on a web server. When information is stored in application
state, it is available to all the users.
To provide for the use of application state, ASP.NET creates an application state object
for each application from the HTTPApplicationState class and stores this object in
server memory. This object is represented by class file global.asax.
Application State is mostly used to store hit counters and other statistical data, global
application data like tax rate, discount rate etc. and to keep the track of users visiting
the site.
The HttpApplicationState class has the following properties:
Properties
Description
Item(name)
Count
Description
Add(name, value)
Clear
Remove(name)
RemoveAll
collection.
RemoveAt
Lock()
Unlock()
Application state data is generally maintained by writing handlers for the events:
Application_Start
Application_End
Application_Error
Session_Start
Session_End
(Q.3.1)ASP.NET validation controls validate the user input data to ensure that
useless, unauthenticated, or contradictory data don't get stored.
ASP.NET provides the following validation controls:
RequiredFieldValidator
RangeValidator
CompareValidator
RegularExpressionValidator
CustomValidator
ValidationSummary
BaseValidator Class
The validation control classes are inherited from the BaseValidator class hence they
inherit its properties and methods. Therefore, it would help to take a look at the
properties and the methods of this base class, which are common for all the validation
controls:
Members
Description
ControlToValidate
Display
EnableClientScript
Enabled
ErrorMessage
Text
IsValid
SetFocusOnError
ValidationGroup
Validate()
RequiredFieldValidator Control
The RequiredFieldValidator control ensures that the required field is not empty. It is
generally tied to a text box to force input into the text box.
The syntax of the control is as given:
<asp:RequiredFieldValidator ID="rfvcandidate"
runat="server" ControlToValidate ="ddlcandidate"
ErrorMessage="Please choose a candidate"
InitialValue="Please choose a candidate">
</asp:RequiredFieldValidator>
RangeValidator Control
The RangeValidator control verifies that the input value falls within a predetermined
range.
It has three specific properties:
Properties
Description
Type
MinimumValue
MaximumValue
Description
Type
ControlToCompare
ValueToCompare
Operator
RegularExpressionValidator
The RegularExpressionValidator allows validating the input text by matching against a
pattern of a regular expression. The regular expression is set in the
ValidationExpression property.
The following table summarizes the commonly used syntax constructs for regular
expressions:
Character Escapes
Description
\b
Matches a backspace.
\t
Matches a tab.
\r
\v
\f
\n
Escape character.
Apart from single character match, a class of characters could be specified that can be
matched, called the metacharacters.
Metacharacters
Description
[abcd]
[^abcd]
[2-7a-mA-M]
\w
\W
\s
etc.
\S
\d
\D
Description
{N}
N matches.
{N,}
N or more matches.
{N,M}
The server side validation routine must be called from the control's ServerValidate
event handler. The server side validation routine should be written in any .Net
language, like C# or VB.Net.
The basic syntax for the control is as given:
<asp:CustomValidator ID="CustomValidator1" runat="server"
ClientValidationFunction=.cvf_func. ErrorMessage="CustomValidator">
</asp:CustomValidator>
ValidationSummary
The ValidationSummary control does not perform any validation but shows a summary
of all errors in the page. The summary displays the values of the ErrorMessage
property of all validation controls that failed validation.
The following two mutually inclusive properties list out the error message:
A join clause takes two source sequences as input. The elements in each
sequence must either be or contain a property that can be compared to a
corresponding property in the other sequence.
The join clause compares the specified keys for equality by using the
special equals keyword. All joins performed by the join clause are equijoins.
The shape of the output of a join clause depends on the specific type of join you
are performing. The following are three most common join types:
Inner join
The following example shows a simple inner equijoin. This query produces a flat
sequence of "product name / category" pairs. The same category string will appear
in multiple elements. If an element from categories has no matching products, that
category will not appear in the results.
var innerJoinQuery =
from category in categories
join prod in products on category.ID equals prod.CategoryID
select new { ProductName = prod.Name, Category = category.Name };
//produces flat sequence
Group join
A group join produces a hierarchical result sequence, which associates elements in
the left source sequence with one or more matching elements in the right side
source sequence. A group join has no equivalent in relational terms; it is essentially
a sequence of object arrays.
var innerGroupJoinQuery =
from category in categories
join prod in products on category.ID equals prod.CategoryID into prodGroup
select new { CategoryName = category.Name, Products = prodGroup };
use null as the default value for any reference type, or you can specify a userdefined default type. In the following example, a user-defined default type is shown:
var leftOuterJoinQuery =
from category in categories
join prod in products on category.ID equals prod.CategoryID into prodGroup
from item in prodGroup.DefaultIfEmpty(new Product { Name = String.Empty,
CategoryID = 0 })
select new { CatName = category.Name, ProdName = item.Name };
Root Node
o Each siteMapPath has one root node
Selected Node
o The current node matches the page the user is on
Parent Nodes
o A node that has children besides the root node
Leaf Nodes
o Nodes that have a parent but no children
Customizing
Click the autoformat option in the smart tag of the treeView
There are also several property that you can attach a style sheet to
nodeStyle
o default style of all nodes in the treeView
HoverNodeStyle
o Style spplied when the user hovers his mouse over a certain node
levelStyles
o allows you to apply style info for certain levels of the treeview
Menus
The menu will use the sitemap to display each item and it uses submenus for each item
in a lower hierarchy
Add a menu control
Configure it to the siteMapDataAccess Control
indicates the number of rows that were affected by the operation. You can use
that information to determine if the operation was successful.
If you execute a command that contains a Select statement, the result is a
result set that contains the rows you requested. To read through the rows in the
result set, you use a data reader object.
Although a data reader provides an efficient way of reading the rows in a result
set, you cant use it to modify those rows. In addition, it only lets you read rows in a
forward direction.
Once you read the next row, the previous row is unavailable. Because of that,
you typically use a data reader to retrieve and work with a single database row at
a time.
Description
Instead of using a data adapter to execute commands to retrieve, insert, update,
and delete data from a database, you can execute those commands directly
To retrieve data from a database, you execute a command object that contains a
Select statement.
Then, the command object uses a connection to connect to the database and
retrieve the data. You can then read the results one row at a time using a data
reader object.
To insert, update, or delete data in a database, you execute a command object
that contains an Insert, Update, or Delete statement. Then, the command object
uses a connection to connect to the database and update the data. You can then
check the value thats returned to determine if the operation was successful.
If you use this technique in an application that maintains the data in a database,
you
typically work with a single row at a time. Because of that, the chance of a
concurrency
error is reduced.
Then, the application can work with the data in the dataset without affecting
the data in the database. If the application makes changes to the data in the
dataset, it can use ihc data adapters Update method to execute the
commands identified by the
DeleteCommand, InsertCommand, and UpdateCommand properties and post
the changes back to the database.
Common members of the SqlDataAdapter class
Property Description
SelectCommand A SqlCommand object representing the Select
statement used to query the database.
DeleteCommand A SqlCommand object representing the Delete
statement used to delete a row from the database.
InsertCommand A SqlCommand object representing the Insert
statement used to add a row to the database.
UpdateCommand A SqlCommand object representing the Update
statement used to update a row in the database.
Method Description
Fill Executes the command identified by the
SelectCommand property and loads the result into a
dataset object.
Update Executes the commands identified by the
DeleteCommand, InsertCommand, and UpdateCommand
properties for each row in the dataset that was
deleted, added, or updated.
Description
A data reader provides read-only, forward-only access to the data in a database.
Because it doesnt require the overhead of a dataset, it s more efficient than
using a data adapter. However, it cant be used to update data.
When the Fill method of a data adapter is used to retrieve data from a database,
the data adapter uses a data reader to load the results into a dataset.
(Q.37)How to define the connection
The first step in configuring a SqlDataSource control is to create the connection
for th data source click the New Connection button to display the Add Connection
dialog box.
This dialog box helps you identify the database that you want to access and
provide the information you need to access it.
In the Add Connection dialog box, you select the name of the server that
contains the database you want to access, enter the information that s required
to log on to the server, and select the name of the database you want to access.
If youre using SQL Server Express on your own PC, you can type
localhost\sqlexpress for the server name.
For the logon information, you can click on the Use Windows Authentication
option.
Then, SQL Server Express will use the login name and password that you use for
your computer as the name and password for the database too.
As a result, you wont need to provide a separate user name and password in
this dialog box. Last, you select the
name of the database that you want to connect to. When you re done, you can
click on the Test Connection button to be sure that the connection works.
Once you establish a connection to a database, you can use that connection for
all of the applications that use that database.
Readonly="True" SortExpression="CategorylD">
cltemStyle Widths"10Opx" />
</asp:BoundField>
<asp:BoundField DataField="ShortName" HeaderText="Short Name"
SortExpression="ShortName" >
<ItemStyle Width="150px />
</asp:BoundField>
<asp:BoundField DataField="LongName" HeaderText="Long Name"
SortExpres sion="LongName">
<ItemStyle Width="200px" />
</asp:BoundField>
<asp:CommandField ButtonType="Button ShowEditButton="True"
CausesValidation=False" />
<asp:CommandField ButtonType="Button" ShowDeleteButton="True
CausesValidation="False" />
</Columns>
</asp:GridView>
Basic attributes of the GridView control
ID The ID of the control.
Runat Must specify server.
DataSourceID The ID of the data source to bind to.
DataKeyNames The names of the primary key fields separated
by commas.
AutoGenerateColumns Specifics whether the controls columns should
be
automatically generated.
Selectedlndex Specifies the row to be initially selected.
Description
The GridView control displays data from a data source in a row and column format.
The
data is rendered as an HTML table.
To create a GridView control, drag the GridView icon from the Data group of the
Toolbox.
To bind a GridView control to a data source, use the smart tag menu s Choose Data
Source command.
Q:Attributes of the GridView control that affect paging
Attribute Description
AllowPaging Set to True to enable paging.
PageSize Specifies the number of rows to display on each
page. The default is 10.
Q:Attributes of the PagerSettings element
Attribute Description
Mode Controls what buttons are displayed in the
pager area. You can specify
The after action events let you check that database operations have completed
successfully. To
do that, you need to check for two types of errors as
illustrated in the example in this figure. First, you should check for database
exceptions by testing the Exception property of the e argument. If it is not null,
database exception has occurred. Then, you should display an appropriate
error message to let the user know about the problem.
If the data source uses optimistic concurrency, you should also check to
make sure there hasnt been a concurrency error. You can do that by testing the
AffectedRows property of the c argument. If a concurrency error has occurred,
this property will be set to zero meaning that no rows have been changed. Then,
you can display an appropriate error message.
If no errors occurred during the update operation, the ItemUpdated event
shown in this figure ends by calling the DataBind method for the drop-down list
control. This is necessary because view state is enabled for this control. As a
result, this control will continue to display the old data unless you call its
DataBind method to refresh its data. If view state were disabled for this control,
the DataBind call wouldn't be necessary.
templates to render all of the fields as a single row by default. This gives you complete
control
over the layout of the fields within the row.
When you create a FormView control and bind it to a data source, the Web Forms
Designer will
automatically create default templates for you. Then, you can edit the templates to
achieve the
layout you want. To do that, choose Edit Templates from the smart tag menu.
For most applications, youll use just the Item, Editltem, and Insertltem templates.
How the FormView control differs from the DetailsView control
The DetailsView control can be easier to work with, but the FormView control provides
more formatting and layout options.
The DetailsView control can use BoundField elements or TemplateField elements with
templates that use data binding expressions to define bound data fields. The FormView
control can use only templates with data binding expressions to display bound data.
The DetailsView control renders each field as a table row, but the FormView control
renders all the fields in a template as a single table row.
Description
A FormView control is similar to a DetailsView control, but its templates give you more
control over how its data is displayed. To accomplish that, all the columns in the data
source can be laid out within a single template.
After you create a FormView control and assign a data source to it, you can edit the
controls templates so the data is displayed the way you want.
ASP.NET Provider Model
Description
Skip
Skips elements up to a specified position starting from the first element in a sequence.
SkipWhile Skips elements based on a condition until an element does not satisfy the condition. If the
first element itself doesn't satisfy the condition, it then skips 0 elements and returns all the
elements in the sequence.
Take
Takes elements up to a specified position starting from the first element in a sequence.
TakeWhile Returns elements from the first element until an element does not satisfy the condition. If t
first element itself doesn't satisfy the condition then returns an empty collection.
Example: Skip() - C#
IList<string> strList = new List<string>(){ "One", "Two", "Three", "Four", "Five" };
var newList = strList.Skip(2);
foreach(var str in newList)
Console.WriteLine(str);
Example: SkipWhile in C#
IList<string> strList = new List<string>() {"One","Two","Three","Four","Five","Six" };
var resultList = strList.SkipWhile(s => s.Length < 4);
foreach(string str in resultList)
Console.WriteLine(str);
Example: Take() in C#
IList<string> strList = new List<string>(){ "One", "Two", "Three", "Four", "Five" };
var newList = strList.Take(2);
foreach(var str in newList)
Console.WriteLine(str);
Example: TakeWhile in C#
IList<string> strList = new List<string>() {"Three","Four","Five","Hundred" };
var result = strList.TakeWhile(s => s.Length > 4);
foreach(string str in result)
Console.WriteLine(str);
Description
First
Returns the first element of a collection, or the first element that satisfies a conditio
FirstOrDefault
Returns the first element of a collection, or the first element that satisfies a conditio
Returns a default value if index is out of range.
Description
Last
Returns the last element from a collection, or the last element that satisfies a condi
LastOrDefault
Returns the last element from a collection, or the last element that satisfies a
condition. Returns a default value if no such element exists.
Returns the only element from a collection, or the only element that satisfies a condition. If
Single() found no elements or more than one elements in the collection then throws
InvalidOperationException.
Single
Or
The same as Single, except that it returns a default value of a specified generic type, instead
throwing an exception if no element found for the specified condition. However, it will thrown
InvalidOperationException if it found more than one element for the specified condition in the
Defaul collection.
t
IList<int> oneElementList = new List<int>() { 7 };
IList<int> intList = new List<int>() { 7, 10, 21, 30, 45, 50, 87 };
references of the objects. So, if the objects have the same reference then they
considered as equal otherwise they are considered not equal.
The following example demonstrates the SequenceEqual method with the collection of
primitive data types.
Example: SequenceEqual in Method Syntax C#
IList<string> strList1 = new List<string>(){"One", "Two", "Three", "Four", "Three"};
IList<string> strList2 = new List<string>(){"One", "Two", "Three", "Four", "Three"};
bool isEqual = strList1.SequenceEqual(strList2); // returns true
Console.WriteLine(isEqual);
Element Operators: ElementAt, ElementAtOrDefault
Element operators return a particular element from a sequence (collection).
The following table lists all the Element operators in LINQ.
Element Operators
(Methods)
Description
ElementAt
ElementAtOrDefault Returns the element at a specified index in a collection or a default value if the
index is out of range.
First
Returns the first element of a collection, or the first element that satisfies a
condition.
FirstOrDefault
Returns the first element of a collection, or the first element that satisfies a
condition. Returns a default value if index is out of range.
Last
Returns the last element of a collection, or the last element that satisfies a
condition
LastOrDefault
Returns the last element of a collection, or the last element that satisfies a
condition. Returns a default value if no such element exists.
Single
Returns the only element of a collection, or the only element that satisfies a
condition.
SingleOrDefault
Returns the only element of a collection, or the only element that satisfies a
condition. Returns a default value if no such element exists or the collection doe
not contain exactly one element.
chapter we will focus on using timers with UpdatePanels, so if you haven't already read
the chapter on UpdatePanels, please do so now.
Here is a small example of using the Timer control. It simply updates a timestamp every
5 seconds.
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs"
Inherits="_Default" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN"
"http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Timers</title>
</head>
<body>
<form id="form1" runat="server">
<asp:ScriptManager ID="ScriptManager1" runat="server" />
<asp:Timer runat="server" id="UpdateTimer" interval="5000"
ontick="UpdateTimer_Tick" />
<asp:UpdatePanel runat="server" id="TimedPanel" updatemode="Conditional">
<Triggers>
<asp:AsyncPostBackTrigger controlid="UpdateTimer" eventname="Tick" />
</Triggers>
<ContentTemplate>
<asp:Label runat="server" id="DateStampLabel" />
</ContentTemplate>
</asp:UpdatePanel>
</form>
</body>
</html>
We only have a single CodeBehind function, which you should add to your CodeBehind
file:
protected void UpdateTimer_Tick(object sender, EventArgs e)
{
DateStampLabel.Text = DateTime.Now.ToString();
}
This is all very simple. We have a normal UpdatePanel, which carries a Trigger
reference to our new Timer control. This means that the panel is updated when the
Timer "ticks", that is, fires the Tick event. The Timer control uses the interval attribute to
define the number of milliseconds to occur before firing the Tick event. As you can see
from our CodeBehind code listing, we just update the DateStampLabel each time the
Timer fires. This could be done more efficient with a simple piece of JavaScript, which
updates the time on the clientside instead of involving the server. The example is only
used to demonstrate the potential of the Timer control.
Common UpdatePanel Properties