This document was uploaded by user and they confirmed that they have the permission to share
it. If you are author or own the copyright of this book, please report to us by using this DMCA
report form. Report DMCA
Overview
Download & View Is Share Point Workflow Same As Windows Workflow-2 as PDF for free.
Windows Workflow Foundation(WWF) – FAQ Introduction In this FAQ we will quickly run through and get a feel of how WWF (Windows Workflow Foundation) will help you in making custom work flows in your project. Happy job hunting...... What is Windows Workflow Foundation? WWF is a programming model for building workflow-enabled applications on windows. System. Workflow namespace has all the necessary modules to develop any type of workflow. What is a Workflow? A Workflow is a set of activities, which is stored as model and they depict a process. Below figure depicts clearly the difference between Workflow and Activity. Every task is an activity and group of activity depicts a complete workflow. Workflow is run by the Workflow runtime engine.
Figure 1: - Work Flow Foundation Architecture Workflow model can be written in pure .NET code, pure XAML or Mix of XAML and .NET Code. A workflow model is compiled and can execute under windows, ASP.NET, Web services or windows services application.
What are different types of Workflow in Windows Workflow foundation? There are two basics type of workflow Sequential Workflow and State machines workflow. A sequential workflow has clear start and finish boundaries. Workflow controls execution in Sequential workflow. In sequential execution, one task is executed after other. Sequential workflow is more rigid in format and execution path has a deterministic nature. A State machine workflow is more dynamic in nature. Workflow has states and the state waits for events to help it move to next state. In State machine execution path is undeterministic nature. Below figure shows visual conceptualization of fundamentals. You can see in Sequential workflow the execution path is very determent. Shiv performs the entire task sequentially and these tasks are very determent. Now have a look at the second workflow. Every state goes to other state when it receives some external events. For instance when Shiv is seeing star trek there is an event of flashing news which triggers him to see the flashing new.
Figure 2: - Sequential and State machine workflow When should we use a sequential workflow and when should we use state machines? If the workflow is very rigid then you go for sequential workflow and if the workflow is dynamic then go for State machine workflow. For instance you have placed an order and the
order will not pass until your supervisor approves is a rigid flow. Because your order has to be approved by, a supervisor or else it will not be approved. But what if your order moves from one place to other place. For instance, it moves from approval to waiting and then clarification a state machine workflow model is more appropriate. Below is a simple code snippet which shows practically how to use sequential workflow. Let try to understand step by step as marked in the figure:1 - First you need to select System. Workflow namespace. 2, 3, and 4 - In these three steps we created code object and linked them with activity. 5, 6, 7, and 8 - We start the workflow and create workflow instance object to run the sequential workflow. You can see the output in 8. Depending on how you add the activity in section 3, it executes sequentially. Because we have added codeactivity1, first it executes the first activity first. The sequence on how you add the activity to the activities collection the activities are run.
Figure: - 3 Code snippet for workflow Note: - The above code snippet was developed with out using designer. The whole point was to make you understand what happens behind the scenes. In real projects you will be dependent on designer rather than coding manually. You can find the above code in SimpleWorkFlowSampleManual folder.
How do we create workflows using designer? As said previously it is very easy to design workflows using designer. So we will answer this question by actually doing a small sample. Below is the code snippet and image snapshot which shows how we can use the designer to create workflows. So lets understand all the below numbered snapshot. 1. First select a sequential workflow project. In this case, we have selected Sequential workflow console application to keep the sample simple.
2. When you are done with creating the project you will see the solution explorer as
shown in the second snapshot. There are two files one the WorkFlow1.cs and the other Workflow1.designer.cs.If you click on the WorkFlow1.cs you will get a designer pane as shown in snapshot 3. If you double click on Workflow1.designer.cs, you will get behind code as shown in snapshot 4.
3. So let us drag drop a code activity on the workflow designer and associate this
activity with a method called as MyActivity1. This association is done by entering the method name in Execute Code property. In MyActivity1, we have just displayed in the console that this is my first activity. Again, we have added one more code activity, which points to MyActivity2. If you see the designer pane we have sequenced code1 first and code2 next. So in short, code1 will execute first and the code2. This is clear from the output displayed below.
4. This is the behind code of the workflow.
Figure 4 Sequential workflow using designer How do we specify conditions in Work flow? Yes, you can define conditions in workflow by using conditionedActivitygroup. Below is the numbered snapshot, which shows how to use conditionedActivitygroup. 1. You can see in this snapshot we have defined a conditionedActivitygroup with two conditions. The two boxes inside the group define two conditions. 2. You can select one of the condition box and define the condition using the When Conditions property. If this condition is true you need to specify in the execute code which method to execute. For instance in the current snapshot we have said that old1 method should execute if age > 21. The same procedure we need to follow for the second condition box. In the second condition box we have specified to execute young1 method if age < 21. Currently the second condition is not visible in the below snapshot. 3. Workflow editor also provides a cool interface called as Rule Condition Editor, which can be used to specify conditions. Age is a public property in the behind code. You can also get the Age in the intelligence of rule condition editor. 4. Both the condition will execute inside the condition activity group. We need to also specify when this conditionactivitygroup should exit. Therefore, we have made a
function called as exit. If the user inputs age as -1 it will exit from the loop or else it will take inputs from user and continue evaluating depending on the two conditions.
Figure 5:- Sequential workflow with conditions How do you handle exceptions in workflow? Exception handling in Workflow is somewhat different than how we do in normal .NET application. Below is the numbered snapshot of how we can handle exceptions in Workflow. 1. We have small tab, which says view exceptions. If you click on view exception, you will be redirected to a workflow design only for exception as shown in numbered snapshot 2. 2. This is the workflow which will execute incase we have exceptions. We have put a code activity, which points to a method called as raise Exception. Incase of exception in the workflow this path will be followed.
Figure 6:- Workflow with exception handling What is the use of XOML files? Twist: - How can we serialize workflows? Windows Workflow Foundation gives developers a declarative way to create workflows by using XAML. See WPF chapter for more details about XAML. These markup files are Stored with XOML (Extensible Object Markup Language) extension. In the below snapshot you can see Workflow1.xoml file created by designer. Markup file can also have code behind. The whole concept of having code behind for XOML file is to separate the presentation from logic files. In the below code snapshot we have made a simple XOML sample. Below is the explanation number wise: 1. In order to create a XOML file you need to add sequential workflow with separation. Which means that XOML file will be created with a behind code. 2. Currently we have two activity code3 and code1. Below is the XOML file contents:
ClrNamespace="System.Workflow.ComponentModel.Compiler" Assembly="System.Workflow.ComponentModel" ?> <SequentialWorkflow x:Class="WorkflowSeq.Workflow1" x:CompileWith="Workflow1.xoml.cs" ID="Workflow1" xmlns:x="Definition" xmlns="Activities"> See the above snippet of the XOML file. You can see how the behind code is linked using the Compile With attribute. Code forms the element of the Sequential Workflow tag. One of the best thing with Markup is we can change the sequence just by changing the XOML file we do not need to compile the whole application again.
Figure 7:- XOML in action In the above snapshot, one of the things to now is 3, 4, and 5 numbered sections. These sections are not linked with the sample. But just to make you aware you can create serialize any workflow and deserialize them again using the text writer object.
How can we pass parameters to workflow? When you call the start workflow function, you can pass as name / value pairs using the dictionary object.
Figure 8:- Passing value to workflow
Windows Communication Foundation(WCF) FAQ: Part I Introduction In this section we will run through a quick FAQ for WCF. I am sure after reading this you will get a good understanding of the fundamentals of WCF. Enjoy… the article
What is .NET 3.0? In one simple equation .NET 3.0 = .NET 2.0 + Windows Communication Foundation + Windows Presentation Foundation + Windows Workflow Foundation + Windows Card Space.
What is Windows Card Space? It was previously known by its codename Info Card. It is a framework by Microsoft, which securely stores digital identities of a user and provides a unified interface to choose the identity for a particular transaction, such as logging in to a website. Windows Card Space is a central part of Microsoft's effort to create an identity met system, or a unified, secure and interoperable identity layer for the internet.
What is WCF? First let us give a short answer to this: - "WCF (Indigo was the code name for WCF) is a unification of .NET framework communication technologies ".WCF is a unification technology, which unites the following technologies:•
What are the important principles of SOA (Service oriented Architecture)? WCF is based on SOA. All big companies are playing big bets on SOA. So how can Microsoft remain behind? So in order to implement SOA architecture easily you need to use WCF. SOA is based on four important concepts:-
•
Boundaries are well defined In SOA, everything is formalized. The client who is consuming the service does not need to know how the implementation of the service is done. If you look at some old methodologies of communication like DCOM. Any changes at server level the client also has to change. Therefore, the server and client implementation was so much bound that changes need to be done at all places. In SOA, the rule is if you do enhancement you do not need to change anything at the client. SOA based application only understands that there is an end point, contract, and bindings. Note: - Just to clarify shortly about end point and contract. Any SOA service is exposed through an end point. End point defines three important aspects What, Where and How. We will understand more details of the same in the later questions.
•
Services evolve Change is the law of nature and services will evolve. In SOA, services can be versioned and you can host those services in new ends. For instance, you have a service called as "Search Tickets (Ticket Number) "which gives details based on Ticket Number and its exposed on end point "ep1". Tomorrow you want make your Search Tickets service more useful by also providing an extra option of allowing him to search by passenger name. Therefore, you just declare a new end "ep2" with service "Search Tickets (Ticket Number, Passenger Name)". So the client who is consuming the service at end ep1 continues and at the other end, we have evolved our service by adding new ends ep2.
•
Services share only schemas and contracts Services use Schemas to represent data and contracts to understand behavior. They do not use language dependent types or classes in order to understand data and behavior. XML is used to define schemas and contracts. Due to this, there is not heavy coupling between environments.
•
Service compatibility is policy based Policy describes the capabilities of the system. Depending on policies, the service can degrade to match the service for the client. For instance your service needs to be hosted for two types of client one which uses Remoting as the communication methodology while other client uses DCOM. An ideal SOA service can cater to both of them according to there communication policies.
Note: - Many people assume Web services are the base for SOA. The answer is 50 % right. What web services lack is the policy based Service compatibility. If you host a web service it can only serve with HTTP communication channel and SOAP message. Any other type of client trying to communicate he will not degrade it self. This is what is provided by WCF. You can host the service in one or more mode. For instance you can host a WCF service using remoting and ASMX.
What are ends, contract, address, and bindings? The above terminologies are the core on which SOA stands. Every service must expose one or more ends by which the service can be available to the client. End consists of three important things where, what and how:-
•
Contract (What) Contract is an agreement between two or more parties. It defines the protocol how client should communicate with your service. Technically, it describes parameters and return values for a method.
•
Address (Where) An Address indicates where we can find this service. Address is a URL, which points to the location of the service.
•
Binding (How) Bindings determine how this end can be accessed. It determines how communications is done. For instance, you expose your service, which can be accessed using SOAP over HTTP or BINARY over TCP. So for each of these communications medium two bindings will be created.
Below figure, show the three main components of end. You can see the stock ticker is the service class, which has an end hosted on www.soa.com with HTTP and TCP binding support and using Stock Ticker interface type.
Figure 2: - Endpoint Architecture Note: - You can also remember the end point by ABC where A stands for Address, B for bindings and C for Contract.
Which specifications does WCF follow? WCF supports specifications defined by WS-* specifications. WS-* specifications are defined together by Microsoft, IBM, SUN and many other big companies so that they can expose there service through a common protocol. WCF supports all specifications defined we will understand them one by one. •
Messaging (WS-Addressing):- SOAP is the fundamental protocol for web services. WS Addressing defines some extra additions to SOAP headers, which makes SOAP free from underlying transport protocol. One of the good things about Message transmission is MTOM, also termed as Message Transmission Optimization Mechanism. They optimize transmission format for SOAP messages in XML-Binary formant using XML optimized packaging (XOP). Because the data will sent in binary and optimized format, it will give us huge performance gain.
•
Security (WS-Security, WS-Trust, and WS-Secure Conversation):- All the three WSdefine authentication, security, data integrity and privacy features for a service.
•
Reliability (WS-Reliable Messaging):- This specification ensures end-to-end communication when we want SOAP messages to be traversed back and forth many times.
•
Transactions (WS-Coordination and WS-Atomic Transaction):- These two specifications enable transaction with SOAP messages.
•
Metadata (WS-Policy and WS-Metadata exchange):- WSDL is a implementation of WS-Metadata Exchange protocol. WS-Policy defines more dynamic features of a service, which cannot be expressed by WSDL.
We have stressed on the WS-* specification as it is a specification which a service has to follow to be compatible with other languages. Because WCF follows WS-* specifications other languages like JAVA , C++ can also exploit features like Messaging , Security ,
Reliability and transactions written in C# or VB.NET. This is the biggest achievement of WCF to integrate the above features with other languages. Note: - During interview the interviewer expects that you know what WS-* specification are supported by WCF and its advantages with respect to interacting with other languages.
What are the main components of WCF? We need to define three main components in WCF:•
Service class.
•
Hosting environment
•
End point
Explain how Ends, Contract, Address, and Bindings are done in WCF?
what is a service class? what is a service contract, operation contract and Data Contract? In this example, we will make simple service, which displays the total cost of the complete product group. In simple words, this service will take three parameters per product cost, number of products and the product name. In return the service will return the total cost of all the products by multiplying number of products * cost per product. As we go ahead in this explanation, we will try to understand all the terminologies, which are asked in the above question. First, you need to create a Winfx service project. You can see in the below figure we have selected the Winfx project.
Figure 3: - Create new WinFX Service class In this project, we add a new class and name it as "serviceGetCost.cs". This class will have our core implementation and this is the class, which has all the action. The service class, which has to be exposed to the external client. We need to use the Service Contract attribute to mark it as a service class. Service Contract attribute define saying which application interface will be exposed as a service. You can see in the below code snippet we have made an interface and marked it as Service Contract. It is not essential that you need to use an interface you can also use a simple class and mark it as Service but interface represent a contract and do not have implementation. In short, they stand at a very higher level of abstraction. So as a good design practice-using interface to represent a service contract makes more sense. The next thing to note is the Operation Contract attribute. Operation Contract dictates which methods should be exposed to the external client using this service.
It defines individual exchange or request and replies. In the current sample, we have defined GetTotalCost method, which will be used by the end client to get the total cost results. The next thing to note in the code snippet is the Data Contract attribute. In the previous two steps, we have exposed class as a service by using Service Contract and methods by using Operation Contract. Every operation will definitely do some kind of data transfer. Data Contract attributes defines which type of complex data will be exchanged between the client and the service. They determine which parameters to be serialized. When you are using simple data types like int, bolo etc it is not necessary that you need to mark the data contract attribute. Because you will always find matching types on the client. However, complex structure like one shown in the below code snippet you will need to define a data contract. Remember data contract define how this data will be passed during transmission. In short data contract attribute define how data will be serialized will transmission. In the below sample we have marked the structure product data to be serialized.
Figure 4:- The Service class As data contract are all about serialization you need to import System.Runtime.Serialization name space. In the next step, we implement the GetTotalCost function. It just returns a simple string with product name and the total cost of all products.
Once our service class is done its time to host this service. There are various ways of hosting a WCF service we will look in to the same in the next question. For the current example, we will host in their own process.
Figure 5: - Hosting the service Hosting the WCF service needs two things one is the config file and second is the hosting code on startup. Because we are hosting this service in its own application process this needs to be a windows application. So first let us have a look what entries do, we need to make in the App.config file. In the above figure, everything is clear but let us understands all the section defined in the App.config file. In the configuration section, we need to add a new section <system.serviceModel>. The most important part of <system.serviceModel> is the endpoint tag. As said in the previous answer End gives three important answers Where, What and How. In short where is the service, what the contract of the service is and how do we communicate with the service. In the above code snippet, we have only defined the contract i.e. what and how that is bindings. The where is defined in the application entry point static void main (). Therefore, the contract attribute defines the interface and binding says that the end clients can communicate using "HTTP" protocol. In Static void Main method, we create an object of Service Host class and use the open method to host the service. We have used the URI object to define the address where the service will be hosted.
Figure 6: - Service Started If you compile the project, you will see something as shown in the above figure. This says that the service is up and running and ready to serve any WCF client. Now its time to develop consumer, which will consume this WCF service. Microsoft has provided a decent automation to generate the client. Therefore, below figure depicts the various steps.
Figure 7: - svcutil in action Go to command prompt of windows SDK and run the following command:Svcutil <Service hosted URI> In the above command <Service Hosted URI> is the URI on which the service is hosted. One you run the command against the URI it will generate two files one is the config file and the other is the proxy. You can see in the above figure two files are generated serviceGetCost.cs and output.config file. With the help of these two files, we will make our client.
Figure 8: - Client code walkthrough You can see in the above figure we have made WFCClientGetCost project. In that, we have added output.config and serviceGetCost.cs to the client project. We have renamed output.config to app.config. Once we have done with everything, its time to write the client code, which calls the proxy who in turn will call the service hosted. In the above figure, you can see we have the client code also. It is a simple code we first created the object of the data structure set the values. Then we create the object of the service and call the GetTotalCost function. If everything is compiled and you run the server and client, you should get your output as shown below.
Figure 9: - Output of WCF service
what are the various ways of hosting a WCF service? There are three major ways to host a WCF service:•
Self-hosting the service in his own application domain. This we have already covered in the first section. The service comes in to existence when you create the object of
Service Host class and the service closes when you call the Close of the Service Host class. •
Host in application domain or process provided by IIS Server.
•
Host in Application domain and process provided by WAS (Windows Activation Service) Server.
How do we host a WCF service in IIS? Note: - The best to know how to host a WCF in IIS is by doing a small sample. So what we will do is host the same GetCost sample which was self hosted in the previous question. First thing you will need is to create the SVC file, which exposes the service class. SVC file contains the pointer to the class. You can see from the figure below the class attribute points to the class whose interface is exposed by the service.svc.cs file. Also, note the actual interface is in service.svc.cs file. Below figure, have both the files service.svc, which has the class attribute which points to the service class, and the interface, which resides in service.svc.cs file. We have taken the same sample, which was self-hosted in the previous question.
Figure 10: - The SVC file and the behind code We also need to provide implementation for the interface. So we have made a class ServiceGetCost which has the actual implementation. Below figure shows the same in detail. In the below figure you can also see the solution files.
Figure 11: - Implementation of Service.svc.cs We also need to specify the service type and endpoint in web.config file. Also, note we have specified HTTP binding because we will be hosting the service on IIS.
Figure 12: - Web.config file for hosting service on IIS Now that we are done with the coding part. We need to create the virtual directory in IIS. In the below figure in Step1 and Step2 we have shown how to create the virtual directory in IIS. One important thing to note while creating virtual directory set the access permission to execute.
Figure 13:- IIS Configuration In the third step, we will publish the website to our virtual directory. Note the fourth step in which we have copied the svc file so that the service can be requested. Note: - ASP.NET compilation has changed in ASP.NET 2.0. In 2.0 there is no concept of solution files. So if you want to have full compiled DLL you need to publish the project to a virtual directory. Once you have hosted the SVC file you can test the same by request the service.svc file. If everything works fine you will get something as shown in the below figure
Figure 14:- IIS WCF client Using the Svcutil.exe, you will need to generate the proxy class and the config file. The proxy and config will be same, as we had done for self-hosting. The one important change is the address. The config file URL now points to the service.svc, which is hosted on IIS. You can run the same client, which we had created for self-hosting. The only change you will need to do is change the endpoint address.
Figure 15:- Output of WCF client at IIS LOL…You should get the same output, which we had received, for self-hosting. what are the advantages of hosting WCF Services in IIS as compared to selfhosting? 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 loose 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.
Figure 16:- IIS recycle option
what are the major differences between services and Web services? What is the difference WCF and Web services? Web services can only be invoked by HTTP. While Service or a WCF component can be invoked by any protocol and any transport type. Second web services are not flexible. However, 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. 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 incase 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. Note: - MTOM is discussed in one of the pervious questions in this chapter. 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:-Ths 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 interprocess 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.
Which are the various programming approaches for WCF? What is one-way operation? IsOneWay equal to true ensures that the client does not have to wait for the response. So methods marked by IsOneWay to true should always return void. In this, the caller does not get anything in return so it is called as one-way communication. In order to understand one-way implementation in WCF lets make a code walkthrough of a sample. Note: - You can find code for the same in "WCFIsOneWay" folder in CD.
Figure 17: - One-Way in action Above is the code snippet, which describes practically how one way works in WCF. The above given code snippet is numbered. Below is the explanation according to the numbers marked in figure:1 - This is the code snippet of the server service. We have created a method called as doHugeTask. DoHugeTask makes the method sleep for 5000 MS and then displays the time when the task is completed. 2 - This code snippet is for client. It creates a proxy object of serviceIsOneWay and calls the doHugeTask method. After calling the doHugeTask, the client execution continues ahead. So as a proof, we display the time when the method calling was completed. 3 - This screen shot shows the output given by both server and client. The top window displays the server output and the below windows displays the client output. Note: - You can find the code for the same in WCFIsOneWay folder. For generating the proxies you have to follow the same steps which are shown in the previous steps.
So run the server program first i.e. ServiceIsOneWay and run the client later. You will see the client runs the doHugeTask and moves ahead. Therefore, the client completion time is less than the server is. One more thing to understand is that one way does not give any notification back of completion. Therefore, it is like fire and forgets.
Windows Communication Foundation FAQ: Part II Introduction In this section we will run through a quick FAQ for WCF. I am sure after reading this you will get a good understanding of the fundamentals of WCF. If you have not viewed the Part 1 of WCF article, click here Can you explain duplex contracts in WCF? In duplex contracts when client initiates an operation the server service provides a reference call back Uri back to the client. So the client initiates a call using the proxy class and when server finishes its work it notifies the client using the callback channel. This is called as duplex messaging in WCF. If you remember in the previous question, we had no way to know when the server finished its task.
Figure 18:- Duplex Service code Let us try to understand the duplex concept by doing a small sample. The code snippet is as shown in the above figure. We will extend the previous sample, which was shown in the first question only that now we will provide the notification to the client once the doHugeTask is completed. The first step is to change the service class. Above is the code snippet of the service class. Again, we have numbered them so that we can understand how to implement it practically line by line. So below is the explanation number by number:1 - In the service contract attribute we need to specify the callback contract attribute. This Callback Contract attribute will have the interface, which will define the callback. 2 - This is the interface which client will call. In order that it should be asynchronous, we have defined the one-way attribute on the doHugeTask method. 3 -This is the most important interface. As it forms the bridge of communication between server and client. The server will call the client using Completed method. Client needs to provide implementation for the completed method at the client side and server will call that method once it completes the doHugeTask method. 4 and 5 - In this we implement the Interface Duplex interface and provide implementation for doHugeTask () method. 6 - This is an important step. The OperationContext.Current.GetCallBackChannel will be used to make callback to the client. 7 - We will expose the service using HTTP protocol. In this sample, because we want to do duplex communication we need to use wsDualHttpBinding rather than just using simple Http Binding. This new binding configuration is then assigned to the end on which the service is hosted. This completes the server side explanation for duplex.
Figure: - 19 Duplex Client side code Above is the code snippet for client side. So let us explain the above code with numbers. 1- We implement the completed method. This is the callback method, which the server will call when doHugeTask is completed. 2- In this step we create object of the Instance Context class. Instance Context represents context information of a service. The main use of Instance Context is to handle incoming messages. In short, proxy is used to send messages to server and Instance Context is used to accept incoming messages. 3 -In this step we pass the Instance Context object to the constructor of the proxy. This is needed, as the server will use the same channel to communicate to the client. 4 - In this section two windows are shown. The top windows is the servers output and the below windows is of the client. You can see in the below window that server as made a callback to the client. Note: - You can get source code for the same in WCFDuplex folder. Feel Free to experiment with it. Try making one simple project of client to client chat using WCF duplex fundamentals I am sure your doubts will be cleared in and out. How can we host a service on two different protocols on a single server? Let us first understand what this question actually means. Let us say we have made a service and we want to host this service using HTTP as well as TCP. You must be wondering
why to ever host services on two different types of protocol. When we host a service, multiple types of client consume it and it's very much possible that they have there own protocol of communication. A good service has the capability to downgrade or upgrade its protocol according the client who is consuming him. Let us do a small sample in which we will host the ServiceGetCost on TCP and HTTP protocol. Note: - You can the below sample in "WCFMultipleProtocolGetHost" folder in the CD provided. Below is the code snippet pasted from the same sample? As usual, we have numbered them and here is the explanation of the same:1 and 2 - As we are hosting the service on two protocols we need to create two objects if the URI. You can also give the URI through config file. Pass these two objects of the URI in the constructor parameter when creating the service host object.
Figure 20:- Server side code for Multi Protocol hosting 3 - In the config file we need to define two bindings and end as we are hosting the service in multiple protocols. Once we are done the server side coding its time to see make a client by which we can switch between the protocols and see the results. Below is the code snippet of the client side for multi-protocol hosting.
Figure 21:- Multi Protocol Client code Let us understand the code:1 - In the generated config file we have added two ends. When we generate the config file, it generates only for one protocol. The other end has to be manually added. 2 - To test the same we have a list box, which has the name value given in the end point. 3 - In the list box select event we have then loaded the selected protocol. The selected protocol string needs to be given in the proxy class and finally call the proxy class GetTotalCost. How can we use MSMQ bindings in WCF? First let us understand why MSMQ came in to picture and then rest will follow. Let us take a scenario where your client needs to upload data to a central server. If everything will works fine and the server is available 24 hours to client then there are no issues. In case the server is not available, the clients will fail and the data will not be delivered. There is where MSMQ comes in to picture. It eliminates the need of persistent connection to a server. Therefore, what you do is deploy a MSMQ server and let the clients post message to this MSMQ server. When your actual server runs, it just picks up the message from the queue.
In short, neither the client nor the server needs to be up and running on the same time. In WCF we have a client and service model and in real world it is very much practical possible that both the entities will not be available at one time. In order to use MSMQ you need to install the Message queuing by click on Install windows component and selecting MSMQ queuing. Once that done we are all set to make our sample of MSMQ using WCF
Figure 22:- MSMQ Installation This sample will be simple. We send some messages from the client and keep the server down. As the server is down it will make postings to the MSMQ server. Then we will run the server service and service should pick up the message and display the same.
Figure 23:- MSMQ Server side code walkthrough Above snippet is the server side code. So let us understand the whole snippet:1 - First thing is the queue name where the messages will go if the server is not running. The server name we can get from the config file. You can see in the above snippet we have defined the Mismanage in App.config file. 2 - We first check does this queue exist if it exists then go-ahead. If not then go to create a queue. Please note you need import using System. Messaging namespace. Then we can use the Message Queue to create a queue if the queue does not exist. 3 - First thing which should surprise you is why we are creating a URI with HTTP protocol as we are going to use MSMQ. Ok! This is bit tricky but fun. As we know in order to connect to this service, we need to generate a client proxy using SVCUTIL. Therefore, this URI will help us do that. It is not actually used by the client to connect. 4 - We need our end and the MSMQ bindings.
5 and 6 - Again as usual we need is an interface and implementation for the same. In implementation we have created a method called send Message. Once the above steps are executed, run the server and generate the client proxy using SVCUTIL utility. Now comes the final step making a client. One change you need to make is change the address to the MSMQ server in the app.config. In this, we have just looped ten times and fired an offline message. Please note to keep your server down.
Figure 24:- MSMQ Client side code Now go to computer management and you can see your queue messages waiting to be
picked by the server. Run the server and below should be the output. If you come back again you will see that there are no messages in the queue.
Figure 25:- MSMQ Server side display One of the important concepts is to understand when to use MSMQ protocol. When we expect that client and server will not be available, at one time this is the best option to opt for. Can you explain transactions in WCF? What different transaction isolation levels provided in WCF? Transactions assure that a group of related activity occurs as a single atomic unit. In simple words, every activity in the unit must either all succeed or all should fail. WCF provides a central transaction system that can be used to handle transaction operations. One of the things WCF provides is a single unified transaction system for both database and nondatabase activity. For instance, BeginTrans and CommitTrans are database related syntaxes but we can not use the same for other activities like if we want to upload all message in a single transaction to a MSMQ server. One thing to note is that WCF transaction abides to WS specifications. That means any other language like JAVA can take advantage of this transaction.... I think that is the best part of WCF embracing other languages.
Figure 26:- Transactions in WCF In order to support transaction the service should first support transactions. Above is a simple code snippet of the server service and client and explanation for the same:The top code snippet is of the server service and the below code snippet is of the client.
1 - At interface level the operation contract is attributed with [Transaction Flow] attribute. There are three values for it Allowed (which mean operation mar or may not be used in transaction), Not Allowed (Where it is never used in transaction) and required (Where the service can only be used in transactions). Below code snippet currently says that this service can only be used with transactions. 2 - In this section the [Service Behavior] attribute specifies the transaction isolation level property. Transaction isolation specifies the degree of isolation most compatible with other applications. So let us review what are the different levels you can provide in transaction isolation. The data affected by a transaction is called volatile. Chaos: - pending changes from more highly isolated transactions cannot be overridden. Read Committed: - Volatile data can be modified but it cannot be read during the transaction. Read Uncommitted: - Volatile data can be read as well as modified during the transaction. Repeatable Read: - Volatile data can be read but not modified during the transaction and new data can be added. Serializable: - Volatile data can be only read. However, no modifications and adding of new data is allowed. Snapshot: - Volatile data can be read. However, before modifying the data it verifies if any other transaction had changed data. If yes then it raises error. By default, the System. Transactions infrastructure creates Serializable transactions. 3 - This defines the transaction behavior with in the service. [Operation Behavior] has a property called as transaction scope. Transaction Scope setting indicates that operation must be called within a transaction scope. You can also see TransactionAutoComplete is set to true which indicates that transaction will complete by default if there are no errors. If you do not provide the TransactionAutoComplete to true then you will need to call OperationContext.Current.SetTransactionComplete() to make the transaction complete. Now let us make a walkthrough of the client side code for the service. 4 and 5 - You can see from the client we need to define Isolation level and the scope while making the call to our Update Accounts method Can we do transactions using MSMQ? While doing MSMQ there can be scenarios in the project, where we would like all the messages are uploaded to either MSMQ or all messages read from MSMQ. After any message is read from MSMQ, it is deleted from the queue. Therefore, some times this can be critical if there are exceptions in reading or uploading messages. As said before WCF transaction can be applied to database as well as other operations like MSMQ. So let us try to understand the same by doing a small sample. Below is a numbered code snippet of MSMQ transactions. 1 - Send message is the exposed method in the service. We have marked this method as TransactionScopeRequired=true 2 - On the client side we have use the transaction scope to say that we are starting a transaction to MSMQ server. You can see we have used the send Message to send the messages to MSMQ.
3- We can then use Complete or Dispose method to complete or rollback the transactions. The below MSMQ transaction code ensures that either all messages are send to the server or none are sent. Thus satisfying consistency property of transactions.
Figure 27:- Transaction snippet code Can we have two-way communications in MSMQ? Yes 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. <system.serviceModel> <services> <service name="Samples.StockTickerServ" behaviorConfiguration="CalculatorServiceBehavior"> ... <endpoint address="net.msmq://localhost/private/ServiceModelSamplesVolatile" binding="netMsmqBinding" bindingConfiguration="volatileBinding" contract="Samples.InterfaceStockTicker" /> ... ... 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.
Windows Presentation Foundation (WPF) Beginners FAQ Introduction In this article we will go through FAQ's from WPF section. We will start first with understanding why WPF..? and later we will create a small sample hello world project for WPF which will make us understand WPF much better. What is the need of WPF when we had GDI, GDI+ and DirectX? First let us try to understand how display technology has evolved in Microsoft technology.
User32:- This provides the windows look and feel for buttons and textboxes and other UI elements. User32 lacked drawing capabilities.
GDI (Graphics device interface):- Microsoft introduced GDI to provide drawing capabilities. GDI not only provided drawing capabilities but also provided a high level of abstraction on the hardware display. In other words it encapsulates all complexities of hardware in the GDI API. GDI+:- GDI+ was introduced which basically extends GDI and provides extra functionalities like JPG and PNG support, gradient shading and anti-aliasing. The biggest issue with GDI API was it did not use hardware acceleration and did not have animation and 3D support. Note: - Hardware acceleration is a process in which we use hardware to perform some functions rather than performing those functions using the software which is running in the CPU. DirectX:- One of the biggest issues with GDI and its extension GDI+ was hardware acceleration and animation support. This came as a biggest disadvantage for game developers. To answer and server game developers Microsoft developed DirectX. DirectX exploited hardware acceleration, had support for 3D, full color graphics , media streaming facility and lot more. This API no matured when it comes to gaming industry. WPF:- Microsoft almost had 3 to 4 API's for display technologies , so why a need for one more display technology. DirectX had this excellent feature of using hardware acceleration. Microsoft wanted to develop UI elements like textboxes,button,grids etc using the DirectX technology by which they can exploit the hardware acceleration feature. As WPF stands on the top of directX you can not only build simple UI elements but also go one step further and develop special UI elements like Grid, FlowDocument, and Ellipse. Oh yes you can go one more step further and build animations.WPF is not meant for game development. DirectX still will lead in that scenario. In case you are looking for light animation ( not game programming ) WPF will be a choice. You can also express WPF using XML which is also called as XAML.In other words WPF is a wrapper which is built over DirectX. So let's define WPF.
WPF is a collection of classes that simplify building dynamic user interfaces. Those classes include a new set of controls, some of which mimic old UI elements (such as Label, TextBox, Button), and some that are new (such as Grid, FlowDocument and Ellipse). How does hardware acceleration work with WPF? Hardware acceleration is a process in which we use hardware to perform some functions rather than performing those functions using the software which is running in the CPU. WPF exploits hardware acceleration in a two tier manner.
WPF API first detects the level of hardware acceleration using parameters like RAM of video card , per pixel value etc. Depending on that it either uses Tier 0, Tier 1 or Tier 2 rendering mode. Tier 0:- If the video card does not support hardware acceleration then WPF uses Tier 0 rendering mode. In other words it uses software acceleration. This corresponds to working of DirectX version less than 7.0. Tier 1:- If the video card supports partial hardware acceleration then WPF uses Tier 1 rendering mode. This corresponds to working of DirectX version between 7.0 and 9.0. Tier 2:- If the video card supports hardware acceleration then WPF uses Tier 2 rendering mode. This corresponds to working of DirectX version equal or greater than 9.0. Does that mean WPF has replaced DirectX? No, WPF does not replace DirectX. DirectX will still be still needed to make cutting edge games. The video performance of directX is still many times higher than WPF API. So when it comes to game development the preference will be always DirectX and not WPF. WPF is not a optimum solution to make games, oh yes you can make a TIC TAC TOE game but not high action animation games. One point to remember WPF is a replacement for windows form and not directX. So can we define WPF in a precise way?
Windows Presentation Framework is the new presentation API. WPF is a two and three dimensional graphics engine. It has the following capabilities:•
Has all equivalent common user controls like buttons, check boxes sliders etc.
•
Fixed and flow format documents
•
Has all of the capabilities of HTML and Flash
•
2D and 3D vector graphics
•
Animation
•
Multimedia
•
Data binding
Can you explain the overall architecture of WPF?
Above figure shows the overall architecture of WPF. It has three major sections presentation core, presentation framework and milcore. In the same diagram we have shown how other section like direct and operating system interact with the system. So let's go section by section to understand how every section works. User32:- It decides which goes where on the screen.
DirectX:- As said previously WPF uses directX internally. DirectX talks with drivers and renders the content. Milcore:- Mil stands for media integration library. This section is a unmanaged code because it acts like a bridge between WPF managed and DirectX / User32 unmanaged API. Presentation core:- This is a low level API exposed by WPF providing features for 2D, 3D, geometry etc. Presentation framework:- This section has high level features like application controls, layouts. Content etc which helps you to build up your application. Which are the different namespaces and classes in WPF?
There are ten important namespaces / classes in WPF. System.Threading.DispatcherObject All WPF objects derive from the DispatcherObject. WPF works on STA model i.e. Single Threading Apartment Model. The main duty of this object is to handle concurrency and threading. When any message like mouse clicks, button clicks etc are initiated they are sent to the DispatcherObject who verifies whether code is running on the correct thread. In the coming section we will look in to detail how WPF threading works.
System.Windows.DependencyObject When WPF was designed property based architecture was considered. In other words rather than using methods, functions and events object behavior will interact using properties. For now we will only restrict ourselves to this definition. In the coming section we have dedicated question for the same. System.Windows.Media.Visual Visual class is a drawing object which abstracts drawing instructions, how drawing should be drawn like clipping, opacity and other functionalities. Visual class also acts like a bridge between unmanaged MilCore.dll and WPF managed classes. When any class derived from visual it can be displayed on windows. If you want to create your own customized user interface then you can program using visual objects.
System.Windows.UIElement UIElement handled three important aspects layout, input and events. System.Windows.FrameworkElement FrameWorkElement uses the foundation set by UIElement. It adds key properties like HorizontalAlignment , VerticalAlignment , margins etc. System.Windows.Shapes.Shape This class helps us to create basic shapes such as Rectangle, Polygon, Ellipse, Line, and
Path. System.Windows.Controls.Control This class has controls like TextBox,Button,ListBox etc. It adds some extra properties like font,foreground and background colors. System.Windows.Controls.ContentControl It holds a single piece of content. This can start from a simple label and go down to a unit level of string in a layout panel using shapes. System.Windows.Controls.ItemsControl This is the base class for all controls that show a collection of items, such as the ListBox and TreeView. System.Windows.Controls.Panel This class is used for all layout containers-elements that can contain one or more children and arrange them as per specific layout rules. These containers are the foundation of the WPF layout system, and using them is the key to arranging your content in the most attractive, flexible way possible. What is XAML? XAML (pronounced as Zammel) is a declarative XML-based language by which you can define object and properties in XML. XAML document is loaded by a XAML parser. XAML parser instantiates objects and set their properties. XAML describes objects, properties and their relation between them. Using XAML, you can create any kind of objects that means graphical or non-graphical. WPF parses the XAML document and instantiates the objects and creates the relation as defined by XAML. So XAML is a XML document which defines objects and properties and WPF loads this document in actual memory. So is XAML meant only for WPF? No, XAML is not meant only for WPF. XAML is a XML-based language and it had various variants. WPF XAML is used to describe WPF content, such as WPF objects, controls and documents. In WPF XAML we also have XPS XAML which defines an XML representation of electronic documents. Silverlight XAML is a subset of WPF XAML meant for Silverlight applications. Silverlight is a cross-platform browser plug-in which helps us to create rich web content with 2-dimensional graphics, animation, and audio and video. WWF XAML helps us to describe Windows Workflow Foundation content. WWF engine then uses this XAML and invokes workflow accordingly. Can explain the different elements involved in WPF application practically? In order to understand the different elements of WPF, we will do a small 'hello world' sample and in that process we will understand the different elements of WPF.
Note:- For this sample we have VS 2008 express edition. So start VS 2008 express and from the templates select the WPF application as show in the below figure below.
Once we have created the WPF application project you will see two file types one the XAML file and the other is the behind code i.e. XAML.cs. XAML files are nothing but XML files which has all the elements needed to display the windows UI. Every of the XAML elements maps to come class. For instance the 'Window' element maps to 'WpfApplication1.Window1' class , 'Button' elements in XAML file maps to 'System.Windows.Control.Button' class and 'Grid' XAML element is mapped to 'System.Windows.Control.Grid'.
The 'App.XAML' and 'App.XAML.CS' are the entry point files. If we see the code for 'App.XAML.CS' you will see the reference to XAML file which needs to be loaded. So the first code which runs in the application is 'void main()' method from 'App.XAML.CS' which in turn loads the 'Window1.XAML' file for rendering.
We can now connect the behind code method and function to events in XAML file elements.
You can see from the above code snippet how the button element has the click event linked to the 'MyButton_Click' function. 'MyButton_Click' is the method which is in the XAML.CS behind code. So now if you run the code you can see the button and if you click on it you can see the message box for the same.
What are dependency properties?
These dependency properties belong to one class but can be used in another. Consider the below code : Height and Width are regular properties of the Rectangle. But Canvas. Top and Canvas. Left is dependency property as it belongs the canvas class. It is used by the Rectangle to specify its position within Canvas. Are XAML file compiled or built on runtime? XAML files are usually compiled rather than parsing on runtime. But it also supports parsing during runtime. When we build a XAML based project, you will see it creates g.cs extension in obi\Debug folder. Therefore, for every XAML file you will find a g.cs file. For instance, a Shiv.XAML will have Shiv.g.cs file in obi\Debug folder. In short, in runtime you actually do not see the XAML file. But if you want to do runtime, parsing of XAML file it also allows that to be done. Can you explain how we can separate code and XAML? This is one of the most important features of WPF, separating the XAML from the code to be handled. So designers can independently work on the presentation of the application and developers can actually write the code logic independent of how the presentation is.
Figure 16.1:- XAML and behind code in action Above is the code snippet, which shows a XAML file and the code completely detached from the XAML presentation. In order to associate a class with XAML file you need to specify the x: Class attribute. Any event specified on the XAML object can be connected by defining a method with sender and event values. You can see from the above code snippet we have linked the MyClickEvent to an event in the behind code. Note: - You can get a simple sample in WindowsSimpleXAML folder. Feel free to experiment
with the code… experimenting will teach you much more than reading something theoretical. How can we access XAML objects in behind code? To access XAML objects in behind code you just need to define them with the same name as given in the XAML document. For instance in the below code snippet we named the object as objtext and the object is defined with the same name in the behind code.
Figure 16.2 Accessing XAML object Note: - You can get the source code in WindowsAccessXAML folder. What kind of documents are supported in WPF? There are two kind of major document supported in WPF Fixed format documents and Flow format document. Fixed format documents look like PDF format. They display content regardless of screen size and resolution. But flow format document adjust depending on screen size and resolution. Below is the code snippet for fixed format. You can see the document has a look of PDF reader. Step 1 defines the tag to define a document and Step 2 shows how the document looks.
Figure 16.3:- Document viewer in action
(WPF) Windows Presentation Foundation – FAQ Introduction In this section we will make a quick walkthrough of WPF which will help you understand WPF instantly. What is WPF? Windows Presentation Foundation (Avalon was the code name for WPF) is the new presentation API in WinFX. WPF is a two and three dimensional graphics engine. It has the following capabilities:•
Has all equivalent common user controls like buttons, check boxes sliders etc.
•
Fixed and flow format documents
•
Has all of the capabilities of HTML and Flash
•
2D and 3D vector graphics
•
Animation
•
Multimedia
•
Data binding
What is XAML?
XAML (pronounced as Zammel) is a declarative XML-based language by which you can define object and properties in XML. XAML document is loaded by a XAML parser. XAML parser instantiates objects and set there properties. XAML describes objects, properties and there relation in between them. Using XAML, you can create any kind of objects that means graphical or non-graphical. WPF parses the XAML document and instantiates the objects and creates the relation as defined by XAML. So XAML is a XML document which defines objects and properties and WPF loads this document in actual memory. What are dependency properties? These dependency properties belong to one class but can be used in another. Consider the below code snippet: Height and Width are regular properties of the Rectangle. But Canvas. Top and Canvas. Left is dependency property as it belongs the canvas class. It is used by the Rectangle to specify its position within Canvas. Are XAML file compiled or built on runtime? XAML files are usually compiled rather than parsing on runtime. But it also supports parsing during runtime. When we build a XAML based project, you will see it creates g.cs extension in obi\Debug folder. Therefore, for every XAMl file you will find a g.cs file. For instance, a Shiv.XAML will have Shiv.g.cs file in obi\Debug folder. In short, in runtime you actually do not see the XAML file. But if you want to do runtime, parsing of XAML file it also allows that to be done. Can you explain how we can separate code and XAML? This is one of the most important features of WPF, separating the XAML from the code to be handled. So designers can independently work on the presentation of the application and developers can actually write the code logic independent of how the presentation is.
Figure .1:- XAML and behind code in action Above is the code snippet, which shows a XAML file and the code completely detached from the XAML presentation. In order to associate a class with XAML file you need to specify the x: Class attribute. Any event specified on the XAML object can be connected by defining a method with sender and event values. You can see from the above code snippet we have linked the MyClickEvent to an event in the behind code. How can we access XAML objects in behind code? To access XAML objects in behind code you just need to define them with the same name as given in the XAML document. For instance in the below code snippet we named the object as objtext and the object is defined with the same name in the behind code.
Figure .2 Accessing XAML object What kind of documents are supported in WPF? There are two kind of major document supported in WPF Fixed format documents and Flow format document. Fixed format documents look like PDF format. They display content regardless of screen size and resolution. But flow format document adjust depending on screen size and resolution. Below is the code snippet for fixed format. You can see the document has a look of PDF reader. Step 1 defines the tag to define a document and Step 2 shows how the document looks.
Figure 3:- Document viewer in action
SQL Server - FAQ's In this article we will go through the most basic and frequently asked FAQ's on SQL Server. Please do not think that I am writing this article to show shortcuts to candidates who are searching for jobs on SQL Server. But I think no matter how much experience you have, an interview is a different ball game. A good project executioner can get knocked off on simple SQL Server questions. Happy job hunting.... Chapter 1: Database Concepts (Q) What is a Database or Database Management System (DBMS)? Twist: What is the difference between a file and a database? Can files qualify as a database? Note: Probably these questions are too basic for experienced SQL SERVER guys. But from a fresher's point of view, it can be a difference between getting a job and being jobless.
1. Database provides a systematic and organized way of storing, managing and retrieving from a collection of logically related information. 2. Secondly, the information has to be persistent, that means even after the application is closed the information should be persisted. 3. Finally, it should provide an independent way of accessing data and should not be dependent on the application to access the information. Ok, let me spend a few more sentences on explaining the third aspect. Below is a simple figure of a text file that has personal detail information. The first column of the information is Name, second Address and finally Phone Number. This is a simple text file, which was designed by a programmer for a specific application.
Figure 1.1: Non-Uniform Text File It works fine in the boundary of the application. Now, some years down the line a third party application has to be integrated with this file. In order for the third party application to be integrated properly, it has the following options: •
Use the interface of the original application.
•
Understand the complete details of how the text file is organized, example the first column is Name, then Address and finally Phone Number. After analyzing, write a code which can read the file, parse it etc. Hmm, lot of work, right.
That's what the main difference is between a simple file and a database; database has an independent way (SQL) of accessing information while simple files do not (That answers my twisted question defined above). File meets the storing, managing and retrieving part of a database, but not the independent way of accessing data. Note: Many experienced programmers think that the main difference is that file cannot provide multi-user capabilities which a DBMS provides. But if you look at some old COBOL and C programs where files were the only means of storing data, you can see functionalities like locking, multi-user etc. provided very efficiently. So it's a matter of debate. If some interviewers think of this as a main difference between files and database, accept it's going in to debate means probably losing a job. (Just a note for fresher's: Multi-user capabilities mean that at one moment of time more than one user should be able to add, update, view and delete data. All DBMS' provides this
as in-built functionalities, but if you are storing information in files, it's up to the application to write logic to achieve these functionalities). (Q) What is the Difference between DBMS and RDBMS? As mentioned before, DBMS provides a systematic and organized way of storing, managing and retrieving from a collection of logically related information. RDBMS also provides what DBMS provides, but above that, it provides relationship integrity. So in short, we can say: RDBMS = DBMS + REFERENTIAL INTEGRITY For example, in the above Figure 1.1, every person should have an Address. This is a referential integrity between Name and Address. If we break this referential integrity in DBMS and files, it will not complain, but RDBMS will not allow you to save this data if you have defined the relation integrity between person and addresses. These relations are defined by using "Foreign Keys" in any RDBMS. Many DBMS companies claimed that their DBMS product was RDBMS compliant, but according to industry rules and regulations, if the DBMS fulfills the twelve CODD rules, it's truly a RDBMS. Almost all DBMS (SQL SERVER, ORACLE etc.) fulfill all the twelve CODD rules and are considered truly as RDBMS. Note: One of the biggest debates is whether Microsoft Access is an RDBMS? We will be answering this question in later section. (DB)What are CODD Rules? Twist: Does SQL SERVER support all the twelve CODD rules? Note: This question can only be asked on two conditions when the interviewer is expecting you to be at a DBA job or you are complete fresher, yes and not to mention the last one he treats CODD rules as a religion. We will try to answer this question from the perspective of SQL SERVER. In 1969, Dr. E. F. Codd laid down 12 rules, which a DBMS should adhere to in order to get the logo of a true RDBMS. Rule 1: Information Rule "All information in a relational database is represented explicitly at the logical level and in exactly one way - by values in tables." In SQL SERVER, all data exists in tables and are accessed only by querying the tables. Rule 2: Guaranteed Access Rule "Each and every datum (atomic value) in a relational database is guaranteed to be logically accessible by resorting to a combination of table name, primary key value and column name." In flat files, we have to parse and know the exact location of field values. But if a DBMS is truly an RDBMS, you can access the value by specifying the table name, field name, for instance Customers.Fields ['Customer Name']. SQL SERVER also satisfies this rule. In ADO.NET we can access field information using table name and field names. Rule 3: Systematic Treatment of Null Values "Null values (distinct from the empty character string or a string of blank characters and distinct from zero or any other number) are supported in fully relational DBMS for
representing missing information and inapplicable information in a systematic way, independent of data type. In SQL SERVER, if there is no data existing, NULL values are assigned to it. Note NULL values in SQL SERVER do not represent spaces, blanks or a zero value; it is a distinct representation of missing information and thus satisfies rule 3 of CODD. Rule 4: Dynamic On-line Catalog Based on the Relational Model "The database description is represented at the logical level in the same way as ordinary data, so that authorized users can apply the same relational language to its interrogation as they apply to the regular data." The Data Dictionary is held within the RDBMS. Thus, there is no need for off-line volumes to tell you the structure of the database. Rule 5: Comprehensive Data Sub-language Rule "A relational system may support several languages and various modes of terminal use (for example, the fill-in-the-blanks mode). However, there must be at least one language whose statements are expressible, per some well-defined syntax, as character strings and that is comprehensive in supporting all the following items: •
Data Definition
•
View Definition
•
Data Manipulation (Interactive and by program)
•
Integrity Constraints
•
Authorization
•
Transaction boundaries ( Begin, commit and rollback)"
SQL SERVER uses SQL to query and manipulate data, which has a well-defined syntax and is being accepted as an international standard for RDBMS. Note: According to this rule, CODD has only mentioned that some language should be present to support it, but not necessary that it should be SQL. Before the 80's, different's database vendors were providing their own flavor of syntax until in 1980, ANSI-SQL came in to standardize this variation between vendors. As ANSI-SQL is quite limited, every vendor including Microsoft introduced their additional SQL syntax in addition to the support of ANSI-SQL. You can see SQL syntax varying from vendor to vendor. Rule 6: View-updating Rule "All views that are theoretically updatable are also updatable by the system." In SQL SERVER, not only views can be updated by the user, but also by SQL SERVER itself. Rule 7: High-level Insert, Update and Delete "The capability of handling a base relation or a derived relation as a single operand applies not only to the retrieval of data, but also to the insertion, update and deletion of data." SQL SERVER allows you to update views that in turn affect the base tables. Rule 8: Physical Data Independence "Application programs and terminal activities remain logically unimpaired whenever any changes are made in either storage representations or access methods."
Any application program (C#, VB.NET, VB6, VC++ etc) does not need to be aware of where the SQL SERVER is physically stored or what type of protocol it is using, the database connection string encapsulates everything. Rule 9: Logical Data Independence "Application programs and terminal activities remain logically unimpaired when informationpreserving changes of any kind that theoretically permit un-impairment are made to the base tables." Application programs written in C# or VB.NET do not need to know about any structure changes in SQL SERVER database. Example: adding of new field etc. Rule 10: Integrity Independence "Integrity constraints specific to a particular relational database must be definable in the relational data sub-language and storable in the catalog, not in the application programs." In SQL SERVER, you can specify data types (integer, nvarchar, Boolean etc.) which put in data type checks in SQL SERVER rather than through application programs. Rule 11: Distribution Independence "A relational DBMS has distribution independence." SQL SERVER can spread across more than one physical computer and across several networks; but from application programs, it has not a big difference but just specifying the SQL SERVER name and the computer on which it is located. Rule 12: Non-subversion Rule "If a relational system has a low-level (single-record-at-a-time) language, that low level cannot be used to subvert or bypass the integrity Rules and constraints expressed in the higher level relational language (multiple-records-at-a-time)." In SQL SERVER whatever integrity rules are applied on every record are also applicable when you process a group of records using application program in any other language (example: C#, VB.NET, J# etc.). Readers can see from the above explanation that SQL SERVER satisfies all the CODD rules, some database gurus consider SQL SERVER as not truly being an RDBMS, but that's a matter of debate. (Q) Is Access Database a RDBMS? Access fulfills all rules of CODD, so from this point of view, yes it's truly an RDBMS. However, many people can contradict it as a large community of Microsoft professionals think that Access is not an RDBMS. (Q) What is the Main Difference between ACCESS and SQL SERVER? As mentioned before, Access fulfills all the CODD rules and behaves as a true RDBMS. But there's a huge difference from an architecture perspective, due to which many developers prefer to use SQL SERVER as the major database rather than Access. Following is the list of architecture differences between them:
•
Access uses file server design and SQL SERVER uses the Client / Server model. This forms the major difference between SQL SERVER and ACCESS. Note: Just to clarify what is client server and file server I will make a quick description of widely accepted architectures. There are three types of architectures:
○
Main frame architecture (This is not related to the above explanation but just mentioned as it can be useful during an interview and also for comparing with other architectures)
○
File sharing architecture (Followed by ACCESS)
○
Client Server architecture (Followed by SQL SERVER).
In Main Frame architecture, all the processing happens on central host server. User interacts through a dumb terminal that only sends keystrokes and information to the host. All the main processing happens on the central host server. So the advantage in such type of architecture is that you need least configuration clients. But the disadvantage is that you need a robust central host server like Main Frames. In File sharing architecture, which is followed by Access database, all the data is sent to the client terminal and then processed. For instance, if you want to see customers who stay in India, in File Sharing architecture all customer records will be sent to the client PC regardless whether the customer belongs to India or not. On the client PC customer records from India are sorted/filtered out and displayed, in short all processing logic happens on the client PC. Therefore, in this architecture, the client PC should have heavy configuration and it increases network traffic as a lot of data is sent to the client PC. However, the advantage of this architecture is that your server can be of a low configuration.
Figure 1.2: File Server Architecture of Access In client server architecture, the above limitation of the file server architecture is removed. In client server architecture, you have two entities, client and the database server. File server is now replaced by database server. Database server takes up the load of processing any database related activity and the client does any validation aspect of database. As the work is distributed between the entities it increases scalability and reliability. Second, the
network traffic also comes down as compared to file server. For example if you are requesting customers from India, database server will sort/ filter and send only Indian customer details to the client, thus bringing down the network traffic tremendously. SQL SERVER follows the client-server architecture.
Figure 1.3: Client Server Architecture of SQL SERVER
•
The second issue comes in terms of reliability. In Access, the client directly interacts with the Access file, in case there is some problem in the middle of a transaction, there are chances that an Access file can get corrupt. But in SQL SERVER, the engine sits in between the client and the database, so in case of any problems in the middle of a transaction, it can revert back to its original state. Note: SQL SERVER maintains a transaction log by which you can revert back to your original state in case of any crash.
•
When your application has to cater to a huge load demand, highly transactional environment and high concurrency, then its better to go for SQL SERVER or MSDE.
•
But when it comes to cost and support, Access stands better than SQL SERVER. In case of SQL SERVER, you have to pay for per client license, but Access runtime is free.
Summarizing: SQL SERVER gains points in terms of network traffic, reliability and scalability whereas Access gains points in terms of cost factor. (Q) What is the Difference between MSDE and SQL SERVER 2000? MSDE is a royalty free, redistributable and cut short version of the giant SQL SERVER database. It is primarily provided as a low cost option for developers who need a database server, which can easily be shipped and installed. It can serve as a good alternative for Microsoft Access database as it overcomes quite a few problems which Access has. Below is a complete list, which can give you a good idea of the differences:
•
Size of database: Microsoft Access and MSDE have a limitation of 2GB while SQL SERVER has 1,048,516 TB1.
•
Performance degrades in MSDE 2000 when maximum number of concurrent operations goes above 8 or is equal to 8. It does not mean that you cannot have more than eight concurrent operations but the performance degrades. Eightconnection performance degradation is implemented by using SQL SERVER 2000 workload governor (we will be looking into more detail of how it works). As compared to SQL SERVER 2000, you can have 32,767 concurrent connections.
•
MSDE does not provide OLAP and Data warehousing capabilities.
•
MSDE does not have support facility for SQL mail.
•
MSDE 2000 does not have GUI administrative tool such as enterprise manager, Query analyzer or Profiler. But there are roundabout ways by which you can manage MSDE 2000:
○
Old command line utility OSQL.EXE
○
VS.NET IDE Server Explorer: Inside VS.NET IDE, you have a functionality which can give you a nice GUI administrative tool to manage IDE.
○
SQL SERVER WEB Data administrator installs a web based GUI which you can use to manage your database. For any details refer here.
•
SQL-DMO objects can be used to build your custom UI
•
There are many third party tools, which provide administrative capability GUI, which is out of scope of the book as it is only meant for interview questions.
•
MSDE does not support Full text search.
Summarizing: There are two major differences: The first is the size limitation (2 GB) of the database and second is the concurrent connections (eight concurrent connections) which are limited by using the workload governor. During an interview, this answer will suffice if the interviewer is really testing your knowledge. (Q) What is SQL SERVER Express 2005 Edition? Twist: What is the difference between SQL SERVER Express 2005 and MSDE 2000? Note: Normally comparison is when the product is migrating from one version to other version. When SQL SERVER 7.0 was migrating to SQL 2000, asking differences was one of the favorite questions. SQL SERVER Express edition is a scaled down version of SQL SERVER 2005 and the next evolution of MSDE. Listed below are some major differences between them: •
MSDE maximum database size is 2GB while SQL SERVER Express has around 4GB.
•
In terms of programming language support MSDE has only TSQL, but SQLSERVER Express has TSQL and .NET. In SQL SERVER Express 2005, you can write your stored procedures using .NET.
•
SQL SERVER Express does not have connection limitation, which MSDE had and was controlled through the workload governor.
•
There was no XCOPY support for MSDE, SQL SERVER Express has it.
•
DTS is not present in SQL SERVER express while MSDE has it.
•
SQL SERVER Express has reporting services while MSDE does not.
•
SQL SERVER Express has native XML support and MSDE does not.
Note: Native XML support means now in SQL SERVER 2005:
•
You can create a field with data type XML.
•
You can provide SCHEMA to the SQL SERVER fields with XML data type.
•
You can use new XML manipulation techniques like XQUERY also called as XML QUERY.
There is a complete chapter on SQL SERVER XML Support, so till then this will suffice. Summarizing: The major difference is the database size (2 GB and 4 GB), support of .NET support in stored procedures and native support for XML. This much can convince the interviewer that you are clear about the differences. (DB) What is SQL Server 2000 Workload Governor? Workload governor limits the performance of SQL SERVER Desktop engine (MSDE) if the SQL engine receives more load than what is meant for MSDE. MSDE was always meant for trial purpose and non-critical projects. Microsoft always wanted companies to buy their full blow version of SQL SERVER, so in order that they can put limitation on MSDE performance and number of connections, they introduced Workload governor. Workload governor sits between the client and the database engine and counts the number of connections per database instance. If Workload governor finds that the number of connections exceeds eight connections, it starts stalling the connections and slowing down the database engine. Note: It does not limit the number of connections but makes the connection request go slow. By default 32,767 connections are allowed both for SQL SERVER and MSDE. But it just makes the database engine go slow above eight connections. What is the Difference between SQL SERVER 2000 and 2005? Twist: What is the difference between Yukon and SQL SERVER 2000? Note: This question will be one of the favorites during SQL SERVER interviews. I have marked the points which should be mentioned by developers as PG and DBA for Database Administrator. Following are some major differences between the two versions: •
(PG) The most significant change is the .NET integration with SQL SERVER 2005. Stored procedures, user-defined functions, triggers, aggregates, and user-defined types can now be written using your own favorite .NET language (VB.NET, C#, J# etc.). This support was not there in SQL SERVER 2000 where the only language was T-SQL. In SQL 2005, you have support for two languages T-SQL and .NET.
•
(PG) SQL SERVER 2005 has reporting services for reports which is a newly added feature and does not exist for SQL SERVER 2000. It was a separate installation for SQL Server 2000.
•
(PG) SQL SERVER 2005 has introduced two new data types varbinary (max) and XML. If you remember in SQL SERVER 2000, we had image and text data types. Problem with image and text data types is that they assign the same amount of storage irrespective of what the actual data size is. This problem is solved using
varbinary (max) which acts depending on amount of data. One more new data type is included XML which enables you to store XML documents and does schema verification. In SQL SERVER 2000, developers used varchar or text data type and all validation had to be done programmatically. •
(PG) SQL SERVER 2005 can now process direct incoming HTTP request without IIS Web server. In addition, stored procedure invocation is enabled using the SOAP protocol.
•
(PG) Asynchronous mechanism is introduced using server events. In Server event model the server posts an event to the SQL Broker service, later the client can come and retrieve the status by querying the broker.
•
For huge databases, SQLSERVER has provided a cool feature called “Data partitioningâ€Â. In data partitioning, you break a single database object such as a table or an index into multiple pieces. But for the client application accessing the single database object, “partitioning†is transparent.
•
In SQL SERVER 2000, if you rebuilt clustered indexes even the non-clustered indexes where rebuilt. But in SQL SERVER 2005 building the clustered indexes does not build the non-clustered indexes.
•
Bulk data uploading in SQL SERVER 2000 was done using BCP (Bulk copy program's) format files. Now in SQL SERVER 2005 bulk, data uploading uses XML file format.
•
In SQL SERVER 2000 there were maximum 16 instances, but in 2005 you can have up to 50 instances.
•
SERVER 2005 has support of “Multiple Active Result Sets†also called as “MARSâ€Â. In previous versions of SQL SERVER 2000 in one connection, you could only have one result set. Now in one SQL connection, you can query and have multiple results set.
•
In previous versions of SQL SERVER 2000, system catalog was stored in the master database. In SQL SERVER 2005, it's stored in a resource database which is stored as sys object. You cannot access the sys object directly as in the older version we were accessing the master database.
•
This is one of the hardware benefits which SQL SERVER 2005 has over SQSERVER 2000 – support of hyper threading. WINDOWS 2003 supports hyper threading; SQL SERVER 2005 can take advantage of the feature unlike SQL SERVER 2000 which did not support hyper threading. Note: Hyper threading is a technology developed by INTEL which creates two logical processors on a single physical hardware processor.
•
SMO will be used for SQL Server Management.
•
AMO (Analysis Management Objects) to manage Analysis Services servers, data sources, cubes, dimensions, measures, and data mining models. You can mapm AMO in old SQL SERVER with DSO (Decision Support Objects).
•
Replication is now managed by RMO (Replication Management Objects). Note: SMO, AMO and RMO are all using .NET Framework.
•
SQL SERVER 2005 uses current user execution context to check rights rather than ownership link chain, which was done in SQL SERVER 2000. Note: There is a question on this later see for execution context questions.
•
In previous versions of SQL SERVER the schema and the user name was same, but in current, the schema is separated from the user. Now the user owns schema. Note: There are questions on this, refer “Schema†later. Note: Ok below are some GUI changes.
•
Query analyzer is now replaced by query editor.
•
Business Intelligence development studio will be used to create Business intelligence solutions.
•
OSQL and ISQL command line utility is replaced by SQLCMD utility.
•
SQL SERVER Enterprise manager is now replaced by SQL SERVER Management studio.
•
SERVER Manager which was running in system tray is now replaced by SQL Computer manager.
•
Database mirror concept is supported in SQL SERVER 2005, which was not present in SQL SERVER 2000.
•
In SQL SERVER 2005 Indexes can be rebuilt online when the database is in actual production. If you look back in SQL SERVER 2000, you cannot do insert, update, and delete operations when you are building indexes.
•
(PG) Other than Serializable, Repeatable Read, Read Committed, and Read Uncommitted isolation levels, there is one more new isolation level “Snapshot Isolation levelâ€Â. Note: We will see “Snapshot Isolation level†in detail in the coming questions.
Summarizing: The major significant difference between SQL SERVER 2000 and SQL SERVER 2005 is in terms of support of .NET Integration, Snap shot isolation level, Native XML support, handling HTTP request, Web service support and Data partitioning. You do not have to really say all the above points during an interview. A sweet summary and you will rock. (Q) What are E-R diagrams? E-R diagram also termed as Entity-Relationship diagram shows the relationship
between
various tables in the database. Example: Tables Customer and Customer Addresses have a one to many relationship (i.e. one customer can have multiple addresses) this can be shown using the ER diagram. ER diagrams are drawn during the initial stages of a project to forecast how the database structure will shape up. Below is a screen shot of a sample ER diagram of 'Asset Management' which ships free with Access.
Figure 1.4: Asset management ER diagram. (Q) How many Types of Relationship Exist in Database Designing? There are three major relationship models:
•
One-to-one
Figure 1.5: One-to-One relationship ER diagram
•
One-to-many In this many records in one table correspond to the one record in another table. Example: Every one customer can have multiple sales. So there exist one-to-many relationships between customer and sales table. One Asset can have multiple Maintenance. So Asset entity has one-to-many relationship between them as the ER model shows below.
Figure 1.6: One-to-Many Relationship ER diagram
•
Many-to-many In this, one record in one table corresponds to many rows in another table and also vice-versa. For instance: In a company, one employee can have many skills like Java , C# etc. and also one skill can belong to many employees. Given below is a sample of many-to-many relationship. One employee can have knowledge of multiple Technology. So in order to implement this, we have one more table Employee Technology which is linked to the primary key of Employee and Technology table.
Figure 1.7: Many-to-Many Relationship ER diagram (Q) What is Normalization? What are the Different Types of Normalization? Note: A regular .NET programmer working on projects often stumbles on this question, which is but obvious. The bad part is sometimes the interviewer can take this as a very basic question to be answered and it can be a turning point for the interview. So let's cram it. It is set of rules that have been established to aid in the design of tables that are meant to be connected through relationships. This set of rules is known as Normalization. Benefits of Normalizing your database include: •
Avoiding repetitive entries
•
Reducing required storage space
•
Preventing the need to restructure existing tables to accommodate new data
•
Increased speed and flexibility of queries, sorts, and summaries
Note: During an interview, people expect to answer a maximum of three normal forms and that's what is expected practically. Actually you can normalize database to fifth normal form. But believe this book, answering three normal forms will put you in a decent shape during an interview. The three normal forms as follows: First Normal Form For a table to be in first normal form, data must be broken up into the smallest units possible. In addition to breaking data up into the smallest meaningful values, tables in first normal form should not contain repetitions groups of fields.
Figure 1.8: Repeating groups example In the above example, city1 and city2 are repeating. In order for these tables to be in First normal form, you have to modify the table structure as follows. Also note that the Customer Name is now broken down to first name and last name (First normal form data should be broken down to the smallest unit).
Figure 1.9: Customer table normalized to first normal form Second Normal Form The second normal form states that each field in a multiple field primary key table must be directly related to the entire primary key. In other words, each non-key field should be a fact about all the fields in the primary key. In the above table of customer, city is not linked to any primary field.
Figure 1.10: Normalized customer table.
Figure 1.11: City is now shifted to a different master table. That takes our database to a second normal form. Third Normal Form A non-key field should not depend on another Non-key field. The field Total is dependent on Unit price and qty.
Figure 1.12: Fill third normal form So now the Total field is removed and is the multiplication of Unit price * Qty. (Q) What is Denormalization? Denormalization is the process of putting one fact in numerous places (it is vice-versa of normalization). Only one valid reason exists for denormalizing a relational design - to enhance performance. The sacrifice to performance is that you increase redundancy in a database. (DB) Can you Explain Fourth Normal Form? Note: Whenever the interviewer is trying to go above the third normal form, there can be two reasons, ego or to fail you. Three normal forms are really enough, practically anything more than that is an overdose. In fourth normal form, it should not contain two or more independent multi-valued facts about an entity and it should satisfy "Third Normal form". So let us try to see what multi-valued facts are. If there are two or more many-to-many relationship in one entity and they tend to come to one place, it is termed as "multi-valued facts".
Figure 1.13: Multi-valued facts In the above table, you can see that there are two many-to-many relationships between Supplier / Product and “Supplier / Location (or in short multi-valued facts). In order for the above example to satisfy the fourth normal form, both the many-to-many relationships should go in different tables.
Figure 1.14: Normalized to Fourth Normal form. (DB) Can you Explain Fifth Normal Form? Note: UUUHHH if you get this question after joining the company, do ask him if he himself really uses it? Fifth normal form deals with reconstructing information from smaller pieces of information. These smaller pieces of information can be maintained with less redundancy. Example: Dealers sell Product which can be manufactured by various Companies. Dealers in order to sell the Product should be registered with the Company. So these three entities have a mutual relationship within them.
Figure 1.15: Not in Fifth Normal Form. The above table shows some sample data. If you observe closely, a single record is created using lot of small information. For instance: JM Associate can sell sweets under the following two conditions:
•
JM Associate should be an authorized dealer of Cadbury
•
Sweets should be manufactured by Cadbury company
These two smaller bits of information form one record of the above given table. So in order for the above information to be “Fifth Normal Form†all the smaller
information should be in three different places. Below is the complete fifth normal form of the database.
Figure 1.16: Complete Fifth Normal Form (DB) What is the Difference between Fourth and Fifth normal form? Note: There is a huge similarity between Fourth and Fifth normal form, i.e. they address the problem of 'Multi-Valued fact's. "Fifth normal form" multi-valued facts are interlinked and "Fourth normal form" values are independent. For instance in the above two questions Supplier/Product and Supplier/Location are not linked. While in fifth form, the Dealer/Product/Companies are completely linked. (DB) Have you Heard about Sixth Normal Form? Note: Arrrrggghhh yes there exists a sixth normal form also. But note guys you can skip this statement. Just in case you want to impress the interviewer... If you want a relational system in conjunction with time, you use sixth normal form. At this moment SQL Server does not support it directly. (Q) What is Extent and Page? Twist: What is the relationship between Extent and Page? Extent is a basic unit of storage to provide space for tables. Every extent has a number of data pages. As new records are inserted new data, pages are allocated. There are eight data pages in an extent. So as soon as the eight pages are consumed, it allocates a new extent with data pages. While extent is basic unit storage from a database point of view, page is a unit of allocation within extent. (DB) What are the Different Sections in Page? Page has three important sections: •
Page header
•
Actual data i.e. Data row
•
Row pointers or Row offset
Page header has information like timestamp, next page number, previous page number etc.
Data rows are where your actual row data is stored. For every data row, there is a row offset which points to that data row.
Figure 1.17: General view of a Extent (Q) What are Page Splits? Pages are contained in extent. Every extent will have around eight data pages. But all the eight data pages are not created at once; they are created depending on data demand. So when a page becomes full it creates a new page, this process is called as "Page Split". (Q) In which Files does SQL Server Actually Store Data? Any SQL Server database is associated with two kinds of files: *.mdf and *.ldf. *.mdf files are actual physical database files where your data is stored finally. *.ldf (LOG) files are actually data, which is recorded from the last time data was committed in the database.
Figure 1.18: MDF and LDF files. (Q) What is Collation in SQL Server? Collation refers to a set of rules that determine how data is sorted and compared. Character data is sorted using rules that define the correct character sequence, with options for specifying case-sensitivity, accent marks, kana character types, and character width.
Figure 1.19: Collation according to language Note: Different languages will have different sort orders.
Case Sensitivity If A and a, B and b, etc. are treated in the same way, then it is case-insensitive. A computer treats A and a differently because it uses ASCII code to differentiate the input. The ASCII value of A is 65, while a is 97. The ASCII value of B is 66 and b is 98. Accent Sensitivity If a and A, o and O are treated in the same way, then it is accent-insensitive. A computer treats a and A differently because it uses ASCII code for differentiating the input. The ASCII value of a is 97 and A 225. The ASCII value of o is 111 and O is 243. Kana Sensitivity When Japanese kana characters Hiragana and Katakana are treated differently, it is called Kana sensitive. Width Sensitivity When a single-byte character (half-width) and the same character when represented as a double-byte character (full-width) are treated differently then it is width sensitive. (DB) Can We Have a Different Collation for Database and Table? Yes, you can specify different collation sequence for both the entities differently.
ASP.NET FAQ's: Part I Introduction In this section we will touch base on one of important concepts in ASP. NET. Happy job hunting........ (B) What is the sequence in which ASP.NET events are processed? Following is the sequence in which the events occur:•
Page_Init.
•
Page Load.
•
Control events
•
Page- Unload event.
Page_init event only occurs when first time the page is started, but Page Load occurs in subsequent request of the page.
(B) In which event are the controls fully loaded? Page load event guarantees that all controls are fully loaded. Controls are also accessed in Page_Init events but you will see that view state is not fully loaded during this event.5 (B) How can we identify that the Page is Post Back? Page object has an "IsPostBack" property, which can be checked to know that is the page posted back. (B) How does ASP.NET maintain state in between subsequent request? Refer Caching chapter. (A) What is event bubbling? Server controls like Data grid, Data List, and Repeater can have other child controls inside them. Example Data Grid can have combo box inside data grid. These child control do not raise there events by themselves, rather they pass the event to the container parent (which can be a data grid, data list, repeater), which passed to the page as "ItemCommand" event. As the child control send events to parent it is termed as event bubbling. (B) How do we assign page specific attributes? Page attributes are specified using the @Page directive. (A) How do we ensure view state is not tampered? Using the @Page directive and setting 'EnableViewStateMac' property to True. (B) What is the use of @ Register directives? @Register directive informs the compiler of any custom server control added to the page. (B) What is the use of Smart Navigation property? It's a feature provided by ASP. NET to prevent flickering and redrawing when the page is posted back. Note:- This is only supported for IE browser. Project is who have browser compatibility as requirements have to think some other ways of avoiding flickering. (B) What is AppSetting Section in "Web.Config" file? Web.config file defines configuration for a web project. Using "AppSetting" section, we can define user-defined values. Example below defined is "Connection String" section, which will be used through out the project for database connection. (B) Where is View State information stored? In HTML Hidden Fields. (I) what is the use of @ Output Cache directive in ASP.NET. It is used for caching. See more for Caching chapter.
(B) How can we create custom controls in ASP.NET? User controls are created using .ASCX in ASP.NET. After .ASCX file is created you need to two things in order that the ASCX can be used in project:. •
Register the ASCX control in page using the
•
Now to use the above accounting footer in page you can use the below directive.
(B) How many types of validation controls are provided by ASP.NET? There are six main types of validation controls:RequiredFieldValidator It checks whether the control have any value. It is used when you want the control should not be empty. RangeValidator It checks if the value in validated control is in that specific range. Example TxtCustomerCode should not be more than eight lengths. CompareValidator It checks that the value in controls should match some specific value. Example Textbox TxtPie should be equal to 3.14. RegularExpressionValidator When we want the control, value should match with a specific regular expression. CustomValidator It is used to define User Defined validation. Validation Summary It displays summary of all current validation errors on an ASP.NET page. Note: - It is rare that some one will ask step by step all the validation controls. Rather they will ask for what type of validation which validator will be used. Example in one of the interviews i was asked how will you display summary of all errors in the validation control...just uttered one word Validation summary. (B) Can you explain "AutoPostBack"? If we want the control to automatically post back in case of any event, we will need to check this attribute as true. Example on a Combo Box change we need to send the event immediately to the server side then set the "AutoPostBack" attribute to true.
(B) How can you enable automatic paging in Data Grid? Following are the points to be done in order to enable paging in Data grid:•
Set the "Allow Paging" to true.
•
In PageIndexChanged event set the current page index clicked.
Note: - The answers are very short, if you have implemented practically its just a revision. If you are fresher, just make sample code using Datagrid and try to implement this functionality. (B) What is the use of "GLOBAL.ASAX" file? It allows to execute ASP.NET application level events and setting application-level variables. (B) What is the difference between "Web.config" and "Machine.Config"? "Web.config" files apply settings to each web application, while "Machine.config" file apply settings to all ASP.NET applications. (B) What is a SESSION and APPLICATION object? Session object store information between HTTP requests for a particular user, while application object are global across users.
ASP.NET FAQ's: Part 2 Introduction In this section we will touch base on one of important concepts in ASP. Net. For ASP.NET FAQ's - Part I Happy job hunting...... (I) Do session use cookies? Twist:- How can we make session to not to use cookies ? Left to the user, you will enjoy to find this answer. (I) How can we force all the validation control to run? Page.Validate (B) How can we check if all the validation control are valid and proper? Using the Page.IsValid () property you can check whether all the validation are done. (A) If client side validation is enabled in your Web page, does that mean server side code is not run. When client side validation is enabled server emit's JavaScript code for the custom validators. However, note that does not mean that server side checks on custom validators do not execute. It does this redundant check two times, as some of the validators do not support client side scripting. (A)Which JavaScript file is referenced for validating the validators at the client side? WebUIValidation.js JavaScript file installed at "aspnet_client" root IIS directory is used to validate the validation controls at the client side
(B)How to disable client side script in validators? Set 'EnableClientScript' to false. (A)How can I show the entire validation error message in a message box on the client side? In validation summary set "ShowMessageBox" to true. (B)You find that one of your validations is very complicated and does not fit in any of the validators, what will you do? Best is to go for CustomValidators. Below is a sample code for a custom validator, which checks that a textbox should not have zero value Input: <script language="javascript"> (I)What exactly happens when ASPX page is requested from a browser? Note: - Here the interviewer is expecting complete flow of how an ASPX page is processed with respect to IIS and ASP.NET engine. Following are the steps which occur when we request a ASPX page :The browser sends the request to the webserver. Let us assume that the webserver at the other end is IIS. Once IIS receives the request he looks on which engine can serve this request.When we mean engine means the DLL who can parse this page or compile and send a response back to browser. Which request to map to is decided by file extension of the page requested. Depending on file extension following are some mapping •
.aspx, for ASP.NET Web pages,
•
.aspx, for ASP.NET Web pages,
•
.asmx, for ASP.NET Web services,
•
.config, for ASP.NET configuration files,
•
.ashx, for custom ASP.NET HTTP handlers,
•
.rem, for remoting resources
You can also configure the extension mapping to which engine can route by using the IIS engine.
Figure: - 7.1 following screen shows some IIS mappings Example an ASP page will be sent to old classic ASP.DLL to compile. While .ASPX pages will be routed to ASP.NET engine for compilation.
•
As this book mainly will target ASP.NET we will look in to how ASP.NET pages that is ASPX pages generation sequence occurs. Once IIS passes the request to ASP.NET engine page has to go through two section HTTP module section and HTTP handler section. Both these section have there own work to be done in order that the page is properly compiled and sent to the IIS. HTTP modules inspect the incoming request and depending on that, they can change the internal workflow of the request. HTTP handler actually compiles the page and generates output. If you see your machine.config file you will see following section of HTTP modules
/ rel="nofollow"> The above mapping will show which Namespace handles which functionality. Example FormsAthuentication is handled by "System. Web. Security.FormsAuthenticationModule". If you look at the web.config, section HTTP module is where authentication and authorization happens. Ok now the HTTP handler is where the actual compilation takes place and the output is generated. Following is a paste from HTTP handler section of WEB.CONFIG file. ... •
Depending on the File extension handler decides which Namespace will generate the output. Example all .ASPX extension files will be compiled by System.Web.UI.PageHandlerFactory
•
Once the file is compiled it will be send back again to the HTTP modules and from there to IIS and then to the browser.
Figure: - 7.2 IIS flow from various sections. (B) How can we kill a user session? Session abandon (I) How do you upload a file in ASP.NET? I will leave this to the readers ... Just a hint we have to use System.Web.HttpPostedFile class. (I) How do I send email message from ASP.NET? ASP.NET provides two namespace SystemWEB.mailmessage class and System.Web.Mail.Smtpmail class. Just a small homework creates a Asp.NET project and send a email at [email protected]. Do not Spam. (A) What are different IIS isolation levels? IIS has three level of isolation:-
LOW (IIS process):- In this main IIS, process, and ASP.NET application run in same process. So if any one crashes the other is also affected. Example let us say (well this is not possible) I have hosted yahoo, hotmail .amazon and goggle on a single PC. So all application and the IIS process runs on the same process. In case any website crashes, it affects every one.
Figure: - 7.3 LOW IIS process scenario Medium (Pooled):- In Medium pooled scenario, the IIS, and web application run in different process. Therefore, in this case there are two processes process1 and process2. In process1, the IIS process is running and in process2, we have all Web application running
Figure: - 7.4 Medium pooled scenario High (Isolated):-In high isolated scenario every process is running is there own process. In below figure there are five processes and every one handling individual application. This consumes heavy memory but has highest reliability.
Figure: - 7.5 High isolation scenario (A)ASP used STA threading model, what is the threading model used for ASP.NET. ASP.NET uses MTA threading model. (A)What is the use of <%@ page aspcompat=true %> attribute? This attribute works like a compatibility option. As mentioned before ASP worked in STA model and ASP.NET works in MTA model, but what if your ASP.NET application is using a VB COM component. In order that VB COM runs properly in ASP.NET threading model, we have to set attribute. After defining the ASPCOMPAT directive attribute ASP.NET pages runs in STA model thus building the compatibility between ASP.NET and old COM components that does not support MTA model. (B) Explain the differences between Server-side and Client-side code? Server side code is executed at the server side on IIS in ASP.NET framework, while client side code is executed on the browser. (I)Can you explain Forms authentication in detail? In old ASP if you where said to create a login page and do authentication you have to do hell lot of custom coding. Now in ASP.NET that has made easy by introducing Forms authentication. So let us see in detail what form authentication is. Forms authentication uses a ticket cookie to see that user is authenticated or not. That means when user is authenticated first time a cookie is set to tell that this user is authenticated. If the cookies expire then Forms authentication mechanism sends the user to the login page. Following are the steps, which defines steps for Forms authentication:•
Configure Web.config file with forms authentication. As shown below in the config file you can see we have give the cookie name and loginurl page. <system.web>
•
Remove anonymous access to the IIS web application, following are changes done to web.config file. <system.web> <deny users="?" />
•
Create the login page, which will accept user information. You will have create your login page that is the Login.aspx, which will actually take the user data.
•
Finally a small coding in the login button. Let us assume that the login page has two textboxes TX name and txtapssword. Also, import System.Web.Security and put the following code in login button of the page. If Page.IsValid Then If FormsAuthentication.Authenticate(txtName.Text, txtPassword.Text) Then FormsAuthentication.RedirectFromLoginPage(txtName.Text, False) Else lblStatus.Text = "Error not proper user" End If End If
(A)How do I sign out in forms authentication? FormsAuthentication.Signout () (A)If cookies are not enabled at browser end does form Authentication work? No, it does not work. (A)How to use a checkbox in a data grid? Twist: - How can I track event in checkbox, which is one of the columns of a data grid? Note: - This is normally asked when the interviewer want to see that have you really worked practically on a project. Following are the steps to be done:In ASPX page you have to add Item template tag in data grid.
If you look at the Item template, we have "OnCheckChanged" event. This "OnCheckChanged" event has "Check Clicked" subroutine is actually in behind code. Note this method, which is in behind code, should either be "protected" or "public" Following below is the subroutine, which defines the method Protected Sub Check Clicked (By Val sender As Object, By Val e As EventArgs) 'Do something End Sub The above steps should be defined in short to the interviewer, which will give a quick feeling of your practical experience with ASP.NET' (I)What are the steps to create a windows service in VB.NET? Windows Services are long-running executable applications that run in its own Windows session, which then has the ability to start automatically when the computer boots and also can be manually paused, stopped or even restarted. Following are the steps to create a service:Create a project of type "Windows Service".
Figure 7.6:Create project for Windows Service If you see, the class created it is automatically inheriting from "System.ServiceProcess.ServiceBase". You can override the following events provided by service and write your custom code. All the three main events can be used that is Start, stop and continue.
protected override void OnStart(string[] args) { } protected override void OnStop() { } protected override void OnContinue() { } Now to install the service you need to do run the install util exe. InstallUtil \BIN\MyNewService.exe (A) What is the difference between "Web farms" and "Web garden"? "Web farms" are used to have some redundancy to minimize failures. It consists of two or more web server of the same configuration and they stream the same kind of contents. When any request comes there is switching / routing logic, which decides which web server from the farm, handles the request. For instance, we have two servers "Server1" and "Server2" which have the same configuration and content. Therefore, there is a special switch, which stands in between these two servers and the users and routes the request accordingly.
Figure 7.7: Web Farm in action Above figure explains in detail how web farm work. You can see there is a router in between which takes a request and sees which one of the server is least loaded and forwards the request to that server. Therefore, for request1 it route is server1, for request2 it routes server2, for request3 it routes to server3 and final request4 is routed to server4. So you can see because we have web farm at place server1 and server2 are loaded with two request each rather than one server loading to full. One more advantage of using this kind of architecture is if one of the servers goes down we can still run with the other server thus having 24x7 uptime. The routing logic can be a number of different options:•
Round robin: Each node gets a request sent to it "in turn". Therefore, server1 gets a request, then server2 again, then server1, then server2 again. As shown in the above figure.
•
Least Active: Whichever node show to have the lowest number of current connects gets new connects sent to it. This is good to help keep the load balanced between the server nodes.
•
Fastest Reply: Whichever node replies faster is the one that gets new requests. This is also a good option - especially if there are nodes that might not be "equal" in
performance. If one performs better than the other, then send more requests there rather than which is moving slowly? Before we try to understand what a web garden is let's try to understand how IIS handles processes. All requests to IIS are routed to "aspnet_wp.exe" for IIS 5.0 and "w3wp.exe" for IIS 6.0. In normal case i.e. with out web garden, we have one worker process instance ("aspnet_wp.exe" / "w3wp.exe") across all requests. This one instance of worker process uses the CPU processor as directed by the operating system.
Figure 7.8: with out Web Garden However, when we enable web garden for a web server it creates different instances of the worker process and each of these worker process runs on different CPU. You can see in the below diagram we have different worker process instances created which run on different CPU's.
Figure 7.9: With Web Garden
multiple CPUs in a single server machine are termed as Web garden.
In short, we can define a model in which multiple processes run on
(A) How do we configure "Web Garden"? "Web garden" can be configured by using process model settings in "machine.config" or "Web.config" file. The configuration section is named <process Model> and is shown in the following example. The process model is enabled by default (enable="true"). Below is the snippet from config file. <process Model enable="true" timeout="infinite" idle Timeout="infinite" shutdown Timeout="0:00:05" requestLimit="infinite" requestQueueLimit="5000" memoryLimit="80" webGarden="false" cpuMask="12" userName=""
password="" logLevel="errors" clientConnectedCheck="0:00:05" /> From the above process model section for web garden, we are concerned with only two attributes "web garden" and "cpuMask". Web Garden: - Controls CPU affinity. True indicates that processes should be affinities to the corresponding CPU. The default is False. CpuMask:- Specifies which processors on a multiprocessor server are eligible to run ASP.NET processes. The cpuMask value specifies a bit pattern that indicates the CPUs eligible to run ASP.NET threads. ASP.NET launches one worker process for each eligible CPU. If web Garden is set to false, cpuMask is ignored and only one worker process will run regardless of the number of processors in the machine. If web Garden is set to true, ASP.NET launches one worker process for each CPU that corresponds to a set bit in cpuMask. The default value of cpuMask is 0xffffffff. Below are detail steps of how to implement web garden •
Click Start and then click Run.
•
Type calc.exe and then click OK.
•
Go to View menu, click Scientific.
•
Go to View menu, click Binary.
•
Use zero and one to specify the processors ASP.NET can or cannot use. Use one for the processor that you want to use for ASP.NET. Use 0 for the processor that you do not want to use for ASP.NET. For example, if you want to use the first two processors for ASP.NET of a four-processor computer, type 1100.
•
On the View menu, click Decimal. Note the decimal number.
•
Open the Web.config or machine.config file in a text editor such as Notepad. The Web.config file is located in the folder where the application is saved.
•
In the Web.config file, add the process Model configuration element under the System. Web element. Before adding <process Model> to Web.config file, the user has to make sure that the allow Definition attribute in the <process Model> section of the Web.config file is set to everywhere.
•
Add and then set the web Garden attribute of the process Model element to True.
•
Add and then set the cpuMask attribute of the process Model element to the result that is determined in your calculation. Do not preface the number with zerox because the result of the calculation is a decimal number.
The following example demonstrates the process Model element that is configured to enable only the first two processors of a four-processor computer. <processModel enable="true" webGarden="true" cpuMask="12" /> Save the Web.config file. The ASP.NET application automatically restarts and uses only the specified processors.
(B) What is the main difference between Grid layout and Flow Layout? Grid Layout provides absolute positioning for controls placed on the page. Developers that have their roots in rich-client development environments like Visual Basic will find it easier to develop their pages using absolute positioning, because they can place items exactly where they want them. On the other hand, Flow Layout positions items down the page like traditional HTML. Experienced Web developers favor this approach because it results in pages that are compatible with a wider range of browsers. If you look in to the HTML code created by absolute positioning you can notice lot of DIV tags. While in Flow layout, you can see more of using HTML table to position elements, which is compatible with wide range of browsers. (I) What's the difference between trace and debug in ASP.NET? Debug and trace enables you to monitor the application for errors and exception with out VS.NET IDE. In Debug mode compiler inserts some debugging code inside the executable. As the debugging code is the part of the executable they run on the same thread where the code runs and they do not given you the exact efficiency of the code ( as they run on the same thread). So for every full executable DLL you will see a debug file also as shown in figure 'Debug Mode'.
Figure 7.10 : Debug mode Trace works in both debug as well as release mode. The main advantage of using trace over debug is to do performance analysis which can not be done by debug. Trace runs on a different thread thus it does not impact the main code thread. Note: - There is also a fundamental difference in thinking when we want to use trace and when want to debug. Tracing is a process about getting information regarding program's execution. On the other hand debugging is about finding errors in the code. (A) How do you enable tracing in on an ASP.NET page? To enable tracing on an ASP.NET page we need to put the 'trace' attribute to true on the page attribute as shown in figure 'Tracing in Action' ( Its numbered as 1 in the figure). In the behind code we can use the trace object to put tracing like one we have shown on the page load numbered as (4). We have used the 'trace.write' to display our tracing. You can also see the trace data which is circled. 2 and 3 show the actual data. You can see how trace shows in details the tracing information for a page with events and time period for execution. If you make the 'trace' as false you will only see the actual display i.e. 'This is the actual data'. So you can enable and disable trace with out actually compiling and uploading new DLL's on production environment.
Figure 7.11 : - Tracing in Action The above sample enables tracing only at page level. To enable tracing on application level we need to modify the 'web.config' file and put the 'trace' tag with 'enabled=true'. (B) Which namespace is needed to implement debug and trace ? Debug and trace class belongs to 'System.Diagnostic' namespace.
(A) Can you explain the concept of trace listener? 'Tracelistener' are objects that get tracing information from the trace class and they output the data to some medium. For instance you can see from the figure 'TraceListener' how it listens to the trace object and outputs the same to UI, File or a windows event log. There are three different types of 'tracelistener' first is the 'defaulttracelistener' (this outputs the data to UI), second is 'textwritertracelistener' (this outputs to a file) and the final one is 'Eventlogtracelistener' which outputs the same to a windows event log.
Figure 7.12 : TraceListener Below is a code snippet for 'textwritertracelistener' and 'eventlogtracelistener'. Using 'textwritertracelistener' we have forwarded the trace's to 'ErrorLog.txt' file and in the second snippet we have used the 'Eventlogtracelistener' to forward the trace's to windows event log.
Figure 7.13 :- Tracelistener in action (I) What are trace switches? Trace switches helps us to control and govern the tracing behavior of a project. There are two types of trace switches 'BooleanSwitch' and 'TraceSwitch'. BooleanSwitch, as the name says, is a kind of on/off switch which can be either enabled (true) or disabled (false).
Figure 7.14 :- Trace switches 'TraceSwitch' on the other hand offers more options rather than simple true/false like 'BooleanSwitch'. Tracing is enabled for a TraceSwitch object using the Level property. When we set the Level property of a switch to a particular level, it includes all levels from the indicated level down. For example, if you set a TraceSwitch's Level property to TraceLevel.Info, then all the lower levels, from TraceLevel.Error to TraceLevel.Warning, will be taken in to account. Below are the various levels in 'TraceSwitch' object. Off a Outputs no messages to Trace Listeners Error a Outputs only error messages to Trace Listeners Warning a Outputs error and warning messages to Trace Listeners Info a Outputs informational, warning and error messages to Trace Listeners Verbose a Outputs all messages to Trace Listeners TraceSwitch objSwitch = new TraceSwitch("TraceWarningandError", "Error in trace") ; objSwitch.Level = TraceLevel.Warning ;
Service Oriented Architecture (SOA) - FAQ's Introduction In my previous section we had concentrated on Design Patterns and UML which is one of the most important fundamentals for architecture interviews. One of the other areas other than both of them which needs to be stronger for architects is understanding of SOA. Again I repeat do not think you get an architecture position by reading interview questions. But yes there should be some kind of reference which will help you quickly revise what are the definition. Just by reading these answers you get to a position where you are aware of the fundamentals. But if you have not really worked you will surely fail with scenario based questions. So use this as a quick revision rather than a shot cut.
Happy job hunting...... (B) What is SOA? SOA stands for service oriented architecture. Before we define SOA lets first define a service. In real world service is what we pay for and we get the intended service. For instance you go to a hotel and order food. Your order first goes to the counter and then it goes to the kitchen where the food is prepared and finally the waiter serves the food.
Figure: - Hotel and services So in order to order a item from a hotel you need the three logical departments / services to work together (counter, kitchen and waiter). In the same manner in software world these services are termed as business services. They are self contained and logical. So let's first define a business service, SOA definition will be just an extension of the same. Definition of business service: - It's a logical encapsulation of self contained business functionality. For instance figure 'order system' shows a simple ordering system which is achieved by different services like payment gateway, stock system and delivery system coming together. All the services are self contained and logical. They are like black boxes. In short we do not need to understand the internal details of how the business service works. For the external world it's just a black box which takes messages and serves accordingly. For instance the 'payment gateway' business service takes message 'check credit' and gives out output does the customer have credit or not. For the 'order system' business service 'payment gateway' service is a black box.
Figure: - Order system
Now let's revise some bullet points of SOA before we arrive to a definition of SOA.
•
SOA components are loosely coupled. When we say loosely coupled means every service is self contained and exist in alone logically. For instance we take the 'payment gateway' service and attach it to a different system.
•
SOA services are black boxes. In SOA services hide there inner complexities. They only interact using messages and send services depending on those messages. By visualizing services as black boxes services become more loosely coupled.
•
SOA service should be self defined: - SOA services should be able to define themselves.
•
SOA Services are maintained in a listing: - SOA services are maintained in a central repository. Applications can search the services in the central repository and use them accordingly.
•
SOA components can be orchestrated and linked to achieve a particular functionality. SOA services can be used/orchestrated in a plug and play manner. For instance figure 'Orchestration' shows two services 'Security service' and 'Order processing service'. You can achieve two types of orchestrations from it one you can check the user first and then process order or vice-versa. Yes you guessed right using SOA we can manage work flow between services in a loosely coupled fashion.
Figure: - Orchestration So let us define SOA. SOA is a architecture for building business applications using loosely coupled services which act like black boxes and can be orchestrated to achieve a specific functionality by linking together. (I) In SOA do we need to build systems from scratch? No. If you need to integrate or make an existing system as a business service, you just need to create loosely coupled wrappers which will wrap your custom systems and expose the systems functionality in generic fashion to the external world. (I) Can you explain business layers and plumbing layers in SOA? In SOA we can divide any architecture in two layers. The first which has direct relevance to business as it carries out business functions. The second layer is a technical layer which
talks about managing computer resources like database, web server etc. This division is needed to identify a service. Consider the figure 'Simple order system'. It has various components which interact with each other to complete the order system functionality.
Figure: - Simple order System The simple order system can be divided in to two layers (see figure 'business and plumbing layer' one which is business related and second which is more technical related. You can see the plumbing layer consisting of data access layer , AJAX , yes more of technical stuff.
Figure: - Business layer and plumbing layer (I) what's the difference between services and components? Services are logical grouping of components to achieve business functionality. Components are implementation approaches to make a service. The components can be in JAVA, C#, C++ but the services will be exposed in a general format like Web Services.
(A) Can you describe the complete architecture of SOA? Figure 'Architecture of SOA' shows a complete view of a SOA. Please note this architecture diagram is not tied up with implementation of Microsoft, IBM etc. It's a general architecture. Any vendor who implements SOA needs to fulfill the below SOA components. How they do it is completely their own technological implementation.
Figure: - Architecture of SOA The main goal of SOA is to connect disparate systems. In order that these disparate system work they should messages to each other. ESB (Enterprise service bus) acts like a reliable post office which guarantees delivery of messages between systems in a loosely coupled manner. ESB is a special layer which delivers messages between applications. In the figure we have shown a huge plump pipe. It's not hardware or some wire etc. It's a group of components/software which helps you to send and receive messages between the disparate applications. Do not try to code your own ESB, you can think of buying one from Microsoft, IBM, Oracle, progress etc. SOA registry is like a reference database of services. It describes what each services do, where are they located and how can they communicate. It's a central reference of metadata for services. SOA workflow allows us to define work flow using the services in SOA registry. We will read more about BPM in the further questions. Service broker reads the work flow and takes services from the SOA registry and ties them together. Service brokers are normally middleware like EAI (Enterprise application
Integration) products. You can get a list of decent EAI from Sun, Microsoft, and IBM etc. Process manager is nothing but the collection of SOA registry, SOA workflow and service broker. SOA supervisor is traffic cop ensuring that services do not have issues. It deals mainly with performance issues of the system so that appropriate service levels are met. If any of the services have performance problems it sends messages to the proper infrastructure to fix the issue. Note: - The above explanation is of general architecture for SOA. Any vendor (Microsoft, IBM, SUN etc) who gives solution for SOA should have the above components in some or other manner. As this is a Software architecture book, we will not be covering specific vendor implementation. We would advise the reader to map the same to their vendor products for better understanding. (I) Can you explain a practical example in SOA?
(I) What are ends, contract, address, and bindings? These three terminologies on which SOA service stands. Every service must expose one or more ends by which the service can be available to the client. End consists of three important things where, what and how:-
•
Contract (What) Contract is an agreement between two or more parties. It defines the protocol how client should communicate with your service. Technically, it describes parameters and return values for a method.
•
Address (Where) An Address indicates where we can find this service. Address is a URL, which points to the location of the service.
•
Binding (How) Bindings determine how this end can be accessed. It determines how communications is done. For instance, you expose your service, which can be accessed using SOAP over HTTP or BINARY over TCP. So for each of these communications medium two bindings will be created.
Below figure, show the three main components of end. You can see the stock ticker is the service class, which has an end hosted on www.soa.com with HTTP and TCP binding support and using Stock Ticker interface type.
Figure: - Endpoint Architecture Note: - You can also remember the end point by ABC where A stands for Address, B for bindings and C for Contract. (I) Are web-services SOA ? SOA is a thinking, it's an architectural concept and web service is one of the technical approach to complete it. Web services are the preferred standards to achieve SOA. •
In SOA we need the services to be loosely coupled. A web service communicates using SOAP protocol which is XML based which is very loosely coupled. It answers the what part of the service.
•
SOA services should be able to describe themselves. WSDL describes how we can access the service.
•
SOA services are located in a directory. UDDI describes where we can get the web service. This nothing but implementation of SOA registry.
Ajax Quick Start FAQ Introduction This FAQ is like a starter kit. It will help you understand the main aspects of Ajax in a rapid fashion.... So get set go.... (B) What problem does Ajax solve?
In order to answer this question first lets understand how does browser and server work when we request any website. Below figure depicts pictorially the web environment. When client sends data to the server it post backs form element data, hidden fields,images,cookie information to the server and server make the page and sends the same information back to the browser. The bad part this happens with every request and response. Below are the issues with the above model:
•
Unnecessary data transfers: - In the above model, unnecessary data is transferred between client and server. For instance, the whole page is posted and refreshed even when we want small data of the page to be refreshed.
Figure 18.1:- The problem
•
Synchronous processing: - When a user requests for a page he has to wait until the complete round trip happens. In short, the request / response work on a synchronous model rather than asynchronous which makes user experience very difficult. How many times it has happened that you are requesting a page and you see the below screen…frustrating right.
Figure 18.2:- Synchronous processing
•
Unnecessary processing by server: - Because we are posting unnecessary information to the server, the server is overloaded with unnecessary processing.
(B) What is Ajax? Ajax is a set of client side technologies that provides asynchronous communication between user interfaces and web server. So the advantages of using Ajax are asynchronous communication, minimal data transfer and server is not overloaded with unnecessary load. (B) What is the fundamental behind Ajax? XmlHttpRequest is the fundamental behind Ajax. This allows the browser to communicate to a back end server asynchronously.XmlHttpRequest object allows the browser to communicate with server with out posting the whole page and only sending the necessary data asynchronously. (B) What is JSON? JSON is a very lightweight data format based on a subset of the JavaScript syntax, namely array and object literals. JSON allows communicating with server in a standard way. JSON is used as communication notation instead of XML. var oBike = { "color" : "Green", "Speed": 200, }; alert(oBike.color); //outputs "Green" alert(oBike.Speed); //outputs 200 The above code creates an javascript object bike with two properties Color and Speed. (B) How do we use XMLHttpRequest object in JavaScript? Below is a code snippet, which shows how to use XMLHttpRequest object. In this code snippet, we are sending a GET request on the local IIS. Below is the explanation of the code snippet according to the numbers specified in the code snippet? •
1,2,3,4 -> This is like checking which is this browser and create the objects accordingly. XMLHttpRequest objects have different ways of technical implementation according to different browsers. In Internet explorer it is an activex object but in other browsers its XMLHttpRequest. So if windows.XMLHttpRequest does not return null then we can create XMLHttpRequest object. If it returns null then we can try creating the activex object Microsoft.XMLHttp object. In case it fails probably then probably we have an older version of XML that is MSXML2. So in the error handling we will try to create the MSXML2 object.
•
5 -> In this snippet, we OPEN the connection to the local host server and specify what type of request we are using. In this case, we are using the GET method.
•
6 -> Finally, we make a request to the server.
•
7 -> Here we get the request sent by the server back to the client browser. This is a blocking call as we need to wait to get the request back from the server. This call is synchronous that means we need to wait for the response from the server.
Figure 18.3:- Basic XMLHTTP code (B) How do we do asynchronous processing using Ajax? xmlHttpObj.onreadystatechange = function1(); Above is the code snippet, which will help us to do asynchronous processing. So function1 () will be called when the XMLHTTP request object goes to on ready state change. (B) What are the various states in XMLHttpRequest and how do we check the same? (B) How can we get response text? (B) How can we send request to the server using the XMLHttpRequest component? Note :- All the above answers are discussed in detail in the below section. •
Abort ():- This method cancels a user request.
•
getAllResponseHeaders ():- Returns a collection of HTTP headers as string. If you want a specific header value, you can use getResponseHeader ("header name")
•
Open ("method", "URL", "async", "uname", "pswd"):- This method takes a URL and other values needed for a request. You can also specify how the request is sent by GET, POST, or PUT. One of the important values is how this request will be sent asynchronously or synchronously. True means that processing is carried after the
send () method, without waiting for a response. False means that processing is waits for a response before continuing. •
Send (content):- Sends a request to the server resource.
•
SetRequestHeader ("label"," value"):- Sets label value pair for a HTTP header.
•
Onreadystatechange: - This is a event handler, which fires at every state change.
•
Ready State: - Returns the current state of the object. ○
0 = uninitialized
○
1 = loading
○
2 = loaded
○
3 = interactive
○
4 = complete
If you want to check the state use if (xmlHttpObj.readyState ==4). •
Response Text: - Returns the response in plain string.
•
Response: - Returns the response as XML. Therefore, this gives us DOM object model, which can then be traversed.
•
Status: - Returns the status as a numeric For instance 404 for "Not Found" or 200 for "OK", 500 for "Server Error" etc.
•
Status Text: - Returns the status as a string. For instance, "not found" or "OK".
(I) How do we pass parameters to the server? Below are the two ways of passing data to server. The first one shows by using GET and the second by POST. xmlHttpObj.open("GET","http://" + location.host + "/XmlHttpExample1/WebForm1.aspx?value=123", true); xmlHttpObj.open("POST","http://" + location.host + "/XmlHttpExample1/WebForm1.aspx?value=123", true); (I) How can we create a class in JavaScript using Atlas? JavaScript is object based language and this a new feature which is provided by Atlas. Using Atlas you can now define classes, do inheritance, create interfaces etc in JavaScript. You can now implement all the object-oriented concepts in JavaScript. So let us understand the same with an example. Once you install the Atlas setup you will get the following JS files and a web.config file as shown in the below figure. In order to use Atlas you need to add the JS files in your project. You can see from the figure below we have added the JavaScript files and the web.config file to the project that was installed with Atlas setup. We also need to add Microsoft.Web.Atlas.dll to the project.Components.js has the class definition, which we will discuss in the coming sections.
Figure 18.4:- Ajax folder structure Below figure has two important code snippets the top one is taken from components' it defines the class definition and the second code snippet is of ASPX page which consumes the JavaScript class. So let us understand all the numbered points one by one. 1. In this section we register namespace-using register Namespace function. We have named our namespace as Namespace Customer. 2. Here we have defined our class clsCustomer.
3. We have defined two properties Customer Code and Customer Name. Both the properties have get and set function. We have also defined a read-only function getCodeAndName, which returns the concatenation of customer code and customer name. 4. Finally we register the class with the namespace.
5. In this section we have consumed the class.getCOdeAndName will display the concatenated value of customer code and customer name.
Note: - You can find the above code in AtlasClass folder. Feel free to experiment with the same.
Figure 18.5:- Code snippet for consuming the class (A) How do we do inheritance-using Atlas? (A) How do we define interfaces using Atlas? Below is a numbered code snippet, which will answer both the upper questions. Let us understand in detail the numbered sections. •
1 and 2 -- This defines the interface definition. Function.abstractMethod () defines a method as abstract.
•
3 - We need to register the interface, which is done by using register Interface method.
•
4, 5 and 6 - Inheritance and Interface is defined when we register the class. Register Class has three inputs. 4th section defines the main class, which needs to be registered. 5th section defines the parent class from which it will inherit. 6th section defines the interface. So clsMyCustomCustomer is the class which derives from clsCustomer and implements I Customer interface.
Figure 18.6:- Inheritance and Interfaces in action (A) How do we reference HTML controls using Atlas? You can reference the above HTML defined button using the below code snippet of JavaScript. We have also attached the on click method with the button. This method will be called when we click the button. var btnVisibility = new Sys.UI.Button($('Button1')); btnVisibility.intialize(); btnVisibility.click.add(onClick);
You can refer other HTML elements like Label, Textbox m Checkbox, Hyperlinks etc using the Sys.UI. Note: - We have added some extra questions in this edition for Ajax as promised. In CD we have provided 'AtlasSetup'. This you need to install to get the below Ajax project template in VS.NET 2005.
Figure 18.7 :- Ajax template One more thing to ensure before we start Ajax is to add the Ajax controls on the tool box. So do the following right click on the tool box ? click choose items ? click 'Browse' button ? add 'C:\Program Files\Microsoft ASP.NET\Atlas\v2.0.50727\Atlas\Microsoft.Web.Atlas.dll'. Once done you should see some new components as shown in figure 'Ajax controls'. Now we are ready to see how Ajax works.
Figure 18.8:-Ajax control (I) Can you explain Scriptmanager control in Ajax?
Scriptmanager control is the central heart of Ajax. They manage all the Ajax related objects on the page. Some of the core objectives of scriptmanager control are as follows:•
Helps load core Ajax related script and library.
•
Provides access to web services.
•
ASP.NET authentication, role and profile services are loaded by scriptmanager control.
•
Provided registration of server controls and behaviors.
•
Enable full or partial rendering of a web page.
•
Provide localization features.
In short , any Ajax enable page should have this control. (B) Can you explain Enablepartialrendering and UpdatePanel control in Ajax? Let's answer the above questions with a simple sample Ajax application. As we move through this application we will be answering the above questions. If you have already installed the Ajax setup and added the reference to 'Microsoft.Web.Atlas.dll' you should see those controls in your tool box as shown in the above figure 'Ajax controls'. Let's follow the below steps to complete this sample: •
So first drag and drop 'ScriptManager' control from the tool box on the ASPX page. We have already discussed in the previous question how important a 'ScriptManager' control. In order to ensure that the full page does not post back we need to make 'EnablePartialRendering' to true. If this is false then the full page will refresh.
•
Now drag the 'UpdatePanel' control from the tool box on the ASPX page. Using 'UpdatePanel' we can restrict the area of post back. In normal ASPX pages the whole page posts back i.e. there is a full refresh. But by using 'UpdatePanel' we define which area has to be refreshed. 'UpdatePanel' forms a container for controls and thus defining the area of post back.
•
Now we drag two controls a button and textbox and put a long loop code as shown in figure 'Long loop code'.
Below figure 'ScriptManager and UpdatePanel' shows how the 'ScriptManager', 'UpdatePanel' and 'EnablePartialRendering' will look like.
Figure 18.9 : - ScriptManager and UpdatePanel
Figure 18.10: - Long loop code Just to understand the inside basics you can switch in to the HTML of the ASPX you should see the below code snippet as shown in figure 'ScriptManager and UpdatePanel code view'. Note: - 'ScriptManager' should come as a first control on any Ajax ASPX page. So:
•
1 -> Defines the 'ScriptManager' control,
•
2 -> Defines the 'UpdatePanel' control,
•
3 -> all the controls should come under 'ContentTemplate' tag and
•
4 -> defines the controls which will be wrapped under the 'UpdatePanel' tag. Figure 'Long loop code' is called on button1 click to do some heavy task so that we can judge the advantage of using Ajax.
Figure 18.11: - Script Manager and Update Panel code view Once done you can check the project with 'EnableRendering' true and with false value to see the effect of how Ajax actually works. (I) Can you explain the concept of triggers in 'UpdatePanel' control? Triggers are child tags for 'UpdatePanel' tag. Many times we would like to update the panel when some event occurs or a value change on a control. This can be achieved by using triggers. There are two types of triggers 'ControlEventTrigger' and 'ControlValueTrigger'. So let's first understand 'ControlEventTrigger'. Using 'ControlEventTrigger' we define on which control and at which event the update panel should refresh. Below is a simple code snippet for 'ControlEventTrigger'. 'ControlEventTrigger' are defined using '' tag. We have numbered the code snippet below so let's understand the same with numbers:•
1 -> We need to define 'ControlEventTrigger' using '' tag.
•
2 -> In this sample we will link trigger in 'UpdatePanel1' with the click event of 'Button1'.
•
3 -> In the '' tag we need to define the control and event using 'ControlId' and 'EventName' properties respectively.
So now when the button click event happens 'UpdatePanel1' is refreshed.
Figure 18.12: - Code snippet for 'ControlEventTrigger' Using 'ControlValueTrigger' we can update a panel when an external control has reached some value. So again we need to define the same in a 'Triggers' tag. We need to put the 'ControlvalueTrigger' tag with control and property defined using the 'ControlId' property. So according to below code snippet when the value of 'Textbox1' changes we need to update the top panel.
Figure 18.13:- 'ControlValueTrigger' code snippet (I) Can you explain the 'UpdateProgress' component?
Some times we have huge task at the back end for processing and we would like to show a user friendly message until the processing finishes. That's where the 'UpdateProgress' control comes in to picture. To use 'UpdateProgress' control we need to use 'UpdatePanel' tag. 'UpdateProgress' forms the child tag of 'UpdatePanel' control. Until the server processing finishes we can display a message which can be defined in the 'ProgressTemplate' tag which is the child tag of 'UpdateProgress' tag.
Figure 18.14:- Update Progress in action (A) How can you do validations in Ajax? We can perform all the necessary validation like required field, type checking, range checking etc using Ajax. Below is a small snippet which shows how to use a required field validator. We have numbered the code snippet to understand the code more proper. •
1 -> We have defined a text box 'TextBox1' which will be validated for required field.
•
2 -> We have defined a simple '<span>' HTML tag which will display the error message.
•
3, 4 and 5 -> We use the XML declarative Ajax script to define that 'TextBox1' has validators and it's a required field validator. To define the required field validator we need the 'RequiredFieldValidator' controls inside the validators.
•
6 -> We then define where the error should be displayed using the 'ValidationErrorLabel'. In this case we will be displaying error in the span 'Validator1' which was defined previously.
Figure 18.15:- Validations in Ajax Note :- The above sample shows a sample for 'requiredFieldValidator' , but we can also use other validators like rangeValidator, typeValidator, rangeValidator and regexValidator. As this is a interview book we will not be getting in to details of the other validators, please feel free to practice some sample for the same. (A) How do we do exception handling in Ajax? Exception handling in Ajax is done using the 'ErrorTemplate' which forms the child tag of 'ScriptManager'. There are three steps to achieve error handling in Ajax. Below figure 'ErrorHandling' in Ajax shows the three steps in a pictorial fashion.
Figure 18.16:- Error Handling in Ajax •
Step 1 -> Right click on the script manager and click 'Create Error Template'.
•
Step 2 -> Once done click on 'Edit Templates'.
•
Step 3 -> Enter which error message you want to display when there is a error and then finally click 'End Template Editing'.
Just click back on the HTML view to see what we have in the HTML. You can see the 'ErrorTemplate' tag is the fundamental driver for handling errors. (A) How do we consume web service in Atlas? There are two ways by which we can consume a web service one is using 'Services' tag and the other is by using properties defined in Ajax components like 'ServicePath' , 'ServiceMethod' and 'ServiceURL'. We can define the web service URL in the 'Services' tag using 'atlas:ServiceReference' tag. 'Path' property defines the web service URL. If we also want to generate javascript proxy we need to set the 'GenerateProxy' to true. We have also set one more property i.e. 'InlineProxy' property needs to be true so that the proxy code is available to the client javascript.
Figure 18.17 :- Referencing web service If you make 'InLineProxy' property to true you should see the below code snippet when do a view source on the browser. <script type="text/javascript"> var WebService=new function() { this.appPath = "http://localhost:4430/AtlasWebSite3/"; var cm=Sys.Net.ServiceMethod.createProxyMethod; cm(this,"HelloWorld"); cm(this,"GetWordList"); } Let's look at the second method using 'ServiceMethod' and 'ServicePath'. Atlas components which display data to the end user have certain properties which help you in consuming web service and invoke methods on those web services. So let's demonstrate a simple sample using the 'AutoCompleteExtender' component. 'AutoCompleteExtender' is used to enhance a text box with auto complete functionalities. Below is a text box which is enhanced with the 'AutoComplete' feature.
Figure 18.18: - Textbox with AutoComplete feature So let's first define the web service. Below is a simple web service which exposes a word list for implementing the auto complete feature in the text box.
Figure 18.19: - Web Service for auto complete functionality Once we have defined the web service we need to drag and drop the 'AutoCompleteExtender' on the ASPX page.
Figure 18.20: - Drag and drop AutoCompleteExtender Now if you do a view source you should see the below code in HTML. We have numbered the code to highlight the important section. •
1 -> This is the 'autocompleteextender' tag which is dragged and dropped from the tool box.
•
2 -> We need to specify the web service URL and the method of the web service. These can be defined using 'ServiceMethod' and 'ServicePath' properties.
•
3 -> We also need to define which text box control the 'AutoCompleteExtender' will be point to. This is achieved by using the 'TargetControlId' property.
That's it, run the program and see text box performing the auto extender functionality.
Figure 18.21: - ServiceMethod and ServicePath The 'ServiceURL' property can be found in DataSource control. (A) How can we consume data directly in web services? We can consume data directly using 'Sys.Data' controls. We know this is a very short answer for such an important question, but the bandwidth of this book does not allow for the same. We suggest the readers to practice some sample using the 'Sys.Data' control. Note: - We have left important controls like Data controls, Login controls, Web part controls, mobile controls and profilescriptservice control. These controls will be rarely asked during interviews, but from project aspects they are very important.