Purpose
|
||||
|
Creational
|
Structural
|
Behavioral
|
|
Scope
|
Class
|
|
|
|
Object
|
|
|
|
Technical Archive
A technical library where you can find a fix for your bug...!!
Tuesday, June 17, 2014
Classification of Design Patterns
Tuesday, December 6, 2011
OPENDATASOURCE load data from excel
sp_configure 'show advanced options', 1;
RECONFIGURE;
sp_configure 'Ad Hoc Distributed Queries', 1;
RECONFIGURE;
GO
Drop TABLE #myTable
CREATE TABLE #myTable
(
C1 ntext,
C2 ntext,
C3 ntext,
C4 ntext,
C5 ntext,
C6 ntext,
C7 ntext,
C8 ntext,
)
SELECT * INTO #myTable FROM OPENDATASOURCE('Microsoft.Jet.OLEDB.4.0','Data Source=E:\RegStuff\Downloads\datafilesandlocationdetails\crida installation.xlsx;Extended Properties=Excel 8.0')...[Sheet2$]
select * from #myTable
RECONFIGURE;
sp_configure 'Ad Hoc Distributed Queries', 1;
RECONFIGURE;
GO
Drop TABLE #myTable
CREATE TABLE #myTable
(
C1 ntext,
C2 ntext,
C3 ntext,
C4 ntext,
C5 ntext,
C6 ntext,
C7 ntext,
C8 ntext,
)
SELECT * INTO #myTable FROM OPENDATASOURCE('Microsoft.Jet.OLEDB.4.0','Data Source=E:\RegStuff\Downloads\datafilesandlocationdetails\crida installation.xlsx;Extended Properties=Excel 8.0')...[Sheet2$]
select * from #myTable
Monday, November 28, 2011
How IIS Process ASP.NET Request
Note: Referenced from Abhijit Jana article
Introduction
When request come from client to the server a lot of operation is performed before sending response to the client. This is all about how IIS Process the request. Here I am not going to describe the Page Life Cycle and there events, this article is all about the operation of IIS Level. Before we start with the actual details, let’s start from the beginning so that each and every one understands its details easily. Please provide your valuable feedback and suggestion to improve this article.What is Web Server?
When we run our ASP.NET Web Application from visual studio IDE, VS Integrated ASP.NET Engine is responsible to execute all kind of asp.net requests and responses. The process name is "WebDev.WebServer.Exe" which actually take care of all request and response of an web application which is running from Visual Studio IDE.Now, the name “Web Server” come into picture when we want to host the application on a centralized location and wanted to access from many locations. Web server is responsible for handle all the requests that are coming from clients, process them and provide the responses.
What is IIS?
IIS (Internet Information Server) is one of the most powerful web servers from Microsoft that is used to host your ASP.NET Web application. IIS has it's own ASP.NET Process Engine to handle the ASP.NET request. So, when a request comes from client to server, IIS takes that request and process it and send response back to clients.Request Processing:
Hope, till now it’s clear to you that what is Web server and IIS is and what is the use of them. Now let’s have a look how they do things internally. Before we move ahead, you have to know about two main concepts
1. Worker Process
2. Application Pool
Worker Process: Worker Process (w3wp.exe) runs the ASP.Net application in IIS. This process is responsible to manage all the request and response that are coming from client system. All the ASP.Net functionality runs under the scope of worker process. When a request comes to the server from a client worker process is responsible to generate the request and response. In a single word we can say worker process is the heart of ASP.NET Web Application which runs on IIS.
Application Pool: Application pool is the container of worker process. Application pools is used to separate sets of IIS worker processes that share the same configuration. Application pools enables a better security, reliability, and availability for any web application. The worker process serves as the process boundary that separates each application pool so that when one worker process or application is having an issue or recycles, other applications or worker processes are not affected. This makes sure that a particular web application doesn't not impact other web application as they are configured into different application pools.
Application Pool with multiple worker process is called “Web Garden”.
Now, I have covered all the basic stuff like Web server, Application Pool, Worker process. Now let’s have looked how IIS process the request when a new request comes up from client.
If we look into the IIS 6.0 Architecture, we can divided them into Two Layer
1. Kernel Mode
2. User Mode
Now, Kernel mode is introduced with IIS 6.0, which contains the HTTP.SYS. So whenever a request comes from Client to Server, it will hit HTTP.SYS First.
Now, HTTP.SYS is Responsible for pass the request to particular
Application pool. Now here is one question, How HTTP.SYS comes to know where to
send the request? This is not a random pickup. Whenever we create a new
Application Pool, the ID of the Application Pool is being generated and it’s
registered with the HTTP.SYS. So whenever HTTP.SYS Received the request from
any web application, it checks for the Application Pool and based on the
application pool it send the request.
Till now, Client Requested for some information and request came to the Kernel level of IIS means at HTTP.SYS. HTTP.SYS has been identified the name of the application pool where to send. Now, let’s see how this request moves from HTTP.SYS to Application Pool.
In User Level of IIS, we have Web Admin Services (WAS) which takes the request from HTTP.SYS and pass it to the respective application pool.
When Application pool receive the request, it simply pass the request to worker process (w3wp.exe) . The worker process “w3wp.exe” looks up the URL of the request in order to load the correct ISAPI extension. ISAPI extensions are the IIS way to handle requests for different resources. Once ASP.NET is installed, it installs its own ISAPI extension (aspnet_isapi.dll) and adds the mapping into IIS.
Note: Sometimes if we install IIS after installing asp.net, we need to register the extension with IIS using aspnet_regiis command.
When Worker process loads the aspnet_isapi.dll, it start an HTTPRuntime, which is the entry point of an application. HTTPRuntime is a class which calls the ProcessRequest method to start Processing.
When this methods called, a new instance of HTTPContext is been created. Which is accessible using HTTPContext.Current Properties. This object still remains alive during life time of object request. Using HttpContext.Current we can access some other objects like Request, Response, and Session etc.
Now, the concept comes called “HTTPPipeline”. It is called a pipeline because it contains a set of HttpModules (For Both Web.config and Machine.config level) that intercept the request on its way to the HttpHandler. HTTPModules are classes that have access to the incoming request. We can also create our own HTTPModule if we need to handle anything during upcoming request and response.
All the request now passes from httpModule to respective HTTPHandler then method and the ASP.NET Page life cycle starts. This ends the IIS Request processing and start the ASP.NET Page Lifecycle.
Conclusion
When client request for some information from a web server, request first reaches to HTTP.SYS of IIS. HTTP.SYS then sends the request to respective Application Pool. Application Pool then forward the request to worker process to load the ISAPI Extension which will create an HTTPRuntime Object to Process the request via HTTPModule and HTTPHanlder. After that the ASP.NET Page LifeCycle events start.This was just overview of IIS Request Processing to let Beginner’s know how the request get processed in backend. If you want to learn in details please check the link for Reference and further Study section.
Tuesday, November 1, 2011
Interview Questions Silverlight
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.What is RIA service?
WCF RIA Services simplifies the development of n-tier solutions for Rich Internet Applications (RIA), such as Silverlight applications. A common problem when developing an n-tier RIA solution is coordinating application logic between the middle tier and the presentation tier. To create the best user experience, you want your RIA Services client to be aware of the application logic that resides on the server, but you do not want to develop and maintain the application logic on both the presentation tier and the middle tier. RIA Services solves this problem by providing framework components, tools, and services that make the application logic on the server available to the RIA Services client without requiring you to manually duplicate that programming logic. You can create a RIA Services client that is aware of business rules and know that the client is automatically updated with latest middle tier logic every time that the solution is re-compiled.What is the difference between WCF and RIA service?
RIA Services gives you is code generation. It creates your classes for you. You only need to put the business logic. I think RIA Services is very useful for developing small to mid apps very rapidly.Another difference is that it hides the asynchronous calls to the web service. Many people don't like the async model (which is the only one you can use in Silverlight) and a RIA service handles that for you.
How many types of binding are there in Silverlight?
There are three types of data binding that happens in Silverlight applications between a source and target.
1.
OneTime data binding
2.
OneWay data binding (default mode)
3.
TwoWay data binding
OneTime
data binding: As the name suggests, data binding happens between the source and target
only once. In this binding, the source (CRL object) data will bind with the
target (XAML element) only when the page executes the first time. Later on, any
changes made in the source will not be reflected back in the target element.
You will prefer to use this binding mode to reduce overhead if you know that
the source property won’t change.
OneWay data binding:
In this data binding, the source
will immediately inform about changes to the target control. We will be using
this binding only for frequently changed elements. This is the default mode.
TwoWay data binding: This happens in bidirectional mode. Whenever any change occurs in the
backend or the CRL object, it will inform to the XAML controls immediately, and
vice versa.
What is a storyboard?
Controls animations with a
timeline, and provides object and property targeting information for its child
animations.
What is the difference between Label and a text block controls?
Even though TextBlock lives in
the System.Windows.Controls namespace, it is not a control. It derives
directly from FrameworkElement. Label, on the other hand, derives from
ContentControl. This means that Label can:
1.
Be given a
custom control template (via the Template property).
2.
Display
data other than just a string (via the Content property).
3.
Apply a
DataTemplate to its content (via the ContentTemplate property).
4.
Do
whatever else a ContentControl can do that a FrameworkElement cannot.
What are Pixel Shedders?
A pixel shader is an object that
transforms pixels output from the rendering pipeline before they're rendered
to the display surface.
What is the difference between WPF and Silverlight?
WPF is for desktop applications-
you create an .exe file when you build WPF applications. To run a WPF exe
requires you to have Framework 3 or higher on your pc.
Silverlight is on the web. What
you create is an application that can be hosted either in an html page or an
asp.net page. To watch it from your browser it requires to have installed in
your browser the silverlight plugin. Silverlight uses very fewer libraries than
WPF does, and that's pretty logical because Silverlight’s CLR is in the plugin
which is about 5-10 MB.
WPF and silverlight though use
the same logic in development and the same technology.
Can WPF application runs in browser, if so then why do I go for Silverlight?
WPF applications can be deployed
to the desktop or run in Internet Explorer (on Windows only, as far as I know).
When WPF application run in Internet Explorer they run in a sandbox, so users
simply point Internet Explorer at an URL and your application appears without
any installation or confirmation need. All development tools are the same
(Visual Studio) when making desktop and browser-based WPF applications and you
can use the same widgets for both.
WPF running in Internet Explorer
have some restrictions compared to a program running on the desktop. For
example, opening new windows is not possible and communication (WCF) is not
allowed. Apparently SOAP calls can be used instead.
Making a WPF application run in
the browser is easy. You create a project in Visual Studio marking it as a “WPF
Browser Application”. After compilation, you publish the executable to a web
server. I think one idea in Visual Studio is to allow a desktop-based WPF
application and the same browser-based application to be produced from the same
codebase. I have not tried this yet, but this looks like a promising concept.
Like WPF-applications can run in
a browser, so do Silverlight applications. But Silverlight applications can be
deployed to more platforms (OS X and Linux) and more browsers. This does
however come with a cost… Like browsers-based WPF applications lose access
to some functions compared to desktop applications, Silverlight applications
can build on even less infrastructure. The GUI is one (of many) missing
elements in Silverlight
What us the difference between DataTemplate, ControlTemplate and HierarchicalDatatemplate?
Before we get into differences
between them, let me show how one would typically use them. It’s a good
practice that all your templates are embedded inside resources / styles. It
makes your XAML centralized, shareable and easier to understand (a refactored
XAML of sorts, waiting for ReSharper to include this refactoring.
Don’t Do:
The above XAML holds true also for HierarchicalDataTemplate & ItemsPanelTemplate. But it won’t quite work for ControlTemplate, as ControlTemplate can be assigned to Template property of a class that inherits from ContentControl class, which ListBox doesn’t.
[ListBox]
[ListBox.ItemTemplate]
[DataTemplate]
[!– Your Data Template Goes here–]
[/DataTemplate]
[/ListBox.ItemTemplate]
[/ListBox]
[ListBox.ItemTemplate]
[DataTemplate]
[!– Your Data Template Goes here–]
[/DataTemplate]
[/ListBox.ItemTemplate]
[/ListBox]
Recommended:
[Window.Resources]
[DataTemplate x:Key=”myDataTemplate”]
[!– Your Data Template Goes here–]
[/DataTemplate]
[/Window.Resources]
[ListBox
ItemTemplate=”{StaticResource myDataTemplate}” /][Window.Resources]
[DataTemplate x:Key=”myDataTemplate”]
[!– Your Data Template Goes here–]
[/DataTemplate]
[/Window.Resources]
The above XAML holds true also for HierarchicalDataTemplate & ItemsPanelTemplate. But it won’t quite work for ControlTemplate, as ControlTemplate can be assigned to Template property of a class that inherits from ContentControl class, which ListBox doesn’t.
So the listbox code would
typically look like this:
[ControlTemplate
x:Key=”myControlTemplate” TargetType=”{x:Type ListBoxItem}”]
[TextBox /]
[/ControlTemplate]
[TextBox /]
[/ControlTemplate]
[ListBox]
[ListBoxItem Template=”{StaticResource myControlTemplate}” /]
[/ListBox]
[ListBoxItem Template=”{StaticResource myControlTemplate}” /]
[/ListBox]
But the problem with above
snippet is, you are manually specifying item which is never the case in real
world. Ideally you would like to bind ItemsSource Property of ListBox with some
collection obtained at runtime from your data access layer. Solution to this
problem is creating a style and binding it to ItemContainerStyle property of
ListBox. By doing that you will be able to use ItemsSource for Binding &
the ControlTemplate which is present inside the style will be applied to each
binded item.
ItemsPanelTemplate is mainly used by controls inheriting from ItemsControl class for displaying their Items. ItemsPanelTemplate can be customized through ItemsPanel property of ItemsControl class or any class which inherits from ItemsControl.
[ListBox
x:Name=”myList” ItemsSource=”{Binding}” ItemContainerStyle=”{StaticResource
myStyle}” /]
[Style x:Key=”myStyle” TargetType=”{x:Type ListBoxItem}”]
[Setter Property=”Template”]
[Setter.Value]
[ControlTemplate TargetType=”{x:Type ListBoxItem}”]
[TextBox Text=”{Binding collectionPropertyName}” /]
[/ControlTemplate]
[/Setter.Value]
[/Setter]
[/Style]
[Style x:Key=”myStyle” TargetType=”{x:Type ListBoxItem}”]
[Setter Property=”Template”]
[Setter.Value]
[ControlTemplate TargetType=”{x:Type ListBoxItem}”]
[TextBox Text=”{Binding collectionPropertyName}” /]
[/ControlTemplate]
[/Setter.Value]
[/Setter]
[/Style]
ItemsPanelTemplate is mainly used by controls inheriting from ItemsControl class for displaying their Items. ItemsPanelTemplate can be customized through ItemsPanel property of ItemsControl class or any class which inherits from ItemsControl.
[ListBox
x:Name=”myList” ItemsPanel=”{StaticResource myItemsPanelTemplate}” /]
[ItemsPanelTemplate x:Key=”myItemsPanelTemplate”]
[StackPanel Orientation=”Horizontal” /]
[/ItemsPanelTemplate]
[ItemsPanelTemplate x:Key=”myItemsPanelTemplate”]
[StackPanel Orientation=”Horizontal” /]
[/ItemsPanelTemplate]
The point of confusion is
normally between selecting a ControlTemplate or DataTemplate. Normal saying
goes as DataTemplate provides visualization to a business object while
ControlTemplate does the same to a UI control. But in my project I see
ControlTemplate used almost everywhere. Normally UI guys start creating screens
while we are still giving shapes to our domain model (deadlines issues you
see). Moreover, I feel one has to get slightly deep with WPF control properties
to create an appealing professional UI. So atleast here, we developers
don’t quite mind giving a free hand to UI guys. We just go over to control templates
residing inside styles & giving names of Business Object properties inside
the bindings created by them. Also ControlTemplate triggers are based on UI
control properties which is what UI team is often interested in. Few more
differences are given here.
HierarchicalDataTemplate is an
extension of DataTemplate with an additional ItemSource property. It is used to
render hierarchical data in controls like treeview or menu.
HierarchicalDataTemplate ends with a Data Template.
[HierarchicalDataTemplate
DataType=”{x:Type Department}” ItemsSource=”{Binding Path=Classes}”]
[TextBlock Text=”{Binding Path=DepartmentName}” /]
[/HierarchicalDataTemplate]
[TextBlock Text=”{Binding Path=DepartmentName}” /]
[/HierarchicalDataTemplate]
[DataTemplate
DataType=”{x:Type UniversityClass}”]
[TextBlock Text=”{Binding Path=ClassName}” /]
[/DataTemplate]
[TextBlock Text=”{Binding Path=ClassName}” /]
[/DataTemplate]
Attached property vs. Dependency property?
Attached properties are a type of
dependency property. The difference is in how they're used.
With an attached property, the
property is defined on a class that isn't the same class for which it's being
used. This is usually used for layout. Good examples are Panel.ZIndex or
Grid.Row - you apply this to a control (ie: Button), but it's actually defined
in Panel or Grid. The property is "attached" to the button's
instance.
This allows a container, for
example, to create properties that can be used on any UIelement.
As for implementation differences
- it's basically just a matter of using Register vs. RegisterAttached when you
define the property.
Define Framework element?
UIElement is a base class for most of the objects that have visual appearance and
can process basic input in Silverlight.
FrameworkElement provides a framework of common APIs for objects that participate in
Silverlight layout. FrameworkElement also defines APIs related to data binding,
object tree, and object lifetime feature areas in Silverlight.
What kind of elements used in storyboard?
From/To Animation: Animates between a starting and ending value. While creating the
Animation, we will be having From and To properties to set the beginning and
ending values.
Use the From property to set the
starting value
Use the To property to set the
ending value
These are simple to implement and
these are basic animations. Animations belonging to this category are:
·
ColorAnimation
·
DoubleAnimation
·
PointAnimation
Key-frame Animation: Animates between a series of values specified using key-frame objects.
Key-frame animations are more powerful than From/To animations because you can
specify any number of target values and even control their interpolation
method. This kind of Animation implementation is a bit complex than basic
animations. Animations belonging to this category are:
·
ColorAnimationUsingKeyFrames
·
DoubleAnimationUsingKeyFrames
·
PointAnimationUsingKeyFrames
What is Downloader Object in Silverlight?
This object will retrieve objects
(images, video, xaml) asynchronously, much like AJAX. There is a gaping
limitation being that it cannot go cross domain.
An interesting feature of
the Downloader object is the ability to get XAML asynchronously. This
gives us the ability to create module Silverlight applications and code XAML
Plug-ins.
What is BAML?
XAML stands for extended application markup language. It is nothing but an xml file which is used to declarative create the user interface of the silver light or the WPF applications. This XAML file generally rendered by the silverlight plugin and displayed inside the browser. When you compile your project which includes XAML pages,those first converts into BAML (Binary application markup language) and then rendered in the web browser.
XAML stands for extended application markup language. It is nothing but an xml file which is used to declarative create the user interface of the silver light or the WPF applications. This XAML file generally rendered by the silverlight plugin and displayed inside the browser. When you compile your project which includes XAML pages,those first converts into BAML (Binary application markup language) and then rendered in the web browser.
What kind of Brushes you are used in Silver light project?
a) Linear Gradient
b) Solid color brush
What kind of audio video formats is supported in Silverlight?
Silverlight supports Windows
Media Audio and Video (WMA, WMV7-9) and VC-1, as well as MP3 audio.
What is the XAP mime type in Silverlight?
The .xap mime type is:
application/x-silverlight
Tuesday, September 13, 2011
Interview Questions - WCF
What are the important principles of SOA
(Service oriented Architecture)?
What are the main components of WCF?
The main components of WCF are
Service Contract:
Service Contract specifies the description of methods which our service will provide to consuming application. For WCF to identify contracts for the service, we need to use interface/class with [ServiceContract] attribute. In WCF we can do interface/Class level programming.
Operation Contract:
We need to expose some methods to consuming application to use our services. Those methods will have [OperationContract] attribute. Making them public will not make them accessible from outside. So OperationContract Specifies the methods can be accessible from outside.
Data Contracts:
WCF data contracts provide a mapping function between .NET CLR types that are defined in code and XML Schemas Definitions defined by the W3C organization (www.w3c.org/) that are used for communication outside the service.
Message Contracts:
Message contracts describe the structure of SOAP messages sent to and from a service and enable you to inspect and control most of the details in the SOAP header and body. Whereas data contracts enable interoperability through the XML Schema Definition (XSD) standard, message contracts enable you to interoperate with any system that communicates through SOAP. Using message contracts gives you complete control over the SOAP message sent to and from a service by providing access to the SOAP headers and bodies directly. This allows use of simple or complex types to define the exact content of the SOAP parts.
What are the various ways of hosting a WCF service?
There are two main advantages of using IIS over self-hosting:
Automatic activation
IIS provides automatic activation that means the service is not necessary to be running in advance. When any message is received by the service it then launches and fulfills the request. But in case of self-hosting the service should always be running.
Process recycling
If IIS finds that a service is not healthy that means if it has memory leaks etc., IIS recycles the process. Ok let us try to understand what is recycling in IIS process. For every browser instance, a worker process is spawned and the request is serviced. When the browser disconnects the worker, process stops and you lose all information. IIS also restarts the worker process. By default, the worker process is recycled at around 120 minutes. So why does IIS recycle. By restarting the worker process it ensures any bad code or memory leak do not cause issue to the whole system.
In case of self-hosting both the above features, you will need to code yourself. Lot of work right! That is why IIS is the best option for hosting services until you are really doing something custom.
Below figure shows where the recycle option is located in IIS. You need to click on the DefaultAppool and then Properties.
What is the difference WCF and Web services?
Web services can only be invoked by HTTP (traditional webservice with .asmx). While WCF Service or a WCF component can be invoked by any protocol (like http, tcp etc.) and any transport type.
Second web services are not flexible. However, WCF Services are flexible. If you make a new version of the service then you need to just expose a new end. Therefore, services are agile and which is a very practical approach looking at the current business trends.
We develop WCF as contracts, interface, operations, and data contracts. As the developer we are more focused on the business logic services and need not worry about channel stack. WCF is a unified programming API for any kind of services so we create the service and use configuration information to set up the communication mechanism like HTTP/TCP/MSMQ etc.
What are different bindings supported by WCF?
WCF includes predefined bindings. They cover most of bindings widely needed in day-to-day application. However, just in case you find that you need to define something custom WCF does not stop you. So let us try to understand what each binding provides.
BasicHttpBinding: - This binding is used when we need to use SOAP over HTTP. This binding can also be configured to be used as HTTPS. It can be also configured to send data in plain text or in optimized form like MTOM.
WsHttpBinding: - It is same like BasicHttpBinding. In short, it uses SOAP over HTTP. But with it also supports reliable message transfer, security and transaction. WS-Reliable Messaging, security with WS-Security, and transactions with WS-Atomic Transaction supports reliable message.
NetTcpBinding: - This binding sends binary-encoded SOAP, including support for reliable message transfer, security, and transactions, directly over TCP. The biggest disadvantage of NetTcpBinding is that both server and client should be also made in .NET language.
NetNamedPipesBinding:-This binding Sends binary-encoded SOAP over named pipes. This binding is only usable for WCF-to-WCF communication between processes on the same Windows-based machine.
Note: - An inter process control (IPC) protocol is used for exchanging information between two applications, possibly running on different computers in a network. The difference between Named pipes and TCP is that named pipes have good performance in terms of communication with in processes. But when it comes to communicate across network TCP holds the best choice. So if you are using WCF to communicate with process it’s the best choice to use in terms for performance. Named pipes do not perform when the traffic is heavy as compared to TCPIP.
NetMsmqBinding: - This binding sends binary-encoded SOAP over MSMQ. This binding can only be used for WCF-to-WCF communication.
What is one-way operation?
There are cases when an operation has no returned values and the client does not care about the success or failure of the invocation. To support this sort of fire-and-forget invocation, Windows Communication Foundation offers one-way operations. After the client issues the call, Windows Communication Foundation generates a request message, but no correlated reply message will ever return to the client. As a result, one-way operations can't return values, and any exception thrown on the service side will not make its way to the client. One-way calls do not equate to asynchronous calls. When one-way calls reach the service, they may not be dispatched all at once and may be queued up on the service side to be dispatched one at a time, all according to the service configured concurrency mode behavior and session mode. How many messages (whether one-way or request-reply) the service is willing to queue up is a product of the configured channel and the reliability mode. If the number of queued messages has exceeded the queue's capacity, then the client will block, even when issuing a one-way call. However, once the call is queued, the client is unblocked and can continue executing while the service processes the operation in the background. This usually gives the appearance of asynchronous calls. All the Windows Communication Foundation bindings support one-way operations.
The OperationContract attribute offers the Boolean IsOneWay property, which defaults to false, meaning a request-reply operation. But setting IsOneWay to true configures the method as a one-way operation:
The fact that the client doesn't care about the result of the invocation does not mean the client doesn't care if the invocation took place at all. In general, you should turn on reliability for your services, even for one-way calls. This will ensure delivery of the requests to the service. However, with one-way calls, the client may or may not care about the invocation order of the one-way operations. This is one of the main reasons why Windows Communication Foundation allows you to separate enabling reliable delivery from enabling ordered delivery and execution.
Can you explain duplex contracts in WCF?
A duplex service contract is a message exchange pattern in which both endpoints can send messages to the other independently. A duplex service, therefore, can send messages back to the client endpoint, providing event-like behavior. Duplex communication occurs when a client connects to a service and provides the service with a channel on which the service can send messages back to the client.
Duplex contract allows a service to callback to a client. When a contract is defined for a service, It is possible to specify a corresponding callback contract. The standard service contract defines the operations of the service that can be invoked by the client. The callback contract defines the operations of the client that can be invoked by the service. It is the client's responsibility to implement the callback contract and host the callback object. Each time the client invokes a service operation that is associated to the callback contract, the client supplies the necessary information for the service to locate and invoke the callback operation on the client.
What are Volatile queues?
What are Dead letter queues?
The main use of queue is that you do not need the client and the server running at one time. Therefore, it is possible that a message will lie in queue for long time until the server or client picks it up. But there are scenarios where a message is of no use after a certain time. Therefore, these kinds of messages if not delivered within that time span it should not be sent to the user.
Below is the config snippet, which defines for how much time the message should be in queue.
Can you explain transactions in WCF?
Can we have two-way communications in
MSMQ?
Yes
Enabled by Web services
|
Technology neutral
|
Endpoint platform independence.
|
Standardized
|
Standards-based protocols.
|
|
Consumable
|
Enabling automated discovery and usage.
|
|
Enabled by SOA
|
Reusable
|
Use of Service, not reuse by copying of
code/implementation.
|
Abstracted
|
Service is abstracted from the implementation.
|
|
Published
|
Precise, published specification functionality of service
interface, not implementation.
|
|
Formal
|
Formal contract between endpoints places obligations on
provider and consumer.
|
|
Relevant
|
Functionality presented at a granularity recognized by
the user as a meaningful service.
|
The main components of WCF are
1.
Service class.
2.
Hosting environment.
3.
End point.
What is a service contract, operation
contract, Data Contract and Message Contract?Service Contract:
Service Contract specifies the description of methods which our service will provide to consuming application. For WCF to identify contracts for the service, we need to use interface/class with [ServiceContract] attribute. In WCF we can do interface/Class level programming.
Operation Contract:
We need to expose some methods to consuming application to use our services. Those methods will have [OperationContract] attribute. Making them public will not make them accessible from outside. So OperationContract Specifies the methods can be accessible from outside.
Data Contracts:
WCF data contracts provide a mapping function between .NET CLR types that are defined in code and XML Schemas Definitions defined by the W3C organization (www.w3c.org/) that are used for communication outside the service.
Message Contracts:
Message contracts describe the structure of SOAP messages sent to and from a service and enable you to inspect and control most of the details in the SOAP header and body. Whereas data contracts enable interoperability through the XML Schema Definition (XSD) standard, message contracts enable you to interoperate with any system that communicates through SOAP. Using message contracts gives you complete control over the SOAP message sent to and from a service by providing access to the SOAP headers and bodies directly. This allows use of simple or complex types to define the exact content of the SOAP parts.
What are the various ways of hosting a WCF service?
1.
Self-hosting.
2.
IIS hosting.
3.
Windows hosting.
What are the advantages of hosting WCF
Services in IIS as compared to self-hosting?There are two main advantages of using IIS over self-hosting:
Automatic activation
IIS provides automatic activation that means the service is not necessary to be running in advance. When any message is received by the service it then launches and fulfills the request. But in case of self-hosting the service should always be running.
Process recycling
If IIS finds that a service is not healthy that means if it has memory leaks etc., IIS recycles the process. Ok let us try to understand what is recycling in IIS process. For every browser instance, a worker process is spawned and the request is serviced. When the browser disconnects the worker, process stops and you lose all information. IIS also restarts the worker process. By default, the worker process is recycled at around 120 minutes. So why does IIS recycle. By restarting the worker process it ensures any bad code or memory leak do not cause issue to the whole system.
In case of self-hosting both the above features, you will need to code yourself. Lot of work right! That is why IIS is the best option for hosting services until you are really doing something custom.
Below figure shows where the recycle option is located in IIS. You need to click on the DefaultAppool and then Properties.
What is the difference WCF and Web services?
Web services can only be invoked by HTTP (traditional webservice with .asmx). While WCF Service or a WCF component can be invoked by any protocol (like http, tcp etc.) and any transport type.
Second web services are not flexible. However, WCF Services are flexible. If you make a new version of the service then you need to just expose a new end. Therefore, services are agile and which is a very practical approach looking at the current business trends.
We develop WCF as contracts, interface, operations, and data contracts. As the developer we are more focused on the business logic services and need not worry about channel stack. WCF is a unified programming API for any kind of services so we create the service and use configuration information to set up the communication mechanism like HTTP/TCP/MSMQ etc.
What are different bindings supported by WCF?
WCF includes predefined bindings. They cover most of bindings widely needed in day-to-day application. However, just in case you find that you need to define something custom WCF does not stop you. So let us try to understand what each binding provides.
BasicHttpBinding: - This binding is used when we need to use SOAP over HTTP. This binding can also be configured to be used as HTTPS. It can be also configured to send data in plain text or in optimized form like MTOM.
WsHttpBinding: - It is same like BasicHttpBinding. In short, it uses SOAP over HTTP. But with it also supports reliable message transfer, security and transaction. WS-Reliable Messaging, security with WS-Security, and transactions with WS-Atomic Transaction supports reliable message.
NetTcpBinding: - This binding sends binary-encoded SOAP, including support for reliable message transfer, security, and transactions, directly over TCP. The biggest disadvantage of NetTcpBinding is that both server and client should be also made in .NET language.
NetNamedPipesBinding:-This binding Sends binary-encoded SOAP over named pipes. This binding is only usable for WCF-to-WCF communication between processes on the same Windows-based machine.
Note: - An inter process control (IPC) protocol is used for exchanging information between two applications, possibly running on different computers in a network. The difference between Named pipes and TCP is that named pipes have good performance in terms of communication with in processes. But when it comes to communicate across network TCP holds the best choice. So if you are using WCF to communicate with process it’s the best choice to use in terms for performance. Named pipes do not perform when the traffic is heavy as compared to TCPIP.
NetMsmqBinding: - This binding sends binary-encoded SOAP over MSMQ. This binding can only be used for WCF-to-WCF communication.
What is one-way operation?
There are cases when an operation has no returned values and the client does not care about the success or failure of the invocation. To support this sort of fire-and-forget invocation, Windows Communication Foundation offers one-way operations. After the client issues the call, Windows Communication Foundation generates a request message, but no correlated reply message will ever return to the client. As a result, one-way operations can't return values, and any exception thrown on the service side will not make its way to the client. One-way calls do not equate to asynchronous calls. When one-way calls reach the service, they may not be dispatched all at once and may be queued up on the service side to be dispatched one at a time, all according to the service configured concurrency mode behavior and session mode. How many messages (whether one-way or request-reply) the service is willing to queue up is a product of the configured channel and the reliability mode. If the number of queued messages has exceeded the queue's capacity, then the client will block, even when issuing a one-way call. However, once the call is queued, the client is unblocked and can continue executing while the service processes the operation in the background. This usually gives the appearance of asynchronous calls. All the Windows Communication Foundation bindings support one-way operations.
The OperationContract attribute offers the Boolean IsOneWay property, which defaults to false, meaning a request-reply operation. But setting IsOneWay to true configures the method as a one-way operation:
[ServiceContract]
interface IMyContract
{
[OperationContract(IsOneWay =
true)]
void MyMethod()
}
Because there is no reply associated with a one-way operation, there's no
point in having any returned values or results, and the operation must have a
void return type without any outgoing parameters. Since Windows Communication
Foundation does not have any hooks into the language compiler and can't verify
proper usage at compile-time, it enforces this by verifying the method
signature when loading up the host at run time and throwing an
InvalidOperationException in case of a mismatch.The fact that the client doesn't care about the result of the invocation does not mean the client doesn't care if the invocation took place at all. In general, you should turn on reliability for your services, even for one-way calls. This will ensure delivery of the requests to the service. However, with one-way calls, the client may or may not care about the invocation order of the one-way operations. This is one of the main reasons why Windows Communication Foundation allows you to separate enabling reliable delivery from enabling ordered delivery and execution.
Can you explain duplex contracts in WCF?
A duplex service contract is a message exchange pattern in which both endpoints can send messages to the other independently. A duplex service, therefore, can send messages back to the client endpoint, providing event-like behavior. Duplex communication occurs when a client connects to a service and provides the service with a channel on which the service can send messages back to the client.
Duplex contract allows a service to callback to a client. When a contract is defined for a service, It is possible to specify a corresponding callback contract. The standard service contract defines the operations of the service that can be invoked by the client. The callback contract defines the operations of the client that can be invoked by the service. It is the client's responsibility to implement the callback contract and host the callback object. Each time the client invokes a service operation that is associated to the callback contract, the client supplies the necessary information for the service to locate and invoke the callback operation on the client.
What are Volatile queues?
There are scenarios in the
project when you want the message to deliver in proper time. The timely
delivery of message is more important than losing message. In these scenarios,
Volatile queues are used.
Below is the code snippet, which shows how to configure Volatile queues. You can see the binding Configuration property set to Volatile Binding. This code will assure that message will deliver on time but there is a possibility that you can lose data.
Below is the code snippet, which shows how to configure Volatile queues. You can see the binding Configuration property set to Volatile Binding. This code will assure that message will deliver on time but there is a possibility that you can lose data.
behaviorConfiguration="CalculatorServiceBehavior">
...
binding="netMsmqBinding"
bindingConfiguration="volatileBinding"
contract="Samples.InterfaceStockTicker"
/>
...
durable="false"
exactlyOnce="false"/>
...
What are Dead letter queues?
The main use of queue is that you do not need the client and the server running at one time. Therefore, it is possible that a message will lie in queue for long time until the server or client picks it up. But there are scenarios where a message is of no use after a certain time. Therefore, these kinds of messages if not delivered within that time span it should not be sent to the user.
Below is the config snippet, which defines for how much time the message should be in queue.
deadLetterQueue="Custom"
customDeadLetterQueue="net.msmq://localhost/private/ServiceModelSamples"
timeToLive="00:00:02"/>
A transaction is a collection or
group of one or more units of operation executed as a whole. Another way to say
it is that transactions provide a way to logically group single pieces of work
and execute them as a single unit, or
transaction.
For example, when you place an
order online, a transaction occurs. Suppose you order a nice 21-inch
wide-screen flat-panel monitor from your favorite online hardware source.
Assume you were to pay for this monitor with a credit card. You enter the information
required on the screen and click the "Place Order" button. At this
point, two operations occur. The first operation takes place when your bank
account is debited the amount of the monitor. The second operation occurs when
the vendor is credited that amount. Each of those operations is a single unit
of work.
Now imagine that one of those
operations fails. For example, suppose that the money was removed from your
bank account for the purchase of the monitor, but the payment to the vendor
failed. First, you wouldn't receive your anxiously awaited monitor, and second,
you would lose the amount of money for the cost of the monitor. I don't know
about you, but I would be quite unhappy if this happened.
Conversely, a payment could be
made to the vendor without debiting your account. In this case, the debit from
your account failed but the payment to the vendor succeeded. You would likely
receive the purchase item without having paid for it. Although this scenario is
preferable to the former one, neither is acceptable in that in either case,
someone is not receiving what is rightfully theirs.
The solution to this is to wrap
both of these individual operations into a single unit of execution called a
transaction. A transaction will make sure that both operations succeed or fail
together. If either of the operations fails, the entire unit of work is
cancelled and any and all changes are undone. At this point, each account is in
the same state it was before you attempted your purchase. This undoing is known
as "rolling back" the transaction.
This ensures that you receive
your monitor and the vendor receives its money. Both parties are now happy and
your confidence in doing business online hasn't wavered.
A pure and successful transaction
has four characteristics. You can use the mnemonic aid "ACID" to help
you remember each of them:
- Atomic
- Consistent
- Isolated
- Durable
Atomic
The word "atomic" comes
from the Greek word "atamos," meaning "indivisible; cannot be
split up." In computing terms, this meaning also applies to transactions.
Transactions must be atomic, meaning either all the operations of the
transactions succeed or none of them succeed (that is, all successful
operations up to the point of failure are rolled back).
In the case of the monitor order,
the money is removed from the bank account and deposited into the vendor bank
account. If either of those operations fails, each account returns to the state
it was in prior to the start of the purchase attempt.
Consistent
Consistent transactions mean that
the outcome is exactly what you expected it to be. If you purchase the monitor
for $300 and you have $1,000 in the bank account, consistent transactions mean
that you expect to be charged $300 and have $700 remaining in the bank account
when the transaction is committed and complete.
Isolated
Isolated transactions are
"private," meaning that no one else knows about the transaction until
it is committed.
For example, suppose you have
$1,000 in a bank account from which to purchase the monitor. You purchase the
monitor for $300, and during the purchase of the monitor, while the transaction
is taking place, your husband or wife is at the local ATM checking the balance
of the account from which the money for the monitor is being withdrawn.
Isolated transactions are
invisible to all other transactions, and in this example the husband or wife
would see a balance of $1,000. In fact, if the husband or wife were to withdraw
money from the ATM while the online purchase was taking place, both
transactions would be isolated transactions, completely unknown to one another.
Durable
Durable transactions must survive
failures. When a transaction is complete, it is "committed," meaning
that the changes have taken effect. For a transaction to be durable, it must
maintain its committed state if there is a failure.
What is a failure? It could be a
power outage, hardware failure, and so on. Regardless of the failure, the
transaction must survive it.
Suppose that after the processing
of the transaction, someone yanks the power cord out of the server that is
processing your order. A durable transaction survives this failure. When the
power is restored to the server, the result of the transaction must be in the
committed state.
Transaction Attributes in System.ServiceModel
When version 2.0 of the .NET
Framework was released, it included a new namespace (System.Transactions) that
makes transaction programming easy and efficient. The System.Transactions namespace
supports transactions initiated by many platforms including SQL Server, MSMQ,
ADO.NET, as well as MSDTC (Microsoft Distributed Transaction Coordinator).
Windows Communication Foundation
utilizes the many available objects of this namespace to provide all the
necessary transaction capabilities you will need when building your WCF
services and client applications.
ServiceBehavior Attribute
The
[ServiceBehavior] attribute
has three properties that deal with handling and managing transactions. Each is
shown in the following list:
·
TransactionAutoCompleteOnSessionClose: Specifies whether pending
transactions are completed when the current session closes.
·
TransactionIsolationLevel: Determines the isolation level of
the transaction.
·
TransactionTimeout: Specifies the period in which a
transaction has to complete.
The first of these is the TransactionAutoCompleteOnSessionClose property. It should be used for
cases where you want to ensure that transactions are completed when the session
is closed. As such, the transaction will either be committed or rolled back
when the session is closed, depending on its state.
The one that needs to be
highlighted here is the TransactionIsolationLevel
property. This property
determines how the data is handled when other transactions make modifications
to the data. It also has an impact on how long your transaction can hold locks
on the data, protecting it from other transactions.
The
TransactionTimeout
property determines how long the
transaction can run before it is cancelled. If the transaction has not
completed before the timeout value has been reached, the transaction is rolled
back. Great care must be taken when choosing a timeout interval. Too high of an
interval will cause needless wait times when a failure has occurred. Too small
of an interval will cause the transaction to fail before it has had time to
complete.
These properties are properties
of the [ServiceBehavior] attribute,
which is applied to the class that implements the service interface. The
following code snippet shows the three transaction properties
applied to the [ServiceBehavior]
attribute:
[ServiceBehavior(TransactionAutoCompleteOnSessionClose=true,
TransactionIsolationLevel=IsolationLevel.ReadCommitted,
TransactionTimeout="00:00:30")]
public class
ServiceClass : IServiceClass
{
[OperationBehavior]
string IServiceClass.GetText()
{
StreamReader sw = new
StreamReader(@"c:\Test\WCFServiceTest.txt");
return sw.ReadLine();
}
}
In this case, the
TransactionAutoCompleteOnSessionClose property is set to true, the
TransactionIsolationLevel is set to ReadCommitted, and the TransactionTimeout
is set to 30 seconds. The TransactionTimeout property value is of a Timespan
object.
Prior to running the example,
make sure that the c:\Test\WCFServiceTest.txt file
exists and contains at least a few words of text. If your test file is located
somewhere else, make sure the example is pointed to the correct location.
OperationBehavior Attribute
The
[OperationBehavior] also has a
couple of properties related to transactions. The two properties are:
- TransactionAutoComplete: Specifies that transactions will be auto-completed if no exceptions occur.
- TransactionScopeRequired: Specifies whether the associate method requires a transaction.
The characteristics of a
successful transaction were discussed earlier in this article. Both the TransactionAutoComplete property and TransactionScopeRequired property help fulfill the durable
requirement because it will automatically complete a transaction, thus ensuring
that the specific operation is successful.
The following example illustrates
a service operation that is annotated with the [OperationBehavior] attribute, which specifies the
two transaction properties:
[OperationBehavior(TransactionAutoComplete=true,
TransactionScopeRequired=true)]
string
IServiceClass.GetText()
{
StreamReader sw = new
StreamReader(@"c:\wrox\WCFServiceTest.txt");
return sw.ReadLine();
}
In this example, the
TransactionAutoComplete property is set to true and the
TransactionScopeRequired property is set to true as well.
TransactionFlow Attribute
The
[TransactionFlow]
attribute is used to specify the
level at which a service operation can accept a transaction header. This
attribute has a single property and is the attribute used to annotate a service
operation method. The values for this property come from the
TransactionFlowOption enumeration and are shown in the following list:
- Allowed: Transaction may be flowed.
- Mandatory: Transaction must be flowed.
- NotAllowed: Transaction cannot be flowed.
This property and the associated
values are used to indicate whether transaction flow is enabled for the
associated method.
The following example illustrates
a service operation that is annotated with the
[TransactionFlow]
attribute, which specifies the
level at which the operation is willing to accept incoming transactions. This
example sets the level at mandatory, signifying that transactions are required
for this operation:
[TransactionFlow(TransactionFlowOption.Mandatory)]
int
IServiceClass.MultiplyNumbers(int firstvalue, int secondvalue)
{
return firstvalue * secondvalue;
}
The default value for this
property is NotAllowed.
A flowed transaction is a
situation in which a transaction id is passed over the wire and used on the
receiving side to perform work, usually enlisting in the corresponding
transaction and executing within that scope.
WS-Atomic Transaction
Windows Communication Foundation
utilizes the WS-AT (WS-Atomic Transaction) protocol to flow transactions to
other applications. The WS-AT protocol is an interoperable protocol that enables
distributed transactions to be flowed using web service messages, and
incorporates a two-phase commit protocol to facilitate the outcome between
distributed applications and transaction managers. The transaction protocol
used when flowing a transaction between a client and service is determined by
the binding that is exposed on the endpoint.
You do not need to use this
protocol if your communication is using strictly Microsoft technology (WCF).
Simply enabling the TransactionFlow attribute will get you the desired results.
However, this protocol will be necessary if you are flowing transactions to
other platforms and third-party technologies.
Specifying Transactions Through Configuration
On the client side, transaction
flow is enabled via the binding. The following example, several properties on
the [ServiceBehavior] and [OperationBehavior] attributes
were set so that they enabled transactions on the service. When the service
references were added to the client, the client interrogated the consumed service
and set the appropriate binding attributes in the configuration file.
Transaction flow is enabled by
setting the value of the transactionFlow attribute to true, as shown by
the highlighted line in the following code:
closeTimeout="00:01:00"
openTimeout="00:01:00"
receiveTimeout="00:10:00"
sendTimeout="00:01:00"
bypassProxyOnLocal="false"
transactionFlow="true"
hostNameComparisonMode="StrongWildcard"
maxBufferPoolSize="524288"
maxReceivedMessageSize="65536"
messageEncoding="Text"
textEncoding="utf-8"
useDefaultWebProxy="true"
allowCookies="false">
maxStringContentLength="8192"
maxArrayLength="16384"
maxBytesPerRead="4096"
maxNameTableCharCount="16384" />
inactivityTimeout="00:10:00"
enabled="false" />
proxyCredentialType="None"
realm=""
/>
egotiateServiceCredential="true"
algorithmSuite="Default"
establishSecurityContext="true" />
binding="wsHttpBinding"
bindingConfiguration="WSHttpBinding_IServiceClass"
contract="WCFClientApp.TCP.IServiceClass"
name="NetTcpBinding_IServiceClass">
Yes
Subscribe to:
Posts (Atom)