Monday, 20 January 2014

XAML Introduction Part 1


Understanding XAML (eXtensible Application Markup Language) is a key to creating the latest .NET 
user experiences in WPF and Silverlight. We will introduce the basic concepts around XAML and take a 
look at various features such as namespaces, elements, properties, events, attached properties and some 
basic layout. We’ll create a simple WPF application that covers these fundamentals. Although you will 
probably end up doing most of your UI design with a drag-and-drop tool such as Expression Blend, 
knowing the internals gives you a leg up in making the final tweaks to ensure an excellent user 
experience. 
Visual Studio IntelliSense works in XAML files very well. This means that as we type, we get tag 
completion, attribute completion, and even value completion (for values that are Enums). Depending on 
your preferences, you may find yourself doing a majority of your XAML in the Visual Studio editor and 
saving the visual design tools for complex cases.

An Initial Window
When you start a new WPF application, you get the following XAML as a starter (Window1.xaml):


 xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
 xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
 Title="Window1" Height="300" Width="300">




XAML is XML
The first thing to note about XAML is that it is XML. If you need an overview of XML, you can go here: 
http://www.w3schools.com/xml/default.asp. Since the XAML is an XML document, it can only have a 
single root element. In this case, the root element is “” (but “” and “” 
are also common).

XAML Elements are .NET Classes
Each element in a XAML document refers to a .NET class. This means that both “” and 
” are .NET Classes.

XAML Namespaces
In order to reference a .NET class, we also need to reference the namespace. You can think of this as the 
“using” statements in a .cs file. Namespaces are added to XAML by using the xmlns attribute. You can 
see that by default, there are 2 namespaces included:
 xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
 xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
The first refers to the standard WPF namespace. This is also the default namespace, so any elements that 
do not have a prefix are assumed to come from this location. You’ll notice that the namespace is written 
as a URI. This does not refer to a physical location, but rather the unique identifier of the namespace.
The second refers to the XAML namespace. This is identified by xmlns:x, with the “x” being an alias 
you can use as a prefix for elements from that namespace. We’ll look at this a little more closely in just a 
bit.
Obviously, you can also add your own namespaces to this list. We’ll do that later on

XAML Code Behind
The x:Class attribute references the code-behind for this XAML window. You’ll notice the “x:” which 
means that the Class attribute comes from the XAML namespace noted above. The value of the attribute 
references the “Window1” class in the “SimpleStopWatch” namespace. If you go to the 
Window1.xaml.cs file, you’ll see the partial class that is defined here.
The code behind is where we can put C# (or VB) code for things such as implementation of event 
handlers and other application logic. As a note, it is technically possible to create all of the XAML 
elements in code (WinForms apps create all of the UI in code), but that bypasses the advantages of having 
the XAML.

Other Starting Attributes
The other attributes of the Window element (Title="Window1" Height="300" Width="300") are 
simply properties of the Window class (more below). 

The Grid Element
The final element is the element. We’ll be filling this in soon. For now, note that the Window 
element only allows for a single child. This means that if we want to include more than one Control in 
our Window, we will want to wrap them in some sort of layout control that allows multiple children. The 
Grid is just that sort of control.

Properties as Attributes
Properties of elements can be expressed in a couple of different ways. The first is by using an XML 
attribute. The Title, Height, and Width properties of the Window are examples of this. We’ll go ahead 
and adjust a few of the values now. In addition, we’ll add the “TopMost” property and set it to True. This 
will keep the application on top of other active windows. This makes it more useful as a timer for other 
processes. Here’s our Window markup:


 xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
 Title="Simple Stop Watch" Height="150" Width="250" Topmost="True">

Properties as Nested Elements
Properties can also be expressed as nested elements. This is often required when properties are of a 
complex type. Let’s define some rows for our Grid. Here’s what the markup looks like:

You can see here that we have set the “Grid.RowDefinitions” property by creating a nested element. This 
particular element accepts a list of child objects (“RowDefinition”). We won’t go into all of the options 
for the “Height” property of the rows; that’s best left to a discussion on layout controls. For now, just 
know that “Auto” means that the row will only take up as much space as its contained elements; “*” 
means to take up the remaining space. We won’t define any columns for this application, but they are 
defined much the same way

Attached Properties
An attached property is a property that doesn’t belong to the element that specifies it. Let’s take a look at 
an example. We’ll add a TextBlock to the Grid. This will be the output for the time of our Stop Watch:



 HorizontalAlignment="Center" VerticalAlignment="Center"
 Text="00:00" />

First note that our TextBlock is nested inside our Grid markup. Most of the attributes are simply 
properties of the TextBlock class (FontSize, HorizontalAlignment, VerticalAlignment, Text). 

But Grid.Row is not. The Grid.Row property technically belongs to the Grid class. But since it is an 
attached property, we can use this in any element contained in the Grid to let the Grid know how to 
handle the layout. In this case, we are indicating that the TextBlock should be placed in the first row of 
the grid.

 To be Continued.....

JQUERY Export To Excel HTML Content

exportPage.aspx

<%@ Page Language="C#" AutoEventWireup="true"  CodeFile="exportPage.aspx.cs" Inherits="_Default" %>





   

   

   

   


    Export to excel using jquery


Export to excel


   
      Name
      Age
      Email
   
   
      John
      44
      john@gmail.com
   
   
      Rambo
      33
      rambo@gmail.com
   
   
      It's hot
      33
      test@hotmail.com
   


   
   




exportPage.aspx.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class _Default : System.Web.UI.Page 
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }
    protected void lnkExport_Click(object sender, EventArgs e)
    {
        string data = Request.Form["data"];
        data = HttpUtility.UrlDecode(data);
        Response.Clear();
        Response.AddHeader("content-disposition", "attachment;filename=report.xls");
        Response.Charset = "";
        Response.ContentType = "application/excel";
        HttpContext.Current.Response.Write(data);
        HttpContext.Current.Response.Flush();
        HttpContext.Current.Response.End();
    }
}


Tag:- Export To Excel,Export to Excel in Asp.net,Export Html Content,Export to Excel in .Net,Jquery Export To Excel,Asp.net Export To Excel,Export To PDF

Export DataTable to Excel

Simply use this method  by passing DataTable as First Parameter and also FileName in Second Paramter.

public static void ExportToSpreadsheet(DataTable table, string name)
{
   HttpContext context = HttpContext.Current;
   context.Response.Clear();
   foreach (DataColumn column in table.Columns)
   {
    context.Response.Write(column.ColumnName + ";");
   }
   context.Response.Write(Environment.NewLine);
   foreach (DataRow row in table.Rows)
   {
    for (int i = 0; i < table.Columns.Count; i++)
    {
     context.Response.Write(row[i].ToString().Replace(";", string.Empty) + ";");
    }
    context.Response.Write(Environment.NewLine);
   }
   context.Response.ContentType = "text/csv";
   context.Response.AppendHeader("Content-Disposition", "attachment; filename=" + name + ".csv");
   context.Response.End();
}

Uses:-
DataTable DT=new DataTable();
DT=getData();  // set data in DataTable
ExportToSpreadsheet(DT,"FileName.xls");


Tag:-
export data table to excel,export excel from c#,

WCF Vs Webservices - Why We Use WCF

1 File Format/Extension :
i) ASP.net service - '.asmx'
ii) WCF service - '.svc'

2 Hosting :
i) ASP.net service - Can be hosted in IIS also can be hosted in a Windows Service.
ii) WCF service - Very flexible, can be hosted in IIS, Windows Activation Services(WAS), Managed Windows Services and It also supports Self-Hosting.

3 Transport Protocols/Binding :
i) ASP.net service - It supports HTTP & TCP protocols along with custom binding.
ii) WCF service - supports HTTP, WS-HTTP, TCP, Custom, Named Pipes, MSMQ & P2P(Point to Point) etc.

4 Data Transformation :
i) ASP.net service - XML serializer for Data Transformation.
ii) WCF service - DataContractSerializer for Data Transformation.

5 Serialization NameSpace :
i) ASP.net service - System.XML.Serialization
ii) WCF service - System.RunTime.Serialization

6 Supported Operations :
i) ASP.net service - only One-Way and Request-Response type.
ii) WCF service - Includes One-Way, Request-Response and Duplex.

7 Encoding :
i) ASP.net service - It uses following encoding mechanisms - 
XML1.0, MTOM (Message Transmission Optimization Mechanism), DIME (Direct Internet Message Encapsulation)
ii) WCF service - It uses following encoding mechanisms - 
XML1.0, MTOM, Binary

Tag:-difference between Webservice and WCF,WCF vs Webservice,About WCF,WCF Features

WCF Life Cycle Uses Guidlines

Windows Communication Foundation (WCF) enables applications to communicate whether they are on the same computer, across the Internet, or on different application platforms. This topic outlines the tasks that are required to build a WCF application. For a working sample application, see Getting Started Tutorial.

The Main Tasks Defined

the Main Order are bellow....
  1. Define the service contract. A service contract specifies the signature of a service, the data it exchanges, and other contractually required data. For more information
  2. Implement the contract. To implement a service contract, create a class that implements the contract and specify custom behaviors that the runtime should have. For more information, see Implementing Service Contracts.
  3. Configure the service by specifying endpoints and other behavior information. For more information, seeConfiguring Services.
  4. Host the service. For more information, see Hosting Services.
  5. Build a client application. For more information, see Building Clients.
Although the topics in this section follow this order, some scenarios do not start at the beginning. For example, if you want to build a client for a pre-existing service, you start at step 5. Or if you are building a service that others will use, you may skip step 5.
Once you are familiar with developing service contracts, you can also read Introduction to Extensibility. If you have problems with your service, check WCF Troubleshooting Quickstart to see whether others have the same or similar problems.

WCF to ASP.NET Main Topics

Windows Communication Foundation(WCF) brought around a unified programming model for building service oriented application.All the previous technologies that was used to build services like MSMQ, remoting, ASMX Web Services,all came under one umbrella.

WCF had embraced SOAP,moving away from the restful web giving all sorts of flexibility and configurability.Everyone was happy for sometime thinking about the power that actually WCF gave by just changing a set of configurations and embraced it entirely.But then most of this configuration did not apply to many of the user scenario,and just went unused,coming with the extra ‘baggage’ that SOAP had to carry around.

I found Scott’s summary the best,as in this podcast,when he speaks of WCF
”If you are giving me an api whose strong point is it can talk over multi transport and
has abstracted me away from the details that i actually need in the name of flexibility that i am not going to use,then that is just baggage”

WCF had its own way of being restful,so came WCF WebHTTP,WCF Rest Starter Kit and even a WCF Web Api.Apparently ASP.NET MVC,which is inherently restful,was also having getting capabilities to build basic web Api’s.

With ASP.NET MVC 4 , both the paths that REST had taken merges as ASP.NET Web API.
So yes this is the ideal platform for building Restful services on the .NET Framework.
Web API is nothing but services exposed over http,providing reach to various devices and platforms without doubt,as http is supported across platforms and devices.SOAP did use http,but it used it more as a transport than an application protocol,by sending message packets over http.But with Web Api the ‘contract’  is the actions of HTTP –GET ,PUT ,POST ,DELETE etc..

All said WCF still holds good in cases where SOAP is necessary,where it was actually intended to be used.It’s just the REST’ful part take a new form.


WCF Simplified

Windows Communication Foundation(WCF) is basically a framework that assists in building  service oriented applications.I really felt it to be complicated in the early days that I got exposed to it,and always tried to keep away from it.But the more I tried to keep away,the more closer I needed to be with it(not sure whether that would be another of Murphy’s law).So finally got to sit with a book for couple of days and this is what I came out  with.

WCF is all about exposing CLR types as services and consuming services as CLR types

WCF brings together all the previous distributed programming models that were there, like ASMX,remoting,MSMQ making everyones life easier.You get the power of all previous technologies just by changing a set of configurations in a config file.The keywords in WCF is ABC which itself can be termed Endpoint.Endpoint is nothing but the A(Address),B(Binding) and C(Contract) put together.So now what is this ABC.(I would be relating this to you and explaining as you yourself is a ‘service’  in one way or the other.You provide a service to your family,friends,employer,government etc.)

Address

This is nothing but the address where your service would be located and would also tell the transportation mechanism that would be used like HTTP,TCP,Peer Network,IPC,MSMQ.With respect to,’you as a service‘,this is exactly the address where one  can find you so that a consumer of your service can get the service that you provide.This can be your mail-id,phone number or house address,which also shows the mode of communication,depending on the kind of consumer that you are serving.

Binding

It is just a set of grouped combinations of transport protocol,encoding of the message ,security, reliability,transaction ,interoperability etc.Again with regards to ‘you as a service‘,this can be seen as the langugae accent,how securely the information came on to you and things like that.

Contract

This just specifies what the service does.This specifies what functionalities the service provides and also the way the data can be passed in and given out.With respect to ‘you as a service‘ this can be seen as the functionalities/activities that you do,the language in which that you can communicate(Say Engligh,French etc).Contracts in WCF are basically of 4 types,Service contract,Data contract,Fault contract and Message contract.Service contract specifies the set of functionalities that the service provides,Data contract specifies the way the data is exchanged,Fault contract specifies how faults/exceptions would be communicated out and Message contract specifies the format of  the message that is actually send(this is used very rarely,unless there is a specific structure that is to followed).Contracts aim at supporting interoperability and so it is to be expressed in a technology independent way.

Another key word that might come in between to confuse you more would be Channels.Now this is nothing but,something related to Binding.Since in a binding you specify different things like security,encoding and what not,each of these specific things are handled in its on layer/channel.You can see that there is something called Channel Stack,i.e. a stack of  different classes,each providing a discrete set of functionality.This whole stack would in turn make up your binding.Based on the you choose binding different channels would be stacked up together,just like you have different burgers with different layers of toppings :).As in burgers,you always have the option of making a custom binding too.

Any message that comes in to this channel stack,gets acted upon by different channels providing it/wrapping the message with security,reliability,transaction etc ,so that it comes out of the stack with all the features applied.So this takes away all the extra effort,that otherwise you would have had to do manually.This wrapping happens on the sending side and unwrapping happens on the receiving side.Because of this kind of architecture,WCF’s architecture is also called ‘interception-based‘ architecture,as at each point it is intercepted and injected with additional features.

WCF has an extensible model.This means that at any place you can plugin your own custom implementations if required .System.ServiceModel is the one single namespace that turns life in the distributed world elegant and simple.So do explore it and start thinking everything around you as a service,so that you could relate things more to WCF :)

Callbacks in WCF

Quite often in the client-server model,the requirement of getting notified of certain changes in the server pops up.Say for example in the movie ticket booking system.When a person selects a seat for booking,the selected seat should become disabled for all the users currently logged in,so that you can avoid the message ‘Sorry the seat you were trying to book is already booked‘.
In such scenarios polling the server for changes might be one way to go about it.
Another way might be the server calling back to all the clients when a seat selection happens.
This post is about the second way and when the booking system is developed using WCF :)
The WCF framework provides a easy way to achieve this…..Callbacks

The whole concept is simple.The server keeps track of all the active clients and knows how to call them when the required change happens in the server.
Again its all about certain interfaces that you have implement and some attributes that you have to specify.
The ServiceContract that the client exposes also specifies the CallbackContract type.This is again another interface that the client needs to implement so that the server knows the type of client it is serving and can call back the functions on that interface.
This is much more like the eventing model.All functions in the CallbackContract would be like your event handlers,which would be invoked by the server on a particular event happening in the server.
You can go ahead and create a Publisher-Subscriber framework itself so that any future requirements of such nature would be easy to implement
This article by Juval Lowy suggest a good way to implement a publisher-subscriber framework in WCF using callbacks.

The code provided below shows a quick example of Callbacks.Run minimum of two clients,so you get to understand what it is all about :)

Role Based Access Control

RBAC(Role Based Access Control) is something that is very common in the day-to-day world.
So what is this all about.It is just about a authorization check on whether you have the access to a particular resource or not.
When faced with scenarios like this when developing applications, where you have to implement Role based access for the different users that are to use the system you might be confused on how to implement this.
Say you have a WCF service exposing a set of services.You have a WPF thick client consuming this service.Say for example you are exposing a service to Add/Delete/View Employees.Based on the various roles you need to allow/disallow the access to the functionality.The easiest way would be enable/disable the controls that would be used invoke the corresponding functionality,based on the user role.
So am I done?
What if tomorrow you are exposing this service to some other client of yours,who is to develop his on User Interface(UI) for the service.
Do I have a problem here?
Yes of course!!!
What if he does not make the same check on the UI to enable/disable the controls that would act as his inputs.So here exactly is where you have a access break.Any user will be able to perform all functions irrespective of the access specified for him.
So how do I go about?
Make this check at the service level itself.Check for access and throw a NoAccess exception if not authorized.What exactly happens when you try to enter a no-access area in your office :)
UI synchronization is an added level to this,so that you can stop unnecessary service calls.

WCF Session Management

A transaction is a collection or group of one or more units of operation executed as a whole. Another way to say it is that transactions provide a way to logically group single pieces of work and execute them as a single unit, or transaction.
For example, when you place an order online, a transaction occurs. Suppose you order a nice 21-inch wide-screen flat-panel monitor from your favorite online hardware source. Assume you were to pay for this monitor with a credit card. You enter the information required on the screen and click the "Place Order" button. At this point, two operations occur. The first operation takes place when your bank account is debited the amount of the monitor. The second operation occurs when the vendor is credited that amount. Each of those operations is a single unit of work.
Now imagine that one of those operations fails. For example, suppose that the money was removed from your bank account for the purchase of the monitor, but the payment to the vendor failed. First, you wouldn't receive your anxiously awaited monitor, and second, you would lose the amount of money for the cost of the monitor. I don't know about you, but I would be quite unhappy if this happened.
Conversely, a payment could be made to the vendor without debiting your account. In this case, the debit from your account failed but the payment to the vendor succeeded. You would likely receive the purchase item without having paid for it. Although this scenario is preferable to the former one, neither is acceptable in that in either case, someone is not receiving what is rightfully theirs.
The solution to this is to wrap both of these individual operations into a single unit of execution called a transaction. A transaction will make sure that both operations succeed or fail together. If either of the operations fails, the entire unit of work is cancelled and any and all changes are undone. At this point, each account is in the same state it was before you attempted your purchase. This undoing is known as "rolling back" the transaction.
This ensures that you receive your monitor and the vendor receives its money. Both parties are now happy and your confidence in doing business online hasn't wavered.
A pure and successful transaction has four characteristics. You can use the mnemonic aid "ACID" to help you remember each of them:
  • Atomic
  • Consistent
  • Isolated
  • Durable

Atomic

The word "atomic" comes from the Greek word "atamos," meaning "indivisible; cannot be split up." In computing terms, this meaning also applies to transactions. Transactions must be atomic, meaning either all the operations of the transactions succeed or none of them succeed (that is, all successful operations up to the point of failure are rolled back).
In the case of the monitor order, the money is removed from the bank account and deposited into the vendor bank account. If either of those operations fails, each account returns to the state it was in prior to the start of the purchase attempt.

Consistent

Consistent transactions mean that the outcome is exactly what you expected it to be. If you purchase the monitor for $300 and you have $1,000 in the bank account, consistent transactions mean that you expect to be charged $300 and have $700 remaining in the bank account when the transaction is committed and complete.

Isolated

Isolated transactions are "private," meaning that no one else knows about the transaction until it is committed.
For example, suppose you have $1,000 in a bank account from which to purchase the monitor. You purchase the monitor for $300, and during the purchase of the monitor, while the transaction is taking place, your husband or wife is at the local ATM checking the balance of the account from which the money for the monitor is being withdrawn.
Isolated transactions are invisible to all other transactions, and in this example the husband or wife would see a balance of $1,000. In fact, if the husband or wife were to withdraw money from the ATM while the online purchase was taking place, both transactions would be isolated transactions, completely unknown to one another.

Durable

Durable transactions must survive failures. When a transaction is complete, it is "committed," meaning that the changes have taken effect. For a transaction to be durable, it must maintain its committed state if there is a failure.
What is a failure? It could be a power outage, hardware failure, and so on. Regardless of the failure, the transaction must survive it.
Suppose that after the processing of the transaction, someone yanks the power cord out of the server that is processing your order. A durable transaction survives this failure. When the power is restored to the server, the result of the transaction must be in the committed state.

Transaction Attributes in System.ServiceModel

When version 2.0 of the .NET Framework was released, it included a new namespace (System.Transactions) that makes transaction programming easy and efficient. The System.Transactions namespace supports transactions initiated by many platforms including SQL Server, MSMQ, ADO.NET, as well as MSDTC (Microsoft Distributed Transaction Coordinator).
Windows Communication Foundation utilizes the many available objects of this namespace to provide all the necessary transaction capabilities you will need when building your WCF services and client applications.

ServiceBehavior Attribute

The [ServiceBehavior] attribute has three properties that deal with handling and managing transactions. Each is shown in the following list:
  • TransactionAutoCompleteOnSessionClose: Specifies whether pending transactions are completed when the current session closes.
  • TransactionIsolationLevel: Determines the isolation level of the transaction.
  • TransactionTimeout: Specifies the period in which a transaction has to complete.
The first of these is the TransactionAutoCompleteOnSessionClose property. It should be used for cases where you want to ensure that transactions are completed when the session is closed. As such, the transaction will either be committed or rolled back when the session is closed, depending on its state.
The one that needs to be highlighted here is the TransactionIsolationLevel property. This property determines how the data is handled when other transactions make modifications to the data. It also has an impact on how long your transaction can hold locks on the data, protecting it from other transactions. For a review of the available values for this property, see Chapter 8, "Services," of the book, Professional WCF Programming: .NET Development with the Windows Communication Foundation (Wrox, 2007, ISBN: 978-0-470-08984-2).
The TransactionTimeout property determines how long the transaction can run before it is cancelled. If the transaction has not completed before the timeout value has been reached, the transaction is rolled back. Great care must be taken when choosing a timeout interval. Too high of an interval will cause needless wait times when a failure has occurred. Too small of an interval will cause the transaction to fail before it has had time to complete.
These properties are properties of the [ServiceBehavior] attribute, which is applied to the class that implements the service interface. The following code snippet shows the three transaction properties applied to the [ServiceBehavior] attribute:
[ServiceBehavior(TransactionAutoCompleteOnSessionClose=true,
TransactionIsolationLevel=IsolationLevel.ReadCommitted,
TransactionTimeout="00:00:30")]
public class ServiceClass : IServiceClass
{
[OperationBehavior]
string IServiceClass.GetText()
{
StreamReader sw = new StreamReader(@"c:\wrox\WCFServiceTest.txt");
return sw.ReadLine();
}
}
In this case, the TransactionAutoCompleteOnSessionClose property is set to true, the TransactionIsolationLevel is set to ReadCommitted, and the TransactionTimeout is set to 30 seconds. The TransactionTimeout property value is of a Timespan object.
Prior to running the example, make sure that the c:\wrox\WCFServiceTest.txt file exists and contains at least a few words of text. If your test file is located somewhere else, make sure the example is pointed to the correct location.

OperationBehavior Attribute

The [OperationBehavior] also has a couple of properties related to transactions. The two properties are:
  • TransactionAutoComplete: Specifies that transactions will be auto-completed if no exceptions occur.
  • TransactionScopeRequired: Specifies whether the associate method requires a transaction.
The characteristics of a successful transaction were discussed earlier in this article. Both the TransactionAutoComplete property andTransactionScopeRequired property help fulfill the durable requirement because it will automatically complete a transaction, thus ensuring that the specific operation is successful.
The following example illustrates a service operation that is annotated with the [OperationBehavior] attribute, which specifies the two transaction properties:
[OperationBehavior(TransactionAutoComplete=true,
TransactionScopeRequired=true)]
string IServiceClass.GetText()
{
StreamReader sw = new StreamReader(@"c:\wrox\WCFServiceTest.txt");
return sw.ReadLine();
}
In this example, the TransactionAutoComplete property is set to true and the TransactionScopeRequired property is set to true as well.

TransactionFlow Attribute

The [TransactionFlow] attribute is used to specify the level at which a service operation can accept a transaction header. This attribute has a single property and is the attribute used to annotate a service operation method. The values for this property come from the TransactionFlowOption enumeration and are shown in the following list:
  • Allowed: Transaction may be flowed.
  • Mandatory: Transaction must be flowed.
  • NotAllowed: Transaction cannot be flowed.
This property and the associated values are used to indicate whether transaction flow is enabled for the associated method.
The following example illustrates a service operation that is annotated with the [TransactionFlow] attribute, which specifies the level at which the operation is willing to accept incoming transactions. This example sets the level at mandatory, signifying that transactions are required for this operation:
 [TransactionFlow(TransactionFlowOption.Mandatory)]
int IServiceClass.MultiplyNumbers(int firstvalue, int secondvalue)
{
return firstvalue * secondvalue;
}
The default value for this property is NotAllowed.
A flowed transaction is a situation in which a transaction id is passed over the wire and used on the receiving side to perform work, usually enlisting in the corresponding transaction and executing within that scope.

WS-Atomic Transaction

Windows Communication Foundation utilizes the WS-AT (WS-Atomic Transaction) protocol to flow transactions to other applications. The WS-AT protocol is an interoperable protocol that enables distributed transactions to be flowed using web service messages, and incorporates a two-phase commit protocol to facilitate the outcome between distributed applications and transaction managers. The transaction protocol used when flowing a transaction between a client and service is determined by the binding that is exposed on the endpoint.
You do not need to use this protocol if your communication is using strictly Microsoft technology (WCF). Simply enabling the TransactionFlow attribute will get you the desired results. However, this protocol will be necessary if you are flowing transactions to other platforms and third-party technologies.

Specifying Transactions Through Configuration

On the client side, transaction flow is enabled via the binding. The following configuration file was taken from the behavior example in Chapter 8, "Services," of the book, Professional WCF Programming: .NET Development with the Windows Communication Foundation (Wrox, 2007, ISBN: 978-0-470-08984-2). In that example, several properties on the [ServiceBehavior] and [OperationBehavior] attributes were set so that they enabled transactions on the service. When the service references were added to the client, the client interrogated the consumed service and set the appropriate binding attributes in the configuration file.
Transaction flow is enabled by setting the value of the transactionFlow attribute to true, as shown by the highlighted line in the following code:
























Tag:-WCF Session Mangement,How To Use Session in WCF

TypeScript-Essential: A New Language for .NET and JavaScript+XML

JavaScript is quite possibly the world's most popular programming language. It's nearly impossible to have a website without it. Despite its wild popularity, JavaScript does play some tricks on unsuspecting developers and sometimes does not work as expected, especially from a C# coder's point of view. It's also easy for JavaScript to run amok throughout a project, especially if it is not organized well, both in files and via patterns. This is where TypeScript comes into the picture. TypeScript works excellently as a shim for C# developers who must write JavaScript. In addition to that, JavaScript developers will enjoy TypeScript's implementations of ES6 proposed features (i.e., classes) that put it on syntax parity with OOP languages. That's not to mention while many hardened JavaScripters out there already know how to do all the things TypeScript provides, it still has much nicer syntax than JavaScript's prototypal way of doing it. (of course, the look of syntax is always an opinion; which is better, vanilla or chocolate?)
TypeScript is not a new language as it is a superset of JavaScript that compiles to plain JavaScript. This isn't "compile" in the traditional sense of the word, but that TypeScript is JavaScript that generates more JavaScript. The TypeScript compiler, tsc.exe, creates the prototypal syntactical code as well as the implementation of classes, namespaces, and types. There are no TypeScript designers in Visual Studio (good) and the JavaScript outputted is generally clean and lightweight.  

Why Use TypeScript-Essential? TypeScript Features

You only need to install TypeScript for Visual Studio 2012 and 2013 and you're ready to go. Visual Studio will support TypeScript's .ts files as well as perform "on save" compilations automatically when editing .ts files. While browsing TypeScript online you'll find links to the TypeScript source code and the language specs [.pdf]. TypeScript's mission is to enable JavaScript developers to write complex software with JavaScript that is also maintainable by enabling the following language features:
  • ES6 proposed features, now
  • Easier OOP with classes, interfaces, and inheritance.
  • Parameter and return types as well as type inference
  • Bacon, rainbows, and unicorns[1]
  • Arrow function syntax (Lambda style)
  • Generics
  • Type checking
  • Lots of other good stuff
You can use TypeScript at the TypeScript playground online or in Visual Studio 2012 when you install TypeScript. In Visual Studio 2013 and later, TypeScript is baked right in and there is no need for a separate download. Upon a successful installation you'll find a TypeScript project template and integration between Visual Studio and TypeScript such as Intellisense and the ability to manage .ts files in Solution Explorer.
While Visual Studio boasts of tight integration with TypeScript, each time you save (default behavior) your .ts code it runs the tsc.exe compiler to generate JavaScript output. You can run tsc.exe from the Package Manager Console or an OS command prompt.

A TypeScript-Essential Program

You can organize programs in TypeScript much like namespaces in .NET, except in TypeScript we use the module keyword. To create an object model you can nest modules and classes, as the code sample below shows. Notice the export keyword applied to the Models module and the BankAccount class. For C# or VB.NET folks, that makes them public.
- See more at: http://rachelappel.com/typescript-a-new-language-for-.net-and-javascript-developers#sthash.PZIvzAXX.dpuf

eg.

module BankOfRachii

{
    export module Models

    {       
        export class BankAccount 

        {
            AccountId: string;

            AccountHolderName: string;

            private _balance: number;

            get Balance(): number

            {
                return this._balance;
            }
        }
    }
}

TypeScript generates the output below from the code above: - See more at: 

(function (BankOfRachii) { 

    (function (Models) {

        var BankAccount = (function () {

            function BankAccount() {

            }

            Object.defineProperty(BankAccount.prototype, "Balance", {

                get: function () {

                    return this._balance;

                },
                enumerable: true,

                configurable: true

            });
            return BankAccount;
        })();

        Models.BankAccount = BankAccount;

    })(BankOfRachii.Models || (BankOfRachii.Models = {}));

    var Models = BankOfRachii.Models;

})(BankOfRachii || (BankOfRachii = {}));

//# sourceMappingURL=gen.js.map  


This is the module pattern at work. In JavaScript, the module pattern is a way to organize your code in a way that is especially valuable in projects with large volumes of JavaScript. Modules contain JavaScript in units that if properly designed make it easy to pull a single module out for bug fixes without disturbing others and introducing new bugs. You can of course code this yourself but as you see, TypeScript gives you syntactic sugar so you can code faster if your background is from C# or statically typed, object oriented, languages.
TypeScript organizes code in modules and compiles using the tsc.exe compiler into pure JavaScript using industry standard patterns such as the module pattern. As you go deeper into TypeScript you'll see how to put other patterns put into use as well.

TypeScript-Essential Type System

TypeScript adds an optional type system to JavaScript, so that you can declare variable, argument, and return types. Consider the syntaxes in following BankAccount class. You can see a colon then the type is the syntax that forms types for fields, properties, arguments, and return types.

export  class BankAccount implements IFees

{
    AccountId: string;

    AccountHolderName: string;

    constructor(acctId: string)

    {
        this.AccountId = acctId;
        this._balance = 0;
    }

    private _balance: number;
    get Balance(): number
    {
        return this._balance;
    }

    private _interestRate: number;

    get InterestRate(): number

    {
        return this._interestRate;
    }
    set InterestRate(value: number)

    {
        this._interestRate = value;
    }

    public Deposit(amount: number): boolean
    {
        this._balance += amount;
        return true;
    }

    Withdraw(amount: number): boolean
    {
        if (this._balance > amount)

        {

            this._balance -= amount

    return true;

        }
        return false;

    }

    ChargeFee(amount: number)

    {

        this._balance -= amount;
    }

}


The AccountId, AccountHolderName and Balance fields and properties in the above sample are all typed. The arguments are typed in the constructor which accepts a string. The Deposit, Withdraw, and ChargeFee methods all use typed arguments and returns. Trying to assign a value that is of the wrong type will result in a compile error by the TypeScript compiler. The "Type" in TypeScript should be very clear at this point.

TypeScript and Object Oriented Programming

TypeScript is more than just types, since it can implement the major principles of OOP. This is illustrated in the sample above as the class keyword does not exist in JavaScript proper (although classes but not necessarily the keyword are an ES6 proposal). Also seen in the example is encapsulation, one of the four principles of object oriented development. Encapsulation is implemented through the properties and methods. The BankAccount class also contains getter and setter property syntax, a syntax style not found in plain JavaScript as you must use prototype syntax there, and that is what TypeScript generates for you.
In addition to basic classes is the notion of inheritance as well as abstraction through interfaces. You can use the interface keyword to define an interface and the implements keyword to apply it. Below is an interface definition,