All posts by Diego Marcet

Working together with AntiForgeryToken and OutputCache on ASP.NET MVC

If you develop using ASP.NET MVC you’ll probably know the AntiForgeryToken helper method, used as a protection mechanism for cross-site request forgery.

This mechanism consists of two pieces: a cookie (1) and a hidden field included on the form to be submitted (2).


When submitting to a Controller’s Action annotated with the [ValidateAntiForgeryToken] attribute, the MVC framework will compare the values from the Cookie and the Hidden field (which could match partially only) and decide whether the request is valid or not.

The problem with this two-steps mechanism is that it doesn’t get along very well with cache (at least not with caching’s default behavior). Imagine that the action that renders the page with the AntiForgeryToken helper method invocation is marked with the [OutputCache] attribute, this means that unless you take into account cookie generation, you may be returning a cached version of the page (with the hidden field value set) even though the cookie has not been sent to the requesting user.

In order to avoid this issue you can use the VaryByCustom property on the OutputCache attribute:

  Location = OutputCacheLocation.ServerAndClient,
  Duration = 600,
  VaryByParam = "none",
  VaryByCustom = "RequestVerificationTokenCookie")]
public ActionResult Index()
  return new View();

And then program the rule on the global.asax‘s GetVaryByCustomString method:

public override string GetVaryByCustomString(HttpContext context, string custom)
  if (custom.Equals("RequestVerificationTokenCookie", StringComparison.OrdinalIgnoreCase))
    string verificationTokenCookieName =
        .FirstOrDefault(cn => cn.StartsWith("__requestverificationtoken", StringComparison.InvariantCultureIgnoreCase));
    if (!string.IsNullOrEmpty(verificationTokenCookieName))
      return context.Request.Cookies[verificationTokenCookieName].Value;

  return base.GetVaryByCustomString(context, custom);

This code checks if the anti-forgery token cookie is sent, and in that case, returns its value that acts as the key for the cached version of the page (which can be safely used since the cookie and the hidden field should have the same partial value); otherwise the base class’ method is invoked which ends up ignoring the cached versions of the page.

Please note that this will generate a lot of cached versions of the page (at least one by user’s session) that can greatly degrade the site performance. In this case I decided to keep the cache for that page as it was the home page and I assumed it would be hit several times by the same user.

Validation UI feedback using Attached Behaviors and VisualStateManager on Silverlight

It’s been a long time since my last post!

Way back in June I wrote a small post about getting familiarized with Composite Application Guidance for WPF (Prism). And all this time I have been working on the next version of the guidance: Composite Application Guidance for WPF and Silverlight which will be released in the very near future (in the meantime you can check the latest Drop!).

We faced lots of technical challenges during the development process, and one of them was the differences that exists on Validation between WPF and Silverlight. You can read about this with more detail on Bob’s post, on the Validation in the Reference Implementation section. What I’d like to talk about today is on a different approach we tried on that time, relying on the VisualStateManager for the UI feedback when a validation error occurs.

For this purpose I created a small Silverlight solution with a single view:


As you may notice my designing skills haven’t improved 😛

The scenario for this sample application is a validation that occurs when entering an integer into the TextBox: if it is smaller than 0 or larger than 100, or not a number a validation error will occur, when that happens the TextBox’s background will turn red. If after this, a valid number is set, the background will go back to white. Now let’s dig into the details!

The implementation of this functionality is very similar to what we did on Prism-v2 (again I recommend you to read Bob’s post for more details on this), but instead of declaring an Attached Property for the color of the Background, I created an attached property with a flag that will enable or disable the UI feedback when a validation error occurs:


When set to true for the first time, the ChangeStateOnError property will trigger the creation of the behavior that will monitor the validation errors on the TextBox (through the BindingValidationError event) and the behavior that will change the state on the VisualStateManager for the TextBox:


Now, the ChangeStateBehavior is attached to the TextBox, this means that the behavior will listen to changes on the Errors attached property (which is maintained by the monitoring behavior) and whenever the collection changes the state will be re-set.

This allows for adding other behaviors that respond to this validation error, as in Prism-v2 current approach.


Finally the visual states must be defined on the style applied to the TextBox (in this sample ValidatedTextBoxStyle). Here the states names are hardcoded on the behavior to: ErrorOn and ErrorOff, but of course new attached properties could be set to specify the names of the states to switch.


The benefit with this approach is that the UI feedback can be worked separately by a designer, using Blend for instance, in a more flexible way than if an attached property were set for each change on the UI when a validation error occurs. The negative side of this is that the designer experience on Visual Studio is not very friendly for declaring the states on the style, although this can be easily achieved with Blend 🙂


You can get the source code of the sample application here.

Working with Composite Application Guidance for WPF

The last few days I’ve been working on a sample application (Composite Mail Client) using Composite Application Guidance for WPF.

In this post I’ll explain the steps I took for understanding the guidance reviewing the assets included with the Composite Application Guidance for WPF package, and a small preview of the sample application I’m developing.


Steps for getting familiar with the guidance

The first step was to read the documentation included with the package, which is very complete and prove to be useful during the whole application development. Even though I had little background working with WPF and Unity Application Block (the container used for dependency injection) the induction was quite natural and after the first module, the other modules were very easily created.

Figure 1: Documentation tree


Once I understood the architecture and the HOW-TOs  for the basic tasks I reviewed the Quickstarts, these sample applications show specific tasks implementations and are very useful as a reference when addressing particular tasks (dynamic module discovery, interaction of different views in a decoupled way, etc.).

Figure 2: UI Composition Quickstart sample application


Finally, for a complete features review, I checked out the Stock Trader Reference Implementation included in the package. In this solution you can get a full sample of the capability of the Composite Application Guidance for WPF, and turned to be an useful guidance while I was developing my sample application.

Figure 3: Stock Trader RI


Developing the sample application

My app is still under development, but I’ll give you a quick review of it.

The scenario

The application represents a basic e-mail client, where you have 3 panels: Contact Groups List, Contacts List and Mail List; there is also a second window where you can read the e-mails (by double-clicking on the mail at the Mail List panel).


For implementing the application, each of the 3 panels is represented as a module, with a Service that retrieves data from XML, a View and a Presentation Model. For the Mail List there is an extra View for the mail reader window with a Presenter class.

And ff course it’s being fully TDDed! 😉

Figure 4: Composite Mail Client layout on beta version


Figure 5: Composite Mail Client solution’s structure


I hope I’ll be able to finish developing it soon so the moment I’ve done with it I’ll post the code…



You can get the guidance from: Enjoy it!

Technorati Profile

Introduction to WCF

As a first approach to Windows Communication Foundation, I started reading the book "Microsoft Windows Communication Foundation Step by Step" by John Sharp.

On the first section of the post I’ll talk a little about the fundamental concepts of WCF and SOA; on later sections I’ll explain the steps that must be performed to define a simple WCF service and host it in IIS will be described in the following sections. And on a future post I’ll be writing a little about hosting the service on a different host other than IIS.


Fundamentals of WCF and SOA


A host application makes a service available to client applications by providing an endpoint to which clients can send requests. An endpoint contains three pieces of information commonly known as ABC: Address, Binding and Contract.


  • Endpoint Address:
    The form of a service address depends on several factors, including the transport protocol being used. Different transport mechanisms use different address spaces. If you build your own custom host application, you can use a different transport mechanism, and you must specify an address that is appropriate to your chosen transport mechanism.
  • Binding:
    The binding for a service describes how a client can connect to the service and the format of the data expected by the service. The presence of each binding element describes part of the how of communicating with the Endpoint since for each binding element a channel will be created on the channel stack (see the next section Processing a Client Request)
  • Contract Description:
    A WCF service contract is an interface stored in a .NET Framework assembly and annotated with the [ServiceContract] attribute. The service contract describes the operations implemented by the service by tagging them with the [OperationContract] attribute. Any data passed to and from operations must be serializable.

Processing a Client Request

When a request arrives to the WCF Service’s host, it goes through a channel stack where each element is a channel that receives the message, transforms it in some way (for example decodes it if it’s on binary format, decrypts it if it’s using Asymmetric encryption, etc.), and passes the output as input to the next channel on the stack.

Although there is no order on the channel stack, a transport channel will always be at the bottom of the stack and will be the first channel to receive data from the network. Also an encoding channel must be the first element of the stack. These two channels are the only mandatory, all the rest are optional.



SOA’s 4 Tenets

An Service-Oriented Architecture consists of a set of resources on a network that are made available as independent services, and that can be accessed without requiring any knowledge of how they are implemented. To successfully design and implement an SOA, you should be aware of what has become known as the “Four Tenets of Service Orientation”:

  • Boundaries are explicit
    Applications and services communicate by sending messages to each other:
    • You should not make any assumptions about how a service processes a request or how a client application handles any response to a request.
    • Because of the associated cost in terms of communications when sending and receiving messages. You should design the operations that services implement with this in mind, and ensure that clients call services only when necessary.
    • The services must be easy to consume, for that the client perspective must be taken into account.
    • Keep the service’s scope as small as possible because the more operations the service expose, the more difficult will be to use it by clients.
    • Never expose details of internal implementation.
  • Services are autonomous:
    If you are building an application based on services, you might not have control over every service you are using.
    • Design the service decoupled of the platform in which will be deployed and will be consumed.
    • Contracts must be designed considering that once deployed they can’t be changed.
    • Adopt a pessimistic position: for providers, there will be clients who will make a bad use of the service; for clients, the services will fail or won’t be available.
  • Services share schema and contract, not class:
    Services publish information about the operations that they implement and the structure of the data that they expect to send and receive. Clients use this information when communicating with the service.
    • The contract of the service must be maintained stable, if it’s updated it should maintain compatibility with existing clients by continuing to implement existing contracts and send messages that conform to existing schemas.
    • Contracts must be clear and explicit to avoid bad interpretations.
    • Keep the internal implementation hidden.
    • Version services when changes to the service’s contract are unavoidable. This approach minimizes breakage of existing consumer implementations.
  • Service compatibility is based upon policy:
    The schemas and contracts exposed by a service define the “shape” of the service but not the nonfunctional requirements that a client attempting to access the service must fulfill. These nonfunctional requirements might change over time and so should be decoupled from the service’s and client’s implementation.  You should design services so that their policy requirements are independent of any implementation, and you should enforce clients to abide by any policies required by the service. Additionally, all services and client applications must agree on how to specify this policy information (typically by using some sort of configuration file). This is the purpose of the WS-Policy framework, published by the World Wide Web Consortium, and widely adopted by Web service developers.


Writing your first WCF Service

Define the contracts

As WCF adopts a contract-first the first step to create a service is to define the contract, which is done by defining an Interface. This interface has the only peculiarity that must have a ServiceContract attribute to mark it as a service contract, besides each of the methods that wants to be exposed must have a OperationContract attribute to expose it in the service.


The parameters and values returned can be of any kind as long as WCF can serialize and deserialize them, this includes the native types (int, bool, string, etc), collections (including generics) and Datasets.
To pass your own classes as parameters and return values, you can also define a data contract. To do this add the DataContract attribute to the class and the DataMember attribute to each of the properties that you want to expose of this class, these can be of any kind that WCF is able to serialize/deserialize to XML including other classes tagged with DataContract.

By doing this you’ll be marking the class as serializable and WCF will handle the persistence to XML.


Implement the service

Once you have defined the contract you have to define the class that will implement the contract (interface). Remember that even if you declare public members in this class, if they are not defined in the contract they won’t be visible for the users of the service.


Configure the service

Now that you have your service defined it’s time to configure the service, this will depend on how you will be deploying it. For this example I’ll be explaining how would you do it on an IIS deploy.

The first step is to define an .svc file that will represent the service as a special content file to IIS (in a similar way as ASMX pages are represented inside of an IIS application as .asmx files). The name of this file must be exactly the same as the service binary. Inside this file the WCF-specific processing directive @ServiceHost must be contained, that will allow the WCF hosting infrastructure to activate hosted services in response to incoming messages. For this example the content of the file would be the following:


The last step is to add the service configuration to the .config file (web.config in this case since it’ll be hosted on IIS, app.config otherwise).


The <serviceModel> section of the Web.config file contains the configuration information for a WCF Web service. The <services> section contains the details for each service implemented. The name attribute of the <service> element specifies the namespace and class that implement the service. The <endpoint> element provides the details of the service that client applications require in order to communicate with the service. An endpoint comprises three pieces of information: an address, a binding, and a contract.

  • The address is the location that the application hosting the service uses to advertise the service. In the case of IIS, the address element actually is ignored as IIS will use a URL containing the name of the virtual directory holding the service and the name of the .svc file as the endpoint.
  • The binding element specifies items such as the transport mechanism used to access the Web service, and the protocol to use, amongst other items. For a complete list of the binding elements see "Windows Communication Foundation Bindings".
  • Finally, the contract element indicates the contract that the service implements.

The last action on the Project is changing the Output path to bin (instead of binDebug or binRelease). This has to be done because IIS expects the assemblies containing the code for Web services and Web applications to be located in the bin folder of the Web site.
To do this right-click on the WCF service project and select the Properties option, then select the Build tab and change the Output path to bin.


Now it’s time to create the web application, I’ll show you how to do it on IIS 7.0 (included with Windows Vista and Server 2008), on previous versions of IIS the process is very similar but you’ll have to use Virtual Directory instead of Application.

On the IIS Manager, right-click on the Default Web Site node and select the Add Application… option.


For the Alias select any name you like, this will be part of the URL how you’ll invoke the service, to be consistent I used ProductsService. For the Physical Path select the ProductsService’s project folder.

And that’s it! You have a fully functional WCF Service hosted on IIS 🙂

To check if it’s running you can browse http://localhost/<alias selected>/ProductsService.svc and a page like the following should show up on the browser.




Final thoughts

Windows Communication Foundation is a very complex topic and I’m sure I’ll continue studying it for a long time so expect more posts about it in the future!

Besides the mentioned book, I got recommended "Inside Windows Communication Foundation" as a continuation book for this one since it covers lower level subjects on WCF.


Lessons learnt

  • When hosting a WCF service in IIS, you must have the .svc file extension handled. If you installed IIS after installing WCF as I did, you’ll have to configure the IIS in order to have your WCF services hosted on IIS working. To accomplish this you have two options, you can do it through command line or through the windows UI (only tested on Windows Vista Business).
    For the first option you can check the steps at "Service (.svc) File Type Not Recognized", for the second option go to Control Panel->Programs and Features and select Turn windows features on or off, there check the options under the Microsoft .NET Framework 3.0.


  • Another problem I had was when trying to attach the AdventureWorks database to my SQL Server 2005 Express Edition. Since it was installed with Server authentication set to Windows Authentication mode, and the only user with administrator permissions was the "sa" user which was disabled because its login uses the SQL Server Authentication mode; I couldn’t execute any administrative action, including database attaching. To solve this problem:

    1. Run the MS SQL Server Management Studio as an administrator.


    2. Go to Security->Logins, right-click on your Windows user and select properties.

    3. On the left menu (Select a page), select Server Roles.

    4. Finally check the sysadmin and dbcreator server roles and that’s it, you can now run the Management Studio app normally and log-in with your Windows user and you will have permissions on system databases to create and attach new databases.


The seven habits of highly effective people

I won’t write a summary post of this book because I think I’d miss the whole point. Instead, I’ll enumerate the habits giving a brief explanation and my thoughts about it.

The richness of the book I think it’s in reading and thinking at each step how it applies to you, in fact, I think it’s impossible to no “project” yourself into what it’s said on the book, showing you your strengths and weaknesses.

The most important lesson learnt I think I got from the book is that you have control on what happens around you. Of course there are things you can’t change, but most of what affects you is inside your Circle of Influence. That means you have the power to change the things that make you unhappy, even if you think it’s somebody else’s fault.

Briefly, the seven habits are:

Be proactive

Proactivity means more than merely taking initiative. It means that as human beings, we are responsible for our own lives. Our behavior is a function of our decisions, not our conditions. We can subordinate feelings to values. We have the initiative and the responsibility to make things happen. Look at the word responsibility — “response-ability” — the ability to choose your response.

This is I think the habit that impacted the most on me, when I reviewed situations in my daily life, I recognized that things that I felt where out of my control, actually could be affected by actions and decisions I made. As the author says exist “a gap between stimulus and response“, and you can act on that gap to make your life better.

Begin with the end in mind

Talks about writing your mission, your end in each role you have in life (as professional, as father, as son, etc.) that must focus on what you want to be and to do, and on the values or principles upon which being and doing are based.

Once you have enunciated your mission, you have to always keep it in mind when taking decisions and in every aspect of your life.

I think once a person acquires this habit, he can take decisions that act accordingly to a purpose and to have a goal in mind is always a beacon to which direct our efforts.

Put first things first

This habit is about organize and execute according to priorities, it’s about acting on Important things that are not Urgent: building relationships, acknowledge new opportunities, planification, etc.

To focus on things according to priorities organize our efforts and makes more effective the use of our energy.

Think win-win

Is centered on conducting positive negotiations, looking for an agreement that satisfies all the parts involved and that strengthen the relationship.

Negotiation is a subject I really like, I think most of the relationships (commercial and affective) would seriously improve if we always tried to use the win-win paradigm.

Seek first to understand

This habit is about empathy, is about understanding in every relationship what’s happening to the other person to improve the effectiveness of the communication.

Again, in every relationship it’s important to understand how the other person/s feel about a subject and why, one of the most important step in relationships in general, and negotiations in particular, is to understand the other part in order to talk the same language.


This habit focuses on working together as a team, to make the whole more than the sum of the parts.

From all my experiences in team work I’d learned that the only way to get to the finish line in a productive and effectively way, it’s imperative to trust in the other team members, helping each other and delegating responsibilities, in a manner to act as a whole; so I think this habit is one of the most important.

Sharpen the saw

Finally, this habit concentrates on “… preserving and enhancing the greatest asset you have — you. It’s renewing the four dimensions of your nature — physical, spiritual, mental, and social/emotional.

It may sound selfish, but I agree that it’s important to give some time for oneself, because as said so many times in the book the change is made from inside-out, so being at peace with oneself is the first step to being at peace with the rest of the people.

While reading this book I found I’d several concepts from texts I’d read for some courses on university. So here are some books I know that you might find interesting:

The Aquarian Conspiracy, Marilyn Ferguson. Talks about changing paradigms and several other subject covered in “7 Habits…

– Getting to Yes: Negotiating Agreement Without Giving In, Roger Fisher, William Ury and Bruce Patton. Negotiation.

Getting Past No, William Ury. Negotiation.

Irrationality : The Enemy Within, Stuart Sutherland. Taking decisions.

Impresions on Scrum

For my second post I’d like to write a little about Scrum. Since it’s such a common topic I’ll only give the basics of the method and some impressions I have of this method compared with previous work experiences.

The Scrum Method

Scrum is a “simple set of practices and rules that encompasses the transparency, inspection and adaptation requirements inherent in empirical process control” [What Is Scrum?, Ken Shwaber].

  • Transparency: means that those who control the process must have visibility of the aspects that affect the outcome of the process.
  • Inspection: means that unacceptable variances in the process must be detected by inspecting it with enough frequency.
  • Adaptation: if the inspector determines that one or more aspects of the process are outside limits and that the result will be unacceptable, he must adjust the process as quickly as possible to minimize further deviation.

Scrums employs an iterative, incremental process where each iteration, called Sprint, is planned at a meeting of the Team with the Product Owner; during the Sprint (which usually has a 1 month length), smaller daily-based iterations occur, where the Teams work to develop the requirements into the product that will be delivered at the end of the Sprint. At the start of every day the Team has a short meeting where three questions must be answered by all of the Team’s members:

What have you done on this project since the last Daily Scrum meeting?

What do you plan on doing on this project between now and the next Daily Scrum meeting?

What impediments are in the way of you meeting your commitments toward this Sprint and this project?

These questions are done to synchronize the work of all team members daily and to schedule any meetings that the Team needs to forward its progress. The team members are inspecting each other work and making adaptations to optimize their chance of meeting their commitments.

At the end of the Sprint, a version with the features developed during the iteration is released; this must be a version with value for the customer, who should be able to put in production the application if he chose to.

First Impressions

Having always work in the past with traditional development processes (or no processes at all), the Scrum method seems an interesting approach that I’m anxious to try.

The first thing that caught my attention is the commitment it’s expected by the Team Members and the freedom it gives to plan how you will accomplish these commitments. Even as other methods and processes dictate that commitment has to be given by Team Members on kick-off meetings, estimation of work, etc. With Scrum you are “exposed” to other team members and the client in a way that you don’t have any other option than do what you said you would do or raise an alarm so everybody is aware of the problems you have to accomplish those commitments.

Another thing that I really want to try is how changes on requirements are handled. This has always been a problem on previous project I’d worked in, the changes on the requirements made by customers have always been badly managed (or not managed at all) and for a developer that many times means a “tied with wire” solution (specially on the projects where time is a critical resource and you have only a few hours to come up with a solution to a big problem). But with such a dynamic approach I think changes on requirements can be handled in a proper way and are no longer a developer suffering issue.

Finally I hope that such a collaborative process will allow me to learn a lot from other team members, and will give me a professional growth as I’d never experienced before.

First week @ Southworks

On my fourth day at the company I decided to write my first entry so here I am… I suppose this post will be very similar to the ones written by other Southies on their first days but I'll try to give my own first impressions .

The first thing that caught my attention this first days is how much importance the company gives to communicate its philosophy of work. In all my previous jobs I always had a day or two for reading a couple of documents about the company and the project I would be working on, and immediately after that I'd start coding. Here it's the opposite thing, first you have to focus on understanding the philosophy the company has and how they expect you to behave (like being proactive, collaborative with teammates, and so on), and for this it's particularly important to read and understand the book “The Seven Habits of Highly Effective People” by Stephen Covey, which I'm currently reading and will be posting an entry on it soon. Then you move your attention to a more “implementative” view of the work, by researching the Scrum method and Test-Driven Development (TDD) and how they are used in the company, specially in my case since I haven't work with either in the past. And only after you have aquired all that knowledge, you start focusing on technology matters, but since I haven't reached that milestone I'll leave the details for a future post [:)].

I hope that either if you are a new Southie as I am, or if you are looking to get a picture on how this company works and how it feels to work in it, this post helps you understand that.