Briefly, the basic difference between generic and non-generic collections:
- Non-Generic collections - These are the collections that can hold elements of different data types. It holds all elements as object type.
So it includes overhead of type conversions.
- Generic collections - These are the collections that can hold data of same type and we can decide what type of data that collections can hold.
Some advantages of generic collections - Type Safe, Secure, reduced overhead of type conversions.
- Non-Generic collections - These are the collections that can hold elements of different data types. It holds all elements as object type.
So it includes overhead of type conversions.
- Generic collections - These are the collections that can hold data of same type and we can decide what type of data that collections can hold.
Some advantages of generic collections - Type Safe, Secure, reduced overhead of type conversions.
All lambda expressions use the lambda operator =>, which is read as "goes to". The left side of the lambda operator specifies the input parameters (if any) and the right side holds the expression or statement block. The lambda expression x => x * x is read "x goes to x times x." This
Linq is always associated with Lambda Expressions. In .NET 2.0 we have the concept of Annonymous Methods that allows you to write function body inline without the need of writing a delegate function. Lambda Expression of .NET 3.5 is to consize the concept of Annonymous function writing.
//C#
delegate int DelType(int i);
DelType dd = delegate(int value)
{
return (value +2);
};
int i = dd(10);
---------------------------------------------------------------------------
======================================================================== What is a Worker Process? When the IIS Worker Process or the ASP.NET Worker Process starts a Web application, the Web application inherits the identity of the process if impersonation is disabled. (Impersonation is the process of allowing a thread to run under a different account from its process.) However, if impersonation is enabled, each Web application runs under the user account that is authenticated by IIS or the user account that is configured in the Web.config file. Impersonation can be enabled in either of the following two ways in Web.config:
This allows the Web application to run using the identity that was authenticated by IIS.
This allows the Web application to run using a specific identity.
Where can Viewstate be stored? Anywhere, stored in the file by the server at the time the page is returned to the client.
What is the effect of changing the web.config file in a running application? Resets the cache, app pool, and timing. IIS freaks out, destroys session and “first load” problem because this changes the HASH for the aspx Auth cookie so everyone needs needs to get a new auth cookie.
When/why would you make a windows form instead of an web application? When your volume of data is too high to warrant web traffic and data transfer
What is the difference between String and StringBuilder? Strings are immutable and stringbuilder by-passes this. When you concatenate two strings then a third objects is created (the original 2 and the newly created concatenated string object), the original two then sit on the Heap waiting to be destroyed by the Garbage Collection, an obvious waste of server resources. String.Format uses StringBuilder and ellimiates the overhead of adding an additional third object when two are concatenated.
Are there pointers in .NET? No (although there are delegates) pointers use variables that point to memory locations.
What is a Delegate? A delegate in C# is similar to a function pointer in C or C++. Using a delegate allows the programmer to encapsulate a reference to a method inside a delegate object. The delegate object can then be passed to code which can call the referenced method, without having to know at compile time which method will be invoked. Unlike function pointers in C or C++, delegates are object-oriented, type-safe, and secure.
What is the GAC? Where the .NET DLL’s live so that applications have access to these. “repository for DLL’s that respects versioning”
What is MSIL? Intermediate Language, the Compilers convert the high level code to the IL
Who is considered the father of modern computer science and what concepts did he bring forth that are fundamentally important to computer science as a whole? Alan Turing, He provided an influential formalization of the concept of the algorithm and computation with the Turing machine. With the Turing test, meanwhile, he made a significant and characteristically provocative contribution to the debate regarding artificial intelligence: whether it will ever be possible to say that a machine is conscious and can think.
He later worked at the National Physical Laboratory, creating one of the first designs for a stored-program computer, the ACE, although it was never actually built in its full form. In 1948, he moved to the University of Manchester to work on the Manchester Mark 1, then emerging as one of the world's earliest true computers.
During the Second World War Turing worked at Bletchley Park, the UK's code-breaking centre, and was for a time head of Hut 8, the section responsible for German naval cryptanalysis. He devised a number of techniques for breaking German ciphers, including the method of the bombe, an electromechanical machine that could find settings for the Enigma machine.
Turing Complete: A computational system that can compute every Turing-computable function is called Turing-complete (or Turing-powerful). Alternatively, such a system is one that can simulate a universal Turing machine. The concept of the Turing machine is based on the idea of a person executing a well-defined procedure by changing the contents of an infinite amount of ordered paper sheets that can contain one of a finite set of symbols. The person needs to remember one of a finite set of states and the procedure is formulated in very basic steps in the form of "If your state is 42 and the symbol you see is a '0' then replace this with a '1', remember the state 17, and go to the following sheet."
What is Silverlight? Microsoft Silverlight is a programmable web browser plugin that enables features such as animation, vector graphics and audio-video playback that characterize rich Internet applications. Version 2.0, released October 2008, brings additional interactivity features and support for .NET languages and development tools. It is compatible with multiple web browser products used on Microsoft Windows and Mac OS X operating systems. Mobile devices, starting with Windows Mobile 6 and Symbian (Series 60) phones, will also be supported. A third-party free software implementation named Moonlight is under development to bring compatible functionality to GNU/Linux.
What is SOAP? SOAP (Simple Object Application Protocol) is a light weight protocol intended for the exchanging of structured information in a decentralized, distributed environment. It uses XML technologies to define an extensible messaging framework providing a message construct that can be exchanged over a variety of underlying protocols. The framework has been designed to be independent of any particular programming model and other implementation specific semantics. The technological foundation that makes up Web services includes SOAP, the Web Service Description Language (WSDL), Universal Description, Discovery, and Integration (UDDI), and XML. Specifically, SOAP provides a heterogeneous mechanism to allow the invocation and communication between Web services. Some of the shortcomings of the SOAP 1.1 has been clarified, updated and corrected in SOAP 1.2. SOAP 1.2 contains a number of issues such as those on interoperability and ambiguities that resulted in differences of interpretation.
SOAP 1.1 is based on XML 1.0 and can only use HTTP POST headers to transmit SOAP messages. As a result, it isn't really suitable for wide-scale applications.
What’s the default file extension for a .NET web service? .asmx
What’s the difference between the GET and POST request methods? The GET method appends name/value pairs to the URL, allowing you to retrieve a resource representation. The big issue with this is that the length of a URL is limited (roughly 3000 char) resulting in data loss should you have to much stuff in the form on your page, so this method only works if there is a small number parameters.
The alternative to the GET method is the POST method. This method packages the name/value pairs inside the body of the HTTP request, which makes for a cleaner URL and imposes no size limitations on the forms output, basically its a no-brainer on which one to use. POST is also more secure but certainly not safe. Although HTTP fully supports CRUD, HTML 4 only supports issuing GET and POST requests through its various elements. This limitation has held Web applications back from making full use of HTTP, and to work around it, most applications overload POST to take care of everything but resource retrieval.
Describe briefly your opinions regarding source control: (I like centralized version control, I use version control on every project) Visual Sourse Safe is widely used in government, personally I prefer SubVersion to all that I have used, followed by Microsoft Team Foundation Server
What is OOP? Object-oriented programming may be seen as a collection of cooperating objects, as opposed to a traditional view in which a program may be seen as a group of tasks to compute ("subroutines"). In OOP, each object is capable of receiving messages, processing data, and sending messages to other objects.
Inheritance: ‘Subclasses’ are more specialized versions of a class, which inherit attributes and behaviors from their parent classes, and can introduce their own. Each of its sub-classes will inherit these members, meaning that the programmer only needs to write the code for them once.
Abstraction: Abstraction is simplifying complex reality by modeling classes appropriate to the problem, and working at the most appropriate level of inheritance for a given aspect of the problem.
Abstraction is also achieved through Composition. For example, a class Car would be made up of an Engine, Gearbox, Steering objects, and many more components. To build the Car class, one does not need to know how the different components work internally, but only how to interface with them, i.e., send messages to them, receive messages from them, and perhaps make the different objects composing the class interact with each other.
Encapsulation: Encapsulation conceals the functional details of a class from objects that send messages to it.
Encapsulation is achieved by specifying which classes may use the members of an object. The result is that each object exposes to any class a certain interface — those members accessible to that class. The reason for encapsulation is to prevent clients of an interface from depending on those parts of the implementation that are likely to change in future, thereby allowing those changes to be made more easily, that is, without changes to clients. Members are often specified as public, protected or private, determining whether they are available to all classes, sub-classes or only the defining class. Some languages go further: Java uses the default access modifier to restrict access also to classes in the same package, C# and VB.NET reserve some members to classes in the same assembly using keywords internal (C#) or Friend (VB.NET), and Eiffel and C++allow one to specify which classes may access any member.
Polymorphism: Polymorphism allows the programmer to treat derived class members just like their parent class' members. More precisely, Polymorphism in object-oriented programming is the ability of objects belonging to different data types to respond to method calls of methods of the same name, each one according to an appropriate type-specific behavior. One method, or an operator such as +, -, or *, can be abstractly applied in many different situations. If a Dog is commanded to speak(), this may elicit a bark(). However, if a Pig is commanded to speak(), this may elicit an oink(). They both inherit speak() from Animal, but their derived class methods override the methods of the parent class; this is Overriding Polymorphism.
Overloading Polymorphism is the use of one method signature, or one operator such as ‘+’, to perform several different functions depending on the implementation. The ‘+’ operator, for example, may be used to perform integer addition, float addition, list concatenation, or string concatenation. Any two subclasses of Number, such as Integer and Double, are expected to add together properly in an OOP language. The language must therefore overload the concatenation operator, ‘+’, to work this way. This helps improve code readability. How this is implemented varies from language to language, but most OOP languages support at least some level of overloading polymorphism. Many OOP languages also support Parametric Polymorphism, where code is written without mention of any specific type and thus can be used transparently with any number of new types. Pointers are an example of a simple polymorphic routine that can be used with many different types of objects.
Code Questions:
What is the coolest piece of code you have written? Has to be really cool
Can the constructor of a class be declared as static and if so why? Yes a constructor can be static. When a constructor is declared as static it is fired before all other constructors and is very useful in instantiating variables
What is WSDL? A WSDL file describes all the methods and method signatures, as well as the namespaces and the handling URL for the Web Service in an XML document. This document works very much like a type library does in COM for the client application to determine what functionality is available in the Web Service. Visual Studio.Net uses the WSDL file to create a Web Reference on the client side from your Web Service. It reads the WSDL file and based on the definitions found in the WSDL file creates a proxy class that mimics the interface of the Web Service. The resulting class is actual source code that you can look at. Because this class is actually linked into your client project the class becomes available in IntelliSense and you can actually see the full interface of the class as you type.
WSDL is a Service Description Language.
WSDL is a standard that is used to describe a Web Service's features and how the service should be called. As SOAP standards are getting more complex and include specific namespace references and complex data types the need for a type definition format to provide this information to the SOAP client tools became necessary. Microsoft especially embraced WSDL early on in it SOAP toolkits and relies heavily on the WSDL description – MS SOAP clients don't work without WSDL files. The SOAP spec does not require WSDL, but the ability to have a type definition in WSDL makes it easier to call a Web Service since the client application will not have to set various namespace references manually – this information can be retrieved from the WSDL file. Use of WSDL makes it possible to make single line method calls to various service methods that would otherwise require a number of custom configuration settings.
Define URI and URL? (are they the same thing?) URI (Uniform Resource Identifier) is the unique identifier that represents a service available in a RESTful application such as the World Wide Web.
The Uniform Resource Locator (URL) provides a way of uniquely specifying the location of a resource on the Internet
They are the same thing; URL has been replaced by URI
What is WCF? Can you give an example of when it’s used? Windows Communication Foundation, WCF is designed in accordance with Service oriented architecture principles to support Distributed computing where services are consumed by consumers. Clients can consume multiple services and services can be consumed by multiple clients. Services typically have a WSDL interface which any WCF client can use to consume the service, irrespective of which platform the service is hosted on. WCF implements many advanced web services (WS) standards such as WS-Addressing, WS-ReliableMessaging and WS-Security. WCF could be used when architecting a system that needs to be completely separated from its presentation layer allowing a Windows Forms, Silverlight, and Web Forms front end to interact with the same business logic layers of the system.
Explain an Abstract class An abstract class means that, no object of this class can be instantiated, but can make derivations of this. Abstract classes can have implementation within its methods or properties where as an Interface cannot have implementation within its methods or properties.
Explain a Sealed class. The sealed modifier is used to prevent derivation from a class. An error occurs if a sealed class is specified as the base class of another class. A sealed class cannot also be an abstract class.
The sealed modifier is primarily used to prevent unintended derivation, but it also enables certain run-time optimizations. In particular, because a sealed class is known to never have any derived classes, it is possible to transform virtual function member invocations on sealed class instances into non-virtual invocations.
Explain a Virtual Method: Abstract methods are required to be overridden, whereas virtual methods are not. Abstract methods are similar to C++ pure virtual methods, except C++ pure virtual methods may have an implementation associated with them, whereas C# abstract methods may not. Virtual methods, in contrast to abstract methods, are required to have an implementation associated with them. Virtual methods, along with interfaces, are the only means of implementing polymorphism within C#.
Can you give an example of when you might use reflection? Reflection is Microsoft's implementation of Code Introspection, which is the ability to have code that has Meta Data. For example: You cannot cast a string to an object so you must convert it into an object via Reflection.
What attributes are you familiar with, how have you used them? (inherit from the class System.Attibute) like Test and WebMethod, Serializable (cross Service Oriented Architecture gateway which renders an XML schema defining the Meta Data so look at WCF and Remoting or go into Session)
What is the name of the process that runs aspx code in XP? aspnet_wp.exe
What is new in 2.0?
- Generics and generic collections
- 64-bit platform support
- ADO.NET support for UDT (user defined types)
- ACL (access control list) support which grants/revokes permission to access a resource on a computer.
- Tons of new data control objects introduced to ASP.NET (GridView, new cache features, aspnet membership services, object/sql datasource skips codebehind binding. MasterPages, Themes, Web Application Project model (vs. Website model)
- Controls render output in XHTML 1.1 standards
- Debugger Edit & Continue Support
- Data Protection API: encrypt web.config, passwords, blocks of memory
In 3.5?
- WCF Web Programming Model: enables developers to build Web-style services with WCF. The Web Programming Model includes rich URI processing capability, support for all HTTP verbs including GET, and a simple programming model for working with a wide variety of message formats (including XML, JSON, and opaque binary streams)
- .NET compact Framework support for WCF (Windows Communication Foundation)
- AJAX-Enabled Website projects, AJAX Library
- Linq
- Forms authentication, roles management, and profiles can be consumed in a WCF-compatible application
- ListView Databound control and the LinqDataSource object
- Add-In and Extensibility support (discovery, activation, isolation, sandboxing, UI composition, Versioning)
- TimeZoneInfo
- Suite B cryptographic algorithm support published by the National Security Agency (NSA) including Advanced Encryption Standard (AES) with keys of 128 & 256 bit encryption, Secure Hash Algorithm (SHA-256 & SHA-384) for hashing
- Peer to Peer networking support (PNRP) Peer Name Resolution Protocol
What's the difference between a DataTable and a DataReader?
DataTable: opens the connection for less time so better for network performance, pulling back all the records and storing them for use.
DataReader: pulls back data one record at a time, leaving the connection open, while executing the same query over and over again to obtain the next record. While this is faster on small record sets it is problematic will larger amounts of data and can lead to memory leaks if left unclosed.
What are the different joins, and when would you use them? There are 4: Left Out, Right Out, full Inner, full Outer (x,y cartiesian product)
Explain "Having": Since you cannot do where’s after a Group By you add a Having which is basically a Where clause for filtering a Group By clause
What is the difference between Normalized & Denormalized, and when do you use which? Normalized means separate tables via foreign key relationship (historically inaccurate), Denormalized does not. You use Denormalized form when you have a large amount of data that you want to do calculations on its far greater performance to have Denormalized or you need Reporting)
What is an alternative to using cursors, and why would you use it? A Cursor is used to place you in the location of a record while you loop through other records. They are BAD, take up Temp Table memory, put a lock on the database record it’s on, and holds a lock in the Master database so that no other connection can be made to that record. An alternative is to use a for-loop and a while loop
What is the difference between an index, clustered index and trigger? A clustered index is how the B tree stores the index, you can have unlimited indexes because they are stored in memory but only one clustered index.
What is an interface, and why would you use one? The contract between two classes, although some argue that rather than a contract an interface is merely a means of enforcing uniform language between two classes. An interface can only contain declarations and is used to ensure that all classes that implement the interface conform to the "language" or "contact" required so that other classes can use these your class in a consistent and predictable way. Interfaces are commonly used in the Factory Design Pattern of software architecture.
Does C# support multiple inheritances? No
If not then how can we get around this? We can define multiple interfaces which classes can then implement in order to mimic the functionality of multiple inheritance
How do you bounce IIS from the command line? iisreset
Can you data model the following: User, Group, Permission. If we assume that a user may belong to many groups and may have many permissions. (How many permissions are in a group and how many groups can a user belong to?)
What do you use to decompile a dll? .NET reflector will decompile the DLL into either C# or VB.NET
In try, catch finally: If you call return from the catch, does the finally get executed? Yes, finally always gets executed and if an exception is caused in the finally block it can caused infinite loops
What is the difference between an implicit and explicit interface implementation?
Explicit implementation means the objects are only available when the class is. only shown when you cast the object (you have a method that you don’t want it to be part of the interface that conflicts with the method name) the explicit implementation keeps the interface members out of the class and out of intellisense. Explicit method implementation cannot be virtual and cannot be abstract.
Implicit Implementation: can be abstract, the “public” keyword is attached to the method
How do you create a custom event? (Must declare a delegate in the even handler) need event declaration and something to initiate that event.
Give an example of cross browser difficulties: DOM is traversed differently, Z-indexes are handled different, different color palettes (transparent color is not part of IE 6 and therefore causes transparent images to render with a gray color where they should be transparent) are rendered differently
How can you hide a div using css? Visibility: hidden (makes it take up the space it will normally take up), Display: none (does not take up the space it normally would)
How can you hide a div using javascript? .style.display = none
Do you use any javascript libraries? Which ones? Why? jQuery, it hides all the cross-browser problems for me, gives me a cleaner interface to traverse the DOM, uses CSS selectors which allows me to use it in an un-obtrusive manner
Describe AJAX. Ajax (asynchronous JavaScript and XML), or AJAX, is a group of interrelated web development techniques used for creating interactive web applications or rich Internet applications. With Ajax, web applications can retrieve data from the server asynchronously in the background without interfering with the display and behavior of the existing page. Data is retrieved using a variety of means such as JSON and XML
Describe some disadvantages of AJAX. Two connection limit in browsers is a major constraint and can cause the page to appear to have locked up because the limit has been exceeded, transfering large amount of data can cause the same perception. Ajax has a high number of network calls because your increasing the number of wires in order to pass the data back and forth, if you do GET you can do cross browser but your limited to roughly 3,000 char per request but if you use POST you have an unlimited number of char. however you cannot do cross browser in POST.
What is the "png problem" in IE6? Transparency is not in the IE6 color palette
Why would you use an interface vs. a base class? When you have a large number of objects that do the same basic functions then you use a base class (a good example is System.Web.UI.Page which puts all the core page functions in this page class, allowing what is unique to a page to be separate from this core functionality and instead placed in the .aspx pages which will inherit from System.Web.UI.Page), otherwise an interface would be used.
What do you think about ORM?
ORM is useful in getting you started but becomes a problem in long-term maintenance as you are committed to the ORM you initially select. Another disadvantage is that if the schema is changed the application is not shielded from the change. The relational schema of the data is hard coded into the application. If the data model changes the ORM object won’t know until they are regenerated by the ORM software.
Name some ORMs?
SubSonic, Linq, ADO.NET Entity Framework (released with .NET 3.5 SP1), NHibernate
What ORM patterns have you used?
ActiveRecord pattern, via SubSonic, which allows for the Lazy Loading of objects.
What is Lazy Loading, what is its opposite?
Lazy Loading refers to a design pattern commonly used in computer programming to defer initialization of an object until the point at which it is needed. It can contribute to efficiency in the program's operation if properly and appropriately used.
Eager Loading is the opposite of Lazy Loading.
Name the ways Lazy Loading can be implemented and describe each: There are 4 ways lazy loading can be implemented
Lazy Initialization: The object to be lazily loaded is initially set to NULL, and every request for the object checks for NULL and creates it “on the fly” before returning it first
Virtual Proxy: a virtual proxy is an object that “looks like” the object that is to be lazily loaded. Both the object and the proxy implement the same interface, with the proxy providing a wrapper that instantiates and initialize the object when one of its properties is accessed for the first time
Ghost: a ghost is the object that is to be loaded in a partial state. It may only contain the objects identifier, but it loads its own data the first time one of its properties is accessed.
Value Holder: a value holder is a generic object that handles the lazy loading behavior, and appears in place of the object’s data fields.
What do you think about code generation? SubSonic is a code generator (ORM generator) which is cool. I like it where it can help me automate mundane tasks, it can help you get started but it doesn’t facilitate long-term maintenance making it not practical.
What’s the largest number of concurrent users any app you’ve worked on has supported? (had about 500 concurrent users and can handle about 2000, looking at logs shows how many transaction you support per second which you figure out how many requests a thread can process per second multiplied by the number of threads)
How did you scale to that?
We implemented a Web Farm behind a Proxy Server that handled request distribution. We set up a separate SQL box and a mirrored backup
Any problems scaling? I/O is the biggest bottleneck, we have to closely watch our code to reduce the number of database transactions and page size which is a constant battle.
How do you convert a number that is input in a textbox (string) to an int, float, double, etc.?
char.IsNumber(string s);
int.TryParse(string s, out x);
What is the difference between a double & a decimal? Why would you use one vs. another? Which would you use for money and why?
a double and a float are calculated and can result in “off by one” errors. All the Math functions built into C# only take double. If you were going to write a Money app you would need to rewrite the Math class and the Rounding methods because these built in classes uses Bankers Rounding which cause you to loose the remainder on any rounding.
What is OLAP?
Databases store information about business transactions, plus other data such as employee records. Those types of systems are called online transaction processing (OLTP) databases. OLTP data contains a wealth of information that can help you make informed decisions about your business. The process of analyzing your data for that type of information, and the data that results, are collectively called business intelligence.
You can spend a lot of time and money trying to extract business intelligence information from your database. The time and expense involved in retrieving answers (queried information) from databasesmeans that a lot of business intelligence information often goes unused. The reason: most operational databases are designed to store your data, not to help you analyze it. The solution: an online analytical processing (OLAP) database, a specialized database designed to help you extract business intelligence information from your data in a structured manner.
Microsoft® SQL Server™ 2000 (and newer versions) Analysis Services is a high-performance online analytical processing (OLAP) tool for performing data analysis and data mining.
MVC, MVP and MVVM are design patterns which come under the presentation pattern category and they help to remove any kind of cluttered code in UI like manipulation of user interfaces and maintaining state. Thus keeping your UI code cleaner and better to maintain.
MVC(Model view controller) pattern divides the architecture into 3 parts model, view and controller. The first request comes to the controller and the controller then decides which view to be displayed and ties up the model with the view accordingly.
MVP (Model view presenter) has the same goals as MVC i.e.
separating the UI from the model. It does the same by using a presenter class. The UI talks via an interface to the presenter class and the presenter class talks with the model.
separating the UI from the model. It does the same by using a presenter class. The UI talks via an interface to the presenter class and the presenter class talks with the model.
MVVM is an architectural pattern with the focus of removing UI
cluttered code. It does the same by using an extra class called as view
model. MVVM is mostly suitable for Silverlight and WPF projects because of the rich bindings provided by the technologies.
cluttered code. It does the same by using an extra class called as view
model. MVVM is mostly suitable for Silverlight and WPF projects because of the rich bindings provided by the technologies.
Difference between WCF and Web service
Web service is a part of WCF. WCF offers much more flexibility and portability to develop a service when comparing to web service. Still we are having more advantages over Web service, following table provides detailed difference between them.
Features | Web Service | WCF |
Hosting | It can be hosted in IIS | It can be hosted in IIS, windows activation service, Self-hosting, Windows service |
Programming | [WebService] attribute has to be added to the class | [ServiceContraact] attribute has to be added to the class |
Model | [WebMethod] attribute represents the method exposed to client | [OperationContract] attribute represents the method exposed to client |
Operation | One-way, Request- Response are the different operations supported in web service | One-Way, Request-Response, Duplex are different type of operations supported in WCF |
XML | System.Xml.serialization name space is used for serialization | System.Runtime.Serialization namespace is used for serialization |
Encoding | XML 1.0, MTOM(Message Transmission Optimization Mechanism), DIME, Custom | XML 1.0, MTOM, Binary, Custom |
Transports | Can be accessed through HTTP, TCP, Custom | Can be accessed through HTTP, TCP, Named pipes, MSMQ,P2P, Custom |
Protocols | Security | Security, Reliable messaging, Transactions |
EndPoint
WCF Service is a program that exposes a collection of Endpoints. Each Endpoint is a portal for communicating with the world.
All the WCF communications are take place through end point. End point consists of three components.
Address
Basically URL, specifies where this WCF service is hosted .Client will use this url to connect to the service. e.g
http://localhost:8090/MyService/SimpleCalculator.svc
Binding
Binding will describes how client will communicate with service. There are different protocols available for the WCF to communicate to the Client. You can mention the protocol type based on your requirements.
A binding has several characteristics, including the following:
- Transport -Defines the base protocol to be used like HTTP, Named Pipes, TCP, and MSMQ are some type of protocols.
- Encoding (Optional) - Three types of encoding are available-Text, Binary, or Message Transmission Optimization Mechanism (MTOM). MTOM is an interoperable message format that allows the effective transmission of attachments or large messages (greater than 64K).
- Protocol(Optional) - Defines information to be used in the binding such as Security, transaction or reliable messaging capability
The following table gives some list of protocols supported by WCF binding.
Binding | Description |
BasicHttpBinding | Basic Web service communication. No security by default |
WSHttpBinding | Web services with WS-* support. Supports transactions |
WSDualHttpBinding | Web services with duplex contract and transaction support |
WSFederationHttpBinding | Web services with federated security. Supports transactions |
MsmqIntegrationBinding | Communication directly with MSMQ applications. Supports transactions |
NetMsmqBinding | Communication between WCF applications by using queuing. Supports transactions |
NetNamedPipeBinding | Communication between WCF applications on same computer. Supports duplex contracts and transactions |
NetPeerTcpBinding | Communication between computers across peer-to-peer services. Supports duplex contracts |
NetTcpBinding | Communication between WCF applications across computers. Supports duplex contracts and transactions |
Contract
Collection of operation that specifies what the endpoint will communicate with outside world. Usually name of the Interface will be mentioned in the Contract, so the client application will be aware of the operations which are exposed to the client. Each operation is a simple exchange pattern such as one-way, duplex and request/reply.
Below figure illustrate the functions of Endpoint
Example:
Endpoints will be mentioned in the web.config file on the created service.
<system.serviceModel>
<services>
<service name="MathService"
behaviorConfiguration="MathServiceBehavior">
<endpoint
address="http://localhost:8090/MyService/MathService.svc" contract="IMathService"
binding="wsHttpBinding"/>
</service>
</services>
<behaviors>
<serviceBehaviors>
<behavior name="MathServiceBehavior">
<serviceMetadata httpGetEnabled="True"/>
<serviceDebug includeExceptionDetailInFaults="true" />
</behavior>
</serviceBehaviors>
</behaviors>
</system.serviceModel>
Binding and Behavior
Binding
Simple definition for Binding describes how the client will communicate with service. We can understand with an example.
Consider a scenario say, I am creating a service that has to be used by two type of client. One of the client will access SOAP using http and other client will access Binary using TCP. How it can be done? With Web service it is very difficult to achieve, but in WCF its just we need to add extra endpoint in the configuration file.
<system.serviceModel>
<services>
<service name="MathService"
behaviorConfiguration="MathServiceBehavior">
<endpoint address="http://localhost:8090/MyService/MathService.svc"
contract="IMathService"
binding="wsHttpBinding"/>
<endpoint address="net.tcp://localhost:8080/MyService/MathService.svc"
contract="IMathService"
binding="netTcpBinding"/>
</service>
</services>
<behaviors>
<serviceBehaviors>
<behavior name="MathServiceBehavior">
<serviceMetadata httpGetEnabled="True"/>
<serviceDebug includeExceptionDetailInFaults="true" />
</behavior>
</serviceBehaviors>
</behaviors>
</system.serviceModel>
See how simple it is in WCF. Microsoft is making everything simple.cording to its scope: common behaviors affect all endpoints globally, service behaviors affect only service-related aspects, endpoint behaviors affect only endpoint-related properties, and operation-level behaviors affect particular operations.
Example:
In the below configuration information, I have mentioned the Behavior at Service level. In the service behavior I have mention the servieMetadata node with attribute httGetEnabled='true'. This attribute will specifies the publication of the service metadata. Similarly we can add more behavior to the service.
<system.serviceModel>
<services>
<service name="MathService"
behaviorConfiguration="MathServiceBehavior">
<endpoint address="" contract="IMathService"
binding="wsHttpBinding"/>
</service>
</services>
<behaviors>
<serviceBehaviors>
<behavior name="MathServiceBehavior">
<serviceMetadata httpGetEnabled="True"/>
<serviceDebug includeExceptionDetailInFaults="true" />
</behavior>
</serviceBehaviors>
</behaviors>
</system.serviceModel>
Note:
Application can be controlled either through coding, configuring or through combination of both. Specification mention in the configuration can also be overwritten in code.
Contracts and Service Host
Contracts
In WCF, all services are exposed as contracts. Contract is a platform-neutral and standard way of describing what the service does. Mainly there are four types of contracts available in WCF
Service Contract
Service contracts describe the operation that service can provide. For Eg, a Service provide to know the temperature of the city based on the zip code, this service is called as Service contract. It will be created using Service and Operational Contract attribute.
To know more on Service contract see Service contract tutorial.
Data Contract
Data contract describes the custom data type which is exposed to the client. This defines the data types, that are passed to and from service. Data types like int, string are identified by the client because it is already mention in XML schema definition language document, but custom created class or data types cannot be identified by the client e.g. Employee data type. By using DataContract we can make client to be aware of Employee data type that are returning or passing parameter to the method.
To know more on DataContract see DataContract tutorial.
Message Contract
Default SOAP message format is provided by the WCF runtime for communication between Client and service. If it is not meeting your requirements then we can create our own message format. This can be achieved by using Message Contract attribute.
To know more on Message Contract see Message contract tutorial.
Fault Contract
Suppose the service I consumed is not working in the client application. I want to know the real cause of the problem. How I can know the error? For this we are having Fault Contract. Fault Contract provides documented view for error occurred in the service to client. This helps us to easy identity, what error has occurred.
To know more on Fault Contract see Fault Contract tutorial.
Service Host
Service Host object is in the process of hosting the WCF service and registering endpoints. It loads the service configuration endpoints, apply the settings and start the listeners to handle the incoming request. System.ServiceModel.ServiceHost namespace hold this object. This object is created while self hosting the WCF service.
In the below example you can find that WCF service is self hosted using console application.
//Creating uri for the hosting the service
Uri uri = new Uri("http://localhost/CategoryService");
//Creating the host object for MathService
ServiceHost host = new ServiceHost(typeof(CategoryService), uri);
//Adding endpoint to the Host object
host.AddServiceEndpoint(typeof(ICategoryService),new WSHttpBinding(), uri);
host.Open(); //Hosting the Service
Console.WriteLine("Waiting for client invocations");
Console.ReadLine();
host.Close();
Message and Channel
Message
WCF Message is the unit of data exchange between client and service. It consists of several parts, including a body and headers.
WCF Runtime
WCF runtime is the set of object responsible for sending and receiving message. For example formatting the message, applying security and transmitting and receiving message using various protocol.
Channels:
Channels are the core abstraction for sending message to and receiving message from an Endpoint. Broadly we can categories channels as
Transport Channels
- Handles sending and receiving message from network. Protocols like HTTP, TCP name pipes and MSMQ.
Protocol Channels
- Implements SOAP based protocol by processing and possibly modifying message. e.g. WS-Security and WS-Reliability.
WCF Client and Metadata
WCF Client
WCF client is a client application creates to expose the service operations as method. Any application can host a WCF client, including an application that host a service. Therefore it is possible to create a service that includes WCF clients of other services.
A client application is a managed application that uses a WCF client to communicate with another application. To create a client application for a WCF service requires the following steps:
1. Get the Proxy class and service end point information
Using SvcUtil.exe we can create proxy class for the service and configuration information for endpoints. Example type the following sentence in the Visual studio command prompt, this will generate the class file and configuration file which contain information about the endpoints.
svcutil /language:vb /out:ClientCode.vb /config:app.config http://localhost:8090/MyService/SimpleCalculator.svc?wsdl
2. Call operations.
Add this class files in the client application. Then create the object for this class and invoke the service operation. Configuration information we got from the above step has to be added to the client application configuration file. When the client application calls the first operation, WCF automatically opens the underlying channel. This underlying channel is closed, when the object is recycled.
//Creating the proxy on client side
MyCalculatorServiceProxy.MyServiceProxy proxy
= new MyCalculatorServiceProxy.MyServiceProxy();
Console.WriteLine("Counter: " + proxy.MyMethod());
3. Close the WCF client object.
After using the object created in the above steps, we have to dispose the object. Channel will be closed with the service, when the object is cleared.
Metadata
Characteristics of the service are described by the metadata. This metadata can be exposed to the client to understand the communication with service. Metadata can be set in the service by enabling the ServiceMetadata node inside the servcieBehaviour node of the service configuration file.
<system.serviceModel>
<services>
<service name="MathService"
behaviorConfiguration="MathServiceBehavior">
<endpoint address="" contract="IMathService"
binding="wsHttpBinding"/>
</service>
</services>
<behaviors>
<serviceBehaviors>
<behavior name="MathServiceBehavior">
<serviceMetadata httpGetEnabled="True"/>
<serviceDebug includeExceptionDetailInFaults="true" />
</behavior>
</serviceBehaviors>
</behaviors>
</system.serviceModel>
This metadata can be viewed while creating WCF client application using SvcUtil.exe
WCF Architecture
The following figure illustrates the major components of WCF.
Figure 1: WCF Architecture
Contracts
Contracts layer are next to that of Application layer. Developer will directly use this contract to develop the service. We are also going to do the same now. Let us see briefly what these contracts will do for us and we will also know that WCF is working on message system.
Service contracts
- Describe about the operation that service can provide. Example, Service provided to know the temperature of the city based on the zip code, this service we call as Service contract. It will be created using Service and Operational Contract attribute.
Data contract
- It describes the custom data type which is exposed to the client. This defines the data types, are passed to and from service. Data types like int, string are identified by the client because it is already mention in XML schema definition language document, but custom created class or datatype cannot be identified by the client e.g. Employee data type. By using DataContract we can make client aware that we are using Employee data type for returning or passing parameter to the method.
Message Contract
- Default SOAP message format is provided by the WCF runtime for communication between Client and service. If it is not meeting your requirements then we can create our own message format. This can be achieved by using Message Contract attribute.
Policies and Binding
- Specify conditions required to communicate with a service e.g security requirement to communicate with service, protocol and encoding used for binding.
Service Runtime
- It contains the behaviors that occur during runtime of service.
- Throttling Behavior- Controls how many messages are processed.
- Error Behavior - Specifies what occurs, when internal error occurs on the service.
- Metadata Behavior - Tells how and whether metadata is available to outside world.
- Instance Behavior - Specifies how many instance of the service has to be created while running.
- Transaction Behavior - Enables the rollback of transacted operations if a failure occurs.
- Dispatch Behavior - Controls how a message is processed by the WCF Infrastructure.
Messaging
- Messaging layer is composed of channels. A channel is a component that processes a message in some way, for example, by authenticating a message. A set of channels is also known as a channel stack. Channels are the core abstraction for sending message to and receiving message from an Endpoint. Broadly we can categories channels as
- Transport Channels
Handles sending and receiving message from network. Protocols like HTTP, TCP, name pipes and MSMQ.
- Protocol Channels
Implements SOAP based protocol by processing and possibly modifying message. E.g. WS-Security and WS-Reliability.
Activation and Hosting
- Services can be hosted or executed, so that it will be available to everyone accessing from the client. WCF service can be hosted by following mechanism
- IIS
Internet information Service provides number of advantages if a Service uses Http as protocol. It does not require Host code to activate the service, it automatically activates service code.
- Windows Activation Service
(WAS) is the new process activation mechanism that ships with IIS 7.0. In addition to HTTP based communication, WCF can also use WAS to provide message-based activation over other protocols, such as TCP and named pipes.
- Self-Hosting
WCF service can be self hosted as console application, Win Forms or WPF application with graphical UI.
- Windows Service
WCF can also be hosted as a Windows Service, so that it is under control of the Service Control Manager (SCM).
Binding
Binding will describes how client will communicate with service. There are different protocols available for the WCF to communicate to the Client. You can mention the protocol type based on your requirements.
Binding has several characteristics, including the following:
- Transport
Defines the base protocol to be used like HTTP, Named Pipes, TCP, and MSMQ are some type of protocols.
- Encoding (Optional)
Three types of encoding are available-Text, Binary, or Message Transmission Optimization Mechanism (MTOM). MTOM is an interoperable message format that allows the effective transmission of attachments or large messages (greater than 64K).
- Protocol(Optional)
Defines information to be used in the binding such as Security, transaction or reliable messaging capability
Types of Binding
Let us see more detailed on predefined binding
BasicHttpBinding
- It is suitable for communicating with ASP.NET Web services (ASMX)-based services that comfort with WS-Basic Profile conformant Web services.
- This binding uses HTTP as the transport and text/XML as the default message encoding.
- Security is disabled by default
- This binding does not support WS-* functionalities like WS- Addressing, WS-Security, WS-ReliableMessaging
- It is fairly weak on interoperability.
WSHttpBinding
- Defines a secure, reliable, interoperable binding suitable for non-duplex service contracts.
- It offers lot more functionality in the area of interoperability.
- It supports WS-* functionality and distributed transactions with reliable and secure sessions using SOAP security.
- It uses HTTP and HTTPS transport for communication.
- Reliable sessions are disabled by default.
WSDualHttpBinding
This binding is same as that of WSHttpBinding, except it supports duplex service. Duplex service is a service which uses duplex message pattern, which allows service to communicate with client via callback.
In WSDualHttpBinding reliable sessions are enabled by default. It also supports communication via SOAP intermediaries.
WSFederationHttpBinding
This binding support federated security. It helps implementing federation which is the ability to flow and share identities across multiple enterprises or trust domains for authentication and authorization. It supports WS-Federation protocol.
NetTcpBinding
This binding provides secure and reliable binding environment for .Net to .Net cross machine communication. By default it creates communication stack using WS-ReliableMessaging protocol for reliability, TCP for message delivery and windows security for message and authentication at run time. It uses TCP protocol and provides support for security, transaction and reliability.
NetNamedPipeBinding
This binding provides secure and reliable binding environment for on-machine cross process communication. It uses NamedPipe protocol and provides full support for SOAP security, transaction and reliability. By default it creates communication stack with WS-ReliableMessaging for reliability, transport security for transfer security, named pipes for message delivery and binary encoding.
NetMsmqBinding
- This binding provides secure and reliable queued communication for cross-machine environment.
- Queuing is provided by using MSMQ as transport.
- It enables for disconnected operations, failure isolation and load leveling
NetPeerTcpBinding
- This binding provides secure binding for peer-to-peer environment and network applications.
- It uses TCP protocol for communication
- It provides full support for SOAP security, transaction and reliability.
Throttling
WCF throttling provides some properties that you can use to limit how many instances or sessions are created at the application level. Performance of the WCF service can be improved by creating proper instance.
Attribute | Description |
maxConcurrentCalls | Limits the total number of calls that can currently be in progress across all service instances. The default is 16. |
maxConcurrentInstances | The number of InstanceContext objects that execute at one time across a ServiceHost. The default is Int32.MaxValue. |
maxConcurrentSessions | A positive integer that limits the number of sessions a ServiceHost object can accept. The default is 10. |
Service Throttling can be configured either Adminstractive or Programatically
Administrative(configuration file)
Using tag of the Service Behavior, you can configure the maxConcurrentCalls, maxConcurrentInstances , maxConcurrentSessions property as shown below.
<system.serviceModel>
<services >
<service behaviorConfiguration="ServiceBehavior" name="MyService">
<endpoint address="" binding="wsHttpBinding" contract="IMyService">
<identity>
<dns value="localhost"/>
</identity>
</endpoint>
<endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange"/>
</service>
</services>
<behaviors>
<serviceBehaviors>
<behavior name="ServiceBehavior">
<serviceMetadata httpGetEnabled="true"/>
<serviceDebug includeExceptionDetailInFaults="true "/>
<serviceThrottling maxConcurrentCalls="500"
maxConcurrentInstances ="100"
maxConcurrentSessions ="200"/>
</behavior>
</serviceBehaviors>
</behaviors>
</system.serviceModel>
Programming Model
Use ServiceThrottlingBehavior object to set concurrent calls, session and instance property.
ServiceHost host = new ServiceHost(typeof(MyService));
ServiceThrottlingBehavior throttle
= host.Description.Behaviors.Find();
if (throttle == null)
{
throttle = new ServiceThrottlingBehavior();
throttle.MaxConcurrentCalls = 500;
throttle.MaxConcurrentSessions = 200;
throttle.MaxConcurrentInstances = 100;
host.Description.Behaviors.Add(throttle);
}
host.Open();
========================================================================
J-QUERY
The $() factory function:
All type of selectors available in jQuery, always start with the dollar sign and parentheses: $().
The factory function $() makes use of following three building blocks while selecting elements in a given document:
jQuery | Description |
Tag Name: | Represents a tag name available in the DOM. For example $('p') selects all paragraphs in the document. |
Tag ID: | Represents a tag available with the given ID in the DOM. For example $('#some-id') selects the single element in the document that has an ID of some-id. |
Tag Class: | Represents a tag available with the given class in the DOM. For example $('.some-class') selects all elements in the document that have a class of some-class. |
All the above items can be used either on their own or in combination with other selectors. All the jQuery selectors are based on the same principle except some tweaking.
How to use Selectors?
The selectors are very useful and would be required at every step while using jQuery. They get the exact element that you want from your HTML document.
Following table lists down few basic selectors and explains them with examples.
Selector | Description |
Selects all elements which match with the given element Name. | |
Selects a single element which matches with the given ID | |
Selects all elements which match with the given Class. | |
Selects all elements available in a DOM. | |
Selects the combined results of all the specified selectors E, F or G. |
Similar to above syntax and examples, following examples would give you understanding on using different type of other useful selectors:
- $('*'): This selector selects all elements in the document.
- $("p > *"): This selector selects all elements that are children of a paragraph element.
- $("#specialID"): This selector function gets the element with id="specialID".
- $(".specialClass"): This selector gets all the elements that have the class of specialClass.
- $("li:not(.myclass)"): Selects all elements matched by
- that do not have class="myclass".
- $("a#specialID.specialClass"): This selector matches links with an id of specialID and a class of specialClass.
- $("p a.specialClass"): This selector matches links with a class of specialClass declared within elements.
- $("ul li:first"): This selector gets only the first
- element of the
- .
- $("#container p"): Selects all elements matched by that are descendants of an element that has an id of container.
- $("li > ul"): Selects all elements matched by
- that are children of an element matched by
- $("strong + em"): Selects all elements matched by that immediately follow a sibling element matched by .
- $("p ~ ul"): Selects all elements matched by
- that follow a sibling element matched by .
- $("code, em, strong"): Selects all elements matched by
or or .
$("p strong, .myclass"): Selects all elements matched by that are descendants of an element matched by as well as all elements that have a class of myclass.
$(":empty"): Selects all elements that have no children.
$("p:empty"): Selects all elements matched by that have no children.
$("div[p]"): Selects all elements matched by
that contain an element matched by .$("p[.myclass]"): Selects all elements matched by that contain an element with a class of myclass.
$("a[@rel]"): Selects all elements matched by that have a rel attribute.
$("input[@name=myname]"): Selects all elements matched by that have a name value exactly equal to myname.
$("input[@name^=myname]"): Selects all elements matched by that have a name value beginning with myname.
$("a[@rel$=self]"): Selects all elements matched by that have a class value ending with bar
$("a[@href*=domain.com]"): Selects all elements matched by that have an href value containing domain.com.
$("li:even"): Selects all elements matched by
that have an even index value.
$("tr:odd"): Selects all elements matched by that have an odd index value.
$("li:first"): Selects the first
element.
$("li:last"): Selects the last
element.
$("li:visible"): Selects all elements matched by
that are visible.
$("li:hidden"): Selects all elements matched by
that are hidden.
$(":radio"): Selects all radio buttons in the form.
$(":checked"): Selects all checked boxex in the form.
$(":input"): Selects only form elements (input, select, textarea, button).
$(":text"): Selects only text elements (input[type=text]).
$("li:eq(2)"): Selects the third
element
$("li:eq(4)"): Selects the fifth
element
$("li:lt(2)"): Selects all elements matched by
element before the third one; in other words, the first two
elements.
$("p:lt(3)"): selects all elements matched by elements before the fourth one; in other words the first three
elements.$("li:gt(1)"): Selects all elements matched by
after the second one.
$("p:gt(2)"): Selects all elements matched by after the third one.
$("div/p"): Selects all elements matched by that are children of an element matched by
.$("div//code"): Selects all elements matched by
that are descendants of an element matched by
.$("//p//a"): Selects all elements matched by
that are descendants of an element matched by
$("li:first-child"): Selects all elements matched by
that are the first child of their parent.
$("li:last-child"): Selects all elements matched by
that are the last child of their parent.
$(":parent"): Selects all elements that are the parent of another element, including text.
$("li:contains(second)"): Selects all elements matched by
that contain the text second.
You can use all the above selectors with any HTML/XML element in generic way. For example if selector $("li:first") works for - $("code, em, strong"): Selects all elements matched by
element then $("p:first") would also work for element.
Get Attribute Value:
The attr() method can be used to either fetch the value of an attribute from the first element in the matched set or set attribute values onto all matched elements.
Example:
Following is a simple example which fetches title attribute of tag and setvalue with the same value:
the title This is first paragraph.
This is second paragraph.
Set Attribute Value:
The attr(name, value) method can be used to set the named attribute onto all elements in the wrapped set using the passed value.
Example:
Following is a simple example which set src attribute of an image tag to a correct location:
the title
Applying Styles:
The addClass( classes ) method can be used to apply defined style sheets onto all the matched elements. You can specify multiple classes separated by space.
Example:
Following is a simple example which set src attribute of an image tag to a correct location:
the title This is first paragraph.
This is second paragraph.Useful Attribute Methods:
Following table lists down few useful methods which you can use to manipulate attributes and properties:MethodsDescriptionSet a key/value object as properties to all matched elements.Set a single property to a computed value, on all matched elements.Remove an attribute from each of the matched elements.Returns true if the specified class is present on at least one of the set of matched elements.Removes all or the specified class(es) from the set of matched elements.Adds the specified class if it is not present, removes the specified class if it is present.Get the html contents (innerHTML) of the first matched element.Set the html contents of every matched element.Get the combined text contents of all matched elements.Set the text contents of all matched elements.Get the input value of the first matched element.Set the value attribute of every matched element if it is called on but if it is called on· $("#myID").attr("custom") : This would return value of attribute custom for the first element matching with ID myID.· $("img").attr("alt", "Sample Image"): This sets the alt attribute of all the images to a new value "Sample Image".· $("input").attr({ value: "", title: "Please enter a value" }); : Sets the value of all elements to the empty string, as well as sets the title to the string Please enter a value.· $("a[href^=http://]").attr("target","_blank"): Selects all links with an href attribute starting with http:// and set its target attribute to _blank· $("a").removeAttr("target") : This would remove target attribute of all the links.· $("form").submit(function() {$(":submit",this).attr("disabled", "disabled");}); : This would modify the disabled attribute to the value "disabled" while clicking Submit button.· $("p:last").hasClass("selected"): This return true if lasttag has associated classselected.· $("p").text(): Returns string that contains the combined text contents of all matchedelements.· $("p").text("Hello World"): This would set "Hello World" as text content of the matchingelements· $("p").html() : This returns the HTML content of the all matching paragraphs.· $("div").html("Hello World") : This would set the HTML content of all matchingto Hello World.· $("input:checkbox:checked").val() : Get the first value from a checked checkbox· $("input:radio[name=bar]:checked").val(): Get the first value from a set of radio buttons· $("button").val("Hello") : Sets the value attribute of every matched element
No comments:
Post a Comment