Showing posts with label html 5. Show all posts
Showing posts with label html 5. Show all posts

Tuesday, July 12, 2011

Customizable Password Policy C#

Introduction
To enforce password strength in such a way that user can configure the number of uppercase, lowercase, special characters and digits the password can contain. 

Background
One of my projects, there arises a scenario in which the password strength is configure in the database. Have to make use of this database configuration to validate the password entered by the user. So I needed a class which can enforce this and should be highly customizable.

Using the code
Password Policy contains a method IsValid which takes password string as its parameter and checks for various conditions like minimum lenth of the password, the number of uppercase or lowercase the password can contain. The user can also customize the no of digits and non-alpha numeric characters also.
It does all the Counts throug the Regex.Matches function which retuns the number of occurances of the pattern.


public class PasswordPolicy
    {
        private static int Minimum_Length = 7;
        private static int Upper_Case_length = 1;
        private static int Lower_Case_length = 1;
        private static int NonAlpha_length = 1;
        private static int Numeric_length = 1;
 
        public static bool IsValid(string Password)  
        {
            if (Password.Length < Minimum_Length)
                 return false;               
             if (UpperCaseCount(Password) < Upper_Case_length)
                 return false;
             if (LowerCaseCount(Password) < Lower_Case_length)
                 return false;
             if (NumericCount(Password) < 1)
                 return false;
             if (NonAlphaCount(Password) < NonAlpha_length)
                 return false;
             return true;  
         }
 
        private static int UpperCaseCount(string Password)
        {
            return Regex.Matches(Password, "[A-Z]").Count;
        }
 
        private static int LowerCaseCount(string Password)
        {
            return Regex.Matches(Password, "[a-z]").Count;
        }
        private static int NumericCount(string Password)
        {
            return Regex.Matches(Password, "[0-9]").Count;
        }
        private static int NonAlphaCount(string Password)
        {
            return Regex.Matches(Password, @"[^0-9a-zA-Z\._]").Count;
        }
    }

Tuesday, July 5, 2011

Developers: just a few lines of JavaScript connects your site to Hotmail, Messenger, and SkyDrive


Today, developers almost always integrate multiple web platforms into their sites – Facebook, Twitter, Google, Hotmail, and more. With this in mind, we’ve tried to make it as easy as possible for developers to use our platform alongside others to connect their websites to Messenger, SkyDrive, and Hotmail. We’re achieving this goal by focusing on the following principles:
  1. All it takes is a few lines of JavaScript to unlock powerful integration. Utilize as few lines of script as is feasible to enable single sign-on and (with the user’s consent) to allow the app access to specific data from their Hotmail, Messenger, or SkyDrive account, all without requiring a single line of server-side code for the common scenarios.
  2. The Messenger Connect JavaScript API feels familiar to developers who use other popular web platforms. Ensure the API is familiar to web developers who are already using popular web platforms that perform similar tasks.
  3. Combining our APIs with other integrated services on a page shouldn’t cause clutter. Ensure it is straightforward and cost effective to use Messenger Connect in tandem with other web platform offerings without a negative impact on developers or end users.
These principles have informed the design of our new JavaScript library that developers can include in their websites to add single sign-on and integration with services like Hotmail, Messenger, and SkyDrive.
Let’s see some of these principles in action.

All it takes is a few lines of JavaScript to unlock powerful integration

The following self-contained code sample can be hosted on any website, and will render a Connect button as shown below, which a user can click to connect to the website and be greeted by their first name.
Connect button
In the following code sample, the client_id and redirect_uri should be replaced with the developer client ID you can obtain from our application settings site, and the URL of the HTML page, respectively.
<html><head>
<title>Greeting the User Test page</title>
    <link rel="stylesheet" type="text/css" href="style.css" />
<script src="//js.live.net/v5.0/wl.js" type="text/javascript"></script>
    <script type="text/javascript">
        var APPLICATION_CLIENT_ID = "YOUR CLIENT ID",
        REDIRECT_URL = "YOUR REDIRECT URL";
        WL.Event.subscribe("auth.login", onLogin);
        WL.init({
            client_id: APPLICATION_CLIENT_ID,
            redirect_uri: REDIRECT_URL,
            response_type: "token"
        });
        
        WL.ui({
            name: "signin",
            element: "signInButton",
            brand: "hotmail",
            type: "connect"
        });

        function greetUser(session) {
            var strGreeting = "";
            WL.api(
            {
                path: "me",
                method: "GET"
            },
            function (response) {
                if (!response.error) {
                    strGreeting = "Hi, " + response.first_name + "!"
                    document.getElementById("greeting").innerHTML = strGreeting;
                }
            });
        }
     
        function onLogin() {
            var session = WL.getSession();
            if (session) {
                greetUser(session);              
            }
        }
    </script>
</head>
<body>
    <p>Connect to display a welcome greeting.</p>
    <div id="greeting"></div>
    <div id="signInButton"></div>
</body>
</html>
There are a number of key concepts in the above example that I’ll briefly go over. The first step to using the JavaScript SDK is to include the wl.js script file on your webpage.
<script src="//js.live.net/v5.0/wl.js" type="text/javascript"></script>
If your target audience doesn’t speak English, it is fairly straightforward to load versions of the JavaScript library that contain localized strings for dozens of languages.
After including the Messenger Connect JavaScript API, there are a few setup steps to link up components of the page with the JavaScript API, as shown below:
WL.Event.subscribe("auth.login", onLogin);
WL.init({
            client_id: APPLICATION_CLIENT_ID,
            redirect_uri: REDIRECT_URL,
            response_type: "token"
        });
The WL.Event.subscribe call above indicates that the onLogin() function should be invoked after the user has been successfully signed in. The WL.init call above is used to specify the application’s client ID, and the URL that the user should be redirected to after signing in which, for this example, is the current page:
WL.ui({
name: "signin",
element: "signInButton",
brand: "hotmail",
type: "connect"
});
The call to WL.ui is used to draw the Hotmail connect button. The code above attaches it to the DIV named “signInButton”. Once the user has signed in and granted consent to allow the page to access their data, the onLogin() function is invoked:
function onLogin() {
    var session = WL.getSession();
    if (session) {
        greetUser(session);              
    }
}
This function checks to see if a valid login session has been created and if so, invokes the greetUser() functionshown below:
function greetUser(session) {
    var strGreeting = "";
    WL.api(
    {
        path: "me",
        method: "GET"
    },
    function (response) {
        if (!response.error) {
            strGreeting = "Hi, " + response.first_name + "!"
            document.getElementById("greeting").innerHTML = strGreeting;
        }
    });
}
This method employs the work horse of the JavaScript SDK: WL.api. This function is used for making REST API requests. In this specific example, the request is made to fetch the user object for the current user using the “me” query. Once the user object is obtained, the webpage displays the user’s first name.

The Messenger Connect JavaScript API feels familiar to developers who use other popular web platforms

We want to ensure that we don’t add to the learning curve for developers, so we made sure that our JavaScript API would work in familiar ways for developers who integrate with multiple popular web platforms via JavaScript. For example, you may want to include social sharing for Facebook and Twitter alongside the ability to access SkyDrive photo albums and the ability to add events to your Hotmail calendar.
Common tasks in our JavaScript API such as signing in the user, accessing data from their contact list, viewing their photos, and showing the permission dialog all look and work very similarly to comparable scenarios in other common platforms like Facebook, Twitter, etc. This makes it very easy for any developer who is familiar with programming against these APIs to pick up and start integrating SkyDrive, Hotmail, and Messenger into their websites.

Combining Hotmail, Messenger, and SkyDrive with other integrated services on a page shouldn’t cause clutter

Websites typically don’t just offer integration with one service provider. It is common for a website to want to enable sharing to multiple sites like Facebook and Twitter, or allow users to upload their photos from Flickr, Facebook, and SkyDrive.
One of the challenges with supporting services that identity multiple providers on a website is what many have dubbed “the NASCAR effect,” which is when a site has so many logos from so many different providers that it looks a little like a race car with too many corporate sponsors. This practice often ends up confusing users due to the paradox of choice.
To help with this, we make it easy for your app or site to check if a customer uses one of our services before even offering the option to connect. Again, with just a few lines of JavaScript, you can tailor your connection and offer the right features to the right users – just use the WL.getLoginStatus function as follows:
WL.getLoginStatus(function (response) {
           if (response.status && response.status!= ‘Unknown’) {
               WL.ui({
                name: "signin",
                brand: "hotmail",
                type: "connect",
                element: "signInButton"
               });
           }else{
           /* draw sign-in button for other identity providers */ 
           }
       });
The code above checks to see if the customer uses one of our services, and if the status comes back as “Unknown,” it can then call some fallback code that draws the sign-in control of another identity provider such as Facebook, Twitter, or Google.
These are just a few examples of the ways we’ve improved our JavaScript API to simplify the developer experience. Keep the feedback coming, and we look forward to seeing more of your apps and sites connected to Hotmail, Messenger, and SkyDrive.

Saturday, June 18, 2011

Observer Design Pattern in C#


Definition

The Gang of Four book (Design Patterns: Elements of Reusable Object-Oriented Software, 1995) says that the Observer design pattern should "Define a one-to-many dependency between objects so that when one object changes state, all its dependents are notified and updated automatically."

Purpose of Observer Pattern

The Observer pattern is to notify the interested observers about some change occurred. We can add more observers in runtime as well as remove them.

Example: We have a form to select the color. For each color change we need to update the entire application. There will be observers listening to the color change event for updating themselves.

Subject and Observers

The two important key terms in the pattern are Subject and Observer.

Subject is the object which holds the value and takes responsibility in notifying the observers when the value is changed. The subject could be a database change, property change or so.

We can conclude that the subject contains the following method implementations.
public interface ISubject{
    void Register(IObserver observer);
    void Unregister(IObserver observer);

    void Notify();
}


The Observer is the object listening to the subject's change. Basically it will be having its own updating/calculating routine that runs when get notified.
public interface IObserver{
    void ColorChanged(Color newColor);
}


In the above example, we are using an observer interface which has a ColorChanged method. So the interested observers should implement this interface to get notified.

There will be only one Subject and multiple number of Observers.

Registering and Unregistering

In the above interface, the observer can use the Register() method to get notified about changes . Anytime, it can unregister about notifications using the Unregister() method.

Notifying

The Notify() method will take care of calling the listening observers.

Associations

The Subject and Observer objects will be having a one-to-many association.

ObserverPatt1.gif

Using the Code

The associated code is having a main form, where the Subject would be a class named ColorSubject.
public class ColorSubject : ISubject{
    private Color _Color = Color.Blue;
    public Color Color
    {
        get { return _Color; }
        set
        {
            _Color = value;
            Notify();
        }
    }
    #region ISubject Members
    private HashSet<IObserver> _observers = new HashSet<IObserver>();
    public void Register(IObserver observer)
    {
        _observers.Add(observer);
    }
    public void Unregister(IObserver observer)
    {
        _observers.Remove(observer);
    }
    public void Notify()
    {
        _observers.ToList().ForEach(o => o.ColorChanged(Color));
    }
 
    #endregion}
The class implements ISubject interface and thus takes care of registering, unregistering and notifying the interested observers. All the observers keep registered with the ColorSubject object.

Screen Shot of Application

ObserverPatt2.gif

On running the associated project, we can see a color selector form, which acts as as the subject. All the other forms are observers listening to the ColorChanged event.

Note: The multicast event model in .Net can also be considered as an observer pattern. Here the interested parties register a method with the subject (might be a button) and whenever the button is clicked (an event) it invokes the registered observers (subscribers)

Conclusion

In this article we have seen what Observer pattern is and an example implementation.