WHAT'S NEW?
Loading...
Showing posts with label C#. Show all posts
Showing posts with label C#. Show all posts

Introduction


Today I wanted to create a basic example about how events work in C#. This is a great tool to create loosely coupled applications, removing dependencies and allowing you to change and fix your programs making the least amount of changes.

Events

First of all we need to define three steps that we need to follow when we work with events:

  1. We need to define a delegate with this convention:
    1. add the suffix "EventHandler" in the name of the envent
    2. Parameters: an object which is the source of the event and an EventArgs if we need to pass additional data
  2. Define an event based on that delegate. Note that the signature is defined by the delegate and every subscriber will have to follow that signature. Typically this has its name in past tense as it's something that already happened.
  3. Raise the event.
In the following example I've tried to use the analogy of a regular house with some pets and what they usually do when you get home. I've defined three classes: BreadWinner (you), Cat and Dog. There is an extra class to run the application and subscribe Dog and Cat to the event publisher, in this case, the BreadWinner.


Let's change a little bit my example to pass an argument when my event is raised. This time I've simplified the previous example. See how with my new PapaEventArgs class I can use it to pass content to my subscribers. See changes highlighted.


The final step is to show you how to the same thing but using less code. .Net provides a way to prevent create a delegate every time we want to create an event by using the class EventHandler. In our example we'll use the generic class EventHandler<> as we want to pass PapaEventArgs to our subscribers. Additionally, I've added some exception handling to prevent breaking the flow when a subscriber triggers an exception. See changes highlighted.



The GREAT thing of all of this happens when there is a problem in the subscribers. Imagine this used in a very complex application and an error is raised for a subscriber. We won't need to touch the publisher and we won't need to recompile as is completely de-coupled from the rest of the subscribers.
Here we go again with a new tutorial to show you how to create a customized login using MVC 4 with Microsoft Visual Studio 2010. In this post, I will try to explain you how to develop different views, controllers, models, one database and of course, how all these elements interacts between them.

I have used MVC in older posts but I did not expend too much time explaing you how it works. MVC bornt as a software design pattern for implementing user interfaces. It provides a very useful architecture which splits between: the user interface (View), the logic and bridge between the user and the data (Controller) and finally the data (Model). Although originally developed for desktop computing, Model View Controller has been widely adopted as an architecture for World Wide Web. MVC 5 is the last template version released by Microsoft, but there are not too much differents with version 4. For the views, we are going to use Razor (CSHTML), the Microsoft dynamic view engine released in 2010. It is a new way to create your interfaces easier to use than ASPX, here you can check the differences beteween them.

Here below I show you all the steps to have your own login app:

  • Create the solution in Visual Studio: first of all, we need to create our project in VS2010. If you can't find the ASP.NET MVC4 Web Application template as showed in the image below, probably you need to download from Microsoft site. Remeber you need Service Pack 1 of VS2010. Write a name for your project and press OK.

In the following window, select a Basic template, which contains an specific structure of MVC 4. The view engine should be Razor and optionally create a unit test project.

In this example I am going to show you how to consume with C# a third party image recognition web service (REST). First we need to create a new (30 days free) account in our web service provider: www.recognize.im. Remember to save your account settings to make the connection: client_id, clapi_key and api_key. Then upload some images to your new account and save these images in small size to be used by our new application. I used some star wars images, you will see in the code below. Once all of these steps are finished we can start with our app.


Create a new solution in your VS with two projects inside. A console application will be the interface between the user and the second project, a library which saves all the logic for the web service.
Here below you can see the interface application stored in our console project. It gives some image options to our user. Then the user select one by writing the number reference and we make a call to our library.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections;
using OneFlowApp;

namespace OneFlowApp
{
    class Program
    {
        //Data members
        private static string client_id;
        private static string clapi_key;
        private static string api_key;
        private static string url;
        private static Dictionary<int, string> images;

        private static void Main(string[] args)
        {
            Program p = new Program();
            p.run();
        }

        private Program()
        {
            client_id = ""; //API User ID
            clapi_key = ""; //CLAPI user key
            api_key = ""; //API user key
            url = @"http://recognize.im/v2/recognize/single/";
            images = new Dictionary<int, string> {
                    {1, "anakinT.jpg"}, {2, "kenobiT.jpg"}, {3, "lukeT.jpg"},
                    {4, "vaderT.jpg"}, {5, "winduT.jpg"}, {6, "yodaT.jpg"}};
        }

        private void run()
        {
            Console.WriteLine("\n|-| Star Wars characters recognition system |-|\n");
            Console.WriteLine("\rPlease select a character (1-6) from the list below and press enter:\n");
            Console.WriteLine("1.Anakin\n2.Kenobi\n3.Luke\n4.Vader\n5.Windu\n6.Yoda");

            string opt = Console.ReadLine();
            short selection;
            if (Int16.TryParse(opt, out selection)) {
                if (selection > 0 && selection < 7) {
                    string imagePath = AppDomain.CurrentDomain.BaseDirectory + "..\\..\\Resources\\" + images[selection].ToString();
                    RestService rest = new RestService(api_key, url);
                    Dictionary<string, object> response = rest.sendData(imagePath);
                    if (response.ContainsKey("status") && response["status"].ToString() == "0") {
                        ArrayList responseArray = (ArrayList)response["objects"];
                        Dictionary<string, object> responseImage = (Dictionary<string, object>)responseArray[0];
                        Console.WriteLine("Match found! ID: " + responseImage["id"].ToString() + ", Name: " + responseImage["name"].ToString());
                    }
                    else if (response["status"].ToString() == "1") {
                        Console.WriteLine("Error: " + response["message"].ToString());
                    }
                    else if (response["status"].ToString() == "2") Console.WriteLine("No match found.");
                    else Console.WriteLine("No match found.");
                }
                else Console.WriteLine("Not valid option.");
                Console.ReadLine();
            }
            else {
                Console.WriteLine("Error: wrong selection");
                Console.ReadLine();
            }
        }
    }
}
In this part of the code we read the answer from the recognize server to know if it has been able to recognize the image sent. We get different kind of errors and only number “0” means that everything worked fine. In this case we can show the image reference name in the console view.
In this post I am going to show you how to develop over C# a great game: "Noughts and Crosses". Probably you already know how to play this game but if not, you can check it the wiki directly (I am not going to do it men! is an easy game). My application is console and can play alone, showing the result of the game in the screen after all the movements have been done.


The architecture of the program is divided in 5 different classes:
  1. Program.cs: just runs the start() method of the Play.cs class.
  2. Play.cs: it handles the maximun number of movements, the players (O & X), the currentPlayer and the BoardGame.cs class.
  3. Movement.cs: is like a model class, this class has 3 properties: two are for xy coordinates and one for the player who made the movement.
  4. Player.cs: it has two properties for the Id and a boolean if it wins. It also has a method to make a movement because this application plays alone and it generates a random movement.
  5. BoardGame.cs: it saves in a List class all the movements done by the players and the different positions that we can fill. Also it has several methods to check if there is any winner, to know which user filled what position and to know if a movement is possible or not.
Bellow I show you the different code parts for the classes explained before:
  • Program.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Noughts_and_Crosses
{
    class Program
    {
        /// <summary>
        /// Main method to start the execution
        /// </summary>
        /// <param name="args"></param>
        static void Main(string[] args)
        {
            Play play = new Play();
            play.start();
        }
    }
}
As my first post in this new blog I want to make something a little bit "different". For this reason, this post is about "one time password" (OTP) generation mixed with a little bit of Model View Controller (MVC). The idea for this post is to make an overview (with a little bit of code, of course!) over an authenticator that Google uses.
Most of you already would know about OTP, but if not, your are in the right place. A one-time password (OTP) is a password that is valid for only one login session or transaction. OTPs avoid a number of shortcomings that are associated with traditional (static) passwords. The most important shortcoming that is addressed by OTPs is that, in contrast to static passwords, they are not vulnerable to replay attacks. This means that a potential intruder who manages to record an OTP that was already used to log into a service or to conduct a transaction will not be able to abuse it, since it will be no longer valid. On the downside, OTPs are difficult for human beings to memorize. Therefore they require additional technology to work.
My application is basically a login form which uses username and an OTP provided by the server to login users. The OTP last 30 seconds, after this time, it will expire and the user will need to generate a new one. Now I am going to explain the different parts of my code to make easier your comprehension. First I start with a screenshot of the different program parts and the arquitecture:
  1. Controllers: Encryption.cs is the engine of the app and who generates the OTP password from the user id and a random number. LoginController.cs is the second most important part and is dedicated on handle the user inputs and the management of the information between the Login view and the model.
  2. Models: just User.cs class is needed to handle the user information (login, otp, otp creation date, logged)
  3. Views: UserGetOtp.aspx is the first view where the user writes his login name; UserLogin.aspx is shown to finish the login process with the OTP provided. Finally, after a succesful log process, the Account.aspx view, from the Private Area is shown.

Here bellow you can see the core of the application, the OTP generation method. This algorithm is explained in the point 5.4 of the RFC4226 (see references at the bottom):