AJAX Autocomplete (Suggestion) on ASP.NET from dictionary file

Hi, It's been a long time since my last post about google map. This time I'm going to talk about AJAX autocomplete function. Let's see a sample from the most famous website i've known.

Good News is, It's very easy and you can do it. Just follow my step. First, I'll explain how it works. Most AJAX Libraries require response from server. Every information you want to retrieve from server must be in form of "response" or "JSON" (JavaScript object just like XML for JavaScript). Our Application here is one of examples that i'm going to show you how to retrieve information from server by Response object. Either ASP.NET or PHP can deal with response. So AJAX Library can be applied to those language. All you need to do's write a JavaScript to retrieve response from the server side

Here's an step of how this "Autocomplete" Thing work

  1. Load JavaScript library, initialize and wait for input from user.
  2. User type in letter. Value's passed by "FORM" request to a page named "Default.aspx".
  3. Default.aspx read dictionary file and response to client in a form of unordered list text.
  4. Browser show suggestion to user. User can choose and the text in textbox's completed.

How Simple! here my example

Start!

1. Declare input and output, input is for input from user(Form Request). And output's string output (<ul><li>first item</li><li>second item</li></ul>).

1 protected void Page_Load(object sender, EventArgs e)
2 {
3 String output = "";
4 String input = Request.Form["paramX"];
5 }

Declare it in Page_Load event of Default.aspx

2. Deal with string with space. I'll split the line into array of word. and suggest only the last word. Always response the former text.

1 if (input != null)
2 {
3 String[] arrayS;
4 arrayS = input.Split(' ');
5 for (int i = 0; i < arrayS.Length - 1; i++)
6 {
7 output += arrayS[i] + " ";
8 }
9 input = arrayS[arrayS.Length - 1];

3. Open an fileStream and read "dict.txt". Compare words in the file with input (last word of array) and response in unordered list string

1 using (FileStream fs = new FileStream(Server.MapPath("dict.txt"), FileMode.Open))
2 {
3 using (StreamReader reader = new StreamReader(fs))
4 {
5 String tmp;
6 Response.Write("<ul>");
7 while (!reader.EndOfStream)
8 {
9 tmp = reader.ReadLine();
10 if (tmp.Length >= input.Length && tmp.Substring(0, input.Length) == input || tmp == input) Response.Write("<li>" + output + tmp + "</li>");
11 }
12 Response.Write("</ul>");
13 }
14 }

4. Now, we've done with Default.aspx. This page'll act as service that response text from dictionary when an AJAX Library tried to request the list of suggested word. Next thing, we'll build a page that'll use an AJAX library called "Script Aculo" which has an Autocomplete built-in function. Here's the source code

1 <html xmlns="http://www.w3.org/1999/xhtml" >
2 <head runat="server">
3 <title></title>
4 <script src="js/prototype.js" type="text/javascript"></script>
5 <script src="js/scriptaculous.js" type="text/javascript"></script>
6 <script src="js/controls.js" type="text/javascript"></script>
7 <style type="text/css">
8 /*
9 div.autocomplete {
10 position:absolute;
11 width:500px;
12 background-color:white;
13 border:1px solid #888;
14 margin:0;
15 padding:0;
16 }*/
17 ul {
18 list-style-type:none;
19 margin:0;
20 padding:0;
21 }
22 ul li:hover { background-color: #ffb;}
23 ul li {
24 list-style-type:none;
25 display:block;
26 margin:0;
27 padding:2px;
28 cursor:pointer;
29 }
30 </style>
31
32 </head>
33 <body>
34 <form id="form1" runat="server">
35 <div>
36 <input type="text" id="autocomplete" name="autocomplete_parameter"/>
37 <div id="autocomplete_choices" style=" height:150px; overflow:auto;"></div>
38 <script type="text/javascript">
39 new Ajax.Autocompleter("autocomplete", "autocomplete_choices", "Default.aspx", {
40 paramName : "paramX" 41 });
42 </script>
43 </div>
44 </form>
45 </body>
46 </html>

First thing, include an AJAX library in <head>. Load Script Aculo From www.script.aculo.us It require PROTOTYPE.JS (another javascript library)

put this into your <head>

<script src="js/prototype.js" type="text/javascript"></script>
<script src="js/scriptaculous.js" type="text/javascript"></script>
<script src="js/controls.js" type="text/javascript"></script>

Include downloaded script into your <head>. Then put input box into your <body>

<input type="text" id="autocomplete" name="autocomplete_parameter"/>
<div id="autocomplete_choices" style=" height:150px; overflow:auto;"></div>

Last thing to do! Put javascript after that.

<script type="text/javascript">
new Ajax.Autocompleter("autocomplete", "autocomplete_choices", "Default.aspx", {
    paramName : "paramX"
});
</script>

As usual! Compare your result here.

Make use of the Behavioral State Pattern

Hello my friend ,today I wanna try to write about state behavioral pattern that is used in many areas and cases. When implementing this pattern ,you expect the behavior of objects to be changed when their internal state changes ,for example ,when you move your mouse around (like now) ,your mouse behavior is different according to its current status. Like when you use PenTool or SelectionTool in a drawing program ,two classes for each tool can be created but it's a painful task when dealing with many many objects(tools in this place) ,don't you think? Because most actions(clicking ,dragging) of those tools still are not such a big different. You have mouse_Click() ,mouse_Drag() ,for example. So in this situation ,state pattern will be your choice.

I will illustrate the pattern with my example below ,this example is easy to understand(I think). If you have a better idea or have any questions ,you can leave a message. Also ,I'm not a game developer if I make you guy angry ,I'm so sorry..

This example scenario : I want to have a player of one game that can "Fire a weapon" and take an action "Jump" ,I'm not fill in irrelevant details about weapons ,actions ,or activities that will make my code complicated... The thing that is worth to look at is the state of the player. There are two states (or mode in this scenario) the "Normal" mode and the "Super Power" mode. For those two ,player can still jump and fire but the result damage will be different related to the player's state.I forgot to tell that another important point of this state pattern (actually it depends on the design but most of them) is when you implement it with on the fly loading or lazy loading. Don't mix up with lazy developer (like me). I'll show it to you later on in this article.

Firstly ,I want myself to easily write the code in main function like below ,as you can see that it's very readable. Especially ,when switching the player's state :

static void Main(string[] args)
        {
            Player player1 = new Player(1);
            //default player state is Normal state
            player1.FireWeapon(/*..*/);
            player1.Jump();

            player1.ChangePlayerState(new SuperPowerState());
            player1.FireWeapon(/*..*/);
            player1.Jump();
        }

Player has a field that can keep his state and he can fire weapon and jump... Notice this line of code  if (!playerState.IsStateInitialized)InitializePlayerState(); you can see it in every action because we want to perform lazy loading or load-on-fly ,say that if the PlayerState class isn't instantiated yet ,just do it! This instantiation doesn't cause from manually instantiation but from when we want to take some actions of the player (like FireWeapon() or Jump()).

class Player
    {
        private PlayerState playerState;
        public int PlayerID { get; set; }
        public Player(int ID)
        {
            //use default state
            playerState = new NormalState();
            PlayerID = ID;
        }

        public void InitializePlayerState()
        {
            playerState.InitializeState(this, PlayerID);
        }

        public void ChangePlayerState(PlayerState playerStateTobeChangedTo)
        {
            playerState = playerStateTobeChangedTo;
        }

        public void FireWeapon(/*necessary information e.g. weapon id ,etc.*/)
        {
            if (!playerState.IsStateInitialized)
                InitializePlayerState();

            double damage = playerState.FireWeapon(/*arguments*/);
            Console.WriteLine("Hit : " + damage+" points");

            //...send some messages to tell ,maybe ,the player director class 
            //to know that someone was hit with how much damage value for example...
        }

        public void Jump()
        {
            if (!playerState.IsStateInitialized)
                InitializePlayerState();

            int jumpHeight = playerState.Jump();
            Console.WriteLine("Jump : " + jumpHeight);

            //...take more actions...
        }
    }

We need the state base class that contains basic methods like ChangeState(...) and InitializeState(...) that will support Player class:

class PlayerState
    {
        public bool IsStateInitialized{ get; set; }

        public virtual void InitializeState(Player context, int playerID){}

        protected void ChangeState(Player player, PlayerState playerState)
        {
            player.ChangePlayerState(playerState);
        }

        public virtual double FireWeapon()
        {
            return 0;
        }

        public virtual int Jump()
        {
            return 0;
        }

    }

For "NormalState" and "SuperPowerState" class ,you can add more funtionalities or whatever you want but don't forget to call ChangeState(...) when you want player to initialize his new state.

class NormalState : PlayerState
    {
        private double damageMulplier;
        private int jumpHeight;

        public override void InitializeState(Player player, int playerID)
        {
            //...load necessary information of a player for 
            //this particular state from somewhere...
            damageMulplier = 10.0;  //assumed
            jumpHeight = 100;  //assumed

            Console.WriteLine("=> Player ID {0} mode is Normal.",playerID);

            //NormalState playerState = new NormalState();
            //ChangeState(player, playerState);

            IsStateInitialized = true;

            ChangeState(player, this);
        }

        public override double FireWeapon()
        {
            //...calculate the posibiliy of bullet hit the enemy...
            double hitRate = 0.6;   //assume the result

            return hitRate * damageMulplier;
        }

        public override int Jump()
        {
            return jumpHeight;
        }
    }

    class SuperPowerState : PlayerState
    {
        private double damageMulplier;
        private int jumpHeight;

        public override void InitializeState(Player player, int playerID)
        {
            //...load necessary information of a player for 
            //this particular state from somewhere...
            damageMulplier = 30.0;  //assumed
            jumpHeight = 300;  //assumed

            Console.WriteLine("=> Player ID {0} mode is SuperPower.", playerID);

            //SuperPowerState playerState = new SuperPowerState();
            //ChangeState(player, playerState);

            IsStateInitialized = true;

            ChangeState(player, this);
        }

        public override double FireWeapon()
        {
            //...calculate the posibiliy of bullet hit the enemy...
            double hitRate = 0.5;   //assume the result

            return hitRate * damageMulplier;
        }

        public override int Jump()
        {
            return jumpHeight;
        }
    }

Finally ,I'd like to refer to this UML class diagram of the State Design Pattern. We have State and Handle() which are PlayerState and PlayerState.FireWeapon() ,Context and Request() which are Player and his actions. Context has State and call state.Handle() that's like our Player has PlayerState as an instance field and call playerState.FireWeapon() that will call playerState.FireWeapon() accordingly.

Thanksss!!! kick it on DotNetKicks.com

Categories:   Design Patterns
Actions:   E-mail | del.icio.us | Permalink | Comments (4) | RSS


Observer Design Pattern Implementation

Long time no see... Today I'll create one simple example that uses Observer behavioral pattern of the GOF. Observer pattern is used when you want other objects to be notify when something happens with a particular object. For my example ,I want some parts of our company (may be just a little company :P) knows when stock items of our shop is lower than 10 pieces. If it is below 10 ,then alert the notifications for e.g. the transportation part and the warehouseing part to understand the problem. Our notification message has to be composed of : which part(transportation/warehouseing) we want to send to ,what the shop name ,location ,and type (that sends this notification) is. The code is not too hard too understand ,so I won't explain much in details.

Firstly ,we create the Shop class that holds some information about our shop :

public class Shop
    {
        //Shop ID discarded for simplicity
        public string Name { get; set; }
        public string Location { get; set; }
        private int _StockItemsCount;

        public event StockChanged StockChangedObsever;

        public Shop(string name, string location, int stockItemsCount)
        {
            Name = name;
            Location = location;
            _StockItemsCount = stockItemsCount;
        }

        public int StockItemsCount
        {
            get { return _StockItemsCount; }
            set
            {
                _StockItemsCount = value;

                if (_StockItemsCount < 10)
                    //alert that this inventory items number is too low ,need replenishment
                    this.StockChangedObsever(this);
            }
        }
    }

Delegate helps us make work easier ,it can be called back when we need :

 

public delegate void StockChanged(Shop shop);

 

We then build Observer base class and its derived classes (actually ,you don't need to do like this but I am showing you that there are two different parts in our company that will be notified) :

public class ObserverBase{
        protected virtual void OnStockChanged (Shop outOfStockShop)
        {
            Console.WriteLine("{0} has been run out of stock!!   \nShop type: {1}   Location: {2}", outOfStockShop.Name, outOfStockShop.GetType().ToString(), outOfStockShop.Location);
        }

        public void ObserverStockItems(Shop shop)
        {
            shop.StockChangedObsever += new StockChanged(OnStockChanged);
        }
    }

    public class InventoryObserver : ObserverBase
    {
        protected override void OnStockChanged(Shop outOfStockShop)
        {
            base.OnStockChanged(outOfStockShop);
            Console.WriteLine("=> Updating {0}'s stock items the warehouse...    \nShop type: {1}   Location: {2}\n" , outOfStockShop.Name, outOfStockShop.GetType().ToString(), outOfStockShop.Location);
            //perform an operation ...
        }
    }

    public class TransportationObserver : ObserverBase
    {
        protected override void OnStockChanged(Shop outOfStockShop)
        {
            base.OnStockChanged(outOfStockShop);
            Console.WriteLine("=> Transporting to {0}'s stock from the warehouse...    \nShop type: {1}   Location: {2}\n" , outOfStockShop.Name, outOfStockShop.GetType().ToString(), outOfStockShop.Location);
            //perform an operation ...
        }
    }

For the main class :

static void Main(string[] args)
        {
            Shop shop1 = new Shop("theBlogFor Magazine", "NY ,NewYork",50);
            Shop shop2 = new Shop("Suppy Souvenir", "BKK ,Bangkok", 20);

            //declare all of our observers
            InventoryObserver iObsr = new InventoryObserver();
            TransportationObserver tObsr = new TransportationObserver();

            iObsr.ObserverStockItems(shop1);
            tObsr.ObserverStockItems(shop1);
            iObsr.ObserverStockItems(shop2);
            tObsr.ObserverStockItems(shop2);

            shop1.StockItemsCount = 5;
            shop2.StockItemsCount = 8;
        }

 

Let's check this UML of GOF out. Observer class is obvious in our example code. We have two concrete observer classes that can have different observer states(the notification messages that were printed out) ,on the other hand ,we get some states(name, type ,location) from ConcreteSubject which is our Shop class. Our shop class can be attached with the observer via the event "StockChangedObsever" and delegate. Finally the Shop class can also be notified if something has been changed that is in our StockItemsCount's set property when  its items count is below ten.

Thanks for your attention! you can leave a comment...

kick it on DotNetKicks.com

Categories:   Design Patterns
Actions:   E-mail | del.icio.us | Permalink | Comments (12) | RSS


 

Tag Cloud