Documente Academic
Documente Profesional
Documente Cultură
OOP....................................................................................................................... 1
(B) What is Object Oriented Programming?........................................................1
(B) Whats a Class ?............................................................................................ 2
(B) Whats an Object ?........................................................................................ 2
(B) What are different properties provided by Object-oriented systems ?..........2
(B) What is a Interface ?..................................................................................... 3
(B)What is difference between abstract classes and interfaces?........................3
.NET ARCHITECTURE.............................................................................................. 7
FRAMEWORK.......................................................................................................... 9
ASP.NET................................................................................................................ 14
ADO.NET.............................................................................................................. 20
THREADING.......................................................................................................... 26
REMOTING AND WEB SERVICES...........................................................................27
CASHING.............................................................................................................. 29
SQL SERVER......................................................................................................... 34
XML...................................................................................................................... 36
SILVERLIGHT........................................................................................................ 39
WCF..................................................................................................................... 39
WWF.................................................................................................................... 39
DTSX.................................................................................................................... 39
MVC..................................................................................................................... 39
ENTITY FRAMEWORK............................................................................................ 39
GENERAL
What is an application server?
As defined in Wikipedia, an application server is a software engine that
delivers applications to client computers or devices. The application server runs your
server code. Some well known application servers are IIS (Microsoft), WebLogic Server
(BEA), JBoss (Red Hat), WebSphere (IBM).
What is a stack? What is a heap? Give the differences between the two?
Stack is a place in the memory where value types are stored. Heap is a place in the
memory where the reference types are stored.
The picture above, while not really a true representation of what's happening in memory,
helps us distinguish a Stack from a Heap.
The Stack is self-maintaining, meaning that it basically takes care of its own memory
management. When the top box is no longer used, it's thrown out. The Heap, on the
other hand, must worry about Garbage collection (GC), which deals with how to keep the
Heap clean (no one wants dirty laundry laying around, it stinks!).
bool
byte
char
decimal
double
enum
float
int
long
sbyte
short
struct
uint
ulong
ushort
Reference Types:
All the "things" declared with the types in this list are Reference types (and inherit from
System.Object, except, of course, for object which is the System.Object object):
class
interface
delegate
object
string
Pointers:
The third type of "thing" to be put in our memory management scheme is a Reference to
a Type. A Reference is often referred to as a Pointer. We don't explicitly use Pointers,
they are managed by the Common Language Runtime (CLR). A Pointer (or Reference) is
different than a Reference Type in that when we say something is a Reference Type, it
means we access it through a Pointer. A Pointer is a chunk of space in memory that
points to another space in memory. A Pointer takes up space just like any other thing
that we're putting in the Stack and Heap and its value is either a memory address or
null.
Instructions:
You'll see how the "Instructions" work later in this article...
2. Value Types and Pointers always go where they were declared. This is a little
more complex and needs a bit more understanding of how the Stack works to
figure out where "things" are declared.
The Stack, as we mentioned earlier, is responsible for keeping track of where each
thread is during the execution of our code (or what's been called). You can think of it as
a thread "state" and each thread has its own Stack. When our code makes a call to
execute a method the thread starts executing the instructions that have been JIT
compiled and live on the method table, it also puts the method's parameters on the
thread Stack. Then, as we go through the code and run into variables within the method,
they are placed on top of the Stack. This will be easiest to understand with an example.
Take the following method:
NOTE : the method does not live on the stack and is illustrated just
for reference.
Next, control (the thread executing the method) is passed to the instructions to the
AddFive() method which lives in our type's method table, a JIT compilation is performed
if this is the first time we are hitting the method.
As the method executes, we need some memory for the "result" variable and it is
allocated on the Stack.
And all memory allocated on the Stack is cleaned up by moving a pointer to the available
memory address where AddFive() started and we go down to the previous method on
the stack (not seen here).
In this example, our "result" variable is placed on the stack. As a matter of fact, every
time a Value Type is declared within the body of a method, it will be placed on the stack.
Now, Value Types are also sometimes placed on the Heap. Remember the rule, Value
Types always go where they were declared? Well, if a Value Type is declared outside of a
method, but inside a Reference Type then it will be placed within the Reference Type on
the Heap.
Here's another example.
If we have the following MyInt class (which is a Reference Type because it is a class):
public class MyInt
{
After AddFive() is finished executing (like in the first example), and we are cleaning up...
we're left with an orphaned MyInt in the Heap (there is no longer anyone in the Stack
standing around pointing to MyInt)!
This is where the Garbage Collection (GC) comes into play. Once our program reaches a
certain memory threshold and we need more Heap space, our GC will kick off. The GC
will stop all running threads (a FULL STOP), find all objects in the Heap that are not
being accessed by the main program and delete them. The GC will then reorganize all
the objects left in the Heap to make space and adjust all the Pointers to these objects in
both the Stack and the Heap. As you can imagine, this can be quite expensive in terms
of performance, so now you can see why it can be important to pay attention to what's
in the Stack and Heap when trying to write high-performance code.
Ok, that's great, but how does it really affect me?
Good question.
When we are using Reference Types, we're dealing with Pointers to the type, not the
thing itself. When we're using Value Types, we're using the thing itself. Clear as mud,
right?
Again, this is best described by example.
If we execute the following method:
public int ReturnValue()
{
int x = new int();
x = 3;
int y = new int();
y = x;
y = 4;
return x;
}
We'll get the value 3. Simple enough, right?
However, if we are using the MyInt class from before:
4!
Why?... How does x.MyValue get to be 4? Take a look at what we're doing and see if it
makes sense:
In the first example everything goes as planned:
public int ReturnValue()
{
int x = 3;
int y = x;
y = 4;
return x;
}
In the next example, we don't get "3" because both variables "x" and "y" point to the
same object in the Heap.
Hopefully this gives you a better understanding of a basic difference between Value Type
and Reference Type variables in C# and a basic understanding of what a Pointer is and
when it is used. In the next part of this series, we'll get further into memory
management and specifically talk about method parameters.
What is logging?
Logging is the process of persisting information about the status of an application.
What is a Form?
A form is a representation of any window displayed in your application. Form can be used
to create standard, borderless, floating, modal windows.
A user interface container that enables a user to work with more than one document at a
time. E.g. Microsoft Excel.
What is BLOB ?
A BLOB (binary large object) is a large item such as an image or an exe represented in
binary form.
What is ClickOnce?
ClickOnce is a new deployment technology that allows you to create and publish selfupdating applications that can be installed and run with minimal user interaction.
A shared assembly is kept in the global assembly cache (GAC) and can be used by one
or more applications on a machine.
What is Boxing/Unboxing?
Boxing is used to convert value types to object.
E.g. int x = 1;
object obj = x ;
Unboxing is used to convert the object back to the value type.
E.g. int y = (int)obj;
Boxing/unboxing is quiet an expensive operation.
What is globalization?
Globalization is the process of customizing applications that support multiple cultures
and regions.
What is localization?
Localization is the process of customizing applications that support a given culture and
regions.
What is MIME?
Multipurpose Internet Mail.
MIME extends the Simple Mail Transfer Protocol (SMTP) format of mail messages to
include multiple content, both textual and non-textual. Parts of the message may be
images, audio, or text in different character sets.
OOP
*(B) What is a Interface ?
Interface is a contract that defines the signature of the functionality. So if a
class is implementing a interface it says to the outer world, that it provides
specific behavior. Example if a class is implementing Idisposable interface
that means it has a functionality to release unmanaged resources. Now
external objects using this class know that it has contract by which it can
dispose unused unmanaged objects.
Single Class can implement multiple interfaces.
If a class implements a interface then it has to provide implementation to
all its methods.
An interface is a contract: the guy writing the interface says, "hey, I accept things
looking that way", and the guy using the interface says "OK, the class I write looks
that way".
An interface is an empty shell, there are only the signatures (name / params /
return type) of the methods. The methods do not contain anything. The interface
can't do anything. It's just a pattern.
Implementing an interface consumes very little CPU, because it's not a class, just a
bunch of names, and therefore there is no expensive look-up to do. It's great when it
matters such as in embedded devices.
Abstract classes
Abstract classes, unlike interfaces, are classes. They are more expensive to use
because there is a look-up to do when you inherit from them.
Abstract classes look a lot like interfaces, but they have something more : you can
define a behavior for them. It's more about a guy saying, "these classes should look
like that, and they have that in common, so fill in the blanks!".
Implementation
While abstract classes and interfaces are supposed to be different concepts, the
implementations make that statement sometimes untrue. Sometimes, they are not
even what you think they are.
In Java, this rule is strongly enforced, while in PHP, interfaces are abstract classes
with no method declared.
In Python, abstract classes are more a programming trick you can get from the ABC
module and is actually using metaclasses, and therefore classes. And interfaces are
more related to duck typing in this language and it's a mix between conventions and
special methods that call descriptors (the __method__ methods).
As usual with programming, there is theory, practice, and practice in another
language :-)
of these three colors we can achieve any color in world.Its a model of real
world or concept.
Encapsulation It is a process of hiding all the internal details of an object
from the outside world.
Communication using messages When application wants to achieve
certain task it can only be done using combination of objects. A single object
can not do all the task. Example if we want to make order processing form.We
will use Customer object, Order object, Product object and Payment object to
achieve this functionality. In short these objects should communicate with
each other. This is achieved when objects send messages to each other.
Object lifetime All objects have life time.Objects are created ,and initialized,
necessary functionalities are done and later the object is destroyed. Every
object have there own state and identity which differ from instance to
instance.
Class hierarchies (Inheritance and aggregation) Twist :- What is
difference between Association, Aggregation and Inheritance relationships? In
object oriented world objects have relation and hierarchies in between them.
There are basically three kind of relationship in Object Oriented world :
Association This is the simplest relationship between objects. Example
every customer has sales. So Customer object and sales object have an
association relation between them.
Aggregation This is also called as composition model. Example in order to
make a Accounts class it has use other objects example Voucher,
Journal and Cash objects. So accounts class is aggregation of these three
objects.202
Inheritance Hierarchy is used to define more specialized classes based on a
preexisting generalized class. Example we have VEHICLE class and we can
inherit this class make more specialized class like CAR, which will add new
attributes and use some existing qualities of the parent class. Its shows more
of a parent-child relationship. This kind of hierarchy is called inheritance.
Polymorphism When inheritance is used to extend a generalized class to a
more specialized class, it includes behavior of the top class(Generalized
class). The inheriting class often implement a behavior that can be somewhat
different than the generalized class, but the name of the behavior can be
same. It is important that a given instance of an object use the correct
behavior, and the property of polymorphism allows this to happen
automatically.
Following are features of a abstract class : You can not create a object of abstract class204
Abstract class is designed to act as a base class (to be inherited by other
classes). Abstract class is a design concept in program development and
provides a base upon which other classes are built.
Abstract classes are similar to interfaces. After declaring an abstract class,
it cannot be instantiated on its own, it must be inherited.
In VB.NET abstract classes are created using MustInherit keyword.In C#
we have Abstract keyword.
Abstract classes can have implementation or pure abstract methods which
should be implemented in the child class.
Yes, the variables are inherited but can not be accessed directly by the class
interface.
(B) What are the different accessibility levels defined in .NET ?
Following are the five levels of access modifiers : Private : Only members of class have access.
Protected :-All members in current class and in derived classes can access
the variables. Friend (internal in C#) :- Only members in current project
have access to the elements. Protected friend (protected internal in C#) :All members in current project and all members in derived class can access
the variables.
Public :- All members have access in all classes and projects.
(B) What is the difference between 'protected' and 'protected internal'?
protected:
The type or member can only be accessed by code in the same class or struct, or in a derived
class.
internal:
The type or member can be accessed by any code in the same assembly, but not from another
assembly.
protected internal:
The type or member can be accessed by any code in the assembly in which it is declared, or
from within a derived class in another assembly.
Do you know how to short-circuit operators? In C#, And (&) and Or (|) operators evaluate both
boolean expressions in the statement. However, the && operator only evaluates the first Boolean
if false and the || operator only evaluates the first Boolean if true. This technique prevents the
execution of the second expression if unnecessary therefore optimizing your logic.
int i = 5;
System.out.println(i);
The compiler may optimize this to just print 5, like this:
System.out.println(5);
However, if there is another thread which can change i, this is the wrong behaviour. If another
thread changes i to be 6, the optimized version will still print 5.
The volatile keyword prevents such optimization and caching, and thus is useful when a variable
can be changed by another thread.
The caller of a method which takes an out parameter is not required to assign to the variable
passed as the out parameter prior to the call; however, the callee is required to assign to the out
parameter before returning.
In contrast ref parameters are considered initially assigned by the callee. As such, the callee is
not required to assign to the ref parameter before use. Ref parameters are passed both into and
out of a method.
So, out means out, while ref is for in and out.
These correspond closely to the [out] and [in,out] parameters of COM interfaces, the
advantages of out parameters being that callers need not pass a pre-allocated object in cases
where it is not needed by the method being called - this avoids both the cost of allocation, and
any cost that might be associated with marshaling (more likely with COM, but not uncommon
in .NET).
.NET provides Finalize method in which we can clean up our resources. But
relying on this is not always good so the best is to implement Idisposable
interface and implement the Dispose method where you can put your clean
up routines.
(B) What is the difference between using IDisposable vs a destructor (Finalize) in
C#?
Finalizers are run by the Garbage Collection before an object that is eligible for collection is
reclaimed. Dispose() is meant for cleaning up unmanaged resources, like network connections,
files, handles to OS stuff, &c. It works best in conjunction with the using block where the
compiler makes sure that Dispose() will be called immediately once you are done with an object
and also ensures that you cannot work with the object anymore once it's disposed.
Note that finalizers don't have to run, so relying on that can be dangerous:
What this means for you: Your programs cannot rely on finalizers keeping things tidy. Finalizers
are a safety net, not a primary means for resource reclamation. When you are finished with a
resource, you need to release it by calling Close or Disconnect or whatever cleanup method is
available on the object. (The IDisposable interface codifies this convention.)
Careful also with the precise time when an object becomes eligible for collection. Read the article
linked above it's neither scope (a weird word which has noting to do with the lifetime of an
object it's the region of program text in which it is legal to refer to [a named entity] by its
unqualified name.) nor is it strictly reference counting as an object can become eligible for
collection even before the last reference to it goes away.
.NET Garbage collector does almost all clean up activity for your objects. But
unmanaged resources (ex: - Windows API created objects, File, Database
connection objects, COM objects etc) is outside the scope of .NET framework
we have to explicitly clean our resources. For these types of objects .NET
framework provides Object. Finalize method 218 which can be overridden and
clean up code for unmanaged resources can be put in this section.
(B) What is the use of DISPOSE method?
Polymorphism means many forms (ability to take more than one form). In Polymorphism
poly means multiple and morph means forms so polymorphism means many forms.
In polymorphism we will declare methods with same name and different parameters in
same class or methods with same name and same parameters in different classes.
Polymorphism has ability to provide different implementation of methods that are
implemented with same name.
Overloading
Overloading means we will declare methods with same name but different signatures
because of this we will perform different tasks with same method name. This overloading
also called as compile time polymorphism or early binding.
Method Overloading or compile time polymorphism means same method names with
different signatures (different parameters)
Overriding
In this method overriding or run time polymorphism we can override a method in base
class by creating similar function in derived class this can be achieved by using
inheritance principle and using virtual &override keywords.
Explain what the StringBuilder class is and why you'd want to use it?
string a,b,c,d;
a = b + c + d;
then it would be faster using strings and the plus operator. This is because (like Java, as Eric
points out), it internally uses StringBuilder automatically (Actually, it uses a primitive that
StringBuilder also uses)
However, if what you are doing is closer to:
string a,b,c,d;
a = a + b;
a = a + c;
a = a + d;
Then you need to explicitly use a StringBuilder. .Net doesn't automatically create a StringBuilder
here, because it would be pointless. At the end of each line, "a" has to be an (immutable) string,
so it would have to create and dispose a StringBuilder on each line. For speed, you'd need to
use the same StringBuilder until you're done building:
string a,b,c,d;
StringBuilder e = new StringBuilder();
e.Append(b);
e.Append(c);
e.Append(d);
a = e.ToString();
Generally, readonly means only that you can't re-assign a field outside the
constructor. The field itself can be modified as long as it stays the same instance.
So yes, you can add elements to the collection stored in readonly field.
Marking a field as read-only only means that you cannot change the value of that field. It has no
bearing on the internal state of the object there. In your examples, while you would not be able to
assign a new metadata object to the _metadata field, nor a new ICollection to the _items field
(outside of a constructor that is), you can change the internal values of the existing objects stored
in those fields.
There is nothing preventing you from mutating an object stored in a readonly field. So you CAN
call _items.Add() and metadata._Change() outside the constructor/initializer. readonly only
prevents you from assigning new values to those fields after construction.
You need to specify the size of an array at the time of its declaration. It cannot be resized
dynamically.
2.
Collection:
1.
The size of a collection can be adjusted dynamically, as per the user's requirement. It does
not have fixed size.
2.
When two elements in a program have same name, one of them can hide and
shadow the other one. So in such cases the element which shadowed the
main element is referenced. Below is a sample code, there are two classes
ClsParent and ClsShadowedParent. In ClsParent there is a variable x
which is a integer. ClsShadowedParent overrides ClsParent and shadows
the x variable to a string.
(I) What is the difference between delegate and events?
Actually events use delegates in bottom. But they add an extra layer on the
delegates, thus forming the publisher and subscriber model.
As delegates are function to pointers they can move across any clients. So
any of the clients can add or remove events, which can be pretty confusing.
But events give the extra protection by adding the layer and making it a
publisher and subscriber model.
Twist :- Whats difference between HashTable and ArrayList ? You can access
array using INDEX value of array, but how many times you know the real
value of index. Hashtable provides way of accessing the index using a user
identified KEY value, thus removing the INDEX problem.
They look very much same but are not same. Class is a definition, while
object is a instance of the class created. Class is a blue print while objects are
actual objects existing in real world. Example we have class CAR which has
attributes and methods like Speed, Brakes, Type of Car etc. Class CAR is just
a prototype, now we can create real time objects which can be used to
provide functionality. Example we can create a Maruti car object with 100 km
speed and urgent brakes.
(A) Can events have access modifiers ?
Events are always public as they are meant to serve every one register ing
to it. But you can access modifiers in events.You can have events with
protected keyword which will be accessible only to inherited classes.You can
have private events only for object in that class.
(A) Can we have shared events ?
Yes, you can have shared events note only shared methods can raise shared
events.
Array is whose size can increase and decrease dynamically. Array list can hold
item of different types. As Array list can increase and decrease size
dynamically you do not have to use the REDIM keyword. You can access any
item in array using the INDEX value of the array position.
(A) What is Indexer ?
FRAMEWORK
*(B) What is a IL?
Twist :- What are situations when you register .NET assembly in GAC ? GAC
(Global Assembly Cache) is used where shared .NET assembly reside. GAC is
used in the following situations : If the application has to be shared among several application.
If the assembly has some special security requirements like only administrators
can remove the assembly. If the assembly is private then a simple delete of
assembly the assembly file will remove the assembly. Note :- Registering .NET
assembly in GAC can lead to the old problem of DLL hell, where COM version
was stored in central registry. So GAC should be used when absolutely
necessary.
Using Microsoft Installer Package. You can get download of installer from
http://www.microsoft.com.
Using Gacutil. Goto Visual Studio Command Prompt and type gacutil i
(assembly_name), where (assembly_name) is the DLL name of the project.
can be ported to .NET. So lets play some old music... By the way my
favourite music is Kishore, whats yours???
(B) What are the main components of .NET Framework?
.NET Framework provides enormous advantages to software developers in comparison to the
advantages provided by other platforms. Microsoft has united various modern as well as existing
technologies of software development in .NET Framework. These technologies are used by
developers to develop highly efficient applications for modern as well as future business needs.
The following are the key components of .NET Framework:
Application Domains
Runtime Host
Cross-Language Interoperability
Profiling
Side-by-Side Execution
Networking Improvements
Improvements in WPF 4
After generation of the file you can view the SNK file in a simple notepad.
After the SNK file is generated its time to sign the project with this SNK file.
Click on project -- properties and the browse the SNK file to the respective
folder and compile the project.
(I) Can we force garbage collector to run ?
System.GC.Collect() forces garbage collector to run. This is not recommended
but can be used if situations arises.
(I) What is the difference between System exceptions and Application
exceptions?
All exception derives from Exception Base class. Exceptions can be generated
programmatically or can be generated by system. Application Exception serves
as the base class for all application-specific exception classes. It derives from
Exception but does not provide any extended functionality. You should derive
your custom application exceptions from Application Exception. Application
exception is used when we want to define user defined exception, while system
exception is all which is defined by .NET.
(I) What is CODE Access security?
CAS is part of .NET security model that determines whether or not a piece of
code is allowed to run and what resources it can use while running. Example CAS
will allow an application to read but not to write and delete a file or a resource
from a folder..
(I) What is the difference between Convert.toString and .toString() method ?
Just to give an understanding of what the above question means seethe below
code. int i =0; MessageBox.Show(i.ToString());
MessageBox.Show(Convert.ToString(i)); We can convert the integer i using
i.ToString() or Convert.ToString so whats the difference. The basic difference
between them is Convert function handles NULLS while i.ToString() does not
it will throw a NULL reference exception error. So as good coding practice using
convert is always safe.
(I) What is COM ?
Microsofts COM is a technology for component software development. It is a
binary standard which is language independent. DCOM is a distributed extension
of COM.
There are two types of assembly Private and Public assembly. A private assembly
is normally used by a single application, and is stored in the application's
directory, or a sub-directory beneath. A shared assembly is normally stored in
the global assembly cache, which is a repository of assemblies maintained by the
.NET runtime. Shared assemblies are usually libraries of code which many
applications will find useful, e.g. Crystal report classes which will be used by all
application for Reports.
(A) What is Manifest?
Assembly metadata is stored in Manifest. Manifest contains all the metadata
needed to do the following things (See Figure Manifest View for more details):
Version of assembly
Security identity
Scope of the assembly Resolve references to resources and classes.
The assembly manifest can be stored in either a PE file (an .exe or .dll) with
Microsoft intermediate language (MSIL) code or in a stand-alone PE file that
contains only assembly manifest information
ASP.NET
(B) Please briefly explain ASP.NET Page life Cycle?
ASP.NET page passes through a series of steps during its life cycle. Following is the
high-level explanation of life cycle stages/steps.
Initialization: Controls raise their Init event in this stage.Objects and variables are
initializes for complete lifecyle of request.
LoadViewState: is a post back stage and loads the view state for the controls that
enabled its view state property.
LoadPostBackData: is also a post back stage and loads the data posted for the
controls and update them.
Load: In this stage page as well as all the controls raise their Load event. Till this
stage all the controls are initialized and loaded. In most of the cases, we are coding
this event handler.
RaisePostBackEvent: is again a postback stage. For example, it's raise against a
button click event. We can easily put our code here to perform certain actions.
SaveViewState: Finally, controls state is saved in this stage before Rendering
HTML.
Render: This is the stage where HTML is generated for the page.
Dispose: Lastly, all objects associated with the request are cleaned up.
Page_Init.
Page_Load.
Control events
Page_Unload event.
Page_init event only occurs when first time the page is started, but
Page_Load occurs in subsequent request of the page.
(B) What is the difference between custom controls and user controls?
Custom controls are basically compiled code i.e. DLLs. These can be easily added to
toolbox, so it can be easily used across multiple projects using drag and drop
approach. These controls are comparatively hard to create.
But User Controls (.ascx) are just like pages (.aspx). These are comparatively easy to
create but tightly couple with respect to User Interface and code. In order to use
across multiple projects, we need to copy and paste to the other project as well.
Page_load event guarantees that all controls are fully loaded. Controls are
also accessed in Page_Init events but you will see that viewstate is not fully
loaded during this event.
(B) What is the concept of Postback in ASP.NET?
A postback is a request sent from a client to server from the same page user is
already working with.
ASP.NET was introduced with a mechanism to post an HTTP POST request back to the
same page. It's basically posting a complete page back to server (i.e. sending all of
its data) on same page. So, the whole page is refreshed.
Another concept related to this approach is "Callback" that is also asked sometimes
during a technical interview question. Click here to understand Postback Vs Callback
in ASP.NET.
(B) How can we identify that the Page is PostBack ?
Page object has a IsPostBack property which can be checked to know that
is the page posted back.
(B) How do we assign page specific attributes ?
@Register directive informs the compiler of any custom server control added
to the page.
(B) Whats the use of SmartNavigation property ?
Following are the points to be done in order to enable paging in Datagrid : Set the AllowPaging to true.
In PageIndexChanged event set the current pageindex clicked.
(B) Whats the use of GLOBAL.ASAX file ?
Global.asax is basically ASP.NET Application file. Its a place to write code for
Application-level events such as Application start, Application end, Session start and
end, Application error etc. raised by ASP.NET or by HTTP Modules.
There is a good list of events that are fired but following are few of the important
events in Global.asax:
time.
application.
Session_End fires when user session ends.
Application_End fires when application ends or time out.
(B) What is a SESSION and APPLICATION object ?
Session object store information between HTTP requests for a particular user,
while application object are global across users.
(B) Can you explain in brief how the ASP.NET authentication process works?
ASP.NET does not run by itself, it runs inside the process of IIS. So there are
two authentication layers which exist in ASP.NET system. First authentication
happens at the IIS level and then at the ASP.NET level depending on the
WEB.CONFIG file. Below is how the whole process works:- IIS first checks to
make sure the incoming request comes from an IP address that is allowed
access to the domain. If not it denies the request. Next IIS performs its own
user authentication if it is configured to do so. By default IIS allows
anonymous access, so requests are automatically authenticated, but you can
change this default on a per application basis with in IIS. If the request is
passed to ASP.net with an authenticated user, ASP.net checks to see whether
impersonation is enabled. If impersonation is enabled, ASP.net acts as though
it were the authenticated user. If not ASP.net acts with its own configured
account. Finally the identity from step 3 is used to request resources from
the operating system. If ASP.net authentication can obtain all the necessary
resources it grants the users request otherwise it is denied. Resources can
include much228 more than just the ASP.net page itself you can also use
.Nets code access security features to extend this authorization step to disk
files, Registry keys and other resources.
(B) Whats difference between Datagrid, Datalist and repeater ?
A Datagrid, Datalist and Repeater are all ASP.NET data Web controls. They
have many things in common like DataSource Property, DataBind Method
ItemDataBound and ItemCreated. When you assign the DataSource Property
of a Datagrid to a DataSet then each DataRow present in the DataRow
Collection of DataTable is assigned to a corresponding DataGridItem and this
is same for the rest of the two controls also. But The HTML code generated
for a Datagrid has an HTML TABLE <ROW> element created for the particular
DataRow and its a Table form representation with Columns and Rows. For a
Datalist its an Array of Rows and based on the Template Selected and the
RepeatColumn Property value We can specify how many DataSource records
should appear per HTML <table> row. In short in datagrid we have one record
per row, but in datalist we can have five or six rows per row. For a Repeater
Control, the Datarecords to be displayed depends upon the Templates
specified and the only HTML generated is the due to the Templates. In
addition to these, Datagrid has a in-built support for Sort, Filter and paging
the Data, which is not possible when using a DataList and for a Repeater
Control we would require to write an explicit code to do paging.
(B) How to disable client side script in validators?
Session.abandon
(B) What is the main difference between Gridlayout and FlowLayout ?
(B) What are resource files and how do we generate resource files?
Resource files are files which contain program resources. Many programmers
think resource files for only storing strings. But you can also store bitmaps,
icons, fonts, wav files in to resource files.
(B) Difference between .dll and .exe?
EXE:
1.
2.
3.
4.
DLL:
1.
2.
3.
n C#, there are two different kinds of equality: reference equality (also known as identity)
and value equality. Value equality is the generally understood meaning of equality: it
means that two objects contain the same values. For example, two integers with the
value of 2 have value equality. Reference equality means that there are not two objects
to compare. Instead, there are two object references and both of them refer to the same
object. This can occur through simple assignment, as shown in the following example:
C#
object a = new object();
object b = a;
bool areEqual = System.Object.ReferenceEquals(a, b); //returns true
System.Console.WriteLine("a and b {0} reference equality", areEqual ?
"have" : "do not have");
object c = b;
areEqual = System.Object.ReferenceEquals(a, c); //if a == b and b == c,
then a == c
System.Console.WriteLine("a and c {0} reference equality", areEqual ?
"have" : "do not have");
// Keep the console open in debug mode.
Console.WriteLine("Press any key to exit.");
Console.ReadKey();
In this code, only one object exists, but there are multiple references to that
object: a and b. Because they both refer to the same object, they have reference
equality. If two objects have reference equality, they also have value equality, but value
equality does not guarantee reference equality.
To check for reference equality, use ReferenceEquals. To check for value equality, you
should generally use Equals. However, Equals as it is implemented byObject just
performs a reference identity check. It is therefore important, when you call Equals, to
verify whether the type overrides it to provide value equality semantics. When you create
your own types, you should override Equals.
Because Equals is a virtual method, any class can override its implementation. Any class
that represents a value, essentially any value type, or a set of values as a group, such as
a complex number class, should override Equals. If the type implements IComparable, it
should override Equals.
The new implementation of Equals should follow all the guarantees of Equals:
if (x. Equals (y) && y. Equals (z)) returns true, then x. Equals (z) returns true.
Successive invocations of x. Equals (y) return the same value as long as the
objects referenced by x and y are not modified.
x. Equals (null) returns false (for non-nullable value types only. For more
information, see Nullable Types (C# Programming Guide).)
The new implementation of Equals should not throw exceptions. It is recommended that
any class that overrides Equals also override Object.GetHashCode. It is also
recommended that in addition to implementing Equals (object), any class also
implement Equals (type) for their own type, to enhance performance. For example:
//constructor
Any derived class that can call Equals on the base class should do so before finishing its
comparison. In the following example, Equals calls the base class Equals, which checks
for a null parameter and compares the type of the parameter with the type of the derived
class. That leaves the implementation of Equals on the derived class the task of
checking the new data field declared on the derived class:
class ThreeDPoint : TwoDPoint
{
public readonly int z;
public ThreeDPoint(int x, int y, int z)
: base(x, y)
{
this.z = z;
}
public override bool Equals(System.Object obj)
{
// If parameter cannot be cast to ThreeDPoint return false:
ThreeDPoint p = obj as ThreeDPoint;
if ((object)p == null)
{
return false;
}
// Return true if the fields match:
return base.Equals(obj) && z == p.z;
}
public bool Equals(ThreeDPoint p)
{
// Return true if the fields match:
return base.Equals((TwoDPoint)p) && z == p.z;
}
public override int GetHashCode()
{
return base.GetHashCode() ^ z;
}
}
By default, the operator == tests for reference equality by determining whether two
references indicate the same object. Therefore, reference types do not have to
implement operator == in order to gain this functionality. When a type is immutable, that
is, the data that is contained in the instance cannot be changed, overloading
operator == to compare value equality instead of reference equality can be useful
because, as immutable objects, they can be considered the same as long as they have
the same value. It is not a good idea to override operator == in non-immutable types.
Overloaded operator == implementations should not throw exceptions. Any type that
overloads operator == should also overload operator !=. For example:
//add this code to class ThreeDPoint as defined previously
//
public static bool operator ==(ThreeDPoint a, ThreeDPoint b)
{
// If both are null, or both are same instance, return true.
if (System.Object.ReferenceEquals(a, b))
{
return true;
}
// If one is null, but not both, return false.
if (((object)a == null) || ((object)b == null))
{
return false;
}
// Return true if the fields match:
return a.x == b.x && a.y == b.y && a.z == b.z;
}
public static bool operator !=(ThreeDPoint a, ThreeDPoint b)
{
return !(a == b);
}
A common error in overloads of operator == is to use (a == b), (a == null), or (b ==
null) to check for reference equality. This instead creates a call to the overloaded
operator ==, causing an infinite loop. Use ReferenceEquals or cast the type to Object, to
avoid the loop.
You can create your own custom HTTP handlers that render custom output to the browser.
Typical scenarios for HTTP Handlers in ASP.NET are for example
RSS feeds To create an RSS feed for a Web site, you can create a handler that
emits RSS-formatted XML. You can then bind a file name extension such as .rss to
the custom handler. When users send a request to your site that ends in .rss,
ASP.NET calls your handler to process the request.
Image server If you want a Web application to serve images in a variety of sizes,
you can write a custom handler to resize images and then send them to the user as
the handler's response.
Typical uses for HTTP modules include the following:
Security Because you can examine incoming requests, an HTTP module can
perform custom authentication or other security checks before the requested page,
XML Web service, or handler is called. In Internet Information Services (IIS) 7.0
running in Integrated mode, you can extend forms authentication to all content
types in an application.
Statistics and logging Because HTTP modules are called on every request, you
can gather request statistics and log information in a centralized module, instead of
in individual pages.
Custom headers or footers Because you can modify the outgoing response, you
can insert content such as custom header information into every page or XML Web
service response.
Tuple<String,int>t=newTuple<String,int>("Hellow",2);
Using the Create factory method available in the Tuple class. For example,
Tuple<int,int,int>t=Tuple.Create<int,int,int>(2,4,5);
Create a custom control if you want to make a component where you have full control
over its visual appearance, and you don't want any baggage of unnecessary functionality.
Typical cases would be simple controls with limited functionality (such as a button)
Create a user control if you are going to combine existing controls into reusable
building blocks (such as two lists with buttons where you can move items between the lists).
(B) Which is the root namespace for fundamental types in .NET Framework?
System.Object is the root namespace for fundamental types in .NET Framework.
Important difference
Let me add that the call to GetType gets resolved at runtime, while typeof is resolved at
compile time.
copying the contents of a value type variable into another variable, copies the entire
contents into the new variable, making the two distinct. In other words, after the copy,
changes to one won't affect the other
copying the contents of a reference type variable into another variable, copies the
reference, which means you now have two references to the same somewhere else storage
of the actual data. In other words, after the copy, changing the data in one reference will
appear to affect the other as well, but only because you're really just looking at the same
data both places
When you declare variables or fields, here's how the two types differ:
variable: value type lives on the stack, reference type lives on the stack as a pointer to
somewhere in heap memory where the actual memory lives
class/struct-field: value type lives inside the class, reference type lives inside the class as
a pointer to somewhere in heap memory where the actual memory lives.
A destructor is used to free the dynamic allocated memory and release the resources. You can,
however, implement a custom method that allows you to control object destruction by calling the
destructor.
The main features of a destructor are as follows:
(I) Is there a difference between just saying throw; and throw ex; assuming ex is
the exception you're catching?
throw ex; will erase your stacktrace. Don't do this unless you mean to clear the
stacktrace. Just use throw;
In old ASP if you where said to create a login page and do authentication you
have to do hell lot of custom coding. But now in ASP.NET thats made easy by
introducing Forms authentication. So lets see in detail what form
authentication is. Forms authentication uses a ticket cookie to see that user is
authenticated or not. That means when user is authenticated first time a
cookie is set to tell that this user is authenticated. If the cookies expire then
Forms authentication mechanism sends the user to the login page.
(I) How do we get the current culture of the environment in windows and
ASP.NET?
thing in mind CurrentCulture will only give you the culture on which your
application is running. So if its a windows application this will work fine. But
in ASP.NET 2.0 we need to know what culture the end user has.
(A) How can you turn-on and turn-off CAS?
YOU can use the Code Access Security Tool (Caspol.exe) to turn security on and off.
To turn off security, type the following command at the command prompt:
caspol -security on
In the .NET Framework 4.0, for using Caspol.exe, you first need to set
the <LegacyCasPolicy> element to true.
This can be a tricky question. These two concepts seem altogether similar but
there is wide range of difference. Authentication is verifying the identity of a
user and authorization is process where we check does this identity have
access rights to the system. In short we227 can say the following
authentication is the process of obtaining some sort of credentials from the
users and using those credentials to verify the users identity. Authorization is
the process of allowing an authenticated user access to resources.
Authentication always proceed to Authorization; even if your application lets
anonymous users connect and use the application, it still authenticates them
as being anonymous.
(A) What are the various ways of authentication techniques in ASP.NET?
takes on the identity IIS passes to it. If you are allowing anonymous access in
IIS, this means ASP.NET will impersonate the IUSR_ComputerName account
that IIS itself uses. If you arent allowing anonymous access,ASP.NET will take
on the credentials of the authenticated user and make requests for resources
as if it were that user. Thus by turning impersonation on and using a nonanonymous method of authentication in IIS, you can let users log on and use
their identities within your ASP.NET application. Finally, you can specify a
particular identity to use for all authenticated requests 231 <identity
impersonate=true username=DOMAIN\username password=password/
>With this setting, all the requests are made as the specified user (Assuming
the password it correct in the configuration file). So, for example you could
designate a user for a single application, and use that users identity every
time someone authenticates to the application. The drawback to this
technique is that you must embed the users password in the web.config file
in plain text. Although ASP.NET wont allow anyone to download this file, this
is still a security risk if anyone can get the file by other means.
(A) What is event bubbling ?
Server controls like Datagrid, DataList, Repeater can have other child controls
inside them. Example DataGrid can have combo box inside datagrid. These
child control do not raise there events by themselves, rather they pass the
event to the container parent (which can be a datagrid, datalist, repeater),
which passed to the page as ItemCommand event. As the child control
send there events to parent this is termed as event bubbling.
(A) Administrator wants to make a security check that no one has tampered with
ViewState, how can he ensure this ?
FormsAuthentication.Signout()
(A) If cookies are not enabled at browser end does form Authentication work?
ADO.NET
*(B) What is the difference between DataSet and DataReader ?
Twist :- Why is DataSet slower than DataReader ? Fourth point is the answer
to the twist. Note:- This is my best question and I expect everyone to answer
it. It is asked almost 99% in all companies....Basic very Basic cram it.
Following are the major differences between DataSet and DataReader :-
DataSet is a disconnected architecture, while DataReader has live
connection while reading data. If we want to cache data and pass to a
different tier DataSet forms the best choice and it has decent XML support.
When application needs to access data from more than one table DataSet
forms the best choice. If we need to move back while reading records,
datareader does not support this functionality. But one of the biggest
drawbacks of DataSet is speed. As DataSet carry considerable overhead
because of relations, multiple tables etc speed is slower than DataReader.
Always try to use DataReader wherever possible, as its meant specially for
speed performance.
*(B) Whats difference between Optimistic and Pessimistic locking ?
In pessimistic locking when user wants to update data it locks the record and
till then no one can update data. Other users can only view the data when
there is pessimistic locking. In optimistic locking multiple users can open the
same record for updating, thus increase maximum concurrency. Record is
only locked when updating the record. This is the most 299 preferred way of
locking practically. Now a days browser based application is very common
and having pessimistic locking is not a practical solution.
*(I) What are major difference between classic ADO and ADO.NET ?
Clone: - It only copies structure, does not copy data. Copy: - Copies both
structure and data.
*(A) How can we perform transactions in .NET?
Following are the namespaces provided by .NET for data management :System.data This contains the basic objects used for accessing and storing
relational data, such as DataSet,DataTable, and DataRelation. Each of these is
independent of the type of data source and the way we connect to it.
System.Data.OleDB It contains the objects that we use to connect to a data
source via an OLE-DB provider, such as OleDbConnection, OleDbCommand,
etc. These objects inherit from the common base classes, and so have the
same properties, methods, and events as the SqlClient equivalents.
System.Data.SqlClient: This contains the objects that we use to connect to
a data source via the Tabular Data Stream (TDS) interface of Microsoft SQL
Server (only). This can generally provide better performance as it removes
some of the intermediate layers required by an OLE-DB connection.
System.XML This Contains the basic objects required to create, read, store,
write, and manipulate XML documents according to W3C recommendations.
(B) Can you give a overview of ADO.NET architecture ?
Dataset object represents disconnected and cached data. If you see the
diagram it is not in direct connection with the data store (SQL SERVER,
ORACLE etc) rather it talks with Data adapter, who is responsible for filling
the dataset. Dataset can have one or more Datatable and relations.
Following are some major differences between dataset and datareader : DataReader provides forward-only and read-only access to data, while the
DataSet object can hold more than one table (in other words more than one
rowset) from the same data source as well as the relationships between
them.
Dataset is a disconnected architecture while datareader is connected
architecture. Dataset can persist contents while datareader can not persist
contents, they are forward only.
(B) What is the use of connection object ?
only single value (effectively the first column of the first row of the resulting
rowset) any other returned columns and rows are discarded. It is fast and
efficient when only a "singleton" value is required
(B) What is the use of dataadapter ?
These are objects that connect one or more Command objects to a Dataset
object. They provide logic that would get data from the data store and
populates the tables in the DataSet, or pushes the changes in the DataSet
back into the data store.
An OleDbDataAdapter object is used with an OLE-DB provider
A SqlDataAdapter object uses Tabular Data Services with MS SQL Server.
(B) What are basic methods of Dataadapter ?
There are three most commonly used methods of Dataadapter :- Fill :Executes the SelectCommand to fill the DataSet object with data from the
data source. It an also be used to update (refresh) an existing table in a
DataSet with changes285 made to the data in the original datasource if there
is a primary key in the table in the DataSet. FillSchema :- Uses the
SelectCommand to extract just the schema for a table from the data source,
and creates an empty table in the DataSet object with all the corresponding
constraints. Update:- Calls the respective InsertCommand, UpdateCommand,
or DeleteCommand for each inserted, updated,or deleted row in the DataSet
so as to update the original data source with the changes made to the
content of the DataSet. This is a little like the UpdateBatch method provided
by the ADO Recordset object, but in the DataSet it can be used to update
more than one table.
(B) What is Dataset object?
The DataSet provides the basis for disconnected storage and manipulation of
relational data. We fill it from a data store,work with it while disconnected
from that data store, then reconnect and flush changes back to the data store
if required.
(B) What are the various objects in Dataset ?
Dataset has a collection of DataTable object within the Tables collection. Each
DataTable object contains a collection of DataRow objects and a collection of
DataColumn objects. There are also collections for the primary keys,
constraints, and default values used in this table which is called as constraint
collection, and the parent and child relationships between the tables. Finally,
there is a DefaultView object for each table. This is used to create a DataView
object based on the table, so that the data can be searched, filtered or
otherwise manipulated while displaying the data. Note :- Look back again to
the main diagram for ADO.NET architecture for visualizing this answer in
pictorial form.
pobjDataReader =
pobjCommand.ExecuteReader(CommandBehavior.SchemaOnly)
(B) How can we fine tune the command object when we are expecting a single
row or a single value ?
Twist :- How can we cancel all changes done in dataset ? How do we get
values which are changed in a dataset ? For tracking down changes Dataset
has two methods which comes as rescue GetChanges and HasChanges.
GetChanges Returns dataset which are changed since it was loaded or since
Acceptchanges was executed.
HasChanges This property indicates that has any changes been made since
the dataset was loaded or acceptchanges method was executed.
(A) Can you explain the difference between an ADO.NET Dataset and an ADO
Recordset?
There two main basic differences between recordset and dataset : With dataset you can retrieve data from two databases like oracle and sql
server and merge them in one dataset , with recordset this is not possible
All representation of Dataset is using XML while recordset uses COM.
Recordset can not be transmitted on HTTP while Dataset can be.
ENTITY FRAMEWORK
Below is the code for Entity Framework in which we are working on higher level
domain objects like customer rather than with base level ADO.NET components (like
dataset, datareader, command, connection objects, etc.).
Collapse | Copy Code
EDMX (Entity Data Model XML) is an XML file which contains all the mapping details
of how your objects map with SQL tables. The EDMX file is further divided into three
sections: CSDL, SSDL, and MSL.
Hello
World !
If you create a project using VS 2012, you will see the following hierarchy. At the top
we have the EDMX file, followed by the TT or T4 file, and then the .CS code file.
Create the object of your entity class, add it to the data context
using AddObject method, and then call theSaveChanges method.
Collapse | Copy Code
If you want to update, select the object, make changes to the object, and
call AcceptAllChanges.
Collapse | Copy Code
If you want to delete, call the DeleteObject method as shown in the below code
snippet:
Collapse | Copy Code
You can see the following YouTube video which shows a simple insert, update, and
delete example using Entity Framework:
relationships, you can have performance issues. So you need to be cautious if you
really need lazy loading behavior for all scenarios. For better performance, disable
lazy loading when you are loading a large number of records or use stored
procedures.
context.ContextOptions.LazyLoadingEnabled = false;
[EdmEntityTypeAttribute(NamespaceName="CustomermytestModel", Name="Customer")]
[Serializable()]
[DataContractAttribute(IsReference=true)]
public partial class Customer : EntityObject
{
#region Factory Method
/// <summary>
/// Create a new Customer object.
/// </summary>
/// <param name="id" />Initial value of the Id property.
/// <param name="customerCode" />Initial value of the CustomerCode property.
/// <param name="customername" />Initial value of the Customername property.
public static Customer CreateCustomer(global::System.Int32 id,
global::System.String customerCode, global::System.String customername)
{
Customer customer = new Customer();
customer.Id = id;
customer.CustomerCode = customerCode;
customer.Customername = customername;
return customer;
}
#endregion
#region Primitive Properties
Go to the designer and set the code generation strategy to NONE. This step
means that you would be generating the classes on your own rather than relying on
EF auto code generation.
Now that we have stopped the auto generation of code, we need to create the
domain classes manually. Add a class file and create the domain classes like
the Customer class we created.
Collapse | Copy Code
Write your Context layer code inheriting from ObjectContext. This code you
can copy paste from the behind code of EF, also before disabling auto-generation.
Collapse | Copy Code
And finally you can use the above code in your client as if you where using EF
normally.
Collapse | Copy Code
Entity
Context
Simple entity
framework
Needed
Auto
Auto
POCO approach
Needed
Manual
Auto
Code First
Not
Needed
Manual
Manual
We need to use the Refresh method of the Entity Framework context and provide
the RefreshMode enum values. Below is a simple code snippet which
executes ClientWins.
Collapse | Copy Code
Context.Refresh(System.Data.Objects.RefreshMode.ClientWins,Obj);
Scalar properties are those where actual values are contained in the entities. For
example, in the above customer entity, customername and customerid are scalar
properties. Normally a scalar property will map to a database field.
Navigation properties help to navigate from one entity to another entity. For
instance, consider the below example in which we have two entities: Customer and
Address, and a customer has multiple address objects.
Now we would like to have a facility where at any given moment we would like to
browse from a given customer object to the addresses collection and from the
address object to the customer.
If you open the Entity Designer, you would notice navigation properties as shown
below. The navigation properties are automatically created from the primary and
foreign key references.
So now because of those navigation properties, we can browse from the Customer to
the Addresses object, look at the below code:
Collapse | Copy Code
You can also do vice versa. In other words, from the Address object, you can
reference the Customer object, as shown in the below code.
Collapse | Copy Code
To create a complex type, select the fields which you want to group in a complex
type, click on Refactor, and create the complex type. Below is a figure which shows
this. Once the complex type is created, you can then reuse the complex type with
other entities as well.
LINQ to SQL is good for rapid development with SQL Server. EF is for
enterprise scenarios and works with SQL Server as well as other databases.
LINQ maps directly to tables. One LINQ entity class maps to one table. EF has
a conceptual model and that conceptual model maps to the storage model via
mappings. So one EF class can map to multiple tables, or one table can map to
multiple classes.
LINQ is more targeted towards rapid development while EF is for enterprise
level where the need is to develop a loosely coupled framework.
As a developer you can start with DbContext as its simple to use. When you feel
that some of the operations cannot be achieved by DbContext, you can then
access ObjectContext from DbContext, as shown in the below code:
Collapse | Copy Code
((IObjectContextAdapter)dbContext).ObjectContext
SQL SERVER
(B) What is normalization? What are different types of normalization?
A table may have more than one combination of columns that could uniquely
identify the rows in a table; each combination is a candidate key. During
database design you can pick up one of the candidate keys to be the primary
key. For example, in the supplier table supplierid and suppliername can be
candidate key but you will only pick up supplierid as the primary key.
(B) What are the different types of joins? What is the difference between them ?
INNER JOIN Inner join shows matches only when they exist in both
tables.Example, in the below SQL there are two tables Customers and Orders
and the inner join in made on Customers Customerid and Orders
Customerid.So this SQL will only give you result with customers who have
orders.If the customer does not have order it will not display that record.
SELECT Customers.*, Orders.* FROM Customers INNER JOIN Orders ON
Customers.CustomerID =Orders.CustomerID
LEFT OUTER JOIN Left join will display all records in left table of the SQL
statement.In SQL below customers with or without orders will be displayed.
Order data for customers without orders appears as NULL values. For
example, you want to determine the amount ordered by each customer and
you need to see who has not ordered anything as well. You can also see the
LEFT OUTER JOIN as a mirror image of the RIGHT OUTER JOIN (Is covered in
the next section) if you switch the side of each table. SELECT Customers.*,
Orders.* FROM Customers LEFT OUTER JOIN Orders ON
Customers.CustomerID =Orders.CustomerID307
RIGHT OUTER JOIN Right join will display all records in right table of the SQL
statement. In SQL below all orders with or without matching customer records
will be displayed. Customer data for orders without customers appears as
NULL values. For example, you want to determine if there are any orders in
the data with undefined CustomerID values (say, after a conversion or
something like it). You can also see the RIGHT OUTER JOIN as a mirror image
of the LEFT OUTER JOIN if you switch the side of each table. SELECT
Following are difference between them :- DELETE TABLE syntax logs the
deletes thus make the delete operation slow. TRUNCATE table does not log
any information but it logs information about deallocation of data page of the
table so TRUNCATE table is faster as compared to delete table. DELETE
table can have criteria while TRUNCATE can not. TRUNCATE table can not
trigger. Note :- Thanks to all the readers for pointing out my mistake for the
above question in my first edition. I had mentioned that TRUNCATE table can
not be rolled back while delete can be.
(B) What is the difference between a HAVING CLAUSE and a WHERE CLAUSE?
You can use Having Clause with the GROUP BY function in a query and
WHERE Clause is applied to each row before they are part of the GROUP BY
function in a query.
(B) What is the difference between UNION and UNION ALL SQL syntax ?
UNION SQL syntax is used to select information from two tables. But it selects
only distinct records from both the table, while UNION ALL selects all records
from both the tables. Note :- Selected records should have same datatype or
else the syntax will not work
(B) What is the difference between Stored Procedure (SP) and User Defined
Function (UDF)?
Following are some major differences between a stored procedure and user
defined functions:- UDF can be executed using the SELECT clause while
SPs can not be. UDF can not be used in XML FOR clause but SPs can be
used. UDF does not return output parameters while SPs return output
parameters. If there is an error in UDF its stops executing. But in SPs it just
ignores the error and moves to the next statement. UDF can not make
permanent changes to server environments while SPs can change some of
the server environment. Note :- SQL Server product is equivalently important
from interview point of view. Below are questions taken from my second book
SQL Server Interview questions. If you are interested in buying the book
mail bpb@bol.net.in / bpb@vsnl.com or call the nearest BPB book stall for my
book. For shop phone numbers you can either see the back or front page of
the book.
Following are tips which will increase your SQl performance :- Every index
increases the time takes to perform INSERTS, UPDATES and DELETES, so the
number of indexes should not be too much. Try to use maximum 4-5 indexes
on one table, not more. If you have read-only table, then the number of
indexes may be increased.308 Keep your indexes as narrow as possible.
This reduces the size of the index and reduces the number of reads required
to read the index. Try to create indexes on columns that have integer
values rather than character values. If you create a composite (multicolumn) index, the order of the columns in the key are very important. Try to
order the columns in the key as to enhance selectivity, with the most
selective columns to the leftmost of the key. If you want to join several
tables, try to create surrogate integer keys for this purpose and create
indexes on their columns. Create surrogate integer primary key (identity for
example) if your table will not have many insert operations. Clustered
indexes are more preferable than nonclustered, if you need to select by a
range of values or you need to sort results set with GROUP BY or ORDER BY.
If your application will be performing the same query over and over on the
same table, consider creating a covering index on the table. You can use
the SQL Server Profiler Create Trace Wizard with "Identify Scans of Large
Tables" trace to determine which tables in your database may need indexes.
This trace will show which tables are being scanned by queries instead of
using an index.
(I) What are indexes? What is the difference between clustered and nonclustered
indexes?
Indexes in SQL Server are similar to the indexes in books. They help SQL
Server retrieve the data quickly. There are clustered and nonclustered
indexes. A clustered index is a special type of index that reorders the way in
which records in the table are physically stored. Therefore table can have
only one clustered index. The leaf nodes of a clustered index contain the data
pages. A nonclustered index is a special type of index in which the logical
order of the index does not match the physical stored order of the rows on
disk. The leaf node of a nonclustered index does not consist of the data
pages. Instead, the leaf nodes contain index rows.
MVC
Difference between ASP.NET WebForms and ASP.NET MVC?
ASP.NET Web Forms uses Page controller pattern approach for rendering layout. In
this approach, every page has it's own controller i.e. code-behind file that processes
the request. On the other hand, ASP.NET MVC uses Front Controller approach. In this
approach a common controller for all pages, processes the requests.
There are six broader events which occur in MVC application life cycle below
diagrams summarize it.
Functionality
User interface
View
UI logic
User interface
Controller
Business logic
/validations
Middle layer
Model
Controller
Accessing data
MVC 3
MVC 4
Razor
Readymade project
templates
HTML 5 enabled
templates
Support for Multiple
View Engines, JavaScript,
and AJAX
A
R
modern
templa
templa
M
to sup
E
Model-Validator Providers
New RequireHttpsAttributeAction Filter
Templated Helpers
Display Model-Level Errors
Model Validation
Improvements
For checkbox below is the HTML helper code. In this way we have HTML helper
methods for every HTML control that exists.
Collapse | Copy Code
Html.TextBox("CustomerCode")
Below is Html.TextBoxFor code which creates HTML textbox using the property
name CustomerCode from object m.
Collapse | Copy Code
In the same way we have for other HTML controls like for checkbox we have
Html.CheckBox and Html.CheckBoxFor.
asynch
routes.MapRoute(
"View", // Route name
"View/ViewCustomer/{id}", // URL with parameters
new { controller = "Customer", action = "DisplayCustomer",
id = UrlParameter.Optional }); // Parameter defaults
[HttpGet]
public ViewResult DisplayCustomer(int id)
{
Customer objCustomer = Customers[id];
return View("DisplayCustomer",objCustomer);
}
Temp data - Helps to maintain data when you move from one controller to
another controller or from one action to another action. In other words when you
redirect, tempdata helps to maintain data between those redirects. It internally uses
session variables.
View data - Helps to maintain data when you move from controller to view.
View Bag - Its a dynamic wrapper around view data. When you
use Viewbag type, casting is not required. It uses the dynamic keyword internally.
ViewData/ViewB
ag
TempData
Hidden fields
Session
Controller to
Controller
No
Yes
No
Yes
Controller to View
Yes
No
No
Yes
View to Controller
No
No
Yes
Yes
TempData is available through out for the current request and in the subsequent
request its available depending on whether TempData is read or not.
So if TempData is once read it will not be available in the subsequent request.
@TempData[“MyData”];
TempData.Keep(“MyData”);
The more shortcut way of achieving the same is by using Peek. This function helps
to read as well advices MVC to maintain TempData for the subsequent request.
Collapse | Copy Code
If you want to read more in detail you can read from this detailed blog on MVC Peek
and Keep.
For every page you would like to reuse the left menu, header, and footer controls. So
you can go and create partial views for each of these items and then you call that
partial view in the main view.
Once the partial view is created you can then call the partial view in the main view
using theHtml.RenderPartial method as shown in the below code snippet:
Collapse | Copy Code
<body>
<div>
<% Html.RenderPartial("MyView"); %>
</div>
</body>
One of the easiest ways of doing validation in MVC is by using data annotations. Data
annotations are nothing but attributes which can be applied on model properties. For
example, in the below code snippet we have a simple Customer class with a
property customercode.
This CustomerCode property is tagged with a Required data annotation attribute. In
other words if this model is not provided customer code, it will not accept it.
Collapse | Copy Code
Later in the controller we can check if the model is proper or not by using
the ModelState.IsValid property and accordingly we can take actions.
Collapse | Copy Code
Below is a simple view of how the error message is displayed on the view.
What are the other data annotation attributes for validation in MVC?
If you want to check string length, you can use StringLength.
Collapse | Copy Code
[StringLength(160)]
public string FirstName { get; set; }
If you want to check whether the numbers are in range, you can use
the Range attribute.
Collapse | Copy Code
Sometimes you would like to compare the value of one field with another field, we
can use the Compareattribute.
Collapse | Copy Code
public string Password { get; set; }[Compare("Password")]public string ConfirmPass { get; set; }
In case you want to get a particular error message , you can use
the Errors collection.
Collapse | Copy Code
If you have created the model object yourself you can explicitly
call TryUpdateModel in your controller to check if the object is valid or not.
Collapse | Copy Code
TryUpdateModel(NewCustomer);
In case you want add errors in the controller you can use
the AddModelError function.
Collapse | Copy Code
<%=DateTime.Now%>
@DateTime.Now
<authentication mode="Windows"/>
<authorization>
<deny users="?"/>
</authorization>
Then in the controller or on the action, you can use the Authorize attribute which
specifies which users have access to these controllers and actions. Below is the code
snippet for that. Now only the users specified in the controller and action can access
it.
Collapse | Copy Code
[Authorize(Users= @"WIN-3LI600MWLQN\Administrator")]
public class StartController : Controller
{
//
// GET: /Start/
[Authorize(Users = @"WIN-3LI600MWLQN\Administrator")]
public ActionResult Index()
{
return View("MyView");
}
}
<authentication mode="Forms">
<forms loginUrl="~/Home/Login" timeout="2880"/>
</authentication>
We also need to create a controller where we will check if the user is proper or not. If
the user is proper we will set the cookie value.
Collapse | Copy Code
All the other actions need to be attributed with the Authorize attribute so that any
unauthorized user making a call to these controllers will be redirected to the
controller (in this case the controller is Login) which will do the authentication.
Collapse | Copy Code
[Authorize]
PublicActionResult Default()
{
return View();
}
[Authorize]
publicActionResult About()
{
return View();
}
AJAX libraries
jQuery
Below is a simple sample of how to implement AJAX by using the AJAX helper
library. In the below code you can see we have a simple form which is created by
using the Ajax.BeginForm syntax. This form calls a controller action
called getCustomer. So now the submit action click will be an asynchronous AJAX
call.
Collapse | Copy Code
<script language="javascript">
function OnSuccess(data1)
{
// Do something here
}
</script>
<div>
<%
var AjaxOpt = new AjaxOptions{OnSuccess="OnSuccess"};
%>
<% using (Ajax.BeginForm("getCustomer","MyAjax",AjaxOpt)) { %>
<input id="txtCustomerCode" type="text" /><br />
<input id="txtCustomerName" type="text" /><br />
<input id="Submit2" type="submit" value="submit"/></div>
<%} %>
In case you want to make AJAX calls on hyperlink clicks, you can use
the Ajax.ActionLink function as shown in the below code.
Below is the controller code. You can see how the GetDate function has a pause of
10 seconds.
Collapse | Copy Code
The second way of making an AJAX call in MVC is by using jQuery. In the below code
you can see we are making an AJAX POST call to a URL /MyAjax/getCustomer. This is
done by using $.post. All this logic is put into a function called GetData and you can
make a call to the GetData function on a button or a hyperlink click event as you
want.
Collapse | Copy Code
function GetData()
{
var url = "/MyAjax/getCustomer";
$.post(url, function (data)
{
$("#txtCustomerCode").val(data.CustomerCode);
$("#txtCustomerName").val(data.CustomerName);
}
)
}
3.
4.
The problem with the inline action attribute is that it cannot be reused across
controllers. So we can convert the inline action filter to an action filter attribute. To
create an action filter attribute we need to inherit fromActionFilterAttribute and
implement the IActionFilter interface as shown in the below code.
Collapse | Copy Code
Later we can decorate the controllers on which we want the action attribute to
execute. You can see in the below code I have decorated the Default1Controller with
the MyActionAttribute class which was created in the previous code.
Collapse | Copy Code
[MyActionAttribute]
public class Default1Controller : Controller
{
public ActionResult Index(Customer obj)
{
return View(obj);
}
}
protected override IView CreateView(
ControllerContext controllerContext, string viewPath, string masterPath)
{
var physicalpath = controllerContext.HttpContext.Server.MapPath(viewPath);
MyCustomView obj = new MyCustomView(); // Custom view engine class
obj.FolderPath = physicalpath; // set the path where the views will be stored
return obj; // returned this view paresing
// logic so that it can be registered in the view engine collection
}
protected override IView CreatePartialView(ControllerContext controllerContext, string
partialPath)
{
var physicalpath = controllerContext.HttpContext.Server.MapPath(partialPath);
MyCustomView obj = new MyCustomView(); // Custom view engine class
obj.FolderPath = physicalpath; // set the path where the views will be stored
return obj;
// returned this view paresing logic
// so that it can be registered in the view engine collection
}
}
Step 3: We need to register the view in the custom view collection. The best place to
register the custom view engine in the ViewEngines collection is the global.asax file.
Below is the code snippet for that.
Collapse | Copy Code
Below is a simple output of the custom view written using the commands defined at
the top.
If you invoke this view, you should see the following output:
In MVC, we have the JsonResult class by which we can return back data in JSON
format. Below is a simple sample code which returns back a Customer object in JSON
format using JsonResult.
Collapse | Copy Code
Below is the JSON output of the above code if you invoke the action via the browser.
What is WebAPI?
HTTP is the most used protocol. For the past many years, browser was the most
preferred client by which we consumed data exposed over HTTP. But as years passed
by, client variety started spreading out. We had demand to consume data on HTTP
from clients like mobile, JavaScript, Windows applications, etc.
For satisfying the broad range of clients REST was the proposed approach. You can
read more about REST from the WCF chapter.
WebAPI is the technology by which you can expose data over HTTP following REST
principles.
WEB API
Size
Heavy weight
because of
complicated WSDL
structure.
Protocol
Independent of
protocols.
SOAP
WEB API
Formats
To parse SOAP
message, the client
needs to
understand WSDL
format. Writing
custom code for
parsing WSDL is a
Output of WebAPI are simple string messages,
heavy duty task. If
JSON, simple XML format, etc. So writing parsing
your client is smart
logic for that is very easy.
enough to create
proxy objects like
how we have in
.NET (add
reference) then
SOAP is easier to
consume and call.
Principles
Step 2: Once you have created the project you will notice that the controller now
inherits from ApiControllerand you can now implement POST, GET, PUT, and DELETE
methods of the HTTP protocol.
Collapse | Copy Code
Step 3: If you make an HTTP GET call you should get the below results:
Figure: HTTP
For example consider the below web request to a page . This page consumes two
JavaScript files Javascript1.jsand Javascript2.js. So when this is page is requested it
makes three request calls:
One for the Index page.
Two requests for the other two JavaScript
files: Javascript1.js and Javascript2.js.
The below scenario can become worse if we have a lot of JavaScript files resulting in
multiple requests, thus decreasing performance. If we can somehow combine all the
JS files into a single bundle and request them as a single unit that would result in
increased performance (see the next figure which has a single request).
In BundleConfig.cs, add the JS files you want bundle into a single entity in to the
bundles collection. In the below code we are combining all the javascript JS files
which exist in the Scripts folder as a single unit in to the bundle collection.
Collapse | Copy Code
bundles.Add(new ScriptBundle("~/Scripts/MyScripts").Include(
"~/Scripts/*.js"));
{
public static void RegisterBundles(BundleCollection bundles)
{
bundles.Add(new ScriptBundle("~/Scripts/MyScripts").Include(
"~/Scripts/*.js"));
BundleTable.EnableOptimizations = true;
}
}
Once you have combined your scripts into one single unit we then to include all the
JS files into the view using the below code. The below code needs to be put in the
ASPX or Razor view.
Collapse | Copy Code
If you now see your page requests you would see that script request is combined into
one request.
BundleTable.EnableOptimizations = true;
// This is test
var x = 0;
x = x + 1;
x = x * 2;
After implementing minification the JavaScript code looks like below. You can see how
whitespaces and comments are removed to minimize file size, thus increasing
performance.
Collapse | Copy Code
var x=0;x=x+1;x=x*2;
You can add an area by right clicking on the MVC solution and clicking on Area
menu as shown in the below figure.
In the below image we have two Areas created Account and Invoicing and in
that I have put the respective controllers. You can see how the project is looking
more organized as compared to the previous state.
But when this Customer model object is displayed on the MVC view it looks
something as shown in the below figure. It has CustomerName , Amount plus
Customer Buying Level fields on the view / screen. Customer buying Level is a
color indicationwhich indicates how aggressive the customer is buying.
Customer buying level color depends on the value of the Amount property. If the
amount is greater than 2000 then color is red , if amount is greater than 1500 then
color is orange or else the color is yellow.
In other words Customer buying level is an extra property which is calculated on
the basis of amount.
TxtCustomerName
Amount
TxtAmount
CustomerBuyingLevelColor
Let us first try to understand what the interviewer is asking. When we bind a model
with a view we use the model dropdown as shown in the below figure. In the below
figure we can only select one model.
But what if we want to bind Customer as well as Order class to the view.
For that we need to create a view model which aggregates both the classes as shown
in the below code. And then bind that view model with the view.
Collapse | Copy Code
In the view we can refer both the model using the view model as shown in the below
code.
Collapse | Copy Code
Note :- Do not get scared with the word. Its actually a very simple thing.
For instance if you choose using Entity framework template the following code is
generated.
It creates controller code, view and also table structure as shown in the below figure.
THREADING
*(B)What is Multi-tasking ?
Its a feature of modern operating systems with which we can run multiple
programs at same time example Word, Excel etc.
*(B)What is Multi-threading ?
A thread is the basic unit to which the operating system allocates processor
time.
*(B) What is the difference between a process and a thread
Process
Each process provides the resources needed to execute a program. A process has a virtual
address space, executable code, open handles to system objects, a security context, a unique
process identifier, environment variables, a priority class, minimum and maximum working set
sizes, and at least one thread of execution. Each process is started with a single thread, often
called the primary thread, but can create additional threads from any of its threads.
Thread
A thread is the entity within a process that can be scheduled for execution. All threads of a
process share its virtual address space and system resources. In addition, each thread maintains
exception handlers, a scheduling priority, thread local storage, a unique thread identifier, and a
set of structures the system will use to save the thread context until it is scheduled. The thread
context includes the thread's set of machine registers, the kernel stack, a thread environment
block, and a user stack in the address space of the thread's process. Threads can also have
their own security context, which can be used for impersonating clients
It is Similar to Sleep and Interrupt. Suspend allows you to block a thread until
another thread calls Thread.Resume. The difference between Sleep and
Suspend is that the latter does not immediately place a thread in the wait
state. The thread does not suspend until the .NET runtime determines that it
is in a safe place to suspend it. Sleep will immediately place a thread in a
wait state
This window is only seen when the program is running in debug mode. In
windows one of the window is Threads.
(I)Can we use events with threading ? Yes, you can use events with
thread; this is one of the techniques to synchronize one thread with other.
(B) What is the difference between thread and process? A thread is a
path of execution that run on CPU, a process is a collection of threads that
share the same virtual memory. A process has at least one thread of
execution, and a thread always run in a process context.
.NET remoting is replacement of DCOM. Using .NET remoting you can make
remote object calls which lie in different Application Domains. As the remote
objects run in different process client calling the remote object can not call it
directly. So the client uses a proxy which looks like a real object. When client
wants to make method call on the remote object it uses proxy for it. These
method calls are called as Messages. Messages are serialized using
formatter class and sent to client channel. Client Channel communicates
with Server Channel. Server Channel uses as formatter to deserialize the
message and sends to the remote object.
*(B) What is a Web Service ?
Web Services are business logic components which provide functionality via
the Internet using standard protocols such as HTTP. Web Services uses Simple
Object Access Protocol (SOAP) in order to expose the business
functionality.SOAP defines a standardized format in XML which can be
exchanged between two entities over standard protocols such as HTTP. SOAP
is platform independent so the consumer of a Web Service is therefore
completely shielded from any implementation details about the platform
exposing the Web Service. For the consumer it is simply a black box of send
and receive XML over HTTP. So any web service hosted on windows can also
be consumed by UNIX and LINUX platform.
(B) What is UDDI ?
In short its a bible of what the webservice can do.Clients can consume this
WSDL and build proxy objects that clients use to communicate with the Web
Services. Full WSDL specification is available at http://www.w3.org/TR/wsdl.
(B) Which attribute is used in order that the method can be used as WebService ?
(I) What are two different types of remote object creation mode in .NET ?
There are two different ways in which object can be created using Remoting : SAO (Server Activated Objects) also called as Well-Known call
mode.
CAO (Client Activated Objects) SAO has two modes Single Call
and Singleton.
With Single Call object the object is created with every method call thus
making the object stateless. With Singleton the object is created only once
and the object is shared with all clients. CAO are stateful as compared to
SAO. In CAO the creation request is sent from client side. Client holds a proxy
to the server object created on server.
(I) How can we call methods in remoting Asynchronously ?
All previous examples are a synchronous method calls that means client has
to wait until the method completes the process. By using Delegates we can
make Asynchronous method calls.
(I) What are the situations you will use a Web Service and Remoting in projects?
Well Web services uses remoting concepts internally. But the major
difference between web service and remoting is that web service can
be consumed by clients who are not .NET platform. While remoting you need
the client to be .NET compliant. Regarding the speed issue Remoting is
faster than Web Services. So I think when deciding the architecture side of
choosing between Web services and Remoting keep the cross platform
issue and the speed issue in mind.
(A) What is marshalling and what are different kinds of marshalling ?
Singleton pattern mainly focuses on having one and only one instance of the
object running. Example a windows directory service which has multiple
entries but you can only have single instance of it through out the network.
Note:- May of developers would jump to a conclusion saying using the
STATIC keyword we can have a single instance of object. But thats not the
real case there is something more that has to be done. But please note we
can not define a class as STATIC, so this will not serve our actual purpose of
implementing singleton pattern.
Following are the three steps needed to implement singleton pattern in .NET:264
CASHING
(B) What is an application object ?
You can use two types of output caching to cache information that is to be
transmitted to and displayed in a Web browser:
Page Output Caching Page output caching adds the response of page to
cache object. Later when page is requested page is displayed from cache
rather than creating the page object and displaying it. Page output caching is
good if the site is fairly static.
Page Fragment Caching If parts of the page are changing, you can wrap
the static sections as user controls and cache the user controls using page
fragment caching.
(B) How can you cache different version of same page using ASP.NET cache
object ?
(B) What are ASP.NET session and compare ASP.NET session with classic ASP
session variables?
InProc:- In this mode Session state is stored in the memory space of the
Aspnet_wp.exe process. This is the default setting. If the IIS reboots or web
application restarts then session state is lost. 182
StateServer:-In this mode Session state is serialized and stored in a
separate process (Aspnet_state.exe); therefore, the state can be stored on a
separate computer(a state server).
SQL SERVER:- In this mode Session state is serialized and stored in a SQL
Server database. Session state can be specified in <sessionState> element
of application configuration file. Using State Server and SQL SERVER session
state can be shared across web farms but note this comes at speed cost as
ASP.NET needs to serialize and deserialize data over network again and
again.
(B) What are the other ways you can maintain state ?
Other than session variables you can use the following technique to store
state : Hidden fields View state Hidden frames Cookies Query
strings
(B) What are benefits and Limitation of using Hidden fields ?
Following are the benefits of using Hidden fields : They are simple to implement.
As data is cached on client side they work with Web Farms.
All browsers support hidden field.
No server resources are required. Following are limitations of Hidden field :184
Following are the benefits of using Viewstate : No server resources are required because state is in a structure in the page
code.
Simplicity.
States are retained automatically.185
The values in view state are hashed, compressed, and encoded, thus
representing a higher state of security than hidden fields.
View state is good for caching data in Web frame configurations because
the data is cached on the client.
Following are limitation of using Viewstate: Page loading and posting performance decreases when large values are
stored because view state is stored in the page.
Although view state stores data in a hashed format, it can still be tampered
because it is stored in a hidden field on the page. The information in the
hidden field can also be seen if the page output source is viewed directly,
creating a potential security risk.
Below is sample of storing values in view state. this.ViewState["EnterTime"]
= DateTime.Now.ToString();
(B) What is SQL Cache Dependency in ASP.NET 2.0?
No server resources are required. The query string containing in the HTTP
requests for a specific URL.
All browsers support query strings. Following are limitations of query
string : Query string data is directly visible to user thus leading to security
problems. Most browsers and client devices impose a 255-character limit on URL
length. Below is a sample Login query string passed in URL
http://www.querystring.com/ login.asp?login=testing. This query string data
can then be requested later by using Request.QueryString(login).
(I) Whats the difference between Cache object and application object ?
The main difference between the Cache and Application objects is that the
Cache object provides cache-specific features, such as dependencies and
expiration policies.
(I) How can get access to cache object ?
Following are benefits of using cookies for state management : No server resources are required as they are stored in client.
They are light weight and simple to use Following are limitation of using
cookies : Most browsers place a 4096-byte limit on the size of a cookie, although
support for 8192-byte cookies is becoming more common in the new browser
and client-device versions available today.
Some users disable their browser or client devices ability to receive
cookies, thereby limiting the use of cookies.
Cookies can be tampered and thus creating a security hole.
Cookies can expire thus leading to inconsistency. Below is sample code of
implementing cookies Request.Cookies.Add(New HttpCookie(name, user1))
(A) What are dependencies in cache and types of dependencies ?
When you add an item to the cache, you can define dependency
relationships that can force that item to be removed from the cache under
specific activities of dependenci es.Example if the cache object is dependent
on file and when the file data changes you want the cache object to be
update. Following are the supported dependency : File dependency :- Allows you to invalidate a specific cache item when a
disk based file or files change.
Time-based expiration :- Allows you to invalidate a specific cache item
depending on predefined time.
Key dependency :-Allows you to invalidate a specific cache item depending
when another cached item changes.
(A) Is Session_End event supported in all session modes ?
XML
(B) What is XML?
No, every tag in XML which is opened should have a closing tag. For instance
in the top if I remove </discount> tag that XML will not be understood by lot
of application.427
(B) Is XML case sensitive?
XML describes data while HTML describes how the data should be displayed.
So HTML is about displaying information while XML is about describing
information.
(B) Is XML meant to replace HTML?
No, they both go together one is for describing data while other is for
displaying data.
(B) What is DTD (Document Type definition)?
It defines how your XML should structure. For instance in the above XML we
want to make it compulsory to provide qty and totalcost, also that these
two elements can only contain numeric. So you can define the DTD document
and use that DTD document with in that XML.
(B) What is well formed XML?
If a XML document is confirming to XML rules (all tags started are closed,
there is a root element etc) then its a well formed XML. 428
(B) What is a valid XML?
All data is normally parsed in XML but if you want to exclude some elements
you will need to put those elements in CDATA.
(B) What is CSS?
In the below example invoice is the element and the invnumber the attribute.
<invoice invnumber=1002></invoice>
System.xml.dll is the actual physical file which has all XML implementation.
Below are the commonly used namespaces:- System.Xml
System.Xml.Schema System.Xml.XPath System.Xml.Xsl
(B) What are the core functionalities in XML .NET framework? Can you explain in
detail those functionalities?
The XML API for the .NET Framework comprises the following set of
functionalities:434
XML readers With XML readers the client application get reference to
instance of reader class. Reader class allows you to scroll forward through the
contents like moving from node to node or element to element. You can
compare it with the SqlDataReader object in ADO.NET which is forward only.
In short XML reader allows you to browse through the XML document.
XML writers Using XML writers you can store the XML contents to any other
storage media. For instance you want to store the whole in memory XML to a
physical file or any other media.
XML document classes XML documents provides a in memory
representation for the data in an XMLDOM structure as defined by W3C. It
also supports browsing and editing of the document. So it gives you a
complete memory tree structure representation of your XML document.
(B) What is XSLT?
SILVERLIGHT
framework, Silverlight applications can easily integrate with server-side controls and
services. Using Silverlight's implementation of the .NET framework, developers can
easily integrate existing libraries and code into Silverlight applications.
Support for the .NET Framework if you are already a .NET developer, it is
easy to start programming on Silverlight.
Support for managed code you can write programs in your favorite language
which .NET CLR supports like C#, VB.NET, dynamic languages (IronPython,
IronRuby).
Better development tools -Visual Studio 2010, Expression Blend.
Large community- More learning resources available compared to Flash.
Integration with Enterprise based technologies like WPF, LINQ etc
Silverlight integrates the XAML declarative language with the .NET framework.
It is a cross-browser, cross-platform technology which provides a consistent
user experience everywhere it runs.
The Silverlight plug-in installs in seconds, and leaves a very small footprint.
After you install the plug-in, users no longer need to install anything on their
workstations to run Silverlight applications. The applications are available to them
from whatever browser they are accessing.
It runs a client-side application that can read data and update the UI without
interrupting the user by refreshing the whole page.
It can run asynchronous communications with the server, allowing the UI to
continue to function while waiting for the server response.
It delivers rich video, audio, and graphics.
Mac OS
Windows Vista
Windows XP SP2
Windows 2000
Windows Server 2003
Linux (Moonlight)
Windows
Operating System: Windows 7, Windows Vista, Windows XP Service Pack 2
Intel Pentium III 450MHz or faster processor (or equivalent)
128MB of RAM
Mac OS
Operating System: Apple Mac OS X 10.4.8 or above
Intel Core Duo 1.83GHz or faster processor
128MB of RAM
Linux
Moonlight
6. What is Moonlight?
Moonlight is an Open Source implementation of Silverlight, primarily for Linux and
other Unix/X11 based Operating Systems. In September of 2007, Microsoft and
Novell announced a technical collaboration that includes access to Microsoft's test
suites for Silverlight and the distribution of a Media Pack for Linux users that will
contain licensed media codecs for video and audio.
Moonlight 2 was released December 17, 2009
8. Is Silverlight free?
Yes, Microsoft has made the Silverlight browser plug-in freely available for all
supported platforms and browsers.
Silverlight 1 is purely AJAX and JavaScript based. All the code has to be written
in JavaScript and XAML.
Silverlight 2 supports managed code. When the Silverlight 2 runtime is
installed, it installs a limited version of the .NET runtime on the client machine. This
allows .NET programmers to write managed code to be executed on the client PC,
and provides a better user experience to users. Of course, there is security
restrictions built in to it so that the code has limited access to the client computer.
The biggest change is the implementation of the .NET Framework. If you are
familiar with Silverlight 1.0, then you will be used to coding the application
functionality in JavaScript. You can still implement functionality using JavaScript;
however, you can now also implement functionality using C#, Visual Basic, Python,
Ruby, and managed JavaScript.
Another major change is the introduction of the XAP package. In Silverlight
1.0, the XAML code was referenced directly by the Silverlight object embedded in the
browser. In Silverlight 2, however, the embedded object references an XAP package
that contains the XAP file, assemblies, and resources necessary to run the Silverlight
application.
SDK is not really mandatory to develop Silverlight applications; however, the SDK will
make development much easier.
application includes programming logic, then you might want to choose Visual
Studio.
Silverlight 1.0: Silverlight 1.0, which was developed under the codename
Windows Presentation Foundation/Everywhere (WPF/E), consists of the core
presentation framework which is responsible for the user interface (UI), interactivity,
and user input, basic UI controls, graphics and animation, media playback, Digital
Restrictions Management (DRM), and DOM integration
Silverlight 2: Silverlight 2 (previously referred to as version 1.1) includes a
version of the .NET Framework, implementing the same full Common Language
Runtime (CLR) version as .NET Framework 3.0. The XAML markup as well as the code
is compiled into .NET assemblies which are then compressed using Zip and stored in
a .xap file.
Silverlight 3: Silverlight version 3 was released in July 9, 2009, which is an
extension to Silverlight 2.0, and mainly provides improvements in graphics
capabilities, media management, application development areas (additional controls,
enhanced binding support, and out-of-browser functionality), and integration in the
designers' Expression Blend 3 tools.
Silverlight 4: Silverlight version 4 was released on April 15, 2010 (along
with Silverlight 4 tools for developers).
A .xap file is used to contain and transfer the assemblies and resources of a
managed code application. This managed code application must be run within the
Silverlight 2 browser plug-in.
<UserControl x:Class="SilverlightApplication1.SilverlightControl1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Width="400" Height="300">
<Canvas Width="500" Height="500" Background="White">
<Rectangle Canvas.Left="75" Canvas.Top="90"
Fill="red" Width="100" Height="100" />
</Canvas>
</UserControl>
Output:
When the above XAML is executed, it will display a rectangle filled with red color. You
may notice that XAML is very similar to HTML in nature.
XAML stands for eXtensible Application Markup Language, and is a declarative
markup language that follows the XML rule and is used for developing User
Interfaces in WPF and Silverlight technology. XAML files are XML files that generally
have the .xaml extension, and separates the UI definition from the run-time logic by
using code-behind files, joined to the markup through partial class definitions.
XAML has a set of rules that map object elements into classes or structures,
attributes into properties or events, and XML namespaces to CLR namespaces. XAML
elements map to Microsoft .NET types as defined in referenced assemblies, and the
attributes map to members of those types.
<Deployment xmlns="http://schemas.microsoft.com/client/2007/deployment"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
EntryPointAssembly="SilverlightApplication1"
EntryPointType="SilverlightApplication1.App"
RuntimeVersion="2.0.30226.2">
<Deployment.Parts>
<AssemblyPart x:Name="SilverlightApplication1"
Source="SilverlightApplication1.dll" />
<AssemblyPart x:Name="System.Windows.Controls"
Source="System.Windows.Controls.dll" />
<AssemblyPart x:Name="System.Windows.Controls.Extended"
Source="System.Windows.Controls.Extended.dll" />
</Deployment.Parts>
</Deploymnt>
The first element in AppManifest.xaml is a Deployment node. This node defines the
application, and contains the child AssemblyPart nodes.
As you can see the AssemblyPart nodes define what assemblies (DLLs) are
contained within the .xap file, and give each of them a name.
Now, if you look back up to the top, you'll see the Deployment node has
the EntryPointAssembly andEntryPointType attributes.
The EntryPointAssembly attribute defines which assembly defined below (as a
child AssemblyPart node) is the main assembly (DLL) for the application. And,
the EntryPointType attribute specifies the class contained within the assembly (DLL),
defined in the EntryPointAssembly attribute, is the main class that will be
instantiated to start the application.
The Deployment node also has a RuntimeVersion attribute that defines the version
of Silverlight the application is built for.
{
}
private void Application_UnhandledException(object sender,
ApplicationUnhandledExceptionEventArgs e)
{
}
For ASP.NET developers, the above code will look familiar. This is similar to the
application level event handlers inGlobal.asax.
<UserControl x:Class="SilverlightApplication1.MainPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Width="400" Height="300">
<Grid x:Name="LayoutRoot" Background="White">
</Grid>
</UserControl>
WPF runs on the .NET runtime, and developers can take advantage of the rich .NET
Framework and WPF libraries to build really cool Windows applications. WPF supports
3-D graphics, complex animations, hardware acceleration etc.
Silverlight uses a particular implementation of a XAML parser, with that parser being
part of the Silverlight core installation. In some cases, the parsing behavior differs
from the parsing behavior in Windows Presentation Foundation (WPF), which also has
a particular implementation.
In table format:
Silverlight
WPF
Definition
Windows Presentation
Foundation (WPF) is Microsofts
latest development platform
for building next-generation
Windows client applications.
Subset of
GUI
Support
Windows only.
Software
Required
Framework
support
Silverlight
WPF
an application.
Deployment Silverlight applications are hosted
within a web server and a web page.
To minimize client download size,
Silverlight uses a XAP archive. A XAP
archive is a zip-compressed archive
of the Silverlight application, plus a
manifest file describing the content.
Visual Studio automatically
generates the XAP archive when
using the Silverlight project
template.
3.5 and the AJAX Controls Toolkit for ASP.NET 3.5, now ASP.NET AJAX client-and
server-side libraries are more integrated with Visual Studio 2008. The client-side
library allows you to implement client-level processing such as processing and
validating information entered by the end user, refreshing a portion of the web page,
and developing rich, interactive user interfaces. You can also efficiently integrate the
client-side library components with the server-side ASP.NET controls library in
asynchronous mode. The key technology driver of ASP.NET AJAX is scripting. In
general, script-based web applications face several challenges due to different
browser settings (e.g., JavaScript is not enabled by default) on PCs and mobile
devices. As a result, scripting is often not always the best strategy for enterprises to
use to develop secure and scalable RIAs.
ASP.NET AJAX supports limited features of RIAs, and does not support effective
multimedia integration, managed code-behind integration, or metadata and
information management. Microsoft ASP.NET AJAX is a widely accepted model for
building RIAs, but it is very likely that, having Silverlight as an option, .NET
developers will migrate ASP.NET AJAX applications to Silverlight RIAs.
Visit www.asp.net/ajax/ if you want to learn more about Microsoft ASP.NET AJAX.
vertical stacks.
Grid - Position child elements in rows and columns.
You have to add a layout panel to every XAML page you create. All other UI elements
must be added inside one of the layout panels. Each page can have exactly one
layout panel control.
Microsoft Silverlight is a cross-browser, cross-platform, and cross-device plugin for delivering the next generation of .NET based media experiences and rich
interactive applications for the Web.
Silverlight offers a flexible programming model that supports AJAX, VB, C#,
IronPython, and IronRuby, and integrates with existing Web applications.
By using Expression Studio and Visual Studio, designers and developers can
collaborate more effectively using the skills they have today to light up the Web of
tomorrow.
By leveraging Silverlight's support for .NET, High Definition video, costeffective advanced streaming, unparalleled high-resolution interactivity with Deep
Zoom technology, and controls, businesses can reach out to new markets across the
Web, desktop, and devices.
Silverlight runs completely on the client, while ASP.NET mainly runs on the
server, but also has a few parts running on the client.
When an event fires, Silverlight handles the event on the client, but in
ASP.NET, the browser will make an HTTP POST to the server, and after the server
handles the request, it sends a new HTML page to the client.
A Silverlight application sends rendering commands to the Silverlight
rendering engine by either writing XAML or code, and the Silverlight rendering
engine will handle the rendering task. On the other hand, ASP.NET doesnt have a
rendering engine. It generates an HTML file on the server, sends it to the client, and
allows the browser to parse the HTML file and render the content.
Silverlight cant work with a database directly; instead, it consumes data from
Web Services, while ASP.NET has strong support for working with databases directly.
The most important thing to note is what runs on the client and what runs on the
server, since this will affect almost every part of your system. Silverlight runs on the
client, and ASP.NET runs on the server. They can work together and are compatible
with each other, but this requires some time and effort.
Pure Silverlight
One approach is to completely remove ASP.NET. This solution works best if youre
working on a new development. You only need to work on Silverlight, without any
worry about integration problems. If you need to communicate with the server, you
write Web Services, such as WCF. It will also help you when you need to port part or
whole of your system to another hosting or even another platform, since the client
and the server are completely separate.
Within this approach, there are two branches. One is to mix the client and server
code by using theUpdatePanel, AJAX Control Toolkit, and etc. The other method is to
take the pure AJAX approach, where you write HTML and JavaScript instead of using
server controls, and call Web Services to communicate with the server. The former
branch is easier to implement, especially if you have strong ASP.NET experience but
lack JavaScript knowledge. The latter branch proves to be better in an architecture
when you want to port an AJAX application to other technologies such as Silverlight,
especially since you only need to rewrite the client side code, and can keep the Web
Services as they are. The programming model for the latter branch is similar to
Silverlight. Therefore, this approach is rarely taken if youre experienced in
Silverlight.
Mix Silverlight with ASP.NET
More often, you may want to port an existing ASP.NET application to Silverlight, but
you dont want to completely rewrite the entire application. This is the most difficult
approach since youre mixing client side and server side technologies.
Before going with this approach, please consider if the above approaches can solve
your problem. Ask yourself the following questions:
1.
This is normally a requirement for consumer oriented applications, but for most
business applications, you only need a good user experience, which AJAX is
sufficient to provide.
2.
3.
WCF
What is service ?
A service is a unit of functionality exposed to the world. Service orientation (SO) is an
abstract set of principles and best practices for building service-oriented
applications.
What is WCF ?
HTTP/HTTPS - http://localhost:8001/MyService
TCP - net.tcp://localhost:8002/MyService
IPC - net.pipe://localhost/MyPipe
Peer network
MSMQ - net.msmq://localhost/private/MyQueue
Service bus - sb://MyNamespace.servicebus.windows.net/
Web Service
WCF
Hosting
Programming
Model
Supported
Operations
Logging
Serialization
Supported
Encoding
Supported
Transports
Can be accessed through HTTP, TCP Can be accessed through HTTP, TCP, Named
and Custom.
pipes, MSMQ,P2P(Peer to Peer) and Custom.
Supported
Protocols
Security
Instead of defining a .svc file, you can create and host the service in .config file as
below:
Collapse | Copy Code
<system.serviceModel>
<serviceHostingEnvironment>
<serviceActivations>
<add relativeAddress = "MyService.svc" service = "WcfService.MyService"/>
<add relativeAddress = "MyOtherService.svc" service = "MyOtherService"/>
</serviceActivations>
</serviceHostingEnvironment>
<services>
<service name = "WcfService.MyService">
...
</service>
<service name = "MyOtherService">
...
</service>
</services>
</system.serviceModel>
Self Hosting
Self-hosting is the technique in which the developer is responsible for providing and
managing the lifecycle of the host process. You can host WCF service inside any
Windows process, such as a Windows Forms application, a WPF application, a
Console application, or a Windows NT Service.
You can also host your WCF service as in-proc. In-process (or in-proc) hosting is the
hosting technique where the service resides in the same process as the client. By
definition, the developer provides the host for the in-proc hosting.
Collapse | Copy Code
You can also specify the host factory in the config file when not using an .svc file
explicitly:
Collapse | Copy Code
<serviceActivations>
<add relativeAddress = "MyService.svc" service = "MyService" factory = "MyServiceFactory" />
</serviceActivations>
Note: The host factory class must derive from the ServiceHostFactory class and
override the CreateServiceHost() virtual method.
Windows Server AppFabric
AppFabric is an extension to the WAS. It is geared more toward WF services, which
require support for persistence and state management correlation. Windows Server
AppFabric adds items for managing and monitoring the services, as well as WCF and
WF configuration items, to the IIS 7 management console. Windows Server AppFabric
Supported protocol
IIS6
http, wshttps
http,net.tcp,net.pipe,net.msmq
http,net.tcp,net.pipe,net.msmq
Feature
Self-Hosting
IIS Hosting
WAS Hosting
Executable Process/
App Domain
Yes
Yes
Yes
Configuration
App.config
Web.config
Web.config
Activation
Manual at
startup
Messagebased
Messagebased
Idle-Time
Management
No
Yes
Yes
Health Monitoring
No
Yes
Yes
Process Recycling
No
Yes
Yes
Management Tools
No
Yes
Yes
What is binding ?
A binding is the set of configurations regarding the transport protocol, message
encoding, communication pattern, reliability, security, transaction propagation, and
interoperability.
M
e
HTTP
Te
HTTP
Te
Duplex service
contracts or
Secure, Interoperable.
HTTP
communication through
SOAP intermediaries.
Te
Binding
Feature
Suitable For
BasicHttpBinding
Communication with
WS-Basic Profile
Not secure by default.
conformant Web
Services like ASMX.
WSHttpBinding
Secure, Interoperable.
WSDualHttpBinding
Non-duplex service
contracts.
WSFederationHttpBinding
Te
NetTcpBinding
Secure, Optimized.
Cross-machine
communication
between WCF
applications.
NetPeerTcpBinding
Secure.
Multi-machine
communication.
P2P
NetNamedPipesBinding
Secure, Reliable,
Optimized.
On-machine
communication
between WCF
applications.
Named Pipes B
Cross-machine
communication
between WCF
applications.
MSMQ
Cross-machine
communication
between a WCF
MSMQ
application and existing
MSMQ applications.
P
fo
NetMsmqBinding
MsmqIntegrationBinding
TCP
<endpoint name="BasicHttpGreetingService"
address="http://localhost:5487/MyService/GreetingService.svc" binding="basicHttpBinding"
contract="MyNamespace.MyService.IGreetingService" />
Eg: http://localhost:5487/MyService/GreetingService.svc
<bindings>
<netTcpBinding>
<binding name = "TransactionalTCP" transactionFlow = "true" />
</netTcpBinding>
</bindings>
<configuration>
<system.serviceModel>
<behaviors>
<serviceBehaviors>
<behavior name="CustomServiceBehavior">
<serviceMetadata httpGetEnabled="True" />
<serviceDebug includeExceptionDetailInFaults="False" />
</behavior>
</serviceBehaviors>
</behaviors>
</system.serviceModel>
</configuration>
<configuration>
<system.serviceModel>
<services>
<service name="MyNamespace.MyService.GreetingService"
behaviorConfiguration="CustomServiceBehavior">
<endpoint address="" binding="wsHttpBinding"
contract="MyNamespace.MyService.IGreetingService" />
<endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange" />
</service>
</services>
<behaviors>
<serviceBehaviors>
<behavior name="CustomServiceBehavior">
<serviceMetadata httpGetEnabled="True" />
</behavior>
</serviceBehaviors>
</behaviors>
</system.serviceModel>
</configuration>
Default
reliability
Supports
ordered
delivery
Default Ordered
delivery
BasicHttpBinding
No
N/A
No
N/A
NetTcpBinding
Yes
Off
Yes
On
NetNamedPipeBinding
No
N/A(On)
Yes
N/A(On)
WSHttpBinding
Yes
Off
Yes
On
NetMsmqBinding
No
N/A
No
N/A
Binding name
<bindings>
<netTcpBinding>
<binding name = "ReliableTCP">
<reliableSession enabled = "true"/>
</binding>
</netTcpBinding>
</bindings>
[ServiceContract]
interface ICalculator
{
[OperationContract(Name = "AddInt")]
int Add(int arg1,int arg2);
[OperationContract(Name = "AddDouble")]
double Add(double arg1,double arg2);
}
[DataContract]
[KnownType(typeof(SubClass))]
class BaseClass
{...}
[DataContract]
class SubClass : BaseClass
{...}
What is ServiceKnownType ?
Instead of using the KnownType attribute on the base data contract, you can apply
the
ServiceKnownType attribute on a specific operation on the service side. Then, only
that
operation (across all supporting services) can accept the known subclass.
Collapse | Copy Code
[OperationContract]
[ServiceKnownType(typeof(SubClass))]
void AddContact(BaseClass baseObject);
[ServiceContract]
public interface IGreetingService
{
[OperationContract]
string GreetMe(string userName);
}
public class GreetingService : IGreetingService
{
public string GreetMe(string userName)
{
return string.Format("Welcome {0}", userName);
}
}
If we do not want to create interface then we can apply the attributes on a class
itself.
Collapse | Copy Code
[ServiceContract]
public class GreetingService
{
[OperationContract]
public string GreetMe(string userName)
{
return string.Format("Welcome {0}", userName);
}
}
[DataContract]
public enum Color
{
[EnumMember]
Red,
[EnumMember]
Green,
[EnumMember]
Blue
}
[DataContract]
public class Shape
{
[DataMember]
public string Name { get; set; }
[DataMember]
public Color FillColor { get; set; }
[DataMember]
public double Area { get; set; }
}
However there are some cases when you want to have control over the SOAP
messages. You can achieve this using MessageContract.
Collapse | Copy Code
[MessageContract]
public class Shape
{
[MessageHeader]
public string ID;
[MessageBodyMember]
public string Name;
[MessageBodyMember]
public double Area;
}
In above example, ID will be added as header, Name and Area as body in SOAP
envelope.
When you use MessageContract then you have control over the SOAP message.
However some restrictions are imposed as below:
You can have only one parameter for a service operation if you are using
MessageContract.
You can return either void or MessageContract type from service operation.
Service operation can not return DataContract type.
Service operation can accept and return only MessageContract type.
Some important points about MessageContract:
You can mention the MessageHeader or MessageBodyMember to be signed or
Encrypted using ProtectionLevel property.
The order of the body elements are alphabetical by default. But you can
control the order, using Order property in the MessageBody attribute.
What is FaultContract ?
In most of the cases you would like to convey the details about any error which
occurred at service end. By default, WCF exceptions do not reach client. However
you can use FaultContract to send the exception details to client.
Collapse | Copy Code
[DataContract()]
public class CustomError
{
[DataMember()]
public string ErrorCode;
[DataMember()]
public string Title;
[DataMember()]
public string ErrorDetail;
}
[ServiceContract()]
public interface IGreetingService
{
[OperationContract()]
[FaultContract(typeof(CustomError))]
string Greet(string userName);
}
public class GreetingService : IGreetingService
{
public string Greet(string userName)
{
if (string.IsNullOrWhiteSpace(userName))
{
var exception = new CustomError()
{
ErrorCode = "401",
Title = "Null or empty",
ErrorDetail = "Null or empty user name has been provided"
};
throw new FaultException<CustomError>(exception, "Reason : Input error");
}
return string.Format("Welcome {0}", userName);
}
}
Per-Call: Service instance is created for each client request. This Service
instance is disposed after response is sent back to client.
Per-Session (default): Service instance is created for each client. Same
instance is used to serve all the requests from that client for a session. When a client
creates a proxy to particular service, a service instance is created at server for that
client only. When session starts, context is created and when it closes, context is
terminated. This dedicated service instance will be used to serve all requests from
that client for a session. This service instance is disposed when the session ends.
Singleton: All client requests are served by the same single instance. When
the service is hosted, it creates a service instance. This service instance is disposed
when host shuts down.
You can configure instance mode using [ServiceBehavior] attribute as below:
Collapse | Copy Code
[ServiceBehavior(InstanceContextMode=InstanceContextMode.Single)]
public class MyService:IGreetingService
<behaviors>
<serviceBehaviors>
<behavior name="ServiceBehavior">
<serviceThrottling maxConcurrentCalls="500" maxConcurrentInstances ="100"
maxConcurrentSessions ="200"/>
</behavior>
</serviceBehaviors>
</behaviors>
[ServiceContract(SessionMode = SessionMode.NotAllowed)]
interface IMyContract
{...}
[ServiceBehavior(InstanceContextMode = InstanceContextMode.PerCall)]
class MyService : IMyContract
{...}
Basic
Allowed/
NotAllowed
PerCall/
PerSession
PerCall
TCP, IPC
Allowed/
Required
PerCall
PerCall
TCP, IPC
Allowed/
Required
PerSession
PerSession
WS
(no Message security, no reliability)
NotAllowed/
Allowed
PerCall/
PerSession
PerCall
WS
(with Message security or reliability)
Allowed/
Required
PerSession
PerSession
WS
(with Message security or reliability)
NotAllowed
PerCall/
PerSession
PerCall
For Duplex MEP, you need to specify the one of the binding which supports bidirectional like wsDualHttpBinding as in below example:
Collapse | Copy Code
<services>
<service name="MyWCFServices.DuplexService">
<endpoint address ="" binding="wsDualHttpBinding" contract="MyWCFServices.IDuplexService">
</endpoint>
</service>
</services>
[OperationContract(IsOneWay = true)]
Prepare phase: In this phase the client application performs the operations
of a WCF service. WCF service determines whether the requested operation will be
successful or not and notify the client about the same.
Commit Phase: In the commit phase the client checks for the responses it
got from the prepare phase and if all the responses are indicating that the operation
can be carried out successfully the transaction is committed. If the response from
any one of the operations indicates failure then the transaction will be rolled back.
The actual operation on the service end will happen in the commit phase.
WCF service will have to send the notification of whether the operation will succeed
or fail to the client application. It means that the One way operations can never
support transactions. The operations that support transactions have to follow
the Request-Response MEP. Also the applied binding should support WS-Atomic
Transaction protocol like wsHttpBinding.
<bindings>
<netTcpBinding>
<binding transactionFlow="true"></binding>
</netTcpBinding>
</bindings>
[OperationContract]
[TransactionFlow(TransactionFlowOption.Allowed)]
bool Credit(int accountId, double amount);
[OperationContract]
[TransactionFlow(TransactionFlowOption.Allowed)]
bool Debit(int accountId, double amount);
Note: You can have single operation as which can do credit and debit. However I
have separated as two for illustrating about transaction.
transactionFlow and TransactionFlowOption together enables the transaction flow for
particular operation. If you enable only one of these two, transaction flow can not be
enabled.
<code>[OperationContract]
[TransactionFlow(TransactionFlowOption.Allowed)]
bool Debit(int accountId, double amount);
Step 2: Create the service class which implements the service contract and set the
operation behavior withTransactionScopeRequired = true. This attribute is used to
enable the service transaction when the client transaction is not available.
Collapse | Copy Code
<code>[OperationBehavior(TransactionScopeRequired = true)]
<bindings>
<wsHttpBinding>
<binding name="myTransactionBinding" transactionFlow="true" ></binding>
</wsHttpBinding>
</bindings>
synchronization lock. If there are multiple concurrent callers to the same context
while the lock is locked, all the callers are placed in a queue. Once the context is
unlocked waiting callers are allowed to lock the context in the order of queue. If a
call times out while blocked, WCF will remove the caller from the queue and the
client will get a TimeoutException.
ConcurrencyMode.Multiple - multiple callers at a time are allowed.
WCF will not synchronize access to the service context. It means that the service
context is not associated with any synchronization lock. In this case, you must
manually synchronize access to the service instance state using .NET locks such as
Monitor or a WaitHandle-derived class.
ConcurrencyMode.Reentrant - multiple callers at a time are allowed only if it is
reentrant.
WCF associates the service context with a synchronization lock, so concurrent calls
on the same instance are never allowed. However, if the reentrant service calls
another service or a callback, and that call chain somehow winds its way back to the
service instance that call is allowed to reenter the service instance. For example,
suppose there are three services A, B and C. Service A calls service B, service B calls
service C, and service C calls service A then service C is allowed to call service A
because it is reentrant service.
You can set the concurrency mode for the service by setting the ConcurrencyMode
property of ServiceBehavior attribute.
Collapse | Copy Code
WWF
What is a workflow?
A workflow is a set of activities which is stored as a model and they depict a process.
The figure below clearly depicts the difference between a Workflow and an Activity.
The workflow model can be written in pure .NET code, pure XAML, or a mix of XAML
and .NET code. A workflow model is compiled and can execute under Windows,
ASP.NET, Web Services, or Windows Services application.
performs the entire tasks sequentially and these tasks are very deterministic. Now
have a look at the second workflow. Every state goes to another state when it
receives some external events. For instance, when Shiv is seeing Star Trek, there is
an event of flashing news which triggers him to see the flashing news.
how to use a sequential workflow. Let us try to understand step by step, what is
marked in the figure:
Note: The above code snippet was developed without using a designer. The whole
point was to make you understand what happens behind the scenes. In real projects,
you will be dependent on a designer rather than coding manually. You can find the
above code in the SimpleWorkFlowSampleManual folder.
1.
2.
3.
4.
We have a small tab which says View Exceptions. If you click on View
Exceptions, you will be redirected to a workflow design only for the exception as
shown in the numbered snapshot 2.
2.
This is the workflow which will execute in case we have exceptions. We have
put a code activity which points to a method called as raiseException. In case of
exceptions in the workflow, this path will be followed.
1.
In order to create a XOML file, you need to add a sequential workflow with
separation. Which means that the XOML file will be created with a behind code.
2.
Currently we have two activities: code3 and code1. Below is the XOML file
contents:
Collapse | Copy Code
<?Mapping XmlNamespace="ComponentModel"
ClrNamespace="System.Workflow.ComponentModel"
Assembly="System.Workflow.ComponentModel" ?>
<?Mapping XmlNamespace="Compiler"
ClrNamespace="System.Workflow.ComponentModel.Compiler"
Assembly="System.Workflow.ComponentModel" ?>
<?Mapping XmlNamespace="Activities"
ClrNamespace="System.Workflow.Activities"
Assembly="System.Workflow.Activities" ?>
<?Mapping XmlNamespace="RuleConditions"
ClrNamespace="System.Workflow.Activities.Rules"
Assembly="System.Workflow.Activities" ?>
<SequentialWorkflow x:Class="WorkflowSeq.Workflow1"
x:CompileWith="Workflow1.xoml.cs" ID="Workflow1"
xmlns:x="Definition" xmlns="Activities">
<Code ExecuteCode="Mycode3" ID="code3" />
<Code ExecuteCode="Mycode1" ID="code1" />
</SequentialWorkflow>
See the above snippet of the XOML file. You can see how the behind code is linked
using the CompileWithattribute. Code forms the element of
the SequentialWorkflow tag. One of the best things with markup is we can change
the sequence just by changing the XOML file, we do not need to compile the whole
application again.
In the above snapshot, one of the things to know is the 3, 4, and 5 numbered
sections. These sections are not linked with the sample. But just to make you aware,
you can create and serialize any workflow and deserialize them again using the text
writer object.
DTSX
1) What is SSIS?
SSIS was first introduced with SQL Server 2005, which was the next
generation of SQL Server software after SQL Server 2000. SSIS is a form
of ETL (extraction, transformation and load), which is a database term
that integrates data scheduling and tasks. The SSIS engine automation
many data maintenance tasks, so you can update data without manually
firing procedures and imports.
2) How is SSIS different from DTS?
Older versions of SQL Server used DTS, which was similar to SSIS. DTS let
you create steps that you would then assign a priority order. With SSIS,
you can separate data from work flow, and SSIS has significantly better
performance than older DTS packages. While performance isnt always an
issue when running jobs during off-peak hours, its a problem when you
must run jobs during normal business hours. You can run SSIS during
business hours without too much performance degradation.
3) What is SSIS control flow integration?
When you create a package, you usually need some tasks to complete
before you can move on to the next task. SSIS lets you control the order in
which each data task is performed. This is important, because the wrong
data flow can cause major issues with your data and sometimes cause
severe data corruption.
4) What is data transformation?
Data transformation is a vague term, because you can pull data from any
format and transform it to any other format. That is the goal of data
transformation. In many database jobs, youll have data listed in a simple
file such as a CSV or Excel file. Your job is to automatically pull data from
this file and import it into your database tables. You can sometimes
perform data updates and do scrubbing to the data to clean it up,
because these flat files can contain raw data that needs to be better
formatted. All of this can be accomplished using an SSIS package.
5) What can you do in an SSIS task?
A task is one step in your SSIS job. A task can be almost database
transformation step. It can be connection to another database, importing
data from a file or database table or running a stored procedure against
your database tables. You can also customize tasks with the Microsoft
.NET language, which makes SSIS a very powerful tool with your
database.
There are three statuses after a task attempts to complete. The first status
is Success, which allows the next task to perform. You set what happens
after a task is successfully run. The next status is Failure. This status
seems self explanatory, but its very vague. A failure can be a number of
problems, and you must view your server logs and investigate the issues. A
failure will stop the rest of the SSIS job from running, so you must fix the
failed task to allow the rest of your transformation steps to run. Its not
always easy figuring out the problem, but you can run each task one by
one to help identify the issue.
The final status is Complete. This status tells you if the task is
completed, which means all steps within that task were fully completed.
7) What kind of containers can you use with SSIS packages?
There are three types of containers: sequence, for loops and for each
loops. A sequence container is a simple way to group similar tasks
together. Think of a sequence container as an organization container for
more complex SSIS packages.
A for loop contain is what you can use to repeat steps a certain number of
times. Perhaps you need to update records ten times. You can use this for
loop container to complete a number of tasks 10 times before moving on
to another step.
A for each loop can only be used in a collection. A collection is an
enumerated object. For instance, you can use the for each loop to a
specific number of records in a record set or a certain number of files in a
directory. The for each loop is better than the standard for loop, because
you dont accidentally make a mistake of looping through numerical
values too many times and causing an error in your SSIS package.
8) What kind of variables can you create?
You can create global variables and task level variables in SSIS. For
programmers, these variables are the same as global and function level
variables. A global variable is available to all tasks across the entire job.
Variables created in tasks are only available within that task.
LinQ
What is Language Integrated Query (LINQ)?
LINQ is a programming model that is the composition of general-purpose standard query operators
that allow you to work with data, regardless of the data source in any .NET based programming
language. It is the name given to a set of technologies based on the integration of query
capabilities into any .NET language.
Obtain the data source (The data source can be either an SQL database or an XML file)
Create a query
Write the basic syntax of a LINQ query in Visual Basic as well as in C#.
In Visual Basic, the basic syntax of a LINQ query starts with the From clause and ends with
the Select or Group Byclause. In addition, you can use the Where, Order By, and Order By
Descending clauses to perform additional functions, such as filtering data and generating the
data in a specific order.
In C#, the basic syntax of a LINQ query starts with the From clause and ends with
the Select or group by clause. In addition, you can use the where, orderby, and Orderby
descending clauses to perform additional functions, such as filtering data and generating the data
in a specific order.
A LINQ query is executed in the For Each statement in Visual Basic and in the foreach statement
in C#.
What is PLINQ?
PLINQ stands for Parallel Language Integrated Query. It is the parallel implementation of LINQ, in
which a query can be executed by using multiple processors. PLINQ ensures the scalability of
software on parallel processors in the execution environment. It is used where data grows rapidly,
such as in telecom industry or where data is heterogeneous.
PLINQ also supports all the operators of LINQ. In addition, you can query 'collections by using
PLINQ. It can also run several LINQ queries simultaneously and makes use of the processors on
the system. Apart from this, PLINQ uses parallel execution, which helps in running the queries
quickly. Parallel execution provides a major performance improvement to PLINQ over certain types
of legacy code, which takes too much time to execute.
What are the different Visual Basic features that support LINQ?
Visual Basic includes the following features that support LINQ:
Anonymous types - Enables you to create a new type based on a query result.
Implicitly typed variables - Enables the compiler to infer and assign a type when you
declare and initialize a variable.
Extension method - Enables you to extend an existing type with your own methods
without modifying the type itself.
the Skip clause to skip the first four strings in an array of strings and return the remaining array
of string.
The standard query operators are themselves a set of extension methods that
provide the LINQ query functionality for any type that implements
the IEnumerable<T> interface in Visual Basic. Is it True or False?
False, as it implements the IEnumerable(T) interface in Visual Basic and
the IEnumerable<T> interface is implemented in C#.
Before you query a DataSet object by using LINQ to DataSet, you must first
populate the dataset How can you do this?
You can load the data into the dataset by using different methods, such as:
LINQ to SQL - Refers to a component of.NET Framework version 3.5 that provides a runtime infrastructure to manage relational data as objects.
LINQ to DataSet - Refers to a component that makes it easier and faster to query over
data cached in a DataSet object.
Which command-line tool generates code and mapping for the LINQ to SQL
component of .NET Framework?
The SqlMetal.exe command-line tool generates code and map the LINQ to SQL component.
Name the control that exposes the LINQ features to Web developers through the
ASP.NET data-source control architecture.
The LinqDataSource control exposes the LINQ features to Web developers through the ASP.NET
data-source control architecture.
What is the difference between the Select clause and SelectMany() method in
LINQ?
Both the Select clause and SelectMany() method are used to produce a result value from a
source of values. The difference lies in the result set. The Select clause is used to produce one
result value for every source value. The result value is a collection that has the same number of
elements from the query. In contrast, the SelectMany() method produces a single result that
contains a concatenated collection from the query.
[QUESTIONS]
Now that we have talked about my qualifications, do you have any concerns
about me fulfilling the responsibilities of this position?
As my direct report in this position, what are the three top priorities you would
first like to see accomplished?
[This question, she says, effectively identifies the hot buttons of the hiring
manager, demonstrates that the candidate understands the priorities, and
underscores the candidates commitment to action by the final word in the
question. Remember, accomplish is a term dear to the heart of every hiring
manager.]
Keep it short.
Dont Interrupt
Getting to Yes
Asking Questions that Focus on What the Company Can Do for You
Reelaborate:
[
Whats the makeup of the team as far as experience? Am I going to be a mentor
or will I be mentored?
What does this company value the most and how do you think my work for you
will further these values?
Do team members typically eat lunch together or do they typically eat at their
desk?
Whats the most important thing I can do to help within the first 90 days of my
employment?
Do you have any questions or concerns about my ability to perform this job?
When top performers leave the company why do they leave and where do they
usually go?
What do you see in me? What are my strongest assets and possible weaknesses?
Do you have any concerns that I need to clear up in order to be the top
candidate?
Who are the coolest people on my team? What makes him or her cool? Can I
meet them?
]
+ Company info
+ Training programs? What? How etc..
+ Career info
+ How would yo describe your ideal candidate?
EXERCISE
I think it usually helps to ask your applicants to complete a simple coding exercise such as:
Write your own linked list class without using the built-in classes.
Write your own hashtable class without using the built-in classes.
Write a class that represents a binary tree. Write a method that traverses all nodes of the
tree.
Write a method to perform a binary search on an array without using built-in methods.
Draw a database schema for a blog. Each user only has one blog, each blog has many
categories, each category has many posts, and each post can belong to more than one
category. Ask your applicant to write queries to pull specific information out.
Next, look for specific technical know-how:
(Event handlers) Create a class with a custom event handler, create another class which
hooks onto the custom event handler.
(XML) Load an XML document and select all of the nodes with properties x, y, and z.
(Functional programming) Create a function that accepts another function as a
parameter. A Map or Fold function works really good for this.
(Reflection) Write a function which determines if a class has a particular attribute.
(Regex) Write a regular expression which removes all tags from a block of HTML.