Sunday, April 29, 2012

SDLC


SDLC: A framework that describes the activities performed at each stage of a software
development project.
 
Waterfall Model: For small projects where requirements are 
very clear.
V Model: For big projects where there are a lot of enhance 
ment.
Prototype Model: For small projects where requirements are 
very clear or not clear.
I prefer V Model. V Model is the best one for testing. First verification will come after that validation its the
testers process. Both are important as i concern but most of all validation is some more best than verification. As i
choose validation because to release a quality product at the end validation is necessary so i like to do validation.

Waterfall Model is one of the most widely used Software Development Process.It is also called as "Linear Sequential model" or the "classic life cycle" or iterative model. It is widely used in the commercial development projects. It is called so because here, we move to next phase(step) after getting input from previous phase, like in a waterfall, water flows down to from the upper steps.

In this iterative waterfall model Software Development process is divided into
five phases:-
a)  SRS (Software Requirement Specifications)
b)  System Design and Software Design
c)  Implementation and Unit testing
d)  Integration and System Testing
e)  Operation and Maintenance
Lets discuss all these stages of waterfall model in detail.

Software Requirements Specifications:

This is the most crucial phase for the whole project, here project team along with the customer makes a detailed list of user requirements. The project team chalks out the functionality and limitations(if there are any) of the software they are developing, in detail. The document which contains all this information is called SRS, and it clearly and unambiguously indicates the requirements. A small amount of top-level analysis and design is also documented. This document is verified and endorsed by the customer before starting the project. SRS serves as the input for further phases.

System Design and Software Design:

Using SRS as input, system design is done. System design included designing of software and hardware i.e. functionality of hardware and software is separated-out. After separation design of software modules(see what is modularity) is done.The design process translates requirements into representation of the software that can be assessed for quality before generation of code begins. At the same time test plan is prepared, test plan describes the various tests which will be carried out on the system after completion of development.

Implementation and Unit Testing:

Now that we have system design, code generation begins. Code generation is conversion of design into machine-readable form. If designing of software and system is done well, code generation can be done easily. Software modules are now further divided into units. A unit is a logically separable part of the software. Testing of units can be done separately. In this phase unit testing is done by the developer itself, to ensure that there are no defects.

Integration and System testing:

Now the units of the software are integrated together and a system is built. So we have a complete software at hand which is tested to check if it meets the functional and performance requirements of the customer. Testing is done, as per the steps defined in the test plan, to ensure defined input produces actual results which agree with the required results. A test report is generated which contains test results.

Operation & maintenance:

Now that we have completed the tested software, we deliver it to the client. His feed-backs are taken and any changes,if required, are made in this phase. This phase goes on till the software is retired.
Outputs generated after each phase of Waterfall Model:

Requirements Specifications => SRS, Draft User Manual, Maintenance plan

System Design & Software design => System design document (Hardware and Software design documents), Interface design document, Unit test plan, System test plan
Implementation & Unit testing => Program code, Unit-test report
Integration & system testing => System test report, Final user manual, Working system
Operation & maintenance => No output

 
The Waterfall Model’s linear and sequential methodology does offer a project certain advantages and disadvantages.
Advantages of the Waterfall Model
  • Simplistic to implement and execute for projects and/or company wide
  • Limited demand on resources
  • Large emphasis on documentation
Disadvantages of the Waterfall Model
  • Completed phases cannot be revisited regardless if issues arise within a project
  • Accurate requirement are never gather prior to the completion of the requirement phase due to the lack of clarification in regards to client’s desires.
  • Small changes or errors that arise in applications may cause additional problems
  • The client cannot change any requirements once the requirements phase has been completed leaving them no options for changes as they see their requirements changes as the customers desires change.
  • Excess documentation
  • Phases are cumbersome and slow moving

Advantages of Prototyping
  • Active participation from users and customers
  • Allows customers to change their mind in specifying requirements
  • Customers get a better understanding of the system as it is developed
  • Earlier bug/error detection
  • Promotes communication with customers
  • Prototype could be used as final production
  • Reduced time needed to develop applications compared to the Waterfall method
Disadvantages of Prototyping
  • Promotes constantly redefining project requirements that cause major system rewrites
  • Potential for increased complexity of a system as scope of the system expands
  • Customer could believe the prototype as the working version.
  • Implementation compromises could increase the complexity when applying updates and or application fixes

WCF


WCF (Windows Communication Foundation) :-
WCF is flexible because its services can be hosted in different types of applications. The following lists several common scenarios for hosting WCF services:
IIS
WAS (Windows Activation Service)
Self-hosting
Managed Windows Service
3 major points in WCF :-
Address :- Specifies the location of the service which will be like http://Myserver/MyService.Clients will use this location to communicate with our service.
Binding :- Specifies how the two parties will communicate in term of transport and encoding and protocols
Contract :- Specifies the interface between client and the server. It's a simple interface with some attribute
Web services can only be invoked by HTTP (traditional webservice with .asmx). While WCF Service or a WCF component can be invoked by any protocol (like http, tcp etc.) and any transport type. Second web services are not flexible. However, WCF Services are flexible. If you make a new version of the service then you need to just expose a new end.
The main components of WCF are :-
1. Service class
2. Hosting environment
3. End point
WCF is a unification of .NET framework communication technologies, NET remoting, MSMQ, Web services, COM+.
How to deal with operation overloading while exposing the WCF services :-
By default overload operations (methods) are not supported in WSDL based operation. However by using Name property of OperationContract attribute, we can deal with operation overloading scenario.
[ServiceContract]
interface ICalculator
{
   [OperationContract(Name = "AddInt")]
   int Add(int arg1,int arg2);

   [OperationContract(Name = "AddDouble")]
   double Add(double arg1,double arg2);
}
What is Proxy and how to generate proxy for WCF Services :-
The proxy is a CLR class that exposes a single CLR interface representing the service contract. The proxy provides the same operations as service's contract, but also has additional methods for managing the proxy life cycle and the connection to the service.
The proxy can be generated using Visual Studio by right clicking Reference and clicking on Add Service Reference.
Proxy can also be generated by using SvcUtil.exe command-line utility.
Endpoint :-
Every service must have Address that defines where the service resides, Contract that defines what the service does and a Binding that defines how to communicate with the service. In WCF the relationship between Address, Contract and Binding is called Endpoint. The Endpoint is the combination of Address, Contract and Binding.
Binding:-
A binding defines how an endpoint communicates to the world. A binding defines the transport (such as HTTP or TCP) and the encoding being used (such as text or binary). A binding can contain binding elements that specify details like the security mechanisms used to secure messages, or the message pattern used by an endpoint.
WCF supports nine types of bindings :-
Basic binding
TCP binding
Peer network binding
IPC binding
Web Service (WS) binding
Federated WS binding
Duplex WS binding
MSMQ binding
MSMQ integration binding
Contracts:-
In WCF, all services expose contracts. The contract is a platform-neutral and standard way of describing what the service does.
Service contracts: Describe which operations the client can perform on the service.
There are two types of Service Contracts.
ServiceContract - This attribute is used to define the Interface.
OperationContract - This attribute is used to define the method inside Interface.
[ServiceContract]
interface IMyContract
{
   [OperationContract]
   string MyMethod( );
}
class MyService : IMyContract
{
   public string MyMethod( )
   {
      return "Hello World";
   }
}
Data contracts: Define which data types are passed to and from the service.
There are two types of Data Contracts.
DataContract - attribute used to define the class
DataMember - attribute used to define the properties.
[DataContract]
class Contact
{
   [DataMember]
   public string FirstName;

   [DataMember]
   public string LastName;
}
Fault contracts: Define which errors are raised by the service, and how the service handles and propagates errors to its clients.
Message contracts: Allow the service to interact directly with messages. Message contracts can be typed or untyped.
WCF supports following transport schemas :-
HTTP
TCP
Peer network
IPC (Inter-Process Communication over named pipes)
MSMQ
Difference between WCF and Web services?
Web Services,
1.It Can be accessed only over HTTP
2.It works in stateless environment
WCF,
WCF is flexible because its services can be hosted in different types of applications. The following lists several common scenarios for hosting WCF services:
IIS
WAS
Self-hosting
Managed Windows Service
Web services are not flexible. However, WCF Services are flexible. If you make a new version of the service then you need to just expose a new end.
Various ways of hosting WCF Services :-
Self-hosting the service in his own application domain.
Host in application domain or process provided by IIS Server.
Host in Application domain and process provided by WAS (Windows Activation Service) Server.
Code name for WCF :-
The code name of WCF was Indigo. WCF is a unification of .NET framework communication technologies which unites the following technologies:-
NET remoting
MSMQ
Web services
COM+
How to set the timeout property for the WCF Service client call :-
The timeout property can be set for the WCF Service client call using binding tag.
<client>
   <endpoint
      ...
      binding = "wsHttpBinding"
      bindingConfiguration = "LongTimeout" 
      ...
   />
</client>
<bindings>
   <wsHttpBinding>
      <binding name = "LongTimeout" sendTimeout = "00:04:00"/> 
   </wsHttpBinding>
</bindings>
If no timeout has been specified, the default is considered as 1 minute.
How to configure Reliability while communicating with WCF Services :-
Reliability can be configured in the client config file by adding reliableSession under binding tag.
<system.serviceModel>
   <services>
      <service name = "MyService">
         <endpoint
            address  = "net.tcp://localhost:8888/MyService"
            binding  = "netTcpBinding"
            bindingConfiguration = "ReliableCommunication" 
            contract = "IMyContract"
         />
      </service>
   </services>
   <bindings>
      <netTcpBinding>
         <binding name = "ReliableCommunication">
            <reliableSession enabled = "true"/> 
         </binding>
      </netTcpBinding>
   </bindings>
</system.serviceModel>
Reliability is supported by following bindings only
NetTcpBinding
WSHttpBinding
WSFederationHttpBinding
WSDualHttpBinding
Transport and Message Reliability :-
Transport reliability (such as the one offered by TCP) offers point-to-point guaranteed delivery at the network packet level, as well as guarantees the order of the packets. Transport reliability is not resilient to dropping network connections and a variety of other communication problems.
Message reliability deals with reliability at the message level independent of how many packets are required to deliver the message. Message reliability provides for end-to-end guaranteed delivery and order of messages, regardless of how many intermediaries are involved, and how many network hops are required to deliver the message from the client to the service.
Different elements of WCF Srevices Client configuration file :-
WCF Services client configuration file contains endpoint, address, binding and contract. A sample client config file looks like 
<system.serviceModel>
   <client>
      <endpoint name = "MyEndpoint"
         address  = "http://localhost:8000/MyService/"
         binding  = "wsHttpBinding"
         contract = "IMyContract"
      />
   </client>
</system.serviceModel>
Address formats of the WCF transport schemas :-
Address format of WCF transport schema always follow
[transport]://[machine or domain][:optional port] format.
HTTP Address Format,
http://localhost:8888
"Using HTTP, go to the machine called localhost, where on port 8888 someone is waiting"
When the port number is not specified, the default port is 80.
TCP Address Format,
net.tcp://localhost:8888/MyService
When a port number is not specified, the default port is 808:
net.tcp://localhost/MyService
IPC Address Format,
net.pipe://localhost/MyPipe
We can only open a named pipe once per machine, and therefore it is not possible for two named pipe addresses to share a pipe name on the same machine.
MSMQ Address Format,
net.msmq://localhost/private/MyService
net.msmq://localhost/MyService
Define a service as REST based service in WCF :-
WCF 3.5 provides explicit support for RESTful communication using a new binding named WebHttpBinding.
The below code shows how to expose a RESTful service 
[ServiceContract]
interface IStock
{
[OperationContract]
[WebGet]
int GetStock(string StockId);
}
By adding the WebGetAttribute, we can define a service as REST based service that can be accessible using HTTP GET operation.
Service and client in perspective of data communication :-
A service is a unit of functionality exposed to the world.
The client of a service is merely the party consuming the service.
Namespace is used to access WCF service :-
Service level message and transport level message :-
You can log WCF message at two levels one is service level and the other is transport level. Service level:-In this the messages are logged as they enter the user code or leave the user code. Transport level: - In this the messages are logged as they are ready to be encoded / decoded. You specify the message levels in the diagnostics node as shown in the below code snippet. 
<system.serviceModel> 
<diagnostics>
<messageLogging
logEntireMessage="true"
logMalformedMessages="false"
logMessagesAtServiceLevel="false"
logMessagesAtTransportLevel="true"
maxMessagesToLog="3000"
maxSizeOfMessageToLog="10000"/>
</diagnostics>
</system.serviceModel>

‘Messagelogging’ also has other attributes , below is the short description about the same.
Concept of tracelevel in trace listeners :-
This value indicates what type and level of tracing information you want to record.
Trace level value is specified in ‘source’ tag in switch value. For instance the below ‘web.config’ snippet indicates the trace type as ‘Information’. 
<system.diagnostics>
<sources>
<source name="System.ServiceModel"
switchValue="Information, ActivityTracing">
Enable tracing on the readymade tracing WCF objects :-
We will enable tracing on ‘System.ServiceModel’ tracing object. To enable tracing we need to enable the ‘system.diagnostics’ XML node in the ‘web.config’ file of the WCF service. We need to also define the type of listeners for the ‘System.ServiceModel’ listener object. So we add the ‘listeners’ tag with the type as ‘System.Diagnostics.XmlWriterTraceListener’. We need to also define the file and path where the file is created. For the current scenario we have defined the file as ‘Traces.svclog’ and the folder as ‘c:\’ drive. 
<system.diagnostics>
<sources>
<source name="System.ServiceModel"
switchValue="Information, ActivityTracing">
<listeners>
<add name="log"
type="System.Diagnostics.XmlWriterTraceListener"
initializeData="c:\Traces.svclog" />
</listeners>
</source>
</sources>
</system.diagnostics>

Now if you run the WCF service you can see a XML file created as shown below.
#<E2ETraceEvent xmlns="http://schemas.microsoft.com/2004/06/E2ETraceEvent">
<System xmlns="http://schemas.microsoft.com/2004/06/windows/eventlog/system">
<EventID>0</EventID>
<Type>3</Type>
<SubType Name="Transfer">0</SubType>
<Level>255</Level>
<TimeCreated SystemTime="2009-04-30T03:21:09.5625000Z" />
<Source Name="System.ServiceModel" />
<Correlation ActivityID="{00000000-0000-0000-0000-000000000000}" RelatedActivityID="{d11829b7-d2db-46d5-a4ac-49a37a56376e}" />
<Execution ProcessName="WebDev.WebServer" ProcessID="2660" ThreadID="8" />
<Channel/>
<Computer>COMPAQ-JZP37MD0</Computer>
</System>
<ApplicationData></ApplicationData>
</E2ETraceEvent>
 
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.


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:- Tracelistener in action
Security differences between BasicHttpBinding VS WsHttpBinding :-
In order to understand the security differences between both these entities we will do a small project. In this project we will create two WCF service one service using ‘BasicHttpBinding’ and the second service using ‘WsHttpBinding’. 
Step1:- So let’s first create a simple service using ‘BasicHttpBinding’. For that we just a create a simple WCF project and then modify the ‘ServiceModel’ element as shown below. You can see in the ‘endpoint’ tag we have specified ‘basicHttpBinding’ as the protocol. 
<system.serviceModel>
<services>
<service name="WCFBasicHttpBinding.Service1" behaviorConfiguration="WCFBasicHttpBinding.Service1Behavior">
<!-- Service Endpoints -->
<endpoint address="" binding="basicHttpBinding" contract="WCFBasicHttpBinding.IService1">

<!-- 
Upon deployment, the following identity element should be removed or replaced to reflect the identity under which the deployed service runs. If removed, WCF will infer an appropriate identity automatically.
-->
 
<identity>
<dns value="localhost"/>
</identity>
</endpoint>
<endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange"/>
</service>
</services>
<behaviors>
<serviceBehaviors>
<behavior name="WCFBasicHttpBinding.Service1Behavior">
<!-- To avoid disclosing metadata information, set the value below to false and remove the metadata endpoint above before deployment -->
<serviceMetadata httpGetEnabled="true"/>
<!-- To receive exception details in faults for debugging purposes, set the value below to true. Set to false before deployment to avoid disclosing exception information -->
<serviceDebug includeExceptionDetailInFaults="false"/>
</behavior>
</serviceBehaviors>
</behaviors>
</system.serviceModel>
Step 2 :- We also need to create one more service using ‘WsHttpBinding’. For that you do not need to anything special as such. By default WCF project is created using ‘WsHttpBinding’. Below is how the Web.config file looks like. You can see how the endpoint tag is using ‘wsHttpBinding’. 
<system.serviceModel>
<services>
<service name="WCFWsHttpBindingHttps.Service1" behaviorConfiguration="WCFWsHttpBindingHttps.Service1Behavior">
<!-- Service Endpoints -->
<endpoint address="" binding="wsHttpBinding" contract="WCFWsHttpBindingHttps.IService1">

<!-- 
Upon deployment, the following identity element should be removed or replaced to reflect the identity under which the deployed service runs. If removed, WCF will infer an appropriate identity automatically.
-->
 
<identity>
<dns value="localhost"/>
</identity>
</endpoint>
<endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange"/>
</service>
</services>
<behaviors>
<serviceBehaviors>
<behavior name="WCFWsHttpBindingHttps.Service1Behavior">
<!-- To avoid disclosing metadata information, set the value below to false and remove the metadata endpoint above before deployment -->
<serviceMetadata httpGetEnabled="true"/>
<!-- To receive exception details in faults for debugging purposes, set the value below to true. Set to false before deployment to avoid disclosing exception information -->
<serviceDebug includeExceptionDetailInFaults="false"/>
</behavior>
</serviceBehaviors>
</behaviors> 
</system.serviceModel> 

Step 3 :- We will not be creating any new methods in both the services. We will just use the default code created by the WCF template. So both these services will have a ‘GetData’ function which returns a string. The ‘GetData’ function is a default function created WCF project. 
public class Service1 : IService1
{
public string GetData(int value)
{
return string.Format("You entered: {0}", value);
}
public CompositeType GetDataUsingDataContract(CompositeType composite)
{
if (composite.BoolValue)
{
composite.StringValue += "Suffix";
}
return composite;
}
}

Step 4 :- Now that out services are created we need to create a client which will consume this service. So we have created a simple web application and we have added two references one is a service reference i.e. ‘WsHttpBinding’ and the second is a web reference i.e. ‘BasicHttpBinding’. Please note when you right click to add reference you need to use the ‘Add service reference’ to add ‘WsHttpService’ and you need to add web reference for ‘BasicHttpBinding’. 
 We will add two buttons on the default aspx page. One button will call the http service and the other will call the wshttp service. Below is how the function ‘GetData’ is called in both the button clicks.
 
Step 5 :- So now we are ready with the complete project it is time to sniff and see how data is transported between client and the service in both the scenarios. So let’s download a simple http data recorder from http://www.ieinspector.com/httpanalyzer/download.html  . We will then click both the buttons one by one and record the data transfer using httpanalyzer. You can see the posted data is in simple plain XML format for basic http protocol and it’s in an encrypted format for wshttp protocol.
 

Enable windows authentication on WCF using ‘BasicHttpBinding’ :-
Step 6:- We need to host our service in the IIS. So make the directory as an IIS application so that your service can be hosted. Now if you try to browse the service i.e. the SVC file you will see that it pops up the authentication authorization security dialog box. So this service cannot be executed with windows authentication. 
 
Step 7:- So let’s consume this WCF services. So add an ASP.NET webapplication and do a add webreference. You will be popped up with a dialog box as shown below. Click on add reference so that a proxy is generated for the WCF service.
 
Step 8:- Type in the following code snippet in your page load. So add the namespace reference and call the method ‘GetData’. The most important step to note is the credential supplied. ‘DefaultCredentials’ passes the current windows identity to the WCF service.
If you execute the service you should get the following display as shown below.
 
You can try commenting the below code in your client in other words we are not passing any credentials.
 
obj.Credentials = System.Net.CredentialCache.DefaultCredentials;
Now if you execute you should get the below error stating that this is a unauthorized call.
 
Enable windows authentication on WCF using ‘BasicHttpBinding’ :-
Step 1:- Create a project of WCF service application as shown in the below figure.
 
Circle WCF service application ?Select this
 
By default the WCF project creates a class file which has ‘GetData’ function. This function takes in a number values and displays a explanatory sentence like ‘You entered 1 value’ , in case you have entered ‘1’.
 
public class Service1 : IService1
{
public string GetData(int value)
{
return string.Format("You entered: {0}", value);
}
}
Step 2:- When we create a WCF service application it also has a web.config file associated with it. So open the web.config file and ensure that authentication mode is windows.
 
<authentication mode="Windows" />
Step 3:- The third step is to define the bindings and the transport type. To define the bindings we need to enter ‘basicHttpBinding’ element inside the ‘bindings’ XML tag. We also need to define the ‘clientCredentialType’ as windows.
 
<system.serviceModel>
<bindings>
<basicHttpBinding>
<binding name="BasicHttpEndpointBinding">
<security mode="TransportCredentialOnly">
<transport clientCredentialType="Windows" />
</security>
</binding>
</basicHttpBinding>
</bindings>
<services>
.........
.........
</system.serviceModel>

Step 4:- Now the bindings defined needs to be associated with service interface i.e. ‘service1’. So we need to modify the services elements as shown below. You can note that we have defined a end point which has the binding association.
<system.serviceModel>
........
........
........
<services>
<service behaviorConfiguration="WCFWindowsBasicHttpBinding.Service1Behavior" name="WCFWindowsBasicHttpBinding.Service1">
<endpoint address="" binding="basicHttpBinding"
bindingConfiguration="BasicHttpEndpointBinding"
name="BasicHttpEndpoint" contract="WCFWindowsBasicHttpBinding.IService1">
<identity>
<dns value="localhost" />
</identity>
</endpoint>
</service>
</services>
.........
.........
.........
.........
</system.serviceModel> 
So over all your <system.serviceModel> XML part as whole with bindings and services is a shown below.
 
<system.serviceModel>
<bindings>
<basicHttpBinding>
<binding name="BasicHttpEndpointBinding">
<security mode="TransportCredentialOnly">
<transport clientCredentialType="Windows" />
</security>
</binding>
</basicHttpBinding>
</bindings>
<services>
<service behaviorConfiguration="WCFWindowsBasicHttpBinding.Service1Behavior" name="WCFWindowsBasicHttpBinding.Service1">
<endpoint address="" binding="basicHttpBinding"
bindingConfiguration="BasicHttpEndpointBinding"
name="BasicHttpEndpoint" contract="WCFWindowsBasicHttpBinding.IService1">
<identity>
<dns value="localhost" />
</identity>
</endpoint>
</service>
</services>
<behaviors>
<serviceBehaviors>
<behavior name="WCFWindowsBasicHttpBinding.Service1Behavior">
<!-- To avoid disclosing metadata information, set the value below to false and remove the metadata endpoint above before deployment -->
<serviceMetadata httpGetEnabled="true"/>
<!-- To receive exception details in faults for debugging purposes, set the value below to true. Set to false before deployment to avoid disclosing exception information -->
<serviceDebug includeExceptionDetailInFaults="false"/>
</behavior>
</serviceBehaviors>
</behaviors>
</system.serviceModel> 
Step 5 :- Go to IIS properties and click on security tab and ensure that anonymous access is disabled and only windows authentication is enabled.


Transport level and message level security :-
When we talk about WCF security there are two aspects, the first is the data and the second is the medium on which the data travels i.e. the protocol. WCF has the ability to apply security at the transport level (i.e. protocol level) and also at message level (i.e. data).
Figure: - Transport and Message level security
 
Transport level security happens at the channel level. Transport level security is the easiest to implement as it happens at the communication level. WCF uses transport protocols like TCP, HTTP, MSMQ etc and every of these protocols have their own security mechanisms. One of the common implementation of transport level security is HTTPS. HTTPS is implemented over HTTP protocols with SSL providing the security mechanism. No coding change is required it’s more of using the existing security mechanism provided by the protocol.

Message level security is implemented with message data itself. Due to this it is independent of the protocol. Some of the common ways of implementing message level security is by encrypting data using some standard encryption algorithm.

Core security features that WCF addresses :-
There are four core security features that WCF addresses:-
Confidentiality: This feature ensures that the information does not go in wrong hands when it travels from the sender to the receiver.
Integrity: This feature ensures that the receiver of the message gets the same information that the sender sends without any data tampering.
Authentication: This feature verifies who the sender is and who the receiver is.
Authorization: This feature verifies whether the user is authorized to perform the action they are requesting from the application.
 
Different transaction options :-
We can specify transaction in 3 ways in WCF:-
1. TransactionFlowOption.NotAllowed,
This is a default option. Using this option no transaction will be propagated across the binding. If any client attempts to call the WCF service in a transaction it will be ignored for this option.
2. TransactionFlowOption.Allowed,
This option specifies that client can call this WCF service in a transaction. It’s not compulsory that the service needs to be called in a transaction. You can call without the transaction also.
3. TransactionFlowOption.Mandatory,
This option specifies that client must call the WCF service in a transaction mode. If the WCF service is called without transaction, ‘FaultException’ will be raised.
Simple WCF example of transactions using SQL Server database :-
To enable WCF transaction is a 6 step procedure. So let’s create two WCF services and let’s try to call them in one transaction.

Step 1 :- Create two WCF service
The first step is to create two WCF service projects which will participate in one transaction. In both of these WCF services we will do database transactions and we will try to understand how a WCF transaction unifies them. We have also created a web application with name ‘WCFTransactions’ which will consume both the service in one transaction scope.
Step 2:- Attribute interface methods with TransactionFlow
In both the WCF service we will create a method called as ‘UpdateData’ which will do insert in to the database. So the first thing is to create the interface class with ‘ServiceContract’ attribute and the method ‘UpdateData’ with ‘OperationContract’ attribute. In order to enable transaction in ‘UpdateData’ method we need to attribute it with ‘TransactionFlow’ and we have specified that transactions are allowed for this method using ‘TransactionFlowOption.Allowed’ enum.
[ServiceContract]
public interface IService1
{
[OperationContract]
[TransactionFlow(TransactionFlowOption.Allowed)]
void UpdateData();
}

 

Step 3:- Attribute the implementation with ‘TransactionScopeRequired’

The 3rd step is to attribute the implementation of the WCF services with ‘TransactionScopeRequired’ as true. Below is the code snippet which has a simple database inserting function i.e. ‘UpdateData’ which is attributed by ‘TransactionScopeRequired’ attribute. 
[OperationBehavior(TransactionScopeRequired = true)]
public void UpdateData()
{
SqlConnection objConnection = new SqlConnection(strConnection);
objConnection.Open();
SqlCommand objCommand = new SqlCommand("insert into Customer(CustomerName,CustomerCode) values('sss','sss')",objConnection);
objCommand.ExecuteNonQuery();
objConnection.Close();
} 
Step 4:- Enable transaction flow using WCF service config file 
We also need to enable transactions for ‘wsHttpBinding’ by setting the ‘transactionFlow’ attribute to true. 
<bindings>
<wsHttpBinding>
<binding name="TransactionalBind" transactionFlow="true"/>
</wsHttpBinding>
</bindings> 
The transaction enabled binding we need to attach with the end point through which our WCF service is exposed. 
<endpoint address="" binding="wsHttpBinding" bindingConfiguration="TransactionalBind" contract="WcfService1.IService1">
Step 5:- Call the 2 services in one transaction
Now that we are done with our server side transaction enablement, it’s time to call the above 2 services in 1 transaction. We need to use the ‘TransactionScope’ object to group the above 2 WCF services in one transaction. To commit all the WCF transactions we call the ‘Complete’ method of the ‘Transactionscope’ object. To rollback we need to call the ‘Dispose’ method. 
using (TransactionScope ts = new TransactionScope(TransactionScopeOption.RequiresNew))
{
try
{
// Call your webservice transactions here
ts.Complete();
}
catch (Exception ex)
{
ts.Dispose();
}
}
Below is the complete code snippet in which we have grouped both the WCF transactions in one scope as shown below. 
using (TransactionScope ts = new TransactionScope(TransactionScopeOption.RequiresNew))
{
try
{
ServiceReference1.Service1Client obj = new ServiceReference1.Service1Client();

obj.UpdateData();

ServiceReference2.Service1Client obj1 = new ServiceReference2.Service1Client();

obj1.UpdateData();
ts.Complete();
}
catch (Exception ex)
{
ts.Dispose();
}
}
Step 6:- Test does your transaction work
It’s time to test if the transactions really work. We are calling two services both of these services are doing an insert. After the first WCF service call we are forcing an exception. In other words the data insert of the first WCF service should revert back. If you check the database records you will see no records are inserted by the WCF service.
Can we implement transactions in one-way WCF service calls :-
WCF transactions are 2-phase commits. In other words for every commit you need to get a confirmation response, saying is the commit successful. In one-way WCF services we do not get any response back , so WCF transactions are not possible with 1 way WCF service calls.
How prepare and commit phases work :-
Let’s consider 3 computers as shown in the below figure. The client consuming the WCF service resides in computer ‘A’ while computer ‘B’ and ‘C’ have the WCF services. The transaction is initiated from the computer ‘A’. So as we said previously there are 2 phase one is the prepare phase and the other commit phase. In prepare phase computer ‘A’ sends messages to all the WCF services saying, are they ready to commit?. Once all WCF services respond saying that they are ready for commit it starts the second phase i.e. In the second phase the WCF client issues a commit command. All the WCF services start execution and once they are done they revert back saying they have committed. When all the WCF services revert saying they have committed the transaction is marked as successful. 
 
Two different kinds of phases in WCF transactions :-
WCF transactions follow 2 phase commit. So there are 2 phases one is the prepare phase and the other is the commit phase. All co-ordination of transactions is done by the transaction manager.

In prepare phase the transaction manager checks whether all entities are prepared to commit. In commit phase the actual commit starts. You can think about prepare phase as a check saying that all entities are ready to commit and in the commit phase we do the actual work.
Which protocol is used to handle transactions in WCF :-
WCF follows WS-* specifications. So it uses WS-Atomic protocol to managed transaction across WCF services. So you can have different WCF services hosted on different computers and they all can run under one transaction unit. The best part of WS-Atomic protocol is that in one transaction you can have heterogeneous WCF services developed in different platform. In other words you can have JAVA and .NET web services running under one transaction. WS-* specifications are globally approved standards to create services.
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.
<bindings>
<netMsmqBinding>
<binding name="MyBindings"
deadLetterQueue="Custom"
customDeadLetterQueue="net.msmq://localhost/private/ServiceModelSamples" 
timeToLive="00:00:02"/>
</netMsmqBinding>
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.
<appSettings>
<!-- use appSetting to configure MSMQ queue name -->
<add key="queueName" value=".\private$\ServiceModelSamplesVolatile" />
</appSettings>
<system.serviceModel>
<services>
<service name="Samples.StockTickerServ"
behaviorConfiguration="CalculatorServiceBehavior">
...
<!-- Define NetMsmqEndpoint -->
<endpoint address="net.msmq://localhost/private/ServiceModelSamplesVolatile"
binding="netMsmqBinding"
bindingConfiguration="volatileBinding" 
contract="Samples.InterfaceStockTicker" />
...
</service>
</services>
<bindings>
<netMsmqBinding>
<binding name="volatileBinding" 
durable="false"
exactlyOnce="false"/>
</netMsmqBinding>
</bindings>
...
</system.serviceModel>

MVC


Model,
Model is a domain specific set of classes, which provides interface into the data (whatever data you are using behind the application). It also implements business rules as well as stores application states

View,
View is the applications user interface, which essentially renders the models in a form that user can interact with. So you can think it as a transformation of the model of the data behind the application. view allows user to interact with application.

Controller,
Controller receives requests from user and then initiate some kind of response whatever is appropriate for the application in that state based on user interaction. And then controller interacts with the models as is necessary to change state or save data. It also handle overall application flow. In web application, the controller usually response to http get or http post inputs then hands request over to the model that implements business rule and then selects the view display to the user.

User Interaction with MVC application,
1. Interacts with web page
2. Controller handles request
3. Notify model to changes
4. Controller selects a view
5. Await new user interaction

The tenets of MVC,
1. Separation of concerns : application should be modularized, so that each module focuses on own concerns. Model knows nothing about view or controller, and view knows nothing about controller.
2. Convention over configuration : keep the files in conventional folder helps configuration.
3. Keep it DRY: Don’t Repeat Yourself : a design principle that MVC embraces. Eliminate duplication of code and logic. That helps application faster and easier to maintain. exp. You can decorate a model with attributes that supports validation. So, those attributes in the model that way no matter how many views use that model the all enforce the exact same data validation rules.

Web Forms vs. MVC,
1. ASP.Net has provider model, MVC has a more powerful pluggable model.
2. Web forms almost forces combination of view and controller.
3. MVC server methods, not files,
    exp. In asp.net : file request is like this,
    http://www.example.com/index.aspx?id=5
    in mvc: method request is like this,
    http://www.example.com/Home/Details/5
        1. Maps to the Details action method
        2. Of Home controller
        3. Item Id of 5
4. MVC allows Automated Unit test
5. Control over HTML

Pass data from controller to view,
ViewData[“Message”] = ”Message Data”;
Model object

%: vs %=,
%: allows automatically html encode the data inside it. Where %= have to explicitly call html.Encode in order to encoding.

For accept user input uses Html.BeginForm()

Controller must have,
Implement IController interface
Have a name ending in “Controller”
Marked public, non abstract, no generic parameters

IController Interface,
Single purpose: find a controller and call execute method.

ControllerBase abstract base class,
Implement IController : adds controller features, such as TempData and ViewData.
You could build web site with either IController or ControllerBase

Controller Class,
1. It inherits directly from ControllerBase, so indirectly implements IController interface.
2. Added fetures includes,
    Action Methods
    Action Results
    Filters
3. Normally should implement your controllers using Controller, rather than IController or ControllerBase.


How Action invoker selects the correct action method,
Primary job of action invoker is to select appropriate action method. There could be multiple overloaded methods with same name. And action name may be different from method name.
It starts by getting action portion of route
{controller}/{action}/{id}
If the url doesn’t contain action portion, then the default route definition will be index action. Then it maps action name to the controller method.

Method must meet requirement to be action method,
It must be public and non static or shared. It cannot defined on System.Object or Controller. It cannot have NonAction attribute.

ActionName Attribute,
Normal convention is for controller method name to be same as action name. But you can give action method a different action name.
[ActionName(“MyName”)]

User interaction with MVC application,
1. user makes a request
2. controller handles request with action method
3. controller interacts with model
4. controller selects view as response
5. view awaits new user action

User Input Validation,
Server side,
data posted to server
create method checks it
response sent to the user
Client side,
Add call to EnableClientValidation in view on the top
<% Html.EnableClientValidation(); %>

Code Nugget syntax,
there are 3 main forms of code nugget
1. <% %>
2. <%= %>
3. <%: %>

use with either = or : when code returns string and always prefer the : because it HTML encodes the string and also MVC has smart enough to not double encode.
When code inserts data directly into response stream use <% %>.

WEB SERVICE & XML


 Web Service & XML

Idea about Web Services Architecture component :-
1. Service provider: The service provider provide the service and  implements the service. It make the service available on the internet
2. Service requestor: This is any consumer of the web service. The requestor utilizes an existing web service by opening a network connection and sending an XML request.
3. Service registry: Centralized directory of services. It is logically  registry provides a central place. At that place developers published  new services  and find existing services.
4. Service transport: Service transport is responsible for transporting messages between applications. Its includes hypertext transfer protocol (HTTP), Simple Mail Transfer Protocol (SMTP), file transfer protocol (FTP).
5. XML messaging: Responsible for encoding messages in a common XML format because that messages must be understandable at the second  end. Currently, this layer includes XML-RPC and SOAP.
6. Service description: Responsible for describing the public interface to a specific web service. Currently, service description is handled via the Web Service Description Language (WSDL).
7. Service discovery: Responsible for centralizing services into a common registry. Its provide easy publish and find  functionality for the developer (UDDI).
Characteristic of web services :-
1. XML-based: XML based is totally platform independent and run on any operating system and also language independent
2. Loosely Coupled: Loosely coupled means consumer of a web service does not tied web services directly.
3. Ability to be synchronous or asynchronous: Synchronized provide the facility  to binding the client when client want to execute the Web Services. Means client synchronously used the services.  Asynchronous operations allowed  the client  a client to invoke the web service when client want to execute other functions.

Advantages of Web Services :-
1. Interoperability
2. Reusability
3. Deploy ability
XML-RPC :-
RPC is a mechanism to call  function or procedure that are  available on a remote computer. XML-RPC provide facility to computer to call procedure from other remote computer and make function across network. XML-RPC uses the HTTP protocol to transfer information between a client computer and a server computer. It uses XML vocabulary to describe nature of request and response. XML-RPC = HTTP + XML + Remote Procedure Calls.
UDDI :-
UDDI (Universal Description, Discovery and Integration) is a directory for storing information about web services to  discovering, publishing and finding businesses and integrating business services by using the Internet. It is platform-independent framework for describing services.
WSDL :-
WSDL stands for Web Services Description Language and its represent a layer within a web service protocol stack. WSDL containing the Data types for all XML messages and it provide information about all XML messages.
SOAP :-
SOAP stands for Simple Object Access Protocol and it is a protocol which exchange information between computer. Total transaction is the XML based and it is Platform independent.
WebMethod Attribute :-
The WebMethod attribute tells .NET that a particular public method should be exposed as a web-callable method. The WebMethod attribute has six associated properties to document and change the behavior of your web method. They are,
1. Description
2. MessageName
3. EnableSession
4. CacheDuration
5. TransactionOption
6. BufferResponse
W3C :-
World Wide Web Consortium (W3C) is actively pursuing standardization of Web service protocols.
Protocols a .Net Web Service uses :-
In .Net, a web service is bind with three different protocols such as HTTP/POST, HTTP/GET, and SOAP. Http-Get and Http-Post can only be used when name/value pairs of data is dealt with. But when data is complex in nature such as ASP.NET dataset, XML notes etc, then we can use SOAP that serializes data in simpler form before sending.
Document web services :-
[WebService(Name = "Customer Service", Description = "Retrieve the Customer details",Namespace=http://www.apress.com/ProASP.NET/)]
public class Customer : System.Web.Services.WebService
{
     [WebMethod(Description = "Returns Customer Count")]
     public int GetCustomerCount()
     { ... }
     [WebMethod(Description = "Returns the list of Customer")]
     public DataSet GetCustomer()
     { ... }
}
Namespace allows your web service to be uniquely identified. By default, ASP.NET web services use the default XML namespace http://tempuri.org/, which is suitable only for testing. XML namespace simply identifies your web service. XML namespaces usually look like URLs. However, they don't need to correspond to a valid Internet location.
Required ASP.NET web services  :-
ASP.NET web services are the great way to expose your middle tier components via internet. These components offer no issue communicating across firewalls as they use SOAP as transport protocols that transmit structured data using HTTP channel. Thus, message can be easily exchanged through port 80, i.e. through internet data port without being getting hampered by corporate firewalls or proxy server.
Web services are primarily being used for B2B integration like authorizing employees, supplier, electronically signing of invoice etc.
Different distributed technologies :-
The need of distributed technologies arises with the requirement of distributed computing applications. The distributed computing allows partitioning of application logic into units and spreading the unit over different computers of a network or across different networks. This helps in spreading out loads over many computers. The components once developed can be reuse by other applications. There are many technologies developed to allow the distribution and reuse of application logic.
Advantages of the distributed components:
• The key benefit of having distributed components is that they spread out the load over different machines.
• The components can be upgraded without disturbing the clients' code.
• The distributed application improves security. For example, a company who has many agents wouldn’t like those agents to have direct access to its database. Instead, these agents can be granted access to the components running on the corporate server which can be controlled and restricted.
Web Service Standards :-
WSDL
SOAP
HTTP
UDDI
DISCO
Ways of accessing a web service :-
1. Asynchronous Call: Application can make a call to the Webservice and then continue to do whatever it wants to do.When the service is ready it will notify the application.Application  can use BEGIN and END method to make asynchronous call to the webmethod.We can use  either a WaitHandle or a Delegate object when making asynchronous call.
The WaitHandle class share resources between several objects. It provides several  methods which will wait for the resources to become available
The easiest and most powerful way to to implement an asynchronous call is using a  delegate object. A delegate object wraps up a callback function.
2. Synchronous Call: Application has to wait until has completed.
Default namespaces in ASMX files :-
System,
System.Collections,
System.ComponentModel,
System.Data,
System.Diagnostics,
System.Web,
System.Web.Services
XML :-
• Extensible Markup Language (XML) is the universal language for data on the Web
• XML is a technology which allows us to create our own markup language.
• XML documents are universally accepted as a standard way of representing information in platform and language independent manner.
• XML is universal standard for information interchange.
• XML documents can be created in any language and can be used in any language.
Structure of XML document :-
Schema vs DTD :-
Schema
DTD
Schema document is an XML document i.e., the structure of an XML document is specified by another XML document.
DTDs follow SGML syntax.
Schema supports variety of dataTypes similar to programming language.
In DTD everything is treated as text.
In Schema,  It is possible to inherit and create relationship among elements.
This is not possible in DTD without invalidating existing documents.
In Schema, It is possible to group elements and attributes so that they can be treated as single logical unit.
Grouping of elements and attributes is not possible in DTD.
In Schemas, it is possible to specify an upper limit for the number of occurrences of an element
It is not possible to specify an upper limit of an element in DTDs
Complex Element :-
A complex element is an XML element that contains other elements and/or attributes.
There are four kinds of complex elements:
·         empty elements
·         elements that contain only other elements
·         elements that contain only text
·         elements that contain both other elements and text
Simple Element :-
A simple element is an XML element that can contain only text.
·         A simple element cannot have attributes
·         A simple element cannot contain other elements
·         A simple element cannot be empty
·         However, the text can be of many different types, and may have various restrictions applied to it
Namespaces :-
A simple element is an XML element that can contain only text.
·         Namespaces are a simple and straightforward way to distinguish names used in XML documents, no matter where they come from.
·         XML namespaces are used for providing uniquely named elements and attributes in an XML instance
·         They allow developers to qualify uniquely the element names and relationships and make these names recognizable, to avoid name collisions on elements that have the same name but are defined in different vocabularies.
·         They allow tags from multiple namespaces to be mixed, which is essential if data is coming from multiple sources.
Example: a bookstore may define the <TITLE> tag to mean the title of a book, contained only within the <BOOK> element. A directory of people, however, might define <TITLE> to indicate a person's position, for instance: <TITLE>President</TITLE>. Namespaces help define this distinction clearly.
Ways to use namespaces :-
There are two ways to use namespaces:
·         Declare a default namespace
·         Associate a prefix with a namespace, then use the prefix in the XML to refer to the namespace
XML parser  :-
An XML parser is a piece of software which can do following:
·         Check for well-formedness
·         Validate the document
·         Allows us to read, create or modify existing XML documents
SAX :-
SAX-Simple API for XML processing. SAX provides a mechanism for reading data from an XML document. It is a popular alternative to the Document Object Model (DOM).
Why can't datareader by returned from a Web Service's Method:-
Cos, it's not serializable
CDATA section in XML :-
CDATA Sections are used to escape blocks of text containing characters which would otherwise be recognized as markup. All tags and entity references are ignored by an XML processor that treats them just like any character data. CDATA blocks have been provided as a convenience measure when you want to include large blocks of special characters as character data, but you do not want to have to use entity references all the time.
XSL :-
eXtensible Stylesheet Language(XSL)  deals with most displaying the contents of XML documents.XSL consists of three parts:
·         XSLT - a language for transforming XML documents
·         XPath - a language for navigating in XML documents
·         XSL-FO - a language for formatting XML documents
XSLT?
eXtensible Stylesheet Language Transformation (XSLT) deals with transformation of one XML document into XHTML documents or to other XML documents. XSLT uses XPath for traversing an XML document and arriving at a particular node.
Structure of XSLT :-

XSL template :-
Template specifies transformation rules. A Stylesheet document can be made up of at least one template, which acts as an entry point. Every template uniquely identifies a particular node in the source tree.
XPath :-
XPath is an expression language used for addressing parts of an XML document.  XPath is used to navigate through elements and attributes in an XML document.
XSL-FO :-
XSL-FO   deals with formatting XML data. This can be used for generating output in a particular format like XML to PDF, XML to DOC, etc.
XSL & XSLT :-
XSL started out as a standard for specifying stylesheets just like CSS. But soon it grew to be widely used as XML translation language. Adding specific styles and formating attributes to the XML attributes made it more useful for generating the HTML files from the data obtained from XML files. The XSL still is updated continuously as a standard.
XQuery :-
XQuery is used for querying the values found in the XML file as nodes. It is similar to the SQL language that is used for querying the databases for specific values. The XQuery is the one which is used to transform the XML data to a corresponding XHTML file.
An example of XQuery is:
for $x in doc("abc.xml")/abc_name
where $x/a>30
order by $x/b
return $x/c
Does XML let me make up my own tags :-
No, it lets you make up names for your own element types. If you think tags and elements are the same thing you are already in considerable trouble: read the rest of this question carefully.
Can I use JavaScript, ActiveX, etc in XML files :-
XML is about describing information; scripting languages and languages for embedded functionality are software which enables the information to be manipulated at the user's end, so these languages do not normally have any place in an XML file itself, but in stylesheets like XSL and CSS where they can be added to generated HTML.
Include one XML file in another :-
This works exactly the same as for SGML. First you declare the entity you want to include, and then you reference it by name:
<?xml version="1.0"?>
<!DOCTYPE novel SYSTEM "/dtd/novel.dtd" [
  <!ENTITY chap1 SYSTEM "mydocs/chapter1.xml">
  <!ENTITY chap2 SYSTEM "mydocs/chapter2.xml">
  <!ENTITY chap3 SYSTEM "mydocs/chapter3.xml">
  <!ENTITY chap4 SYSTEM "mydocs/chapter4.xml">
  <!ENTITY chap5 SYSTEM "mydocs/chapter5.xml">
]>
<novel>
  <header>
    ...blah blah...
  </header>
  &chap1;
  &chap2;
  &chap3;
  &chap4;
  &chap5;
</novel>
The one thing to make sure of is that the included file must not have an XML or DOCTYPE Declaration on it. If you've been using one for editing the fragment, remove it before using the file in this way.
Do I need to use XML namespaces :-
Maybe, maybe not.
If you don't have any naming conflicts in the XML documents you are using today, as is often the case with documents used inside a single organization, then you probably don't need to use XML namespaces. However, if you do have conflicts today, or if you expect conflicts in the future due to distributing your documents outside your organization or bringing outside documents into your organization, then you should probably use XML namespaces.
Declare an XML namespace in an XML document :-
To declare an XML namespace, you use an attribute whose name has the form:
xmlns:prefix
--OR--
xmlns
These attributes are often called xmlns attributes and their value is the name of the XML namespace being declared; this is a URI. The first form of the attribute (xmlns:prefix) declares a prefix to be associated with the XML namespace. The second form (xmlns) declares that the specified namespace is the default XML namespace.
Example, <Department xmlns:addr="http://www.google.com/ito/addresses" xmlns="http://www.google.com/ito/servers">
Override an XML namespace declaration that uses a prefix :-
To override the prefix used in an XML namespace declaration, you simply declare another XML namespace with the same prefix. For example,
<google:A xmlns:google="http://www.google.org/">
  <google:B>
    <google:C xmlns:google="http://www.bar.org/">
      <google:D>abcd</google:D>
    </google:C>
  </google:B>
</google:A>
Qualified name :-
A qualified name is a name of the following form. It consists of an optional prefix and colon, followed by the local part, which is sometimes known as a local name.
prefix:local-part
--OR--
local-part

For example, both of the following are qualified names. The first name has a prefix of serv; the second name does not have a prefix. For both names, the local part (local name) is Address.
serv:Address
Address
XPointer :-
XPointer is set of recommendations developed by the W3C. The core recommendations are the XPointer Framework which provides an extensible addressing behavior for fragment identifiers in XML media types.
XPointer gains its extensibility through the XPointer Framework, which identifies the syntax and processing architecture for XPointer expressions and through an extensible set of XPointer addressing schemes.
Use <xsl:apply-template> element in XSLT :-
Using <xsl:apply-template>element we can apply a template on current element or can apply on the child nodes of current element.
Example:
<?xml version="1.0" encoding="ISO-8859-1"?>
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  <xsl:template match="/">
    <html>
      <body>
        <h2>Book Collection</h2>
        <xsl:apply-templates/>
      </body>
    </html>
  </xsl:template>
  <xsl:template match="book">
    <p>
      <xsl:apply-templates select="title"/>
      <xsl:apply-templates select="author"/>
    </p>
  </xsl:template>
  <xsl:template match="title">
    Title: <span style="color:#ff0000">
      <xsl:value-of select="."/>
    </span>
    <br />
  </xsl:template>
  <xsl:template match="author">
    Author: <span style="color:#00ff00">
      <xsl:value-of select="."/>
    </span>
    <br />
  </xsl:template>
</xsl:stylesheet>
Use <xsl:choose> element inXSLT :-
When we want to use <xsl:choose> element in XSL file.Than we use <xsl:when> and<xsl:otherwise> inside the <xsl:choose> element.Using them we can show multiple conditional test cases.
Syntax:
<xsl:choose>
  <xsl:when test="expression">
    ... Than gives that output ...
  </xsl:when>
  <xsl:otherwise>
    ... Than gives that output ....
  </xsl:otherwise>
</xsl:choose>
Use<xsl:if> element in XSLT :-
Using <xsl:if> element we can test the content of an XSL document.
Syntax:
<xsl:if test="expression">
  ...Write here output it will dispay when condition is true...
</xsl:if>
 I have given you example to use of <xsl:if> element.
<?xml version="1.0" encoding="ISO-8859-1"?>
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  <xsl:template match="/">
    <html>
      <body>
        <h2>Book Collection</h2>
        <table border="1">
          <tr bgcolor="#9acd32">
            <th>Title</th>
            <th>Author</th>
          </tr>
          <xsl:for-each select="catalog/book">
            <xsl:if test="price &gt; 150">
              <tr>
                <td>
                  <xsl:value-of select="title"/>
                </td>
                <td>
                  <xsl:value-of select="author"/>
                </td>
              </tr>
            </xsl:if>
          </xsl:for-each>
        </table>
      </body>
    </html>
  </xsl:template>
</xsl:stylesheet>
It will give the title of book with related author which book cost greater than 150.
Use <xsl:sort>element in XSLT :-
We use <xsl:sort> element to sort the given output.
Example:
<?xml version="1.0" encoding="ISO-8859-1"?>
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  <xsl:template match="/">
    <html>
      <body>
        <h2>Book Collection</h2>
        <table border="1">
          <tr bgcolor="#9acd32">
            <th>Title</th>
            <th>Author</th>
          </tr>
          <xsl:for-each select="catalog/book">
            <xsl:sort select="author"/>
            <tr>
              <td>
                <xsl:value-of select="title"/>
              </td>
              <td>
                <xsl:value-of select="author"/>
              </td>
            </tr>
          </xsl:for-each>
        </table>
      </body>
    </html>
  </xsl:template>
</xsl:stylesheet>
Use filtering in XSLT :-
We can filter the XNL output by using filter operators.Some Legal filter operators are given below:
1.=(equal to)
2.!=(not equal to)
3.&lt;(less than)
4.&gt;(greater than)
 I have given you a example. In this I have uses '=' equal to filer operation.
<?xml version="1.0" encoding="ISO-8859-1"?>
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  <xsl:template match="/">
    <html>
      <body>
        <h2>Book Collection</h2>
        <table border="1">
          <tr bgcolor="#9acd32">
            <th>Title</th>
            <th>Author</th>
          </tr>
          <xsl:for-each select="catalog/book[author='Yashwant Kanetkar']">
            <tr>
              <td>
                <xsl:value-of select="title"/>
              </td>
              <td>
                <xsl:value-of select="author"/>
              </td>
            </tr>
          </xsl:for-each>
        </table>
      </body>
    </html>
  </xsl:template>
</xsl:stylesheet>
Above, XML document will give output related to author Yashwant Kanetkar.
Use <xsl:for-each> element in XSLT  :-
Using <xsl:for-each> element we can enable the looping in XSLT.
Example:
<?xml version="1.0" encoding="ISO-8859-1"?>
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  <xsl:template match="/">
    <html>
      <body>
        <h2>Book Collection</h2>
        <table border="1">
          <tr bgcolor="#9acd32">
            <th>Title</th>
            <th>Author</th>
          </tr>
          <xsl:for-each select="catalog/book">
            <tr>
              <td>
                <xsl:value-of select="title"/>
              </td>
              <td>
                <xsl:value-of select="author"/>
              </td>
            </tr>
          </xsl:for-each>
        </table>
      </body>
    </html>
  </xsl:template>
</xsl:stylesheet>
Use <xsl:value-of>element in XSLT :-
We use <xsl:value-of>element to extract the value of an selected XML element.
Example:
<?xml version="1.0" encoding="iso-8859-1"?>
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  <xsl:template match="/">
    <html>
      <body>
        <h2>Book Collection</h2>
        <table border="1">
          <tr bgcolor="#9acd32">
            <th>Title</th>
            <th>Author</th>
          </tr>
          <tr>
            <td>
              <xsl:value-of select="catalog/book/author"/>
            </td>
            <td>
              <xsl:value-of select="catalog/book/author"/>
            </td>
          </tr>
        </table>
      </body>
    </html>
  </xsl:template>
</xsl:stylesheet>
Transform an XML document into another XML document :-
Here, I give you an example which shows you how to transform an XML document into another XML document.
Example:
<?xml version="1.0" ?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
  <xsl:output method="xml" indent="yes"/>
  <xsl:template match="/persons">
    <root>
      <xsl:apply-templates select="person"/>
    </root>
  </xsl:template>
  <xsl:template match="person">
    <name username="{@username}">
      <xsl:value-of select="name" />
    </name>
  </xsl:template>
</xsl:stylesheet>
We can tranform above XML document into another document like that,
<?xml version="1.0" encoding="UTF-8"?>
<root>
  <name username="Abhi">Abhi</name>
  <name username="Sudi">Sudi</name>
</root>