Udemy

Infinite Scroll Paging in Asp.net mvc 4

Friday, December 20, 2013 0 Comments A+ a-

Today i am sharing another feature which Facebook and LinkedIn like paging, i came across a scenario to show doctors list in our database, instead of paging i thought to go for infinite scroll paging like Facebook LinkedIn, on page load i show top 10 or 20 doctors and as user scrolls down i load more doctors via Ajax.


Here i go with the HTML of my view:

<div class="grid-content overflow" id="docsContainer">
<!--grid area -->
    <!--grid area end -->

    <br />
<div style="clear: both;">
</div>
<div class="clearfix">
</div>
@if (ViewBag.Refreshed == "YES")
    {
        <input id="lastDoctorID" type="hidden" value="0" />
    }
    else
    {
        <input id="lastDoctorID" type="hidden" />
    }
    <input id="GetFlag" type="hidden" value="true" />
</div>


On page load i am getting to 20 records from database, here it is:

$(document).ready(function () {


        if ('@ViewBag.Refreshed' == "YES") {

            $('input#lastDoctorID').val("0");

        }

        GetDoctors();

});


here is definition of GetDoctors Method which sends Ajax call to a WCF service which returns result as JSON back:

function GetDoctors() {

        if ($('input#lastDoctorID').val() != null) {

            lastID = $('input#lastDoctorID').val();

        }
        else {

            lastID = 0;
        }

        var url = '@Url.Action("GetDoctors", "SearchPathologist")';

        url = url + "?lastDoctorID=" + lastID;
        $('div#divLoading').show();
        $.ajax({
            type: 'POST',
            url: url,

            success: function (response) {
                // your code from above
                $('div#docsContainer').append(response);
                $('div#divLoading').hide();
                if (response == "ok") {


                }

                else {


                }
            },
            error: function (xhr, textStatus, error) {
                //$('span#loader_' + ID).hide();
                console.log(xhr.statusText);
                console.log(textStatus);
                console.log(error);
                $.fallr('show', {
                    content: 'Request Sending Failed! Try Again after few minutes.

'
                });
            }
        });
    }

In my action i am calling a web-service which return Data-Set and i extract data and create list and pass it to partial view which in rendered on the page.

Here is the action code:

public ActionResult GetDoctors(string lastDoctorID)
        {
            using (OliveCliqService.OliveServiceClient client = new OliveCliqService.OliveServiceClient())
            {

                DataSet result = client.GetDoctorsList(Session["userID"].ToString(),lastDoctorID);

                List doctorsList = new List();

                for (int i = 0; i < result.Tables[0].Rows.Count; i++)
                {

                    CliqDoctor doctor = new CliqDoctor();

                    doctor.DoctorID = int.Parse(result.Tables[0].Rows[i]["DoctorID"].ToString());
                    doctor.Name = result.Tables[0].Rows[i]["FirstName"].ToString() + " " + result.Tables[0].Rows[i]["LastName"].ToString();

                    doctor.Designation = result.Tables[0].Rows[i]["Designation"].ToString();
                    doctor.Speciality = result.Tables[0].Rows[i]["Spaciality_name"].ToString();
                    doctor.Location = result.Tables[0].Rows[i]["Address"].ToString();
                    doctor.ImageName = result.Tables[0].Rows[i]["Image"].ToString();
                    doctor.Friend = result.Tables[0].Rows[i]["Friend"].ToString();

                    doctorsList.Add(doctor);

                }


                return PartialView("~/Views/Shared/_DoctorPartial.cshtml", doctorsList);
            }
        }

Here is my web service method definition:

public DataSet GetDoctorsList(string PersonId,string lastDoctorID)
        {

            string connectionString = System.Configuration.ConfigurationManager.ConnectionStrings["OliveCliq"].ConnectionString;


            MySqlConnection con = new MySqlConnection(connectionString);
            con.Open();
            string cmd = @"SELECT d.DoctorID,d.FirstName,d.LastName,d.Image,de.Designation,d.Address,s.Spaciality_name,
CASE WHEN EXISTS (SELECT id FROM cloud_clinic.doctor_members dm WHERE dm.doctor_id = '" + PersonId + "' AND dm.member_id = d.doctorID) THEN 'YES' ELSE 'NO' END AS Friend FROM cloud_clinic.doctors d LEFT OUTER JOIN cloud_clinic.clinic_doctor_designations cdd on d.doctorid = cdd.doctor_id LEFT OUTER JOIN cloud_clinic.rm_pr_designations de on cdd.designation_id = de.designationid LEFT OUTER JOIN cloud_clinic.doctor_spcialities ds on d.doctorID = ds.doctorid LEFT OUTER JOIN cloud_clinic.spaciality s on ds.spacialityID = s.id where d.DoctorID > '"+lastDoctorID+"' Group by d.DoctorID Order by d.DoctorID LIMIT 30";

            MySqlDataAdapter da = new MySqlDataAdapter(cmd, con);

            DataSet ds = new DataSet();

            da.Fill(ds);

            return ds;
            
        }

When user scroll down, new records are fetched Ajax call and appended on the page, here is that JQuery snippet:

 $(document).ready(function () {
        $(window).scroll(function () {
            console.log("document height:" + $(document).height());
            console.log("window height:" + $(window).height());
            console.log("window scroll:" + $(window).scrollTop());
            if ($(window).scrollTop() + $(window).height() == $(document).height()) {
                GetDoctors();
            }
        });
    });

Hope you understood it.

Cheers!

Thanks
Udemy

Facebook and Linkedin like Searching Funcationality in Asp.net mvc 4

Friday, December 20, 2013 2 Comments A+ a-

Hi friends,


In the last month, i came across to implement doctors searching my application like the one facebook or linkedin is using, i googled to find some plugin but when it failed i thought to made my own using jquery.


Here is the screen shot of my work:




Here i go:

Here is my input control:




<div class="search_input"><input type="text" id="people" placeholder="Search for specialist doctors and more.." />
</div>


Here is jquery code:


<script type="text/javascript">
    $(document).ready(function () {
        var drew = false;
        $("#people").on("keyup", function (event) 
        {
            var query = $("#people").val();

            if ($("#people").val().length >= 1) 
            {
                $('div#loaderContainer').show();
                $.ajax({
                    url: '@Url.Action("Search","SearchPathologist")',
                    dataType: "json",
                    data:
                        {
                            term: query,
                            flag: "all"
                        },
                        error: function()
                        {
                        $.fallr('show', {
            content: '<p>Error occured! May be your session expired.</p>'
                        });
                        },
                    success: function (data) 
                    {
                        $('div#loaderContainer').hide();
                            //First search
                            if (drew == false) 
                            {
                                //Create list for results
                                $("#people").after("<ul id='res' class='ui-autocomplete ui-menu ui-widget ui-widget-content ui-corner-all' role='listbox' aria-activedescendant='ui-active-menuitem' style='z-index: 10005; display: block; width: 293px;'></ul>");

                                //Prevent redrawing/binding of list
                                drew = true;

                                //Bind click event to list elements in results
                                $("#res").on("click", "li.item", function () 
                                {
                                    $("#people").val($(this).text());
                                    $("#res").empty();
                                });
                            }
                            //Clear old results
                            else 
                            {
                                $("#res").empty();
                            }

                            

                            $.each(data.doctors, function (i, item) {
                                if(i==0)
                                {
                                $("#res").append("<div id='doctors'></div>")
                                $("#doctors").append("<li style='background: linear-gradient(to bottom, #499BEA 0%, #207CE5 100%) repeat scroll 0 0 rgba(0, 0, 0, 0); margin-left:2px;text-align:center;color:white;'>Doctors</li>");
                                }
                                $("#doctors").append("<li class='item'><div style='width:100%; margin:auto; background:white; min-height:20px;'><div style='border-bottom:1px dashed gray;'><div style='float:left;  width:16%; min-height:35px; margin:auto;'><img src='http://olivecliq.com/carepoint/doctor_images/"+item.ImageName+"' width='31px' style='margin-top:4px; margin-left:1px;' /></div><div class='mid_card'><h2> " + item.DoctorName + "</h2><h3></h3></div><div style='float:left;width:10%; min-height:25px; margin:auto;'> <img src='@Url.Content("~/images/arrow.png")' width='25' style='margin-top: 10px;' /></div><div style='clear:both;'></div></div></li>");
                            });

                            $.each(data.connections, function (i, item) {
                                if(i==0)
                                {
                                $("#res").append("<div id='connections'></div>")
                                $("#connections").append("<li style='background: linear-gradient(to bottom, #499BEA 0%, #207CE5 100%) repeat scroll 0 0 rgba(0, 0, 0, 0); margin-left:2px;text-align:center;color:white;'>Connections</li>");
                                }
                                $("#connections").append("<li class='item'><div style='width:100%; margin:auto; background:white; min-height:20px;'><div style='border-bottom:1px dashed gray;'><div style='float:left;  width:16%; min-height:35px; margin:auto;'><img src='http://olivecliq.com/carepoint/doctor_images/"+item.ImageName+"' width='31px' style='margin-top:4px; margin-left:1px;' /></div><div class='mid_card'><h2> " + item.ConnectionName + "</h2><h3></h3></div><div style='float:left;width:10%; min-height:25px; margin:auto;'> <img src='@Url.Content("~/images/arrow.png")' width='25' style='margin-top: 10px;' /></div><div style='clear:both;'></div></div></li>");
                            });
                        
                        
                        if($('button#searchDDL').html() == "Doctors")
                        {
                        $('div#connections').hide();
                        }
                        if($('button#searchDDL').html() == "Connections")
                       {
                       $('div#doctors').hide();
                       }
                        
                        
                        
                    }


                });


            }

            else
            {
            $("#res").empty();
            $( "#res" ).remove();
            drew = false;
            }
        });


              $("input#people").focusout(function () {

    $( "#res" ).remove();
    drew = false;
   
});

    });
    </script>

and Here is my server side Action Code:


public JsonResult Search(string term, string flag)
        {
            using (OliveCliqService.OliveServiceClient client = new OliveCliqService.OliveServiceClient())
            {
                PathWay.OliveCliqService.SearchResult result = new PathWay.OliveCliqService.SearchResult();

                result = client.Search(Session["userID"].ToString(), term, flag);

                return Json(result,JsonRequestBehavior.AllowGet);
            }
        }

Here is my Web Service code which returns doctor's name and picture:


        public SearchResult Search(string PersonID,string term,string flag)
        {
            string cmd;
            string connectionString = System.Configuration.ConfigurationManager.ConnectionStrings["OliveCliq"].ConnectionString;


            MySqlConnection con = new MySqlConnection(connectionString);
            con.Open();
            cmd = @"SELECT DISTINCT d.DoctorID,
d.FirstName,
d.LastName,
d.Image,
r.name,
s.Spaciality_name,
oc.clinic_name,
cb.Location,
rpd.acronym
FROM cloud_clinic.doctor_members dm
LEFT OUTER JOIN cloud_clinic.doctors d on dm.member_id = d.doctorid
LEFT OUTER JOIN cloud_clinic.clinic_doctor_designations cdd on d.doctorid = cdd.doctor_id
LEFT OUTER JOIN cloud_clinic.rm_pr_designations de on cdd.designation_id = de.designationid
LEFT OUTER JOIN cloud_clinic.doctor_spcialities ds on d.doctorID = ds.doctorid
LEFT OUTER JOIN cloud_clinic.spaciality s on ds.spacialityID = s.id
LEFT OUTER JOIN cloud_clinic.clinic_doctor_departments dd on dm.member_id = dd.doctor_id
LEFT OUTER JOIN cloud_clinic.rm_pr_departments r on dd.department_id  = r.departmentid
LEFT OUTER JOIN cloud_clinic.clinic_doctors cd on dm.member_id = cd.DoctorID
LEFT OUTER JOIN cloud_clinic.clinic_branches cb on cd.clinic_branch_id = cb.branch_id
LEFT OUTER JOIN cloud_clinic.clinics oc on cb.clinic_id = oc.id
LEFT OUTER JOIN cloud_clinic.doctor_education dee on dm.member_id = dee.doctorid
LEFT OUTER JOIN cloud_clinic.rm_pr_degrees rpd on dee.degreeid = rpd.degreeid
where dm.doctor_id  = '" + PersonID + "' And d.FirstName like '" + term + "%' group by d.DoctorID LIMIT 5";

            MySqlDataAdapter da = new MySqlDataAdapter(cmd, con);

            DataSet ds = new DataSet();

            da.Fill(ds);

            SearchResult result = new SearchResult();

            //List<string> listTest = new List<string>();

            List<Doctor> doctorList = new List<Doctor>();

            List<Connection> connectionList = new List<Connection>();

            for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
            {

                //string test = ds.Tables[0].Rows[i]["TestName"].ToString();

                Connection objConnection = new Connection();

                objConnection.ConnectionID = ds.Tables[0].Rows[i]["DoctorID"].ToString();
                objConnection.ConnectionName = ds.Tables[0].Rows[i]["FirstName"].ToString() + " " + ds.Tables[0].Rows[i]["LastName"].ToString();
                objConnection.ImageName = ds.Tables[0].Rows[i]["Image"].ToString();
                //objConnection.Type = "Connection";
                connectionList.Add(objConnection);
            }

            con.Close();


            cmd = @"SELECT DISTINCT d.DoctorID,
d.FirstName,
d.LastName,
d.Image
FROM cloud_clinic.doctors d
where (d.FirstName like '"+term+"%') and (d.DoctorID not in ( select dm.member_id FROM cloud_clinic.doctor_members dm )) LIMIT 5";

            con.Open();

            MySqlDataAdapter da1 = new MySqlDataAdapter(cmd, con);

            DataSet ds1 = new DataSet();

            da1.Fill(ds1);

            

            //List<string> listTest = new List<string>();

           // List<Doctor> doctorList = new List<Doctor>();

            for (int i = 0; i < ds1.Tables[0].Rows.Count; i++)
            {

                //string test = ds.Tables[0].Rows[i]["TestName"].ToString();

                Doctor objDoctor = new Doctor();

                objDoctor.DoctorID = ds1.Tables[0].Rows[i]["DoctorID"].ToString();
                objDoctor.DoctorName = ds1.Tables[0].Rows[i]["FirstName"].ToString() + " " + ds1.Tables[0].Rows[i]["LastName"].ToString();
                objDoctor.ImageName = ds1.Tables[0].Rows[i]["Image"].ToString();
                objDoctor.Type = "Doctor";
                doctorList.Add(objDoctor);
            }

            result.connections = connectionList;
            result.doctors = doctorList;
            
            
            return result;
        }

Cheers............:D


I hope you like it.......;)




Thanks.
Udemy

How to detect user reached bottom of page while scrolling

Sunday, November 03, 2013 0 Comments A+ a-

Few days before i needed to implement on scroll paging as the facebook or linkedin is doing, instead of paging i thought to do infinite page scroll paging in my application so i decided to share the thing here as well.


Here is a sample code. Add this html to a empty html page:


<div style="height: 4000px">Scroll down!</div>

Here is the jquery code, but remeber to add jquery minified version in your page head as well like this:


<script type="text/javascript"
    src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.3/jquery.min.js"></script>


Here is the jquery code to detect if user has reached page end while scrolling:


<script type="text/javascript">

        $(window).scroll(function () {
            if ($(window).scrollTop() + $(window).height() == $(document).height()) {
                alert("bottom!");
            }
        });

    
    </script>


here is the code to detect if user is near the bottom:


 $(window).scroll(function() {   
   if($(window).scrollTop() + $(window).height() > $(document).height() - 100) {
       alert("bottom!");
   }
});

Hope you got it. -:)

Udemy

How to run multiple skype accounts from one PC (Running Multiple Skype Instances Simultaneously)

Monday, September 23, 2013 0 Comments A+ a-

Running Multiple Skype Instance Simultaneously

Hi friends,

Today i have got a trick type thing for you people that how you can run multiple skype accounts simultaneously on a PC. The following is the way to do that:

Here's a little command that will allow you to have two (active) Skype accounts running at the same time on your PC:

Windows 7 32-bit:
  • Click on Start> Run > enter the following command (including the quotes):
  • "C:\Program Files\Skype\Phone\Skype.exe" /secondary 
  • Press the Enter key
  • A new Skype window will appear> login with your other account


Windows 7 64-bit:
  • Click on Start> Run > enter the following command (including the quotes):
  • "C:\Program Files (x86)\Skype\Phone\Skype.exe"/secondary
  • A new Skype window will appear> login with your other account credentials


Note that: the command may change according to the default installation path of Skype.



Thanks.
Udemy

Bar Charts and Graphs in Asp.net mvc

Tuesday, September 03, 2013 2 Comments A+ a-

Hi friends,

Yesterday i came across a scenario where i needed to display mt data in pictorial format to user for readability, i was searching some jquery plugin to achieve that so that i can make graphs and bar charts in my application and i found many plugins but the one i found best for me was http://www.highcharts.com/

it has a lot of data representation controls available, i used one of this.


The output of it looks like :







Here is the way how you can build a bar chart or graph:



For making chart or graph first we have to add these lines in  the view:



<script src="http://code.highcharts.com/highcharts.js"></script>
<script src="http://code.highcharts.com/modules/exporting.js"></script>

now add a div in view which will contain the chart, it will be our container :


<div id="myDiv" style="min-width: 310px; height: 400px; margin: 0 auto"></div>

Now you add this code in your view, for understanding there is static data here passed but you can get data via Ajax or get in action and on view use it in this function:

 

<script type="text/javascript">
                      var chart1;
                      $(document).ready(function () {
                          chart1 = new Highcharts.Chart({
                              chart: {
                                  type: 'spline',
                                  renderTo: 'myDiv'
                              },
                              title: {
                                  text: 'Monthly Tests Processed',
                                  x: -20 //center
                              },
                              subtitle: {
                                  text: '2013',
                                  x: -20
                              },
                              xAxis: {
                                  categories: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun',
                    'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']
                              },
                              yAxis: {
                                  title: {
                                      text: 'No. of test processed'
                                  },
                                  plotLines: [{
                                      value: 0,
                                      width: 1,
                                      color: '#808080'
                                  }]
                              },
                              tooltip: {
                                  valueSuffix: 'Tests Processed'
                              },
                              legend: {
                                  layout: 'vertical',
                                  align: 'right',
                                  verticalAlign: 'middle',
                                  borderWidth: 0
                              },
                              series: [{
                                  name: '2013',
                                  data: [10, 20, 8, 40, 21, 90, 60, 44, 0, 35, 16,41]
                              }]
                          });
                      });
    

  </script>

but in the below view you will see i am filling data dynamically by getting from server side that will make you better understand.

Controller Action

Here is my controller code:


public class DashboardController : Controller
    {
        //
        // GET: /Dashboard/

        public ActionResult Index()
        {

            if (Session["user"] != null)
            {

                Session["ViewFlag"] = "Dashboard";

                DashboardViewModel objDashboardViewModel = new DashboardViewModel();



                return View(objDashboardViewModel.GetVerifiedTests((long)Session["userID"]));
            }

            else
            {
                return RedirectToAction("Index", "Home");
            }
        }
        

    }

View Model 

Here is my view model code:


public class DashboardViewModel
{
 public int YearCount { get; set; }
 public int TodayCount { get; set; }
 public int TodayOverdueCount { get; set; }
 public int TodayOnTimeCount { get; set; }
 public int JanuaryCount { get; set; }
 public int FabruaryCount { get; set; }
 public int MarchCount { get; set; }
 public int AprilCount { get; set; }
 public int MayCount { get; set; }
 public int JuneCount { get; set; }
 public int JulyCount { get; set; }
 public int AugustCount { get; set; }
 public int SeptemberCount { get; set; }
 public int OctoberCount { get; set; }
 public int NovemeberCount { get; set; }
 public int DecemberCount { get; set; }

 public DashboardViewModel GetEnteredTests(long PersonID)
 {

 DashboardViewModel objDashboardViewModel = new DashboardViewModel();

 using (var db = new bc_limsEntities())
 {
  var result = (from r in db.dc_tresult

                join tr in db.dc_tstatustrack 
                on r.bookingdid equals tr.bookingdid
                where tr.processid == 5
                && tr.enteredby == PersonID

               select new { r.bookingdid, r.enteredon }).Distinct();

                
 int totalCounter = 0;
 int todayCounter = 0;
 int janCounter = 0;
 int febCounter = 0;
 int marCounter = 0;
 int aprCounter = 0;
 int mayCounter = 0;
 int junCounter = 0;
 int julCounter = 0;
 int augCounter = 0;
 int sepCounter = 0;
 int octCounter = 0;
 int novCounter = 0;
 int decCounter = 0;

 foreach (var item in result)
 {
   if(item.enteredon.Month == 1 && item.enteredon.Year == DateTime.Now.Year)
   {
    janCounter ++;
   }
   if (item.enteredon.Month == 2 && item.enteredon.Year == DateTime.Now.Year)
   {
    febCounter++;
   }
   if (item.enteredon.Month == 3 && item.enteredon.Year == DateTime.Now.Year)
   { 
    marCounter++;
   }
   if (item.enteredon.Month == 4 && item.enteredon.Year == DateTime.Now.Year)
   {
    aprCounter++;
   }
   if (item.enteredon.Month == 5 && item.enteredon.Year == DateTime.Now.Year)
   {
    mayCounter++;
   }
   if (item.enteredon.Month == 6 && item.enteredon.Year == DateTime.Now.Year)
   {
    junCounter++;
   }
   if (item.enteredon.Month == 7 && item.enteredon.Year == DateTime.Now.Year)
   {
   julCounter++;
   }
   if (item.enteredon.Month == 8 && item.enteredon.Year == DateTime.Now.Year)
   {
    augCounter++;
   }
   if (item.enteredon.Month == 9 && item.enteredon.Year == DateTime.Now.Year)
   {
    sepCounter++;
   }
   if (item.enteredon.Month == 10 && item.enteredon.Year == DateTime.Now.Year)
   {
    octCounter++;
   }
   if (item.enteredon.Month == 11 && item.enteredon.Year == DateTime.Now.Year)
   {
    novCounter++;
   }
   if (item.enteredon.Month == 12 && item.enteredon.Year == DateTime.Now.Year)
   {
    decCounter++;
   }
   if (item.enteredon == DateTime.Now)
   {
    todayCounter++;
   }
   if (item.enteredon.Year == DateTime.Now.Year)
   {
    totalCounter++;
   }
                    
  
}

                
objDashboardViewModel.TodayCount = todayCounter;
objDashboardViewModel.YearCount = totalCounter;
objDashboardViewModel.JanuaryCount = janCounter;
objDashboardViewModel.FabruaryCount = febCounter;
objDashboardViewModel.MarchCount = marCounter;
objDashboardViewModel.AprilCount = aprCounter;
objDashboardViewModel.MayCount = mayCounter;
objDashboardViewModel.JuneCount = junCounter;
objDashboardViewModel.JulyCount = julCounter;
objDashboardViewModel.AugustCount = augCounter;
objDashboardViewModel.SeptemberCount = sepCounter;
objDashboardViewModel.OctoberCount = octCounter;
objDashboardViewModel.NovemeberCount = novCounter;
objDashboardViewModel.DecemberCount = decCounter;

return objDashboardViewModel;
                
     }
   }
}

Here is my View :



<div class="grid">

              <div class="grid-title">
               <div class="pull-left">
                  <div class="icon-title"><i class="icon-eye-open"></i></div>
                  <span>Dashboard</span> 
                  <div class="clearfix"></div>
               </div>
               <div class="pull-right"> 
                  <div class="btn-group" style="margin-top:4px;margin-right:4px;">
                 @* <button class="btn">Verified Today</button>*@
                  @*<button class="btn">Last Week</button>
                  <button class="btn">Last Month</button*@>
                </div>
               </div>
              <div class="clearfix"></div>   
              </div>

              <div class="clearfix"></div>

              <div class="grid-content overflow">
              
              <div style="position:relative;">
              <h3>Today's Processed</h3><span>@Model.TodayCount</span>
              <h3>2013 Total</h3><span>@Model.YearCount</span>
                  
                  <script type="text/javascript">
                      var chart1;
                      //data: [january, '@Model.FabruaryCount', '@Model.MarchCount', '@Model.AprilCount', '@Model.MayCount', '@Model.JuneCount', '@Model.JulyCount', '@Model.AugustCount', '@Model.SeptemberCount', '@Model.OctoberCount', '@Model.NovemeberCount', '@Model.DecemberCount']
                      var january = @Model.JanuaryCount;
                      $(document).ready(function () {
                          chart1 = new Highcharts.Chart({
                              chart: {
                                  type: 'spline',
                                  renderTo: 'myDiv'
                              },
                              title: {
                                  text: 'Monthly Tests Processed',
                                  x: -20 //center
                              },
                              subtitle: {
                                  text: '2013',
                                  x: -20
                              },
                              xAxis: {
                                  categories: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun',
                    'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']
                              },
                              yAxis: {
                                  title: {
                                      text: 'No. of test processed'
                                  },
                                  plotLines: [{
                                      value: 0,
                                      width: 1,
                                      color: '#808080'
                                  }]
                              },
                              tooltip: {
                                  valueSuffix: 'Tests Processed'
                              },
                              legend: {
                                  layout: 'vertical',
                                  align: 'right',
                                  verticalAlign: 'middle',
                                  borderWidth: 0
                              },
                              series: [{
                                  name: '2013',
                                  data: [@Model.JanuaryCount, @Model.FabruaryCount, @Model.MarchCount, @Model.AprilCount, @Model.MayCount, @Model.JuneCount, @Model.JulyCount, @Model.AugustCount, @Model.SeptemberCount, @Model.OctoberCount, @Model.NovemeberCount,@Model.DecemberCount]
                              }]
                          });
                      });
    

  </script>
 <script src="http://code.highcharts.com/highcharts.js"></script>
<script src="http://code.highcharts.com/modules/exporting.js"></script>
<div id="myDiv" style="min-width: 310px; height: 400px; margin: 0 auto"></div>
          
              
              
              </div>

              </div>

</div>


 


If you have any question you can ask me in comments. Thanks.
Udemy

These are called Real Developers....:D

Friday, August 30, 2013 1 Comments A+ a-

Udemy

Asp.net mvc Ajax File Uploading using JQuery

Monday, August 26, 2013 4 Comments A+ a-


Introduction:

In this post, you will learn how to upload file in asp.net mvc without reloading the whole page or wihtout refreshing the whole page instead we will update specific portion of page which is normally said aync postback in webforms terms.

Background:

Once upon a time i came across scenario where i needed to upload file in my asp.net mvc web application but its quite simple if we want full post-back, but i was thinking of doing it using Ajax by doing Partial Post-back.

Using JQuery to post standard forms is extremely simple, but when posting multi-part forms for uploading files it's not so intuitive.  This is due to browser security restrictions and sandboxing.  Today I'm going to show you how to fake an asynchronous upload without reloading the page and get a result back from the server.

 First Idea that came in my mind was using mvc helper Ajax.BeginForm and i came to know that it not supports file upload by partial post-back, it will do post-back.


Second Idea that was in my mind is to use JQuery and AJAX to post file on server so that i can avoid post-back, i tried my own way by posting file and returning partial view via AJAX but same issue was happening the partial view was rendering independently not on the same view, then i  searched on internet and found a way.

This method uses IFrame and do a fake async postback and it looks like that file uplaoding via ajax, as our view remains same.

How It Works

In order to make the AJAX style file uploads work, we need to to post to an iFrame.  We're going to position an iFrame off the page to hide it and then post to it.  We'll return a partial view to the page and append it in some html container.  It's important to note that due to security limitations, the page being posted to must be on the same domain as the page you're posting from. Also, this solution will be using a single hidden iFrame, but for multiple simultaneous uploads you could dynamically generate the iFrames and post to them.

Main View

Here is my view code i have created a form using mvc Helper and after the form i added an iframe in which our form will be posted:

@{
    ViewBag.Title = "Ajax File Uploading";
    Layout = "~/Views/Shared/_Layout.cshtml";
}

<h2>Ajax File Uploading</h2>


<div>

    <div>
        <h1>Upload File</h1>
    </div>


    @using (Html.BeginForm("Upload", "Home", FormMethod.Post,
    new
    {
        enctype = "multipart/form-data",
        id = "ImgForm",
        name = "ImgForm",
        target = "UploadTarget"
    }))
    {
        
@* DataBase Record ID as Hidden Field against which we are uplaoding file  *@
         
        @Html.Hidden("ID", 65512)
        <div style="width: 100px; margin: auto; float: left; line-height: 30px; font-weight: bold;">File</div>
     
         
        <div style="width: 200px; float: left; margin: auto;">

            <input type="file" id="uploadFile" name="file" data-val="true" data-val-required="please select a file" />
            <span id="validityMessages" style="color: Red;"></span>
        </div>

         
        <div style="clear: both;"></div>
     
        <div style="width: auto; margin-top: 3%;">
            <div style="margin: 5% 18%;">
                <input id="upload" type="button" value="Upload" name="Upload" onclick="UploadImage()" />
                <span id="uploadLoader" style="display: none;">
                    <img id="searchLoader" src="@Url.Content("~/Content/Images/loader.gif")" />Uploading Please Wait</span>
            </div>
        </div>
           
     
    }
    <div id="uploadsContainer"></div>
    <iframe id="UploadTarget" name="UploadTarget" onload="UploadImage_Complete();" style="position: absolute; left: -999em; top: -999em;"></iframe>
</div>




@section Scripts{

    <script type="text/javascript">

        $(document).ready(function () {

            $('img.delUpload').live('click', function () {

                var Id = this.id;

                var url = '@Url.Action("DeleteFile","Home")';

                url = url + "?id=" + Id
                $.get(url, function (response) {

                    $('#uploadsContainer').html(response);


                });


            });

        });


    </script>



    <script type="text/javascript">
        var isFirstLoad = true;

        function UploadImage() {



            // check for size of file not greater than 1MB
            if ($("#uploadFile").val()) {


                var iSize = ($("#uploadFile")[0].files[0].size / 1024);


                iSize = (Math.round((iSize / 1024) * 100) / 100);

                if (iSize > 4) {

                    alert("File must be less than 4MB");

                    $('span#validityMessages').html("File must be less than 4MB");



                    return;

                }
                else {
                    // on form post showing Busy Indicator
                    $('#uploadLoader').show();
                    $("#ImgForm").submit(); // post form
                    console.log(iSize + "Mb");
                }
            }

                // check for no file selected for upload

            else {


                $('span#validityMessages').html("Please select a File of size less than 4MB!");


                return;
            }


        }

        function UploadImage_Complete() {
            //Check to see if this is the first load of the iFrame
            if (isFirstLoad == true) {
                isFirstLoad = false;

            }


            $('#uploadLoader').hide();


            //Reset the image form so the file won't get uploaded again
            document.getElementById("ImgForm").reset();

            // this call will get uploads if any exists on server against this id and after successfull upload refreshing partial view to get the latest uploads
            GetFiles();


        }


        function GetFiles() {

            var url = '@Url.Action("GetFiles","Home")';

            var Id = $('input#ID').val();
            url = url + "?id=" + Id
            $.get(url, function (response) {

                $('#uploadsContainer').html(response);


            });

        }

    </script>
}

 Uploads ViewModel

Here is my uploads view model which is strongly typed with the uploads partial view:

public class UploadsViewModel
    {
        public long ID { get; set; }
        public List Uploads { get; set; }

        public UploadsViewModel()
        {
            this.Uploads = new List();
        }
    }


    public class File
    {
        public string FilePath { get; set; }
        public long FileID { get; set; }
        public string FileName { get; set; }
    }

Upload Controller Method

Here is my controller method, i am taking two parameters input one is the posted form, in form i am posting some values in hidden fields required for DB updates and second parameter is posted file, i am simply saving the file in Uploads directory on server and updating a table in DB using Entity Framework and at the end returning partial view which will display the uploaded file name, thumbnail if its a image type file and button for deleting the file.

For this post i am storing the state in Session:

        [HttpPost]
        public ActionResult Upload(FormCollection form, HttpPostedFileBase file)
        {
            
            UploadsViewModel uploadsViewModel = Session["Uploads"] != null ? Session["Uploads"] as UploadsViewModel : new UploadsViewModel();


            uploadsViewModel.ID = long.Parse(form["id"]);

            File upload = new File();
            upload.FileID = uploadsViewModel.Uploads.Count + 1;
            upload.FileName = file.FileName;
            upload.FilePath = "~/Uploads/" + file.FileName;

            

            //if (file.ContentLength < 4048576)    we can check file size before saving if we need to restrict file size or we can check it on client side as well
            //{

                if (file != null)
                {
                    file.SaveAs(Server.MapPath(upload.FilePath));
                    uploadsViewModel.Uploads.Add(upload);
                    Session["Uploads"] = uploadsViewModel;
                }

                // Save FileName and Path to Database according to your business requirements

            //}


            return PartialView("~/Views/Shared/_UploadsPartial.cshtml", uploadsViewModel.Uploads);
        }



Uploads Partial View

Here is my partial view code:

@model List<AjaxFileUploading.ViewModels.File>
@{
    Layout = null;
    var IsAnyImage = Model.Any(x => new String[] { "jpg", "jpeg", "png", "gif" }.Contains(x.FileName.Split('.').Last()));

}


@if (Model.Any())
{
    <h3>Uploads</h3>
    <hr />
    <table style="width: 500px;">
        <tr>
            @if (IsAnyImage)
            {
                <th>Thumbnail</th>
            }
            <th>FileName</th>
            <th>Action</th>
        </tr>
        <tbody>
            @for(int i=0; i< Model.Count; i++)
            {
                <tr>

                    
                        <td style="text-align: center;">
                            <img width="60" src="@Url.Content(Model[i].FilePath)" />

                        </td>
                    
                    

                    <td style="text-align: center;">
                        <a href="@Url.Content("~/Uploads/" + Model[i].FileName)" target="_blank">@Model[i].FileName</a></td>
                    <td style="text-align: center;">
                        <img id="@Model[i].FileID" class="delUpload" width="20" src="@Url.Content("~/Content/Images/delete.png")" /></td>
                </tr>
            }
        </tbody>
    </table>

}
else
{
    <h3>No Uploads Found!</h3>
}



Javascript and Jquery for MainView

The first thing we need to do is include a version of jQuery.  Since I'm writing an MVC application, I've chosen to use bundles that are provided by the framework, so you will see follwing line written in master layout _Layout.cshtml which is located in Views >> Shared  directory:

    @Scripts.Render("~/bundles/jquery")

Now we can start creating our JavaScript to handle our form posts.  The UploadImage() method isn't absolutely necessary since all our example does is post the form, however as in my case i am displaying a busy indicator so that user is acknowledged that  file is uploading.  Here we're just going to create a global variable that tells whether or not we're on the first load of the iFrame and the function to upload the image:


Now the form is setup to post to our iFrame. Here is the code which checks if any file exists against this record already it is displayed and validation is also applied in this event, actually this event will be called when iframe will load, on first pageload also iframe load event is called so thats why i have put validation code as well here, i am just checking by flag is it a first load of iframe or not, if it's not first load then it means user is uploading file and  we may want to validate on file size, i am not allowing file greater than 4MB, you can also check here for file extension as well, may be you just want to allow user to upload images so in this function you can check that as well if you  want to check on specific type of files to be just uploaded :

<script type="text/javascript">
        var isFirstLoad = true;

        function UploadImage() {



            // check for size of file not greater than 1MB
            if ($("#uploadFile").val()) {


                var iSize = ($("#uploadFile")[0].files[0].size / 1024);


                iSize = (Math.round((iSize / 1024) * 100) / 100);

                if (iSize > 4) {

                    alert("File must be less than 4MB");

                    $('span#validityMessages').html("File must be less than 4MB");



                    return;

                }
                else {
                    // on form post showing Busy Indicator
                    $('#uploadLoader').show();

                    console.log(iSize + "Mb");
                }
            }

                // check for no file selected for upload

            else {


                $('span#validityMessages').html("Please select a File of size less than 4MB!");


                return;
            }


        }

        function UploadImage_Complete() {
            //Check to see if this is the first load of the iFrame
            if (isFirstLoad == true) {
                isFirstLoad = false; 

            }


            $('#uploadLoader').hide();


            //Reset the image form so the file won't get uploaded again
            document.getElementById("ImgForm").reset();

            // this call will get uploads if any exists on server against this id and after successfull upload refreshing partial view to get the latest uploads
            GetFiles();


        }

</script>    

and at last here is the deleting of file using ajax:

        $(document).ready(function () {

            $('img.delUpload').live('click', function () {

                var Id = this.id;

                var url = '@Url.Action("DeleteFile","Home")';

                url = url + "?id=" + Id
                $.get(url, function (response) {

                    $('#uploadsContainer').html(response);


                });


            });

        });



Delete File Controller Method

 Here is the Delete File Action:

        public ActionResult DeleteFile(long id)
        {

            /* Use input Id to delete the record from db logically by setting IsDeleted bit in your table or delete it physically whatever is suitable for you
               for DEMO purpose i am stroing it in Session */

            UploadsViewModel viewModel = Session["Uploads"] as UploadsViewModel;

            File file = viewModel.Uploads.Single(x => x.FileID == id);

            try
            {

                System.IO.File.Delete(Server.MapPath(file.FilePath));
                viewModel.Uploads.Remove(file);

            }

            catch (Exception)
            {
                return PartialView("~/Views/Shared/_UploadsPartial.cshtml", viewModel.Uploads);
            }



            return PartialView("~/Views/Shared/_UploadsPartial.cshtml", viewModel.Uploads);
        }


and GetFiles actions looks like :
        public ActionResult GetFiles(long Id)
        {
            UploadsViewModel viewModel = Session["Uploads"] as UploadsViewModel;

            return PartialView("~/Views/Shared/_UploadsPartial.cshtml", (viewModel == null ? new UploadsViewModel().Uploads : viewModel.Uploads));
        }



I have created a sample project to demonstrate it.The screen shot is attached:


You can download sample source code from here

Download Source Code (AjaxFileUploading.zip) 


Hope you will get the understanding how its working, for reference from where i got help you can also visit this link for more details: AJAX File Uploads with jQuery and MVC 3
Udemy

asp.net mvc 4 routing Urls

Sunday, August 04, 2013 2 Comments A+ a-

Hi guys,

This Saturday i got in to situation, scenario was when we pass parameters to an action when we are calling action as get not post data is passed to the action parameters but if we see our application url, the values is shown in the url as query string this way:


http://localhost:34795/TestDetails?flag=4&sub=2


which looks very awkward as its not a good approach to show database related ids in the urls, its unsafe, user just needs to play with numbers and can access the records that we dont want to be accesssible to him, so i needed a way so that my url be shown like this:



http://localhost:34795/TestDetails/4/2


or like this:

http://localhost:34795/TestDetails




When i go-ogled i came to know that we can configure the mvc application routes  in Global.asax file of our project which was very simple, but in my case it was not very simple, it was really weird and wasted my one day in achieving that i will explain why it happened. We can achieve the thing by writing this code for our particular Controller's action in Global.asax:

as in my case my Verification Controller's Index action was called and two parameters were paased to it and my url was looking like this:


http://localhost:34795/Verification?DepartmentID=3&SubDepartmentID=2 
 

and i dont't want the url to be like this, the solution is simple you have to write this code in Golobal.asax, i  am writing the code for the above controller's action:



public class MvcApplication : System.Web.HttpApplication
    {

      
public static void RegisterRoutes(RouteCollection routes)
        {
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");


            routes.MapRoute(
                "Verification",                                              // Route name
                "Verification/{DepartmentID}/{SubDepartmentID}",                           // URL with parameters
                new
                {
                    controller = "Verification",
                    action = "Index",
                    DepartmentID = UrlParameter.Optional,
                    SubDepartmentID = UrlParameter.Optional
                } // Parameter defaults
            );

            routes.MapRoute(
                name: "Default",
                url: "{controller}/{action}/{id}",
                defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
            );
        
            

            
        }


        protected void Application_Start()
        {

            

            AreaRegistration.RegisterAllAreas();

            RegisterGlobalFilters(GlobalFilters.Filters);
            RegisterRoutes(RouteTable.Routes);

            BundleTable.Bundles.RegisterTemplateBundles();
        }
    }
 
 
 


But in my case i was developing application asp.net mvc 4 and i noticed that asp.net mvc4 adds some classes to the App_Start folder automatically at project creation by defaul, i was adding routing code in the Global.asax file but in the Application_Start method this line was written which i did'nt noticed before :


protected void Application_Start()
        {

            AreaRegistration.RegisterAllAreas();

            WebApiConfig.Register(GlobalConfiguration.Configuration);
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);
            AuthConfig.RegisterAuth();
        }

As you see for registering routes in Application_Start method RegisterRoutes method is called of class RouteConfig which is available in the App_Start folder of Solution, this was the issue i was  writing route code in Global.asax but in actual my that method was not calling method was called of class RouteConfig, when i realized i moved my route code to that class method, and things worked.
Udemy

Sql NOT IN operator in LINQ Query Entity Framework

Monday, July 29, 2013 0 Comments A+ a-

Few days ago, i came across a scenario in which i needed to apply sql NOT IN operator in my project as LINQ Query, my project was in mvc and i used ADO.net Entity Data Model to interact with database.


Here is the sql query which i needed to convert to linq:



SELECT d.processid,d.name,t.test_name
FROM dc_tp_tprocess d
left outer join dc_tp_tprocedured pd on pd.processid=d.processid
left outer join dc_tp_test t on t.procedureid=pd.procedureid
where d.active='Y' and t.testid=1 
                   and d.processid not in (1,2,6,8,9,10)
order by t.testid,d.processid 


At last after posting my question on a forum i got an answer from some one and that was this:



int[] tmp=new int[]{1,2,6,8,9,10};

var query=from d in dc_tp_tprocess
          join pd in dc_tp_tprocedured on d.processid equals pd.processid&nbsp;
         into leftGroup1
          from pd in leftGroup1.DefaultIfEmpty() 
          join t in dc_tp_test on pd.procedureid equals t.procedureid&nbsp;
          into leftGroup2
          from t in leftGroup2.DefaultIfEmpty()
          orderby t.testid,d.processid
          where d.active=="Y"&nbsp;
         &amp;&amp; t.testid==1&nbsp;
         &amp;&amp; !tmp.Contains(d.processid)
          select new {d.processid,d.name,test_name=t==null?"":t.test_name}; 


The tmp is a temporary array taken from which i am checking that the processID coming in the current row not exists in that array then select row.

I hope it will help if you stuck or got same scenario and don't getting how to handle the situation -:).
Udemy

Error 25 The type of one of the expressions in the join clause is incorrect. Type inference failed in the call to 'Join'

Sunday, July 28, 2013 0 Comments A+ a-

I had a scenario where i needed to fetch Result Data from multiple tables on basis of some condition by applying joins between the tables using Entity Framework. I was using Linq queries as in EF linq query is faster than the normal string queries and stored procedures, but i was getting the exception.

Here is the query which i wrote:

I made the object of my EntitiesClass generated by EDM:


OLSContainer ols = new OLSContainer();
        var reSet = from l in ols.LEVEL_COURSE
                    join lp in ols.PACKAGES 
                    on new { l.course_ID, l.levelID } 
                    equals new { lp.course_ID, lp.level_ID }
                    select l; 
which i know was wrong and on this query i was getting this exception:

Error 25 The type of one of the expressions in the join clause is 
incorrect. Type inference failed in the call to 'Join'

The mistake i was making was pretty was pretty simple in this scenario i dont need the join because i was only selecting data from LEVEL_COURSE table which can be achieved by simple where clause in the current scenario like this:



OLSContainer ols = new OLSContainer();
        var reSet = (from l in ols.LEVEL_COURSE
                    from p in ols.PACKAGES
                    where l.course_ID == p.course_ID 
                    &amp;&amp; l.levelID == p.level_ID 
                    &amp;&amp;    l.course_ID==courseID
                    select new { l.levelID, l.levelName }).Distinct();

This solved my problem and the exception that i was getting was due to column names were same. My  PACKAGES table and LEVEL_COURSE table both have column named course_ID which were of same datat type as well so it was confusing compiler to take which one, but at last i got working thing as i needed.


Reference Link:

http://stackoverflow.com/questions/14273879/error25the-type-of-one-of-the-expressions-in-the-join-clause-is-incorrect-typ/14290833#14290833