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