Sunday, 3 September 2017

Movie Booking Application- Using Web API,MVC,JQuery

//Model

    public class Movie
    {
        public int Id { get; set; }
        public string Name { get; set; }
    }

   public class Screen
   {
       [Key]
       public int Id { get; set; }
       public string Name { get; set; }
       public int MovieId { get; set; }
      
       public bool _1 { get; set; }
       public bool _2 { get; set; }
       public bool _3 { get; set; }
       public bool _4 { get; set; }
       public bool _5 { get; set; }
       public bool _6 { get; set; }
       public bool _7 { get; set; }
       public bool _8 { get; set; }
       public bool _9 { get; set; }
       public bool _10 { get; set; }
       public bool _11 { get; set; }
       public bool _12 { get; set; }
       public bool _13 { get; set; }
       public bool _14 { get; set; }
       public bool _15 { get; set; }
       public bool _16 { get; set; }
       public bool _17 { get; set; }
       public bool _18 { get; set; }
       public bool _19 { get; set; }
       public bool _20 { get; set; }
   }

//API

public class MoviesController : ApiController
   {
       ApplicationDbContext _context;
       public MoviesController()
       {
           _context = new ApplicationDbContext();
       }
       // GET api/<controller>
       [HttpGet]
       public IHttpActionResult Get()
       {
           return Ok(_context.Movies.ToList());
       }
       [HttpGet]
       public IHttpActionResult Get(int id)
       {
           var screen=_context.Screens.Where(s=>s.MovieId==id);
           if (screen == null)
               return NotFound();
           else
               return Ok(screen);
       }
}

//Controller

using FisMovieBooking.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace FisMovieBooking.Controllers
{
    public class MovieController : Controller
    {
        ApplicationDbContext _context;
        public MovieController()
        {
            _context = new ApplicationDbContext();
        }
        // GET: Movie
        public ActionResult Index()
        {
            
            return View();
        }
        public ActionResult ConfirmBooking(string movieId,string selectedSeats)
        {
            int id=Convert.ToInt32(movieId);
            float totalPrice;
            float rate=15.24f;
            List<string> lstselected = new List<string>();
            lstselected = selectedSeats.Split(',').ToList();
        
            var screen = _context.Screens.SingleOrDefault(s => s.MovieId ==id );
            if (lstselected.Count() <= 10)
            {
                totalPrice = lstselected.Count() * rate;
            }
            else {
                totalPrice = (10 * rate) + (lstselected.Count() - 10) * (rate + 10);
            }
         
            ViewBag.MovieName = _context.Movies.SingleOrDefault(m => m.Id == id).Name;
            ViewBag.ScreenName = screen.Name;
            ViewBag.NumberOfSeatsSelected = lstselected.Count();
            ViewBag.TotalPrice = totalPrice;
            ViewBag.SelectedTickets = selectedSeats;
            ViewBag.MovieId = id;
            ViewBag.SeatId = selectedSeats;
            return View();
        }
        public ActionResult BookTicket(string movieId, string seatIds)
        {
            int id = Convert.ToInt32(movieId);
            List<string> lstselected = new List<string>();
            lstselected = seatIds.Split(',').ToList();
            var dataFromDb = _context.Screens.SingleOrDefault(s => s.MovieId == id);
            foreach (string s in lstselected)
            {
                dataFromDb.GetType().GetProperty("_" + s).SetValue(dataFromDb,true);
            }
            
            _context.SaveChanges();
            return RedirectToAction("Index");
        }
    }
}



//JavaScript

$.ajax({
    type: "get",
    url: "http://" + window.location.host + "/api/Movies",
    success: function (result) {
        for (var i = 0; i < result.length; i++) {
            $('#ddlMovie').append('<option value="' + result[i].Id + '">' + result[i].Name + '</option>');
        }
    },
    error: function (error) {
    }
});
$(document).ready(function ()
{
    if ($('#ddlMovie').prop('selectedIndex') != 0)
    {
        $('#screen').removeClass('hidden');
    }
    $('#ddlMovie').change(function ()
    {
        var movieId = $(this).prop('selectedIndex');
        var bookedSeats = [];
        if (movieId != 0) {
            $('#screen').removeClass('hidden');
            $.ajax({
                type: "get",
                url: "http://" + window.location.host + "/api/Movies/" + movieId,
                success: function (result) {
                    var screenDetails = Object.keys(result[0]);
                    var totalCol = screenDetails.length - 3;
                    for (var item in result[0]) {
                        if (result[0][item] === true) {
                            bookedSeats.push(parseInt(item.substring(1)));
                        }
                    }
                    // Settings
                    var settings = {
                        rows: 4,
                        cols: totalCol / 5,
                        rowCssPrefix: 'row-',
                        colCssPrefix: 'col-',
                        seatWidth: 35,
                        seatHeight: 35,
                        seatCss: 'seat',
                        selectedSeatCss: 'selectedSeat',
                        selectingSeatCss: 'selectingSeat'
                    };
                   
                    //Seat LayOut
                    var init = function (reservedSeat)
                    {
                        var str = [], seatNo, className;
                        for (i = 0; i < settings.rows; i++)
                        {
                            for (j = 0; j < settings.cols; j++)
                            {
                                seatNo = (i + j * settings.rows + 1);
                                className = settings.seatCss + ' ' + settings.rowCssPrefix + i.toString() + ' ' + settings.colCssPrefix + j.toString();
                              
                                if ($.isArray(reservedSeat))
                                {
                                    if ($.inArray(seatNo, reservedSeat) != -1)
                                    {
                                        className += ' ' + settings.selectedSeatCss;
                                    }
                                }
                                str.push('<li class="' + className + '"' +
                                          'style="top:' + (i * settings.seatHeight).toString() + 'px;left:' + (j * settings.seatWidth).toString() + 'px">' +
                                          '<a title="' + seatNo + '">' + seatNo + '</a>' +
                                          '</li>');
                            }
                        }
                        $('#place').html(str.join(''));
                    };
                    init(bookedSeats);
                    var allSeats = $('.' + settings.seatCss);
                    allSeats.click(function () {
                        if ($(this).hasClass(settings.selectedSeatCss)) {
                            alert('This seat is already reserved');
                            $('#btnBook').addClass('hidden');
                        }
                        else {
                            $(this).toggleClass(settings.selectingSeatCss);
                            var recentySelected = allSeats.filter("." + settings.selectingSeatCss);
                            if (recentySelected.length > 0) {
                                $('#btnBook').removeClass('hidden');
                            }
                            else {
                                $('#btnBook').addClass('hidden');
                            }
                        }
                    });
                },
                error: function (error) {
                }
            });
        }
        else {
            $('#screen').addClass('hidden');
        }
    });
    $('#btnBook').on('click', function () {
        var str = [];
        $.each($('#place li.' + 'selectingSeat' + ' a'), function (index, value) {
            str.push($(this).attr('title'));
        });
        window.location.href = "http://" + window.location.host + "/Movie/ConfirmBooking/?movieId=" + $('#ddlMovie :selected').val() + "&selectedSeats=" + str;
    });
    $('#btnConfirmBooking').on('click', function () {
        if (confirm('Are you sure you want to book the tickets')) {
            window.location.href = "http://" + window.location.host + "/Movie/BookTicket?movieId=" + $('#hdnModieId').val() + "&seatIds=" + $('#hdnSeatId').val();
        }
    });
});


//Css

    
#holder
{    
height:200px;    
width:400px;
background-color:gray;
border:1px solid;
margin-left:10px;   
}
#place {
position:relative;
margin:7px;
}
#place a{
font-size:0.6em;
}
#place li
{
 list-style: none outside none;
 position: absolute;   
}    
#place li:hover
{
background-color:green;      
 /*default seat color*/
#place .seat{
background-color:white;
height:33px;
width:33px;
display:block;   
}
/*Booked Tickets*/
#place .selectedSeat
background-color:black;         
}
/*Once clicked on a li*/
#place .selectingSeat
background-color:blue     
}
#place .row-3, #place .row-4{
margin-top:10px;
}
#seatDescription li{
verticle-align:middle;    
list-style: none outside none;
padding-left:35px;
height:35px;
float:left;
}
//Views

//Index
<p><b>Welcome!</b></p>
<div class="well-lg">
    <select class="dropdown" id="ddlMovie">
        <option value="0">
            -- Select Movie --
        </option>
    </select>
    <br />
    <br />
    <div id="screen" class="hidden">
        <div id="holder">
            <ul id="place"></ul>
        </div>
        <div style="float:left;" class="col-sm-9 row">
            <div class="col-sm-3" style="background-color:black">Booked</div>
            <div class="col-sm-3" style="background-color:white">Available</div>
            <div class="col-sm-3" style="background-color:blue">Selected</div>
          
        <br />
        <br />
        <div>
            <input type="button" id="btnBook" value="Book" class="hidden"/>
        </div>
    </div>
   
</div>
@section scripts
{
<link href="~/Content/custom.css" rel="stylesheet" />
    
<script src="~/Scripts/custom.js"></script>
    
    }
//Confirm Booking
@{
    ViewBag.Title = "ConfirmBooking";
}
<h2>ConfirmBooking</h2>
<div class="form-group"> Your selection
    <div>
        Movie Name :  @ViewBag.MovieName 
    </div>
    <div>
        Screen Name :   @ViewBag.ScreenName  
    </div>
    <div>
        Total Seats:   @ViewBag.NumberOfSeatsSelected  
    </div>
    <div>
       Total Price :   @ViewBag.TotalPrice $ 
    </div>
  <input type="hidden" id="hdnModieId" value=@ViewBag.MovieId />
    <input type="hidden" id="hdnSeatId" value=@ViewBag.SeatId />
    <div>
        <input type="button" value="Confirm Booking" id="btnConfirmBooking" />
    </div>
</div>
@section Scripts
{
    
<script src="~/Scripts/custom.js"></script>
    }

Monday, 29 August 2016

Implementing Multithreading

Hi ,

In the last post I discussed about what multi-threading is all about.
Please refer to "Understanding Multi-Threading in C#" in case you need to know about it.
This blog is all about the implementation of the same.

Too implement Multi-threading we make use of Thread class which is present in "System.Threading" namespace.
To make a portion of code to be implemented in separate thread(also known as worker thread) we need to have that chunk of code in another method.
For example:
If our existing program looks like this:

    class Program
    {
        public static void Main()
        {
            for (int i = 1; i <= 10; i++)
            {
                Console.WriteLine(i);
            }
            Console.WriteLine("Rest of the code");
        }
     }

then in order to make use of another thread we need to have an extra method which will run as the thread.
so the above code will be changed to :

    class Program
    {
        public static void Main() 
        {
            ForMyNewThread(); //just a dummy name;u may give ur pets name too ;)
            Console.WriteLine("Rest of the code");
        }

        private static void ForMyNewThread()
        {
            for (int i = 1; i <= 10; i++)
            {
                Console.WriteLine(i);
            }
        }
     }

Now, we need to pass this method(ForMyNewThread) to the constructor of the Thread class, so that our method can act like a Thread.
Note: Please don't forget to include System.Threading name space;

so our code looks like this now:

public static void Main()
        {
             Thread Mythread = new Thread(ForMyNewThread);
            Mythread.Start();
            Console.WriteLine("Rest of the code");
    
        }

        private static void ForMyNewThread()
        {
            for (int i = 1; i <= 10; i++)
            {
                Console.WriteLine(i);
            }
        }

"Start()" is used to make the Thread functional,if we don't give start the thread will not get started and the our program will return just  "Rest of the code".

I strongly recommend you to try the above example one to have a better understanding.

If you actually try the above example(which u should :p ), u may see that the constructor of the Thread class has four overloads, which expect either "ThreadStart" or "ParameterisedThreadStart".

So what are these and why we got the output without passing the above in our previous example!!???

Magic!! Nah doesn't happen in real life! :-P

Actually "ThreadStart" and "ParameterisedThreadStart" are delegates.

If you don't know what are delegates, then it is advised to see my post named,"Real Use Of Delegates", where I have explained properly what and why should we use Delegates.


So coming back to our current topic :p ;)


Now as we know thread is basically a method which will have a chunk of code in it which will be executed when thread.start() is invoked.

but how do we point a method to thread!! Please note that i wrote "point a method"!!..can you recollect something!!? ..Yes you are right a Delegate(Function pointer!).So a Thread class uses Delegate to point to a particular method.

But how did it work before !!
we didn't passed any delegate there, it is because .Net framework is doing it by itself!!(cool right!, at least if you are a lazy person like me you would love this feature of .Net framework )



Program with the delegate:
   public static void Main()
        {
           
            Console.WriteLine("Rest of the code");
            Thread Mythread = new Thread(new ThreadStart(ForMyNewThread));
            Mythread.Start();
        }

        private static void ForMyNewThread()
        {
            for (int i = 1; i <= 10; i++)
            {
                Console.WriteLine(i);
            }

        }

the output remains the same.

Wondering what is "ParameterizedThreadStart delegate"!!?
If we want to pass some data to the method we make use of ParameterizedThreadStart.

 class Program
    {
        public static void Main()
        {
            Console.WriteLine("Please enter a number for which you want to see all the natural numbers less than or equal to the number");
            object target = Console.ReadLine();
            Thread T1 = new Thread(new ParameterizedThreadStart(ForMyNewThread));
           T1.Start(target);
        }
        public static void ForMyNewThread(object target)
        {
            int numberEnteredByUser = 0;
            if (int.TryParse(target.ToString(), out numberEnteredByUser))
            {
                for (int i = 1; i <= numberEnteredByUser; i++)
                {
                    Console.WriteLine(i);
                }
            }
        }
    }

Here in this program we are prompting the user to enter a number of his choice and we will display all the natural numbers less than or equal to the Entered number.
As you may see we can pass the data in Start() method itself.

Hope This is clear.
Do leave your comments if you need any clarification.

Regards,
Ashish Agarwal



Sunday, 28 August 2016

Understanding Multi-Threading in C#

What is a thread???

Definition: Thread is a light weight process or it can be seen as a subset of process.

wondering what is process!!?
well process is a program which the operating system runs, in order to execute the set of instruction given to it. You may go to task manager(press ctrl+shift+del) and see large number of  processes running on the machine.
Now each process has at least one thread which is commonly called as main thread.A process can have one or more threads.

So what is Multi threading and why do we use it?

Many a times there will be a chunk of code which may take more time to execute and hence makes your application less responsive(slow). In order to prevent this we go for the concept of multi threading.

Let us understand with the help of a day to day life scenario!

"We all have been to schools,colleges or some coaching institutes or say to a place where you need take admission.
Imagine yourself sitting with a person(X) who is responsible to give you all the information about the institute, and you being a very serious candidate(just imagine ;)) ask 100s of questions . For this the person X has to be very very responsive! Or else he may loose other candidates or his manager may fire him!(sounds terrible right!,managers are always harsh!) now obviously if you have to take admission ,there is a need to fill the application form and again it is the responsibility of the institute to do so.
Now imagine person X filling the form as well as responding to our queries side by side!! what do you think what will happen? Can he be responsive with a lengthy task of filling your details!?
Not actually! So what can his manager do?? The manager may allocate another Person(Y) the job of filling your form and let Mr. X concentrate on your queries! This way both the jobs will be done smoothly.
Now imagine person X as your main process(Thread) which has a lengthy and time consuming logic of filling the form which may decrease the responsiveness of X, and now you are the manager(kind one for a change)! so you can create a new thread(Person Y) and assign the lengthy job to it so that your thread(X) is responsive as well as the task of filling the form is also completed!
This way your program will be super cool and you as a Manager will be cool dude! ;)
"

Hope it is clear!


Regards,
Ashish Agarwal

Saturday, 27 August 2016

Real Use Of Delegates

Understanding Delegates:

Hi Readers,

Today I want to take a very confusing topic.(At least was for me, when I first went through it).
It is bit Confusing, as many of us actually don't know what is the use of  Delegates or in what scenarios it should be used.

Now if you search about Delegates, you would get something  like,"Delegates are function Pointers!"
So what actually is a function pointer?
As the name suggests it may be a reference to a function!
True indeed,but why shall we use it?

For the Readers for whom concept of delegate is completely new, I request them to read from "Delegate Explanation Start" to "Delegate Explanation End " first ,others can Skip this block. 

Delegate Explanation Start:
Prerequisite: Some knowledge about OOPS. :)

Well a delegate is a type safe function pointer. i.e  it holds a reference (pointer) to a function.
Wondering what is type safe!?
The signature of the delegate must match the signature of the function, the delegate points to,otherwise you will get a compilier eror.
This is the reason delegates are called type safe function pointers.
Delegates are of Reference type,so you need to create an instance of it and pass a function as the parameter to its constructor.
This is how we declare a delegate:
Access Specifier delegate ReturnType Name(Method Reference).
Example:

public delegate void MyFirstDelegate(string Message);

class Test
{
    public static void Main()
    {
        MyFirstDelegate myDel = new  MyFirstDelegate(Yo);
        myDel ("Delegates are awesome");
    }
    public static void Yo(string strMessge)
    {
        Console.WriteLine(strMessge);
    }
}

If you run the above code, as you may expect you would get result as "Delegates are awesome".
This is the basics of how delegates work.
But did you understand why shall we use delegates ? It looks idiotic to create a method(here "Yo") then create instance of a delegate(MyFirstDelegate) and then passing the method(Yo), Isn't it??
You may argue that we could have directly created an instance of the "Test" class and call the method! then why the heck we have to use delegate?? Just a stupid concept!!??
Not actually!
Please Read the below Explanation. "Real Use of Delegates":) ;)

Delegate Explanation End. 

Real Use of Delegates:

Now lets Assume that you are a Project head of a Products Company(Sounds good right! ;)).
And you are responsible to create a product which returns the Employees' name of different organisation who are eligible for promotion.
Obviously different organisations may have different criteria to promote its Employees,in that case we cant hard code the logic in our base product, as we have to sell it to different organisation and hard coding the logic for one organisation would mean creating 'n' number of products for 'n' number of organisations!! Which we obviously don't wanna do.
Then want can be done in this scenario!!?? Any idea?

Surprisingly,Delegates are the go to Concept!
how?
Lets see ;):

   #region GenericLogic //think of this as a Product

    #region--a generic function pointer
    public delegate Boolean Promotable(Employee emp);
    #endregion


    public class Employee
    {
        public int ID { get; set; }

        public string Name { get; set; }
        public int Salary { get; set; }
        public int Experience { get; set; }
        public void PromoteEmployee(List<Employee> empList,Promotable obj)
   //need the list of Employees and the logic
        {
            foreach(Employee emp in empList)
            {
                if (obj(emp))
                {
                    Console.WriteLine("{0} is Promoted",emp.Name);
                }
            }
        }
    }
    #endregion

Think of region "GenericLogic"  as our Product, which we will be selling.

Here you can see that our Product just needs  the list of employees of the organisation and the logic for promoting those employees.
So now we would ask our client to just give there employee list and the logic specific to there organisation so that they would get the Employee Names who are eligible foe promotion.

What client will do? :

They would just call the Delegate and pass there own logic!!

   public class ClientClass
    {
   
        public static void Main(string[] args)
       {

           #region company has to call the product's method to get the list of Employees Eligible for promotion by giving its internal logic and its employees

           #region company forming an employee list //this is Private data of company!!
           List<Employee> empList = new List<Employee>();
           empList.Add(new Employee()
           {
               ID = 1,
               Name = "asd",
               Experience = 4,
               Salary = 123
           }
                       );
           empList.Add(new Employee()
           {
               ID = 1,
               Name = "ashish",
               Experience = 7,
               Salary = 123567
           });
           empList.Add(new Employee()
           {
               ID = 1,
               Name = "asddfg",
               Experience = 14,
               Salary = 12453
           });
           empList.Add(new Employee()
           {
               ID = 1,
               Name = "asdff",
               Experience = 3,
               Salary = 23
           });
           #endregion

           #region now the company has to have a method(logic) for the promotion of its employees,

           Promotable obj3 = new Promotable(Test.IsPromotable); //making use of Product's Delegate,pls find the logic of IsPromotable
           #endregion

           #region now passing the values to the shared function to the product
           Employee obj = new Employee();
           obj.PromoteEmployee(empList, obj3);
           #endregion

           #endregion
}
        #region IsPromotable Method--logic of a particular company to promote its employees
        public static Boolean IsPromotable(Employee Emp)
        {
            if (Emp.Experience >= 5)
            {
                return true;
            }
            else
                return false;
        }
        #endregion
     
    }

#endregion

Now each and Every client may have different logic to promote there Employees!.
so ,they can just provide there logic to the base product and get the output!.


I hope it is clear.
Please Leave your comments ! :)

Thank you.
Regards,
Ashish Agarwal