Wednesday, December 22, 2010

Making a multi-choice quiz application in Asp.net

I was very interested the quiz that is in w3schools I decided to try to create one in Asp.net.I use a database and Viewstates to manage the quiz .It is very staigtht forward and self explainatory .If you are interested, I can always explain it .


Here is the final view
Database
I use Linq to SQL classes
Finally i create simple Quiz manager to insert,update and delete questions for the quiz.I use a detailsview control because its very optimal for such funtionality


Here is the source code for the quiz i made.
using System;
 using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Collections;

public partial class _Default : System.Web.UI.Page
{ 
   //create variables you will need to use in the application
    ArrayList quizHistory = new ArrayList();
    QuizDataContext qz = new QuizDataContext();
    int questionNum = 1;
    int score = 0;
    int totalQuestions;
    Random generator;

    protected void Page_Load(object sender, EventArgs e)
    {
        // Load quiz on page load
        if (!Page.IsPostBack) 
        {
            totalQuestions = qz.Quizs.Count();
            LoadQuestion(questionNum);
        }
    }

    void LoadQuestion(int questionNum)
    {
        Quiz myQuiz;
        generator = new Random();
        int ranHolder;
        using (QuizDataContext db = new QuizDataContext())
        {
            myQuiz = (from q in db.Quizs
                      where q.QuestionId == questionNum
                      select q).Single(); // only single instance wanted

            // clear Previos items
            answers.Items.Clear();

            //allocate values to controls
            Label1.Text = myQuiz.Question;
            //random template loader
            ranHolder = generator.Next(1, 4); // Quiz template position is random.
            switch (ranHolder)
            {
                case 1: // template One
                    answers.Items.Add(myQuiz.Answer);
                    answers.Items.Add(myQuiz.Anwer2);
                    answers.Items.Add(myQuiz.CorrectAns);
                    answers.Items.Add(myQuiz.Anwer3);
                    // store key items into the ViewState bag
                    SaveAnswers(myQuiz);
                    break;
                case 2:
                    answers.Items.Add(myQuiz.Answer);
                    answers.Items.Add(myQuiz.CorrectAns);
                    answers.Items.Add(myQuiz.Anwer2);
                    answers.Items.Add(myQuiz.Anwer3);
                    // store key items into the ViewState bag
                    SaveAnswers(myQuiz);
                    break;
                case 3:
                    answers.Items.Add(myQuiz.Answer);
                    answers.Items.Add(myQuiz.Anwer2);
                    answers.Items.Add(myQuiz.Anwer3);
                    answers.Items.Add(myQuiz.CorrectAns);

                    // store key items into the ViewState bag
                    SaveAnswers(myQuiz);
                    break;
                case 4:
                    answers.Items.Add(myQuiz.CorrectAns);
                    answers.Items.Add(myQuiz.Answer);
                    answers.Items.Add(myQuiz.Anwer2);
                    answers.Items.Add(myQuiz.Anwer3);

                    // store key items into the ViewState bag
                    SaveAnswers(myQuiz);
                    break;
            }

        }

    }

    private void SaveAnswers(Quiz myQuiz)
    {    // save to viewstate
        ViewState["CorrectAnswer"] = myQuiz.CorrectAns;
        ViewState["History"] = quizHistory;
        ViewState["QuestionNum"] = myQuiz.QuestionId;
        ViewState["Scores"] = score;
        ViewState["QuestionTotal"] = totalQuestions;
    }
    protected void nextBtn_Click(object sender, EventArgs e)
    {
        // store essental variables in the viewState bag
        quizHistory = (ArrayList)ViewState["History"];
        questionNum = (int)ViewState["QuestionNum"];
        score = (int)ViewState["Scores"];
        totalQuestions = (int)ViewState["QuestionTotal"];


        // check for correct answer
        if (answers.SelectedItem.Value == (string)ViewState["CorrectAnswer"])
        {
            score += 1;
            quizHistory.Add("Correct");
        }
        else
        {
            // add to history
            quizHistory.Add(answers.SelectedItem.Value);
        }

        // Check if end of Quiz
        //if end show results
        if (totalQuestions == questionNum)
        {
            ResultPanel.Visible = true;
            ShowResult();
        }
        else
        {    //Hide result panel
            ResultPanel.Visible = false;
            //Go to next question            
            questionNum += 1;
            // show next question
            LoadQuestion(questionNum);
        }
    }
    void ShowResult()
    {

        Label2.Text = "Score " + score.ToString() + " / 4 ";
        LblCongrats.Text = "

Congratulations!!!

"; if (score == qz.Quizs.Count()) LblCongrats.Visible = true; for (int i = 1; i <= totalQuestions; i++) { lblHistory.Text += i.ToString() + " Choice made was " + quizHistory[i - 1] + " "; } } protected void LoadBut_Click(object sender, EventArgs e) { totalQuestions = qz.Quizs.Count(); LoadQuestion(questionNum); Response.Redirect("Default.aspx"); } }
Happy programming
In my next post i will write the same application using ASP.net MVC ."The only way to learn a framework is to build an application with it".

Tuesday, December 21, 2010

Loose Design with Interfaces

I am very interested in design patterns but i have not really had it easy trying to understand how they work .Anyway i think i am getting better in understanding them. I read this wonderful post from this blog Software-design-patterns-for-everyone It helped me understand some patterns better . The truth is that practice makes perfect ."I have to write my own game engine using patterns to learn patterns".Very possible as everything else is, if the goals are realistic to attend .

I am currently reading been reading Professional ASP.NET MVC 2: NerdDinner and in the book there is use of a couple of patterns like repository patterns ,dependency control and others (still reading ) .The was one aspect that caught me and i think it was very interesting It was about loose design with interfaces that can make test driven development(TDD)easy .Objects are not to be passed as parameters just what they do is passed as parameters .After understanding it i decided to try to implement it by building a small home simulator .The program simple simulates a home .I am still learning but to learn something you have to start by learning something somewhere in some way you can understand .

I could have just created a home object and other homes can inherited from it.
What if i want simulate a hotel someday ?
Do i have to start everything adding a bigger home and doing changes in the code in many places .?
All i want is a simulator for a home .The object can simulate home activities .This object can simulate any home .
Call it and tell it how you want the home to be simulated.
Lets simulate a home using interfaces .


namespace LearningInterfaces
{
     public interface ISimulateHomeActivities   // main interface
    {
        void CookFood(string foodType);
        void Sleep(string time);
        void DoLaundry();      
    }

}

This class uses the interface to simulate the home .
namespace LearningInterfaces
{
     public class HomeActivities // main simulator manager
    {
         public void DoActivity(ISimulateHomeActivities activity, string foodType , string sleepTime);
         {
             activity.DoLaundry();
             activity.CookFood(foodType);
             activity.Sleep(sleepTime);
         }
    }
}

Its time to get homes that want to be simulated
The Talla's home is the first on the list .It implements the ISimulateHomeactivities

namespace LearningInterfaces
{
     public class TallasHome:ISimulateHomeActivities
    {
        #region ISimulateHomeActivities Members

        public void CookFood(string foodType)
        {
            Console.WriteLine("We are going to cook " + foodType + " today");
        }

        public void Sleep(string time)
        {
            Console.WriteLine("We  usually sleep at  " + time);
        }

        public void DoLaundry()
        {
            Console.WriteLine("We  are doing laundry ");
        }
        #endregion
    }
}


Peter loved my home simulator and wants his home to be simulated
namespace LearningInterfaces
{
    public  class PetersHome:ISimulateHomeActivities
    {

        #region ISimulateHomeActivities Members

        public void CookFood(string foodType)
        {
            Console.WriteLine("We are going to cook " + foodType + " today");
        }

        public void Sleep(string time)
        {
            Console.WriteLine("We  usually sleep at  "+ time);
        }

        public void DoLaundry()
        {
            Console.WriteLine("We  are doing laundry ");
        }

        #endregion
    }
}
Finally lets get the simulation running

using System;
using System.Collections.Generic;
using System.Linq;
using System
namespace m.Text;
LearningInterfaces
{
    class Program
    {
        static void Main(string[] args)
        {    var tallasHome = new TallasHome();
             var petersHome = new PetersHome();
             var activities = new HomeActivities();
             activities.DoActivity(tallasHome, "Rice and Chicken", "10 pm");
             Console.WriteLine("----------------------------------------------");
             activities.DoActivity(petersHome, "Pasta with Fish", "11:30 pm");

        }
    }
}


The simulator running prints out the following------simulating Talla,s and Peter's home

We are doing laundry
We are going to cook Rice and Chicken today
We usually sleep at 10 pm
----------------------------------------------
We are doing laundry
We are going to cook Pasta with Fish today
We usually sleep at 11:30 pm
Press any key to continue . . .

Happy programming ............................

Saturday, December 4, 2010

Why I should learn ASP.Net MVC .

There has been lot of talk on the internet about Asp.net web form and the new Asp.net framework MVC .I have read a couple of them and watched to a couple of videos that was done by the creators themselves who all work at Microsoft.I have watched Scott Hanselaman's videos on making of the Nerd-dinner portal and even downloaded the book and source code to play with it.

After reading all these blogs and various views about the two frameworks and reading the book Professional ASP.NET MVC 2 about the creation of the Nerd-dinner portal i came to the following conclusion
MVC is just an amazing framework that is good to use if you want control in your application.
It is very easy to turn my applications to be mobile phone adapted and it you can keep on expanding it the way you want and great of all it is easy to do test in MVC.

There is a clear separation of concerns MVC(Models,Views and Controllers)

Nice SEO urls.that are search engine friendly.

There is more work to be done when developing in MVC and the final HTML code is clear and understandable since there is no viewstate and postbacks .

So why should i learn ASP.net MVC ?
I think it will make me a better web developer .I did not know anything about this pattern but after some hard work I now understand it .
I also learned more about the repository pattern and even building a web application using real code and no controls that one can drag and drop .
I learned more about routing URLs and real jquesry and Ajax with no script managers or update panels added into the application .
I should learn MVC to be a complete ASP.net developer who can work and build applications in both frameworks.
There is more real coding and no drag and drops hence the geekiners in me feels good about that.

Finally the choice between ASP.net MVC and ASP.net web form boils down to the kind of project you are doing ,how fast you want to ship it, the number of developers you have and the environment of usage .
If you are intrested about MVC then here is where to go Learn ASP.net MVC

Tuesday, November 16, 2010

The Singleton pattern in C#

Singleton Pattern:Example One
Thread safe example
It is created at the beginning of the application and this makes it thread safe.
The static part of the instance is private and the public Singleton can be gotten using GetInstance() that returns an instance of this class hence making sure that only one instance of the object is created in the application current state for example a shopping cart on a webpage.
using System;
 /// 
/// Thread-safe singleton  created at first call
/// 
namespace Singleton
{  

    
    class Singleton
    {
         private static Singleton instance = new Singleton();

         private Singleton(){}

          public static Singleton GetInstance()
          {
            return instance;
          }

          public double Total { get; set; }
          public string UserName { get; set; }
     }
 }


Here is how you make a call on the Singleton class :
Singleton single = Singleton.getInstance();
single.UserName = "Ngala" ;
single.Total = 345.00 ;
//....

Singleton pattern: Example Two
Lazy Evaluation example
With Lazy evaluation it means it is created in the memory when it is needed. When the class is created, it first make sure that it is not in the memory before creating a one. When it is created it is locked on a single thread.

using System;
 /// 
///  Lazy Evaluation example
/// 
namespace Singleton
{  

    class SingletonLazyEval
    { 
         private static SingletonLazyEval instance;

          private SingletonLazyEval() { }

          public static SingletonLazyEval GetInstance()
          {
              lock (typeof(SingletonLazyEval))
            {
              if (instance == null)
              {
                  instance = new SingletonLazyEval();
              }
              return instance;
            }
          }
        
    }
}

Thursday, November 11, 2010

TekPub - Concepts

TekPub - Concepts
I love watching videos from Microsoft Mix . These videos are very enriching and one gets to know about current and future products of Microsoft .You get to see all these great videos(some of them) from the guys themselves that develop these products. I happen to have fallen on Rob Conery presentation on the MVC Store Front. Its just amazing and I really feel in love with the scripting aspect of his application. So I though to myself to see if this guy offers more. Luckily he had a website called Tekpub that publishes videos tutorials. The quality is really good. For now I am watching all his videos on key concepts in software. He demystifies them and I feel like I can start using all these knowledge the next time I want to build an application. The truth is interfaces are powerful in design of software and knowing how to use them makes you build really groundbreaking and flexible applications. Here are the key concepts he talks about and show us life code examples in his free videos .
1 - Dependency Injection and Inversion of Control
2 - Lambdas
3 - Unit Testing
4 - Loose Design with Interfaces
5 - Behavior-driven Design with Specflow
The truth is I have never really been interested in many of these concepts but when the old and experience guys in the industry tell you that it's important then it is .Since I want to become a big guy in the industry someday I will learn from the real big and experienced guys.
I really started blogging after following his video series from a Coder to a Developer .These videos are really enriching .I will encourage everyone to watch it .
The next thing for me to do is to write about the singleton pattern.Why?Its just a way for me to understand it better.

Sunday, November 7, 2010

A paddle and ball game in Javascript

 As a web developer you just have to know and write some javascript to add some extra feeling and functionality on your web applications .I am not a declared web developer but since i love the web it will be nice to be able understand its own key programming language . Here is where I start .I am building a small paddle and ball game .I am not starting from the basics because I already understand the basics in programming. What I wish to accomplish is to be able to link css to javascript ,move objects on the screen and let it work on all browsers. I wanted to do it with jquery but I feel like I am cheating on myself on my goal to learn the main scripting language for the web. Just some raw Javascript will make me happy.I know i will learn events in javascript,functions definitions,timing,key game concepts and others as I develop the game.
To start the development of this game .They are certain important objects that have to be defined.Anyway lets imagine how the player will play the game.

-load up the game on the browser
-move the paddle from left to right with the mouse
-every time the ball hits the paddle the game points increase.

From the above we see that they are certain key objects that we must have a reference to them and know their states.

1)The playing area.(where the game will be played)
2)The paddle
3)The ball
4)The score
In javascript you can represent your objects like css defined fields.This make life easy for everybody.Every object in the game has its own css properties.Lets not forget.This is a web based game.Hence I wrote these styles to fit the above objects .With this each style can me manipulated using Javascript.
As a web developer you must have some css feeling even if you are not a designer.Anyway you can put this in-line or in a separate file. I choose to put it in-line since its a small program

//Comment
//the ball and paddle object will be represented by images
//Still they will be in a div class representing them.



Coming up next will be the script to handle this objects on the screen.
Let start scripting ....

Since its inline Javascipt,this script will be at the head section of the html page.
1)In every game you must have references your objects or what ever components you will need to know their states in the game.
2)Name the components and initiate them to various positions


The first function is the initiate function
function init(){
      //get the ball,paddles and score references on the document by getting their Ids.           
            ball = document.getElementById('ball');
            paddle = document.getElementById('paddle');
            score = document.getElementById('score');
//since we shall use the keyboard to move the paddle we have to register input from the keyboard to the current document that is out game
            //register key listener with document object
            document.onkeydown = keyListener;
            //start the game loop
            start();
        }
We can find that there is a Keylistner that returns an event on a key press that will be linked to the paddle .Note that this can be different on various browsers.
function keyListener(e){
            if(!e){
                  //if its IE
                 e = window.event;
            }
            if(e.keyCode==37 && paddleLeft > 0){
                //keyCode 37 is left arrow
                paddleLeft -= 5;
                paddle.style.left = paddleLeft + 'px';
            }
            if(e.keyCode==39 && paddleLeft < 436){
                //keyCode 39 is right arrow
                paddleLeft += 5;
                paddle.style.left = paddleLeft + 'px';
            }
            //FYI - keyCode 38 is up arrow, keyCode 40 is down arrow
        }
 

The next function to handle will be the start function.Remember that is the last line in the initialisation function.This is where the magic begins.
That will be coming up next...........

Wednesday, June 30, 2010

On The Value Of Fundamentals In Software Development

On The Value Of Fundamentals In Software Development
Great post above for beginners and even for experts. I decided to follow this rule and truly you become more productive and bettter

Friday, January 22, 2010

Computer Programming

Is Programming an art ? May be its an art when it comes in designing bigger programs and crafting a solid system architecture.What do you think?

Machine learning is the future

I am very enthusiastic about machine learning and the potential it has solve tough problems. Considering the fact that the amount of data we...