Creational Patterns – Singleton

The singleton pattern is perhaps one of the most known and common creational patterns. The intent of the singleton pattern is to make sure that an application has one and only one instance of an object, this is generally done through the restriction of new instances of the object (on many programming languages this is done by simply restricting the access to the constructor while keeping an internal reference to an instance of the object which only gets initialized once).

Sample Use Cases

The singleton pattern becomes useful when EXACTLY ONE object is required for coordinating actions across the system. Below are some scenarios where singletons can be useful:

  • I/O Devices: It is common that I/O devices can only perform one operation at the time, this is the reason that most device controllers are singletons; this helps to ensure that all requests/operations will access and be executed on the same device.
  • ASP.NET Application state: If you are a .NET web developer you have already worked with a singleton whether you were aware of it or not. The Application state is accessible to all users and session on a server, no matter what data they request all of them will be referencing to the same repository (More details an ASP.NET application state here: bit.ly/xmkgKi).
  • Logging: Logging providers are generally centralized, and provide access to a single location where all the data is collected and analyzed.
  • Configurations: Other scenario where is very common to see singleton implementations is when it comes to application configuration and settings; No matter of what your applications do you most likely want all of your operations to use the same settings (for example: connecting to the same database, use the same storage repositories, and so on…).

More about singletons

Like all of the design patterns singletons come with both: benefits and disadvantages; although most of the harm that can come out of design patterns is due incorrect uses or implementations.

In what respects to the Singleton pattern, being one of the most common patterns also comes with its downsides, developers tend to implement singletons without giving a good thought on its requirements and whether these implementations will fulfill future changes to their applications. Some of the facts worth to consider while implementing singletons is that they tend to make applications harder to test and in modern frameworks like .NET or Java performing Garbage Collection on these objects can be difficult.

Here’s a good talk from a few years ago where Misko Hevery* explains some facts and dangers of using Singletons as well as some alternatives for global state handling.

UML diagram

Single Thread Implementation

public sealed class Singleton
{
    private static Singleton _instance;

    // Making the constructor private or protected
    // will prevent further initialization
    private Singleton()
    {
    }

    // You can either have a property and initialize the instance
    // on the getter or provide a public static method for retrieving the
    // actual instance and initialize it if first use (Lazy Initialization).
    public static Singleton GetInstance()
    {
        if (_instance == null)
        {
            _instance = new Singleton();
        }
        return _instance;
    }
}

Multi-Thread Implementation

public sealed class MultiThreadSingleton
{
    private static object lockObject = new object();

    // Declaring the instance as volatile allows multiple threads
    // to access the most recent value for the field.
    private static volatile MultiThreadSingleton _instance;

    private MultiThreadSingleton()
    {
    }

    public static MultiThreadSingleton GetInstance()
    {
        if (_instance == null)
        {

	    // Since the object will only be initialized once for
            // the full application life cycle we need to make
            // sure that the operation is thread-safe.
            lock (lockObject)
            {
                if (_instance == null)
                {
                    _instance = new MultiThreadSingleton();
                }
            }
        }

        return _instance;
    }
}

*Misko Hevery is Google coach and evangelist on automated testing culture, he has given several talks around the world on Test Driven Development and is actively participating on Open Source projects including singleton detector.

Design Patterns in C# series

During this series I’ll talk about what are design patterns, why are they important in software development, what are common uses cases, which advantages do they bring to software as well as how they are implemented in C#. In order for you to be able to fully understand the specifics of the patterns implementations I’m assuming that you’re familiarized with OOP basic concepts like encapsulation, polymorphism, inheritance, abstraction, delegation among others, if you’re not familiar with them here are some resources where you can find more about them: Introduction to OOP concepts and more, Object Oriented Programming Fundamentals. In this first post of the series I’ll talk about a brief introduction to Design Patterns, what are they, what benefits they provide and how are they generally classified.

Now let’s start by defining what a design pattern is: as a general concept a pattern is a model used as guideline for doing something; In terms of software engineering a design pattern is a well-known reusable solution to a common problem. A design pattern is not a complete solution that can be converted into code instead it provides guideline and advice on how the structure, relationships and interactions between the classes or objects should be. The use of design patterns provide benefits not only to software architects they also provide a wide range of benefits to software developers, testers and project managers, for example:

  • Speed up software development by providing tested and proved paradigms
  • Provide a way for understanding and solving a particular problem
  • Allow developers, testers and project managers to improve communication by providing common and well-known terminology
  • Promote coding reusable well tested code
  • Allow project managers and developers to work under tight deadlines
  • Provide developers with more readable code

Design patterns can be mainly classified in three categories Creational, Structural and Behavioral; depending the focus of the problems they are trying to solve. Let’s look closer into each of the categories and find out the definition of the problem each of them tries to address:

Creational Patterns

This type of patterns are all about class (object) instantiation, these particular patterns are focused on separating the systems from how the objects they consume are created, composed and represented.  These patterns are sub-categorized in two groups: class-creation patterns which main focus is to use inheritance properly during the instantiation process and object-creation patterns which use delegation for getting the instantiation of objects effectively done.

Structural Patterns

These patterns main focus is to implement the classes and objects in an efficient way by making use of inheritance and composition. This is usually done by identifying simple ways to handle relationships between the objects.

Behavioral Patterns

This design patterns are all about class-objects communication. Behavioral patterns are focused to increase flexibility in carrying out communication between different classes-objects. These patterns are usually concerned about the assignment of responsibilities between the objects, or encapsulating behavior in an object and delegating requests and processing of it.

In the following posts of the series I’ll dive into each of these three categories and the specifics of the most common patterns in each of them as well as the implementation of each pattern, I’ll also provide explanation to the code and the alternatives that can be used for coding the same pattern, remember that the implementation varies from one language to another and there can even be multiple implementation of the same pattern within the same language according to the specifics of the project, I’ll cover the most common scenarios hoping that these series will be useful for you and will encourage you to promote the use of patterns on your projects and ultimately making your developer life simpler.

One more thing before I move onto the next post, Design Patterns are a great and useful tool for programming, however you have to keep in mind at all times that there might not be the need to apply them to all the things you code as some of them might be simple enough to implement with a few lines, and the use of patterns might add unnecessary complexity and/or overhead. So this week I’ll leave you with two quotes that will help you remember this:

If all you have is a hammer, everything looks like a nail. – Abraham Maslow

Give a small child a hammer and he will find everything needs pounding. – Abraham Kaplan

Tip #4: Refactoring… the when, why and how!

Software must be soft: it has to be easy to change because it will change despite our misguided efforts otherwise.
-The Pragmatic Programmers

Lot of people have the false believing that whatever they do will remain the same forever so when they’re coding they work on “smart” implementations that at some point are not the most efficient way of doing things or they’re just unreadable and very expensive to maintain, modify or fix. Well for all of them I have bad news as time goes by everything needs to evolve, same with your code; One of the things that makes code more expensive and harder to maintain is to keep it “old and rusty”. Whenever a newer version of a framework comes out there are more elegant, simpler and faster ways to do things. Even if the framework doesn’t change at some point in time you might have done something in a certain way that was not completely efficient but it worked and then later on you would like to change it or do a different implementation. Remember as your knowledge grows also your skills do so what you’ve done in the past can be updated to make it more efficient.

As we’ve seen there are situations in which the code you’ve been working with needs to be restructured, updated or reorganized in order to make it more maintainable and easier to understand, this process is called: Refactoring. (If you’re new to the concept you can find more information about it here). The first and main tip about refactoring is that before doing it you need to make sure you have SOLID TESTS for the functionality being refactored keep in mind that the key element of it is to don’t affect external functionality.

In the following lines you’ll find some tips and guidelines about the what/when/why/how on code refactoring:

When:

- Think of refactoring of a whole process, it is not something you can just sit down and start doing it has to be planned and be done with care, nobody wants to mess up things we just want to make them more efficient and maintainable.
- Certain workarounds can be refactored for providing easier access and a centralized place to apply fixes or changes when required.
- When thinking of refactoring make sure you have plenty of time, don’t to it close to delivery dates or when the sprint is becoming to an end thus you might not met your deadlines.
- When adding new functionality to your applications think of refactoring that way you can improve your design which means make your code more sophisticated.

Why:

- Refactoring will keep your code current and efficient. As I’ve mentioned whenever programming languages evolve there are new and more efficient ways to get things done.
- Refactoring makes your application faster, as it changes the ways you do things it will add speed to your application one fix might only get you a few milliseconds or seconds but the more fixes you have the more speed you get.
- Helps you find bugs, since refactoring makes you take a closer look on y our code and design you’ll be able to find those hidden glitches or to think of wrong behaviors you didn’t figure out before.

How:

- Talking about how to refactor is a very complex theme since it is highly dependent on your applications and needs. However there are certain techniques and guidelines which you can use as base for analyzing your code and evaluate which pieces of it are candidates for refactoring.

What:

- Duplicated code. If two or more pieces of code do the same or pretty similar things they can be refactored as just one.
- Long methods. It is important that your methods do one thing only, as I’ve mentioned in previous articles the simpler the method the easier to maintain. If one of your methods is growing up you can take a look at it and think what part can be extracted to another method.
- Switch clauses. When switch classes are used for choosing different behaviors we can consider other options as polymorphism for refactoring.
- Parameters. Sometimes we make our methods so specific that we include an specific value into the name and hardcode it (e.g. CalculateTenPercentTax) this kind of methods can be refactored to have a more generic name and to receive parameters.
- Nested conditions. Having if and else’s that go really deep make the code hard to read and also give other developers a hard time while trying to walk their way along the indentation.
- Long parameters list. There are certain situations in which a long parameters list can be easily replaced and maintained with an object. Also make sure that you don’t have unused parameters as they create confusion.

Lots of things that can be refactored, you can find several websites with specific techniques and advices on how to do it. Particularly the http://refactoring.com/ website gets updated often and adds newer ways of cleaning up your code.

However there are still some situations when refactoring is not an option, you might have come with what we use to call “spaghetti code” or code so messed and complex that the only way to make it better is to start all over again.

* It is not only matter of creating solid tests, make sure that they cover all the functionality and I suggest you to run a few test passes to make sure everything is covered and in place.

Tip #3: Simplify your code, use a smart design.

While nowadays Globalization has taught us that “the more you know/do the better” when it comes to coding it is totally the opposite. This means that the simpler a method is the more easy it is to maintain so in what concerns to us we should keep in mind what Leonardo Davinci once said: “Simplicity is the ultimate sophistication”.

But does this means that our applications need to be simple? Not really, the truth behind this statement is that our business logic or architecture can be complex but this doesn’t means that our code should be too. A good programmer keeps its code simple by working harder on the design phase of each and every component in order to make them as specialized as possible, so a whole process can be perfectly defined and represented by a group of tasks. Some of you might be thinking what’s the upside of this? Well there are quite few and huge advantages when using this coding technique and they can easily be defined with a few words: Maintainability, Scalability, Reusability, Manageability and the last but not least Testability. I know by experience that when it comes to code testing you might don’t care but the truth is that when a code which contains the above mentioned characteristics can be described with just one word elegant.

One of the characteristics of good programmer is that he spends more time designing the components than coding them, why is this? Well I believe that a lot of you will agree with me in the following “coding is always the same”. For those who didn’t the explanation is simple coding is always about loops, methods, interfaces, classes, properties, etc. what actually makes our job difficult is the required logic and the design. A friend of mine recently told me something that made me come up with this idea, he said “Everyone can write code, but just a few can write good and efficient code”. Then the next time you get in front of your computer get your favorite soda, take a deep breath and start thinking of your design before actually writing code this way you’ll notice that the smarter the design, the simpler the code.

So summarizing what I’ve written so far, here are a few guidelines for making your code, as Davinci would say, more sophisticated:

  • Every method should do only one task, if one of your methods does more think about refactoring** it in two or more to keep them simple.
  • If two methods do the same task or a very similar ones, those tasks can be done with less code. Analyze your code and strip it so that you find the common code and create one or less methods for handling the same tasks; Remember the less code you have the easier to maintain.
  • Fix the issues, don’t implement workarounds unless strictly necessary, recently I’ve worked with code that was simple at the very beginning, then someone found an issue and rather than addressing it and fix the code, they implemented a workaround because it was “cheaper” in time, of course after dozens of workarounds the code stopped from being simple and what was cheaper at the beginning is now extremely costly because of the effort required to understand those workarounds and make changes to the actual code.
  • Keep your code clean and organized*, nowadays the different programming languages offer us the possibility to have our code split in as many files as we want, so try to keep your classes clean, one per file (unless they’re nested classes), if a class is too long for one single file group the methods and split it using partial classes.
  • Create a folder structure that helps others to identify each code element quickly.
  • Don’t leave commented code aside, if you did a new implementation of some method or some code refactoring don’t leave the old code commented, that’s why version control was invented so you can keep track of your changes and revert them if something goes wrong.

* Microsoft has published some guidelines for organizing code and of them says that the different code items should follow the below order:

Within a class, struct or interface: (SA1201 and SA1203)

  • Constant Fields
  • Fields
  • Constructors
  • Finalizers (Destructors)
  • Delegates
  • Events
  • Enums
  • Interfaces
  • Properties
  • Indexers
  • Methods
  • Structs
  • Classes

Within each of these groups order by access: (SA1202)

  • public
  • internal
  • protected internal
  • protected
  • private

Within each of the access groups, order by static, then non-static: (SA1204)

  • static
  • non-static

You can find more information on these guidelines by following this link: StyleCop Rules Guide

**Note: For those who aren’t familiar with code refactoring we will have another tip explaining what it is, how it is done and why it is important for becoming a good programmer.

Tip #2: Use proper names and naming conventions

One of the most important things when you’re coding is the right and proper use of names and naming conventions, how many of us have come to a point where we find a variable that you don’t have the minimum clue of what it is used for or you find out a method where its name don’t describe what it does.

Well that’s why a good programmer keeps in mind that his code should be friendly to other programmers so he will always use the right names and name conventions making his code easier to read, understand and most important to maintain.

Here are a few guidelines regarding names and naming conventions:

General

  • Define and follow a naming convention for your project, before you start writing code you should make sure that either you follow the already adopted naming convention or you define a naming convention and distribute it to all the coders so that they all follow it.
  • If you are working on a project where code doesn’t have a naming convention propose and implement one, just because no one has started it you should keep it that way.

Variables/Properties:

  • Use relevant names for the variables and properties, never use names as x, y (unless they’re referring to coordinates) or like aux, variable or any other name that don’t describes the actual element within its context.
  • Use camel Case for variables and Pascal Case for properties, that way you can easily make distinction within the code and access to them faster while coding.

Methods:

  • The method name must describe what it does, although you can’t put all of it in the name you can always define a set of words that describe it, for example if your method extracts all the worlds from a sentence you can use the GetAllWordsFromSentence name for it.
  • Use a verb or a verb phrase as the method name, a method is an action performed and which better word to describe that action than a verb.
  • All method names should begin with capital letters and its recommended that you use Pascal Case for the names.

Classes/Interfaces

  • The class name and the filename should match, although you can have nested classes is a good practice to name the file with the same name as the main class.
  • Never use underscore or prefixes in class names, appending prefixes or using underscores in class names makes them more difficult to maintain.
  • Use a noun or a noun phrase for the class name, try to use a simple name for your class remember that a class is an abstraction of an object, if you can’t name your class with a simple name you might need to “rethink” your class and divide it in a smaller subset that can be represented with simple names.
  • Interfaces names should begin with an I (capital i) that makes them easier to find and maintain.

Also I will share with you some of the naming best practices:

  • Don’t use underscore in the variables or method names, rather adopt a capitalization style like Pascal case (PascalCase), Camel case (camelCase) or Uppercase (UPPERCASE).
  • Don’t create variables or method names with same names but different capitalization (e.g. Number –>number or GetAllValues() –> GetAllvalues()) that would make the code confusing and difficult to read.
  • When using Exceptions name your variables as ‘ex,’ it is considered a best practice because the name ‘e’ is usually associated with an event.

Below you can see by yourself how difficult and annoying it can be to read a poor named code and also compare it against a well named code and decide which one you like the most Winking smile

Example of incorrect use of names:

public void sumnumbersandgetaverage()
{
    int[] x = new[] { 20, 3, 8, 90, 120, 51, 9, 12 };
    int aux = 0;
    int r = 0;

    foreach (int i in x)
    {
        aux += i;
    }

    r = aux / x.Count();
}

Example of right use of names:

public void CalculateAverage()
{
    int[] numbers = new[] { 20, 3, 8, 90, 120, 51, 9, 12 };
    int total = 0;
    int average = 0;

    foreach (int number in numbers)
    {
        total += number;
    }

    average = total / numbers.Count();
}

If you would like go deeper or get more information about naming conventions and for specific guidelines for Attributes, Events, Namespaces, Parameters and some more you can refer to the below link:

MSDN Naming Guidelines

Tip #1: The right way to do code commenting

As you all may know, or if not is a good moment to hear about it, code commenting is one of the basis for every good programmer. Although commenting code can be an annoying you should always ensure that the comments are appropriate and accurate so that they are really useful and not only extra lines within the code. Below you’ll find some tips regarding code comments as well as two examples a “good comment” and a “wrong comment” for knowing the do’s and don’t of it.

Here are the guidelines I suggest for becoming a better code comments writer:

  • When writing comments remember to think of you as the person reading the comments otherwise what makes perfect sense to you might not for someone new in the project.
  • Don’t state the obvious in your comments, don’t explain what the code is doing explain the why it is doing it.The code functionality can be easily understood by following the code while the actual purpose don’t.
  • Not all code needs to be commentedjust the parts that expose critical functionality or business logic so complex that it requires explanation.
  • When you find a bug within your code or someone else’s code fix it, if not possible at the moment explain your workaroundsin the comments so that if later on someone reads it he/she is aware of why you did it that way. And if they later need to use that same defective component or remove the workaround they can easily find either the right place or the right solution.
  • Code comments can also be used for grouping tasks within our code, if you code does this kind of grouping place a comment at the beginning of the taskso that the reader knows that the below lines all refer to the same processing workflow.
  • When commenting some specific behavior or workflow your comments can grow pretty easily when this happens cut your comment every few words and continue on the line belowso that it is easy to read, besides several studies have shown that our eyes are more comfortable when reading short lines.
  • If you have some code that still needs work mark it with a comment starting with the “TODO:”phrase. That way its easier to track and to follow up. Nobody would like to release code with pending tasks on it.
  • Don’t use multiline syntax for your code (/*…*/) use single line syntax instead (//)is easier to work with and in case you have the special chars (*/) within your code you wont mess it and waste time looking for it. Visual Studio has a feature for commenting multiple lines in case you don’t want to spend time on going line by line.
  • Don’t place your comments at the end of the line, put it above the code instead. Comments that are at the end of the line are difficult to read and find, specially if the code is being read in smaller screens.

Example of wrong code commenting:

foreach (string word in Sentence) // Cycle through all words in sentence
{
// Initialize word formatter with 0
WordFormatter formatter = new WordFormatter(0);
    // Initialize word formatter with 125
formatter = new WordFormatter(125);

    // Review word
formatter.Review(word);
    // Invert word
string invertedWord = formatter.Invert(word);
    // Review inverted word
formatter.Review(invertedWord);
    // Need to complete code for tracking the words that didn’t passed the review.
}

Example of the right way to do code commenting:

// For every word we have in the sentence
// we need to pass it through the formatter
// in order to find invalid chars, bad language
// or words that are under copyright.

foreach (string word in Sentence)
{
    // There’s a bug that sometimes prevents the initialzer
// from working properly the first time is used
// as a workaround we intialize it with a dummy value (0)
// then we use our project formatter code (125)

WordFormatter formatter = new WordFormatter(0);
formatter = new WordFormatter(125);

    // The main flow requires us to review the word
// then invert it and review the inverted word
// as per business requirement.

formatter.Review(word);
string invertedWord = formatter.Invert(word);
formatter.Review(invertedWord);
    // TODO: Add logic for keeping track words that
// didn’t passed the review.
}

The Art of share and learn

Hi All,

As part of my personal career path and my willing to share with others what I’ve leaned I’ll create a special posts section where I will publish useful tips to become a better programmer. How can I do this? Do I really belive that I can program better than anyone else? The answer is no and I don’t think someone can claim to be the best programmer there’s a whole world when it comes to styles, designs, architectures and other stuff that affects the how and the why we program something in a certain way, what works efficiently in some architecture might work awfully slow in another one. Well to make a long story short (and if its not too late already), in this particular section I’ll share with you small code pieces and tips that will help you to create more clean code regardless the architecture, design, etc. These code lines and tips are meant for you to use it as a guideline on your day to day programming so that you’re code is elegant and still functional.

In that same way if you find anything in the posted code that can be done in a better way or something that is totally wrong feel free to post it, I like to be a teacher as much as a learner.

Windows 8 preview & demo

Hi All,

Here you can find a live demo on windows 8 or if you’re watching this some other day you want watch the replay.

http://www.buildwindows.com/

for all of those interested in Microsoft Technologies this is a must see!

 

WIF: Windows Identity Foundation a simple walkthrough

What is WIF?

WIF is the acronym for Windows Identity Foundation, it is a new Framework that Microsoft has developed for making authentication and authorization simpler and centralized by using the Simple Sign-On (SSO) concept. For those who aren’t familiar with the concept, SSO talks about a centralized but independent system for signing in and managing roles within applications so once a user gets authorized it is empowered with a token that will grant him access to a set of applications and once he signs off from one all the others will sign off too. For more details and specifics on what SSO is you can take a quick tour here: http://en.wikipedia.org/wiki/Single_sign-on.

Going back to our main theme WIF is an abstraction of the WS-Federation and WS-Trust protocols for making simpler to work and build claim aware applications (RP’s) and security token services(IP’s). Don’t worry at this point if you don’t know what we’re talking about that is why this article was created, to give you insight on the WIF concepts and basics so you can start working with it and discovering all of its features to implement those you need or those you consider “nice to have” but remember the deeper you go on the implementation the more expertise it requires.

What is WIF used for?

All of us who have developed either web or desktop applications have struggled while working with authentication and authorization. To be honest develop, manage and maintain different mechanism for handling the security within our applications becomes a hard task and sometimes this is even more complex than our application itself.

What if right now I come and tell you that from now on you no longer have to take care of it? All you need to do is to modify a little your application configuration and handle a couple of “tokens” in your code; Sounds easy huh!! well actually it is and that’s the whole idea behind WIF, although I won’t lie to you there are also functionalities that can make the implementation more complex but still easy to manage and work with.

How does WIF works?

At this point some of you might be wondering what are those “tokens” you’re talking about? where does those tokens come from? how will I know if the user has really been authenticated and if its authorized for my application? Well for answering all of these questions I’ll put a real life example.

Let’s say that you want to go get a new bank account in most places all you have to do is to show a driver’s license then the bank associate will take your personal information from the license (name, age, address) so they are relying on the information provided by the department of licensing. The bank associate will not ask you for any other documents to prove that the information contained there is real. Why? because he/she trusts that checking the validity and veracity of the information was done by the department of licensing. Well in the WIF world we will call those concepts as Identity Provider (IP) and Relying Party (RP), the department of licensing is the IP since it has verified your information and put it into a document of his own (driver license) then the bank would be the RP since it relays trustworthiness of the information provided on the driver’s license.

Translating the previous example to WIF the IP is also known as Security Token Service (STS’s) and its main function is to validate the user credentials, once it passes the validation (authentication) it will create a token with the user information and specific roles our application might handle (authorization) for that specific user so that whenever the browser or application makes a request it will send the token along and then we can validate its rights and perform actions accordingly.

Is WIF for me?

Windows Identity Foundation, as mentioned before, is for those who are looking to externalize authentication or for those who are thinking of implementing Single Sign-On solutions within their applications.

How to start working with WIF?

The most basic implementation of WIF can be obtained by doing the following:

- Download and Install the latest version of the WIF framework:
http://msdn.microsoft.com/en-us/evalcenter/dd440951.aspx
- Download and Install the WIF developer training kit (SDK):
http://www.microsoft.com/download/en/details.aspx?displaylang=en&id=14347

Once you’ve done that open Visual Studio and do the following:
- File -> New -> Website -> Claims Aware Website

Run your default created website (F5) and notice that it will come to the project default startup page which in my case is the classic Welcome to ASP.NET!  page.

Once the website has been created go to the solution explorer and do the following:
- Right click on the project -> Add STS Reference

A wizard will pop up, then you can review and adjust several configurations for personalizing the implementation, for the purposes of this article we will leave the values as default.

First screen will show us the place where the project web.config is located at (it will updated with some values required for WIF to work) and it will also ask for the URI where our application will be hosted, as I mentioned lets leave them as default.
Sidenote: If your application is not hosted on a https protocol the wizard will warn you and will ask if you want to proceed, this is because since it will be creating security tokens and sending them through the network it should be always hosted on secured channels, right now let’s leave it as it is.

The second screen will ask us for the type of implementation we will work with, since we don’t have an STS configured we should select Create a new STS project in the current solution. (For those who already have a working STS and want to experiment with the application you can add your STS URL by selecting the third option) Don’t worry about details, if all you want to do is work it locally and then come back to point it to a production server you can do it easily as some of you might already have figured the configuration values we’re working on right here will get stored in our web.config file.

The last screen is a summary of whatever we’ve selected, here you can review all the changes we’ve done and also you’ll notice a new section mentioning “Claims requested by the application” also you’ll notice that it will add two claims by default: name and role. This means that the tokens created by the STS we’re implementing will only include information regarding the name and role from the user signing in. Sidenote: If you added your production STS you’ll see a list with all the available claims that it exposes.

Once it does some processing you’ll notice that the wizard has added a second project with the same name as we already had but it appended _STS at the end. Now if you run the project (F5) again instead of seeing the default website page you’ll be redirected first to the STS page so you get authenticated prior to be able to use the website. If you enter a non-empty username on this screen and password (this one is optional it will not validate anything yet) you’ll see that after doing some processing (create and return the security token) the application will redirect you to the actual website main page. At this point you might be thinking, but all this have done is to put an intermediary between the user and my website and then redirected it, well my friends that’s what WIF promised from the very beginning, that the authentication mechanism will be done apart from  your application and once that security token has been created and attached to the requests your application will be able to validate those tokens and act as desired.

I know you might be willing to check on how it worked well first of all add a label on your website’s first page (in my case Default.aspx):
<asp:LabelID=”username” runat=”server”/>
Then on the Page_Load event assign them with the name value from the page User property:
protected void Page_Load(object sender, EventArgs e)
{
username.Text = User.Identity.Name;
}

Run your website again (F5) input any name on the login screen and click Submit, you’ll see on your default’s website page that the name you’ve input was passed to your application by the browser along with the request. Like magic!

I’ll stop here now, I don’t want to get to technical on how it performed all the operations, I’ll leave you at this point to look into your code and try to understand what it have done and if any doubt comes up don’t hesitate on either posting it here or contacting me. On later postings I’ll get a deeper insight on how handling the claims that will come along with the request for our security purposes.

How to create a IN clause query using LINQ

This time I will share with you a quick tip, I’m pretty sure that either if you’re working with LINQ already or you will be working with it at some point you’ll get to the question “How do I create an IN clause query?” well here I’ll leave you a few lines of code that will show you how to do it in a very simple way.

SQL Query:

SELECT ID, NAME, LCID FROM LANGUAGES WHERE ID IN (10,20,30)

Supposing we want to translate the above query to LINQ, the first thing we need to do is to create an array or a list with the items we want to be included in the IN clause, so following the mentioned query we declare the below array:

int [] values = new int [] {10,20,30};

Then we have two options for writing our query, which one you use? It depends on your style.

LINQ Expression:

var result = from language in Languages
                   where values.Contains(language.ID)
                  select new { language.ID, language.Name, language.LCID };

Code Expression:

var result = Languages
                  .Where(c => values.Contains(c.ID))
                  .Select(c => new { c.ID, c.Name, c.LCID });

That’s all for today, no that you learned a new trick be sure to teach it to others Smile

Follow

Get every new post delivered to your Inbox.

Join 564 other followers