Wednesday, June 22, 2016

What's the difference between event.stopPropagation and event.preventDefault?

stopPropagation stops the event from bubbling up the event chain.
preventDefault prevents the default action the browser makes on that event.
Let's say you have
<div id="foo">
 <button id="but" />
</div>

$("#foo").click(function() {
   // mouse click on div
});

$("#but").click(function(ev) {
   // mouse click on button
   ev.stopPropagation();
});

jQuery limit to 2 decimal places

var amount = $("#textid").slider("value") * 1.60;
$("#textboxid2").val('$' + amount.toFixed(2));

Monday, June 20, 2016

Default return type of LINQ Query

If you are querying a database(Linq to SQL) then the return type is IQueryable<T> where T is Product in below example
var product = from p in dbContext.Products
             select p;


If you are using Linq againist a datasource which is an Enumerable collection(List) then the return type will be IEnumerable<t>
------------------------------------------
it depends on your original data source. It can be either IEnumerable or IQueryable 

The result of a Linq database query is typically IQueryable<T> . 

If the database query includes an OrderBy clause, the type is IOrderedQueryable<T> .It is derive from IQueryable<T> 

If the data source is an IEnumerable, the result type is IEnumerable<T> 

You can find out the datatype by calling .GetType() on the source. 

Generate Random Password

Here, we will see how to generate random passwords in ASP.NET. Random numbers may be generated in the .NET Framework using the Random class. You create an instance to an object of Random class and generate random numbers. You have to create a web site and add a new page to the website. Drag and drop two TextBox and one Button control on the form. One TextBox to give the length of the TextBox, another to display the random password of the specified length when we click on the Button control. Let's take a look at a practical example.
First you have to create a web site.
  • Go to Visual Studio 2010
  • New-> Select a website application
  • Click OK

Now add a new page to the website.
  • Go to the Solution Explorer
  • Right Click on the Project name
  • Select add new item
  • Add new web page and give it a name
  • Click OK

Now create a new website and drag and drop two TextBox controls onto the aspx page. The TextBoxcode looks like this:
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="randomnumber.aspx.cs"Inherits="randomnumber" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN""http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
   <div>
       Password Length: &nbsp;&nbsp; <asp:TextBox ID="txtPassLength" runat="server"></asp:TextBox>
        <br />
        Random Password: <asp:TextBox ID="txtpassword" runat="server"></asp:TextBox>
        <br />
        <br />
        <asp:Button ID="Button1" runat="server" onclick="Button1_Click"
            Text="Generate Password" />
        <br />
    </div>
    </form>
</body>
</html>
In ASP.Net you can use a Random class to generate the random numbers. Create an instance to an object of the Random class and generate random numbers. This class may be instantiated using the following code:
 Random rand = new Random();
In the above rand is an object of the Random Class.
Now double-click on the Button control and add the following code:
C# code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class randomnumber : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }
    protected void Button1_Click(object sender, EventArgs e)
    {
        string allowedChars = "";
        allowedChars = "a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z,";
        allowedChars += "A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,Q,R,S,T,U,V,W,X,Y,Z,";
        allowedChars += "1,2,3,4,5,6,7,8,9,0,!,@,#,$,%,&,?";
        char[] sep = { ',' };
        string[] arr = allowedChars.Split(sep);
        string passwordString = "";
        string temp = "";
        Random rand = new Random();
        for (int i = 0; i < Convert.ToInt32(txtPassLength.Text); i++)
        {
            temp = arr[rand.Next(0, arr.Length)];
            passwordString += temp;
        }
        txtpassword.Text = passwordString;
    }
}

Now run the application and test it.

Now give the length of the password.

Now click on the Button to generate a random password.


The above output displays a random password.

how to get last inserted id in C#

SCOPE_IDENTITY returns the last identity value inserted into an identity column in the same scope. A scope is a module: a stored procedure, trigger, function, or batch. Therefore, two statements are in the same scope if they are in the same stored procedure, function, or batch.

You can use SqlCommand.ExecuteScalar to execute the insert command and retrieve the new ID in one query.

using (var con = new SqlConnection(ConnectionString))
                {
                    int newID;
                    var cmd = "INSERT INTO foo (column_name)VALUES (@Value);SELECT CAST(scope_identity() AS int)";
                    using (var insertCommand = new SqlCommand(cmd, con))
                    {
                        insertCommand.Parameters.AddWithValue("@Value", "bar");
                        con.Open();
                        newID = (int)insertCommand.ExecuteScalar();
                    }

                }

Difference between View and PartialView in Asp.net MVC

I have seen a lots of debates and discussions on Difference between View and PartialView in Asp.net MVC. Both are used to return Html but main difference is that View return whole page including Layout while PartialView return only piece of html content. Beside all these points, I made some remarks on difference between view and partialview and some interesting analysis based on return type of view and partialview are described here.
  •  Key Difference between view and partialview in Asp.net mvc

  1. Partialview generally does not have any Layout while view content Layout.
  2. Partialview mostly does not content html attribute like head , tag , meta and body while view can have all this attribute
  3. Partialview is reusable content which is render inside view(parent page)
  4. Partialview mostly used with Ajax request to process fast and update particular portion while view load whole page.
  5. Partialview generally process with mvc Ajax.ActionLink and Ajax.Beginform while View process with mvc Html.ActionLink and Html.Beginform
But above point are not always true for view vs partialview, as I have experienced its practically with different return types and appying layout or not. My analysis with some interesting results, while comparing view and partialview as below.
  • Return view and partialview with or without Layout Result

  1. Return View + Layout = View
  2. Return View – Layout = View (if Layout specified in _ViewState.cshtml)
  3. Return View – Layout = PartialView (if Layout not  specified in _ViewState.cshtml)
  4. Return PartialView + Layout = View
  5. Return PartialView – Layout = PartialView

Difference Between MVC 4 and MVC 5 and MVC 6

MVC 6 New Features
  • Single Programming Model for ASP.Net MVC and ASP.Net Web API.
  • Out of the box support for dependency injection.
  • Having support of side by side deployment of runtime and framework along with your web application.
  • Optimized for Cloud Computing.
  • Everything packaged with NuGet, including the .Net runtime itself.
  • New JSON based project structure.
  • In order to dynamically compile code, Roslyn compiler is used.
  • No need to recompile for every change. Just hit save and refresh the browser.
  • vNext is Open Source and supports running on multiple platforms including Linux and Mac.

MVC 5 Features
  • ASP.Net Identity for authentication and identity management
  • Attribute Routing is now integrated into MVC5
  • Bootstrap replaced the default MVC template
  • Authentication Filters for authenticating user by custom or third-party authentication provider.
  • With the help of Filter overrides, we can now override filters on a method or controller.

MVC 4 Features
  • ASP.net Web API
  • Modernized default project templates and other look & feel improvements
  • Based on jQuery Mobile, new Mobile Project Template introduced.
  • A truly Empty Project Template.
  • Support for adding controller to other project folders also.
  • Task Support for Asynchronous Controllers.
  • Controlling Bundling and Minification through web.config.
  • Support for OAuth and OpenID logins using DotNetOpenAuth library.
  • Support for Windows Azure SDK 1.6 and new releases.

MVC 3 Features
  • Razor View Engine introduced with a bundle of new features.
  • Improved Model validation.
  • New Project Templates having support for HTML 5 and CSS 3.
  • Having support for Multiple View Engines i.e. Web Forms view engine, Razor or open source.
  • Controller improvements like ViewBag dynamic property and ActionResults Types etc. Dynamic property is a new feature introduced in C# 4.0. ViewBag being a dynamic property has an advantage over ViewData that it doesn’t require checking NULL values. For detailed difference between ViewBag and ViewData can be found here.
  • Unobtrusive JavaScript approach that actually separates the functionality from presentation layer on a web page.
  • Improved Dependency Injection with new IDependencyResolver.
  • Partial page output caching.

Random password generator using Ajax in ASP.Net MVC

You can download the project from here : Download MVCPasswordExample 

As title says when user click a button it send ajax request to controller
$.post('@Url.Content("~/Home/GeneratePassword/")' ...
and returns Json with new 8 character password.


MODEL



public class RegisterModel
    {
        [Required]
        [Display(Name = "User name")]
        public string UserName { getset; }

        [Required]
        [DataType(DataType.EmailAddress)]
        [Display(Name = "Email address")]
        public string Email { getset; }

        [Required]
        [StringLength(100, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = 6)]
        [DataType(DataType.Password)]
        [Display(Name = "Password")]
        public string Password { getset; }

        [DataType(DataType.Password)]
        [Display(Name = "Confirm password")]
        [Compare("Password", ErrorMessage = "The password and confirmation password do not match.")]
        public string ConfirmPassword { getset; }
    }
  



VIEW


@{
    ViewBag.Title = "Home Page";
}

@using MVCPasswordExample.Models
@model RegisterModel

<script>
    $(document).ready(function () {
        $('#updateprofile').click(function () {
            $('form')[0].reset();

        });

        $('#autogenerate').click(function () {
            $.post('@Url.Content("~/Home/GeneratePassword/")'function (data) {

                $('#password, #confirmpassword').attr("value", data.password);

            });
        });

    });

</script>


<h2>@ViewBag.Message</h2>

<table style="margin-top:100px;width:40%">
 <tr>
 <th colspan="3">Change Password</th>
 </tr>


  <tr>
      <td>@Html.LabelFor(m => m.Password)
      </td>
     <td style="width:20%">
         @Html.TextBox("password"nullnew { @class = "search_field", @id = "password", @Value = "" })
     </td>
      <td><input type="button" id="autogenerate" value="Auto generate" class="submit_button" /></td>
 </tr>
    
  <tr>
      <td>
         @Html.LabelFor(m => m.ConfirmPassword)
      </td>
     <td class="confirm" colspan="2">
          @Html.TextBox("confirmpassword"nullnew { @class = "search_field", @id = "confirmpassword" })
      </td>

 </tr>


 </table>


CONTROLLER

        [HttpPost]
        public JsonResult GeneratePassword()
        {
           var pass = Guid.NewGuid().ToString().Substring(0, 8);


            return Json(new { password = pass });

        }

You can download the project from here : Download MVCPasswordExample