Tuesday, May 30, 2017

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 produce digitally is growing geometrically as online activity och number of people connected to the internet keeps on increasing. We have to make something good out of that massive information we generate.

That is where machine learning come in. Machines are faster and can handle and processing large amounts of data better than us humans. Here are some of the things machiné learning can achieve today. It can identify images, write music and even stories give an image, It can write rap lyrics. It can predict the stock market better that any human, generate choreography based on the music and so on and forth. We are just scratching the surface in AI.

Due to my interest in this subject, i started watching some videos about machine learning and focused my attention on deep learning which uses neural networks . Most of the implemention  is in the Python language so i started learning python because most of the libraries and tutorials i see online are all written in python and is it an expressive language. If i want to be part of or become a data scientist and learn faster, I need to start writing some python code which i personally think it will be fun.
 
One technique i machine learning is using Neural networks based on how we think our brain takes in and processes information . Neural networks are incredibly powerful The good news is some of the maths subjects I learned in University like calculus, linear algebra and statistics all come together to produce this powerful technique of doing machine learning .I had to brush my skills with the, matrices, derivatives, gradient descent, sigmoid functions ,probabilities and back propagation . It sets a good base to understand what going underneath these python libraries . One can just focus on the building the models and choosing the techniques to handle the data.

Becoming a data scientist is more of brushing some of your maths skills in statistics, linear algebra and calculus . You must be capable to clean, understand and model data and to write code that turns that data to something useful. There are a lot of resources out there. I will start with small datasets about my life and then later handle complex datasets as I get better in this way of problem solving. I think I am in for a treat. It will be fun and a challenge to use and play with data to so some good for humanity.

It is time to train some datasets and solve some real tough problems

Happy machine learning !
Ngala Talla

Friday, August 16, 2013

Becoming an employable programmer

 Here is my take on this issue of becoming an employable programmer.
  1.  Learn and understand data structures and algorithms (searching , stacks,queues , shortest path , sorting etc)
  2.  Do not read books like pragmatic programming or books on how programming should be done. They just make you feel bad and give you low self esteem.
  3. Learn your own way and make mistakes at the beginning but since you want to learn and improve, your programs will become better and smarter. 
  4. Learn one language very well  so that you can write excellent code that solves problems. 
  5. Understand one database scripting language and how database works
  6. Know how the Internet works and it  commonly used terms
  7. You do not need to learn new language  besides the one you are learning.Learn  a new language when you really and truly understand one programming language .
  8. Learn javascript ,Css and Html
  9.  Build some real works stuff  that solves a problem . Choose a framework and your tools to use.
  10.  Master the framework inner workings
  11.  Practice , learn , read lots of code in projects that you think are really interesting . When you are is interested, the learning and understanding process is easier.
  12. Learn how to sell your skills and value you can create to an employer.
  13. Have a blog to monitor your progress and tell the world what you are good in and learning.
  14. Choose some top software developers and  read their blogs and have a role model in the programming world
  15.  Have a beer and watch programming or tech videos.
  16. Good self esteem and be humble
  17. Develop good communication skills
  18. Have a side project with clear goals
  19. Have fun with friends or family
  20. Learn touch typing.
  21. Have a side activity that makes you feel good and enjoy the the present moment.
  22. Give your self reward for a job well done.

Saturday, September 29, 2012

How to implement a simple IoC Container.

I have decided to take a topic related to software development and dig deeper and write about it on weekends. It will be my weekly learning and knowledge sharing. I have myside projects but its always cool and rewarding to understand how something really works. I do not only want to be a framework user but also a Framework contributor. This can only happen if you deep deeper most of the tools of software and language you use. For this week I want to see how easy is it to implement a simple IoC container that can be used in a project.

 What is an IoC container ?
IoC stands  for Inversion of Control and represents a design pattern used in software development. Wikipedia describes it as " a style of software construction where reusable code controls the execution of problem-specific code. It carries the strong connotation that the reusable code and the problem-specific code are developed independently, which often results in a single integrated application. Inversion of control as a design guideline serves the following purposes:

  • There is a decoupling of the execution of a certain task from implementation.
  • Every module can focus on what it is designed for.
  • Modules make no assumptions about what other systems do but rely on their contracts.
  • Replacing modules has no side effect on other modules. "

 What problem does it try to solve?
 Coupling and dependencies between objects .We let some other objects inject the object when we need it hence we are inverting the control of the process .Passing interfaces into classes and not real objects makes it easy to maintain, add and extend functions of a  feature in an application.

What are the basic prerequisites of building one?
  1. You need a container class.
  2.  In the container class you need a delegate ( A function on the fly!)
  3.  You need a dictionary data structure since you need to look up for keys before sending out objects
  4. Create a function to register the interfaces
  5. Create another function to resolve the interfaces
  6. Use the Container and do something with it.

 Before looking at the code you should understand some concepts like Interfaces, Generics and Delegates in C#. The goal is not build something that I will actually use for production code but just to see and learn the core and basic aspects of an IOC container. Here is the code of the whole project.

   
    /*IOC Container main class */
    public class MyIocContainer
    {
        public delegate object CreateInstance(MyIocContainer container);

        public Dictionary Factory;

        public MyIocContainer()
        {
            this.Factory = new Dictionary();
        }

        public void RegisterInterface(CreateInstance ci)
        {
            if (ci == null)
                throw new ArgumentNullException("ci");

            if (Factory.ContainsKey(typeof(T)))
                throw new ArgumentException("Type already registered");

            Factory.Add(typeof(T), ci);
        }
         
        public T Resolve()
        {
            if (!Factory.ContainsKey(typeof(T)))
                throw new ArgumentException("Type not registered");

            // retrieve the object from the dictionary
            var creator = Factory[typeof(T)];

            // call the delegate returning the object created
            return (T)creator(this);
        }      
    }

   // Create some interfaces to use
    public interface IDownloader
    {
        void GetWebSiteContents(string url);
    }

    public interface IExtractHtmlTags
    {
        void ExtractHtmlTags(string pWebsiteHtmlP);
    }

    // Create some classes to use the interfaces 
    public class WebSiteDownLoader : IDownloader
    {
        public void GetWebSiteContents(string url)
        {   //Some code using the webclient class
            Console.WriteLine("Call using the IoC container to load a website");
        }
    }
   
    public class ExtractHtmlTag : IExtractHtmlTags
    {
        public void ExtractHtmlTags(string websiteDataStream)
        {   
            // Some code here using Regex class<.*?>
            Console.WriteLine("Call using the IoC container to extract html tags");
        }
    }

    // Usage class for the interfaces to perform task.
    public class WebSiteTagRemover
    {
        private readonly IExtractHtmlTags _extractHtml;
        private readonly IDownloader _getWebSite;

     public WebSiteTagRemover(IExtractHtmlTags eTag, IDownloader loader)
        {
           _extractHtml = eTag;
            _getWebSite = loader;
        }

     public void PrintResults()
        {
          _getWebSite.GetWebSiteContents("http://ngalatalla.blogspot.se/");
          _extractHtml.ExtractHtmlTags("website html

");
        }
    }
 
  /*Finally execute and use the container Hooray!! */
internal class Program
    {
        private static void Main(string[] args)
        {   
         //Initiate the container
            var container = new MyIocContainer();

        //Register some interfaces to be used
           container.RegisterInterface(x => new WebSiteDownLoader());
           container.RegisterInterface(x => new ExtractHtmlTag());

      //Resolve the interfaces and get the objects mapped to them
            var getContents = container.Resolve();
            var extract = container.Resolve();

        //Do stuff with the interfaces
        var webTagRemover = new WebSiteTagRemover(extract, getContents);
        webTagRemover.PrintResults();
        }
    }

Results---

If you really want to use an IoC Container in any .Net project, you do not need to implement your own. There are much better options out there. Even if you think of implementing your own, I do not think you can implement any feature or features that they do not already have. They are even more mature and free to use in your projects. Here is a list I composed for some popular ones. I use Ninject in my personal projects because it is mature and easily configured. Choose your own based on your needs.
  Happy programming !

Thursday, April 26, 2012

It is time for Javascript . Are you ready to embrace it?


JavaScript is becoming more and more indispensable for any web developer to know. I have heard lost of bad and good stuff about JavaScript but I ask my self if they are not the programmers who write such bad  JavaScript code  are unpredictable or the differences in the JavaScript engines on various browsers makes us think the language is the problem .I have not  really done much JavaScript development  in my short and exciting career but  I think JavaScript works!! and you can see the power on  every client( mobile phones, tablets etc) connected to the web and needs a good experience. Some known JavaScript APIs are Jquery that  make it very easy to navigate the Dom , NodeJs for server and client development in JavaScript and finally I should not forget to mention Knockout Js which give you a clean way to write clean JavaScript code binned to your model using the MVVM pattern.

I bought my first JavaScript book Eloquent javascript after reading the online version of the book and I think it worth the money. It shows you how to think and code generally and in JavaScript. I am still reading and try to do solve the  assignments in the book before looking at the answers. Its really exciting to play with JavaScript learning about closures and the dynamic and functional nature of the language. I mostly write lots of C# and Jquery code at work but to understand Jquery well , one has to understand JavaScript because that's the source and the beginning.

I have been interested to learn  Html5 and I found it rather amazing how easily you can make an animation process with just a few lines of code. I think Html5 is awesome and is good some browsers now accept it. I hope this stays and combining Html5 , Javascript with SignalR that provides a duplex connection to the server one can do some amazing things in real time. May be i should just write a program to prove this.

I think every web developer can bear with me that there is so much  going on  in the web and is difficult to keep the pace with technologies coming and going. I think the key is know a lot of them but be a master in some of them you love. No matter what is going on the web there is only one language that can do all the magic and that is JavaScript. So maybe its time  for you to learn it to. As a developer, learning new stuff, reading and knowing new technologies should be part of your life style. submit to reddit

Thursday, March 22, 2012

Awesome stuff with C#5 and ASP.NET MVC 4

 I have been having a good  time watching these videos of one of my my favorite writers and developers  Steven Sanderson . These videos are all about the new  Asp.net 4 with Upshot, Knockout, WebApi and how they come together to make building Single page applications (SPA) faster and cleaner. The second video is about C#5  asynchronous operations and how this can be applied to web applications. The code to perform asynchronous calls to the database have been made less chunky and less complicated .Finally one also learns how asynchronous call work underneath and how duplex connection to the server are made and handled by SignalR.  You can read this article  Asynchronous scalable web applications with realtime persistent long running connections with SignalR.
I hope to put the  stuff I leanrt from these videos in my next application, Finally it seems as if there is no running away from JavaScript as a modern software developer who love web applications. Its time to embrace it  and have in your bag of tools. This could be a whole post on its own.
Here are the links to the videos.
submit to reddit

Wednesday, January 11, 2012

Personal development, passion and goals

 I should be proud of my achievements last year  because
  1. I had  my degree in Computer Science,
  2. Got  a good job ,
  3. Had my second child Eric
  4. And bought  a house.
 I had goals for last year and I got more than I could have ever thought of .All this was possible because  of hard work and good planning , being realistic and having a wonderful and supportive wife and  daughter .

Since the beginning of December we have been preparing and packing all our stuff into boxes that we shall take along with us to our new home.Yesterday as I was packing, I came across lots of my notes and code I  wrote when I was studying back in the university. Some of the code was good and I was impressed when  l looked at it and some where really crap and I could not even understand what it does.I ask my self if i really wrote this. I had really had a good laugh at my self. Anyway that was then. I will say I am a better coder now compared to then. I had a lot of passion and still do  but I had to pass my courses so passing my courses was more important than passion and I think its just logical. . I had some nice and though times and really enjoyed some programming courses like Compilier thoery , data structures and algorithims , Computer architecture, C and C++ programming ,web development with .Net and discrete mathematics.

Today I get paid for writing code, and solving complex problems and I consider a pass when my technical boss is happy about it, the customer get his or her problem solved , the code is understandable, clear and concise for the human being to read and understand.

This year I intend to blog more and learn more stuff , deepen my knowledge in some advanced stuff deploy an application to the web or build an app . Learn some real time programming.When will I  do this ? My spare time that I can really own for my self. I love and really enjoy what I do and hope you also do. If you do not, then its time for you to be real to yourself and deepen your knowledge in what you love to do and have passion for. Its never to late to learn and everything is possible.

Thursday, November 10, 2011

Using recursion to do permutations

Solving problems using recursion.
 I have always had problems in understanding deep and complex recusion eventhough they all follow a common pattern that  is There is always a base case to stop the recursion and making a recursive call on some smaller part of the solution, I decided to set my bar high . Here are the things i set to use recursion to understand complex recursive calls .

  1. Solving Sudoku using Backtracking
  2. The Chess  Knight - Queen classic
  3. Permutations
  4. More problems as I come across.

Let start with the case that allows you to select all possible combinations of all members a set. I learnt that this recursive pattern in very important to understand because the is a common pattern used in solving the problems that I mentioned above and many others like searching and solving word puzzles
  Permutation
  I define  permutations as all the ways to arrange a set of items for example if you permute the word {cat} you get {cat, tac, act, atc, tca, cta}. Permutations are mathematical and if you want a deeper understanding of this then go to Permutation. in Wikepidia and read more
In the program below  the program does  permutation recursively . I am writing this because I feel I have started getting the power of recursion and how to solve problems with them. The truth is i understood the classical recursive  examples in the university like  Fibonacci ,factorials and the towers of Hanoi  but when it came to complex recursive example like the one below. I got a headache in thinking recursively.
 Here are the tough questions to answer when writing a program that does permutations.

  1. How do you just pick one element on the set and know which one to attach next? 
  2. How do you avoid doubles and repeating each elements?
  3. How do you separate them? 
  4. How do you know that all the possible combinations of the set have been made?
Here is the program written in C# that does permutations .


class Program
    {
        static void Main(string[] args)
        {
            Permutate("ABCD");
        }
        public static void RecPermute(string permutateHolder , string itemToPermutate)
        {
            if (itemToPermutate== string.Empty)
            {
                Console.WriteLine(permutateHolder);
            }
            else
            {
                for (int i = 0; i < itemToPermutate.Length; i++)
                {   // Get the rest of the items remaining in the set
                    var remaining = itemToPermutate.Substring(0, i) + itemToPermutate.Substring(i+1);
               //Take each element from the item and do a recursive call on them
                    RecPermute(permutateHolder + itemToPermutate[i], remaining);                    
                }
            }
        }

        // Wrapper for permutate function
        public static void Permutate(string item)
        {
            RecPermute("", item);
        }
    }
Here is part of the recursive tree of the program Permutate("ABCD").It show permutations for all elements beginning with the letter A.The other elements of the set follow the same pattern.
Happy programming !

Wednesday, November 9, 2011

Using design patterns to build part of a soccer game engine

My goal here is to see if  I can use and understand design patterns and use them to solve a real world problem. I started by first learning the singleton pattern  and used it in my Dynamic quiz application using ASP.net MVC and Entity Framework Code First. I want to design a soccer game engine .Its a big a complex problem to solve but the best way to solve such a problem is to divide it into smaller parts that contains all components of building a soccer game engine. For this post I will focus on the problem of letting the referees  and players know the current position of the ball always .I play soccer and love soccer so lets get real now to see what will be needed for this
  • A soccer game must have a ball
  • They are 11 players in each team
  • There are two teams
  • Two  lines men and one referee
  • Each team has reserve players
  • There is the playground of course
The ball is the center of attention and  everybody of interest for that game wants to know where the ball is and whats happening to it . Who  are the watchers  of the ball ?
Here is where the first problem comes in .
How do I solve the problem where the referees and players know the current position and get updates of  the ball position  as its played on the field.
Lets define some  real objects needed to solve the problem
  1. Ball
  2. Players
  3. Playground
  4. Referee
  5. Team
Now that we have  some real soccer objects you will find on every soccer game. We need to  create some logical objects (objects that connect the real world objects and use  programming logical controls and give them  some life)


 The Game object defines a football game by  putting all components needed for a soccer game together like the players , ball etc...
The SoccerGame object will simply simulate  a football game.


Here is an abstract view of the system as I have described above.


Using design patterns is not the first thing you think when you  want to solve a problem but  they provide good software design principles that have stood the test of time thanks to the "Gang of Four"(GOF). Any way you can read more about this here design patterns. Since I want to know how to actually use them the best way is to try to use them in real world scenario.

I am a visual person so the best way  to see the problem is to get a visual of the problem .Here  is the way i see it below
The pattern that fits this is the Observer pattern which says that "Define a one-to-many dependency between objects so that when one object changes state, all its dependents are notified and updated automatically." In our case  all objects are dependent on the ball for a  soccer game and  the players, referees  must be notified and updated  as it changes state(moving).
The observer pattern in its raw state is shown below




The next step is to put the soccer problem in the context of the  observer pattern  and  this time there is  a position  object in three dimensions(x,y,z)  to connect to the change of the ball state since it describes  the current position on the play ground. Changes of the state of the ball is reflected by the position .It is the state that every observer has be notified and interested  about.


The subject is the soccer ball
The concrete object is the actual football that will be kicked
The observers are the players and referees and they  implement the IObserver interface.


The ball must have a list of observers
The observers have a pointer to the football object
The positions of  all the participants with the ball in the game has to be known.


Now how do we implement this in  C# ? Here is where I have to shut my mouth and get a prototype of the game engine for my customer.


Here is the code of the Game Engine only .It brings everything together

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

namespace SoccerGame
{  
    /// 
    /// Simulating  part of a soccer game using the Observer pattern
    /// 
    public class GameEngine
    {

        public static void Main()
        {
            // Create our ball (the ConcreteSubject)
            var ball = new FootBall();

            // Create few players ( some ConcreteObservers)
            var messi = new Player(ball, "Messi");
            var etofils = new Player(ball, "Etofils");
            var Ibrahimmovic = new Player(ball, "Ibrahimovic");

            // Create some referees (also ConcreteObservers)
            var collina = new Referee(ball, "Collina");
            var ngala = new Referee(ball, "Ngala");

            Console.WriteLine();

            // Attach them with the ball
            ball.AttachObserver(messi);
            ball.AttachObserver(etofils);
            ball.AttachObserver(Ibrahimmovic);
            ball.AttachObserver(collina);
            ball.AttachObserver(ngala);
            Console.WriteLine(" After attaching the observers...");

            // Update the position of the ball. 
            // At this point, all the observers should be notified
            ball.SetBallPosition(new Position());
            Console.WriteLine();


            // Remove some observers
            ball.DetachObserver(etofils);
            ball.DetachObserver(collina);
            Console.WriteLine(" After detaching the refree Collina and Etofils from the ball...");


            // Updating the position of ball again
            // At this point, all the observers should be notified
            ball.SetBallPosition(new Position(10, 10, 30));
            // Press any key to continue....more things happen
            Console.Read();
        }
    }
}
That is it for now and happy programming !

Sunday, November 6, 2011

Building a dynamic quiz application in ASP.net MVC

The quiz application I have build works just like that of W3Schools I got the inspiration from here and I wanted to understand more on asp.net MVC scafolding and Entity framework Code first. I set on my journey to write the application. Here is how it should work.
  • The user goes to the quiz page to take the quiz
  • The quiz has a question and a list of answers choices to choose from.
  • When the user clicks on the next button , a new question is loaded dynamically.
  • When the questions are completed the user is sent to a page showing his or her results.

Some ASP.Net MVC stuff

I used code first method by making poco classes and scaffolded all my controllers and i got all my CRUD methods an views for the controllers I choosed. Asp.net MVC Entity framework now the default database object relational mapper for the framework.To know more about Code first and the new scaffolding in Asp.net MVC check out this link.Scaffolding and Entity framework code first The next thing for me was to decide of what real life objects can be used and how they are connected.In this case
  • I will need a to represent the question, the answer, and the answer choices.
  • I needed one object to bring all these other object together and that is the Quiz object .
  • I needed another object to manage the quiz since I decided to store the users answers in the memory.
Here are the classes and the ASP.net MVC will build the database using EF code first based on certain conventions you have to follow for it to be right .(Check out the tutorial link above)
To manage the quiz I use the Singleton pattern .The is only one quiz in the memory when you start until you finish. The quiz manager manages all events related to the quiz in the memory .I did not want to use the session object because wanted an optimal and a modular solution for the manager. Here is the code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using MyQuiz.Abstract;

namespace MyQuiz.Models
{
    public class QuizManager
    {
        static QuizManager instance;
        private QuizContext db = new QuizContext();
        int questionId = 1;
        public bool IsComplete = false;
        public Quiz quiz;

        private QuizManager()
        {            
            quiz = new Quiz();
            quiz.StartTime = DateTime.Now;
            quiz.QuizId = 1;
            quiz.Score = 0 ;
        }

        public static QuizManager Instance
        {
            get
            {
                if (instance == null)
                    instance = new QuizManager();
                return instance;
            }
        }

        public Question LoadQuiz()
        {
            var question = db.Questions.Find(questionId);
            return question;
        }

        public void SaveAnswer(string answers)
        {
            var question = db.Questions.Include("Answers").Where(x => x.QuestionId == questionId).Single();
            if (question.Answers.AnswerText == answers)
             quiz.Score++;
        }

        public bool MoveToNextQuestion()
        {
            bool canMove = false;

            if ( db.Questions.Count() > questionId)
            {
                questionId++;
                canMove = true;
            }

            return canMove;
        }

        public bool PreviosQuestion()
        {
            bool canMove = false;

            if (questionId > 1)
            {
                questionId--;
                canMove = true;
            }

            return canMove;
        }     
    }
}

The home controller that sends the quiz to the view was implemented this way
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using MyQuiz.Models;

namespace MyQuiz.Controllers
{
    public class HomeController : Controller
    {   

        public ActionResult Index()
        {   
            var question = QuizManager.Instance.LoadQuiz();
            return View(question);
        }
        [HttpPost]
        public ActionResult Index(string answer, int questionId)
        {   
            if(QuizManager.Instance.IsComplete) // Prevent score increase when quix has been completed
             return RedirectToAction("ShowResults");     
          
            QuizManager.Instance.SaveAnswer(answer);
            if (QuizManager.Instance.MoveToNextQuestion())
            {
                var question = QuizManager.Instance.LoadQuiz();
                return View(question);
            }
            QuizManager.Instance.IsComplete = true;
            return RedirectToAction("ShowResults");  
        }
        public ActionResult About()
        {
            return View();
        }
        public ActionResult ShowResults()
        {
            return View(QuizManager.Instance.quiz);
        }
    }
}

The View of the quiz . I use the JQuery live(---) function that allows for asynchronous loading and event handling on the page . After getting the response from the controller I simply replace the quiz div area with new questions using the replaceWith(---) function in JQuery. The process continuous until the user answers the last question .
@model MyQuiz.Models.Question
@{
    ViewBag.Title = "Index";
}

@using (Html.BeginForm("Index", "Home")) {

@Model.QuestionText

@Html.HiddenFor(x => x.QuestionId)

  • @foreach (var choice in Model.AnswerChoices) {
      @Html.RadioButton("answer", @choice.Choices) @choice.Choices
    }
  • }

    The result page just displays the results of the quiz .Here is the source
    @model MyQuiz.Models.Quiz
    
    @{
        ViewBag.Title = "ShowResults";
    }
    
    

    ShowResults

    Your total score is @Model.Score

    Here is a screen shot of the final application

    • There is more to add like scaffolding repositories.
    • Use Dependency injection to reduce coupling of objects

    Here is the source code if want to play with it. I moved the source code to Github since some readers could not access the source code on google drive. I took advantage to play with the new Github for windows which I find intresting since i have always used Apache Subversion, svn.
    I have made some improvement on the code like moving it to MVC4  and  you can see the final application running here  MVC Quiz Application on  AppHarbor (I love these guys)
    Happy programming !

    Sunday, January 9, 2011

    Accessing variables on and from masterpages, pages and usercontrols in asp.net

    I was working on a project and had to perform certain actions like

    -Access variables and functions on another page from an event generated from the MasterPage .
    -Accessing variables on another page from a userControl .
    -Accessing variables on the MasterPage .

    The challenge i had here was that i had never done all these before .I have read a couple of books, blog , read source code from open source applications but never seen a situation like that .Then i asked myself the question.
    Why would one want to carry out any of the procedures i stated above ?
    I had to guess that they are some reasons to do this is ----
    -It means that the design of the program was wrong from the beginning .
    -You are forced to use it to fulfill a certain condition .
    -It is the last choice you got.
    Anyway i solved the problems by carrying out the above three procedures and i think it might help someone out there .Here is how i did it

    Access variables and functions on another page from an event generated from the MasterPage
    Create a function to generate the event on the MasterPage and expose the variable to access using properties {get;set}
    Write no code on the event .You might want to if you need it.
    protected void CheckOut_Click(object sender, EventArgs e)
        {
             
        }
    

    Create a reference to the MasterPage from the child page
    <%@ MasterType VirtualPath="~/MyMasterPage.master" %>
    
    

    Add and Init-Event on the secondary page .On that Init_Page event get the reference to the MasterPage and generate an event handler delegate that will point to a function in the secondary page .
    protected void Page_Init(object sender, EventArgs e)
    {
            Master.CheckOutBut.Click += new EventHandler(bnDoSomethingIn_Click);
    
    }
    

    Function to call on the child page
    protected void bnDoSomethingIn_Click(object sender, EventArgs e)
     {
            Master.CheckOutBut.Click += new EventHandler(bnDoSomethingIn_Click);
    
     }
    

    -Accessing variables on another page from a userControl .
    Create an abstract class and let it inherit from the page class and some abstract methods that are signatures to the methods you have to override on the child page
    public abstract class AbstractPage:System.Web.UI.Page
    {
     public AbstractPage()
     {
      //
      // TODO: Add constructor logic here
      //
     }
    // some methods
        public abstract void DoSomething();
         public abstract void MyMethodTwo();
    
    }
    
    Let the page inherit from abstractPage class you created
    public partial class MyPage : AbstractPage
    {
        public void override DoSomething()
         {  
             ----
             ------
         }
    }
    

    Access a function on the host(.aspx) page from the UserControl
    private void SomeFunction()
        {
            AbstractPage MyPage = (AbstractPage)Page; // reference to  hostPage
            MyPage.DoSomething();
        }
    
    

    -Accessing variables on the MasterPage .
    Expose the variables on the MasterPage
    public LinkButton CheckOutBut
        {
            get { return checkOutBut; }
        }
    
        public Label NameLabel
        {
            get { return lblName; }
        }
    

    Create a reference to the MasterPage from the child page
    // Add this on the top of the child Page(.aspx) under the page definitions
    <%@ MasterType VirtualPath="~/MyMasterPage.master" %>
    
    //from the userControl you can access the MasterPage variables using
     MyMasterPage mp = (MyMasterPage)Page.Master;
     mp.CheckOutBut
    
    //from the childPage you can access the MasterPage variables using
     Master.NameLabel.Text = "Something" ;
    

    Happy Programming .

    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...