Wednesday 26 April 2017

SQL Query interview question part - 3

Here I just created Employee table and on the basis of Write Some common query  which generally asking in interview.

CREATE TABLE [dbo].[tblEmployee](
[EmployeeID] [int] IDENTITY(1,1)  NOT NULL,
[LastName] [nvarchar](20) NOT NULL,
[FirstName] [nvarchar](10) NOT NULL,
[Title] [nvarchar](30) NULL,
[BirthDate] [datetime] NULL,
[HireDate] [datetime] NULL,
[Address] [nvarchar](60) NULL,
[City] [nvarchar](15) NULL,
[Country] [nvarchar](15) NULL
)
GO

 SELECT * FROM [tblEmployee]


1. Ques: List of all employee from tblEmployee table whose "FirstName" start with latter 'a'.

Answer: SELECT * FROM [tblEmployee] WHERE FirstName like 'a%'



2. Ques:  List of all employee from tblEmployee table whose "FirstName" start with any single character between 'a-j'.

Answer: SELECT * FROM [tblEmployee] WHERE FirstName like '[a-j]%'



3.Ques: Get only Year part of "HireDate".
Answer:SELECT DATEPART(YEAR, HireDate) FROM [tblEmployee]


Thursday 20 April 2017

ViewModel Example In MVC ASP.Net With bootstrap

What is ViewModel in MVC ?
Answer: ViewModel contain fields that are represented in the view.It allow you to shape multiple entities from one or more data models or sources into a single object, optimized for consumption and rendering by the view.

In this tutorials i am going to showing demo how to use of ViewModel class in MVC ASP.Net.





In this demo I used flowing version of framework
  • Using Visual studio 2012 MVC 4 version.
  • Sql Server 2012.
  • AutoMapper DLL references  
  • For css using bootstrap and jquery
  • Entity framework (4.4.0.0) references  


Step:1
Create a Three table in sql server database. The three table name as

  • y_category_master
  • y_vendor_master
  • y_Product_Master

CREATE TABLE [dbo].[y_category_master] (
    [CategoryID]   INT          IDENTITY (1, 1) NOT NULL,
    [CategoryName] VARCHAR (50) NULL,
    CONSTRAINT [PK_y_category_master] PRIMARY KEY CLUSTERED ([CategoryID] ASC)
);

GO
CREATE TABLE [dbo].[y_vendor_master] (
    [venderId]   INT          IDENTITY (1, 1) NOT NULL,
    [venderName] VARCHAR (50) NULL,
    CONSTRAINT [PK_y_vendor_master] PRIMARY KEY CLUSTERED ([venderId] ASC)
);

GO
CREATE TABLE [dbo].[y_Product_Master] (
    [ProductId]  INT             IDENTITY (1, 1) NOT NULL,
    [Name]       VARCHAR (50)    NULL,
    [Price]      DECIMAL (18, 2) NULL,
    [CategoryID] INT             NULL,
    [VendorID]   INT             NULL,
    CONSTRAINT [PK_y_Product_Master] PRIMARY KEY CLUSTERED ([ProductId] ASC),
    CONSTRAINT [FK_y_Product_Master_y_category_master] FOREIGN KEY ([CategoryID]) REFERENCES [dbo].[y_category_master] ([CategoryID]),
    CONSTRAINT [FK_y_Product_Master_y_vendor_master] FOREIGN KEY ([VendorID]) REFERENCES [dbo].[y_vendor_master] ([venderId])
);

GO
CREATE NONCLUSTERED INDEX [IX_FK_y_Product_Master_y_category_master]
    ON [dbo].[y_Product_Master]([CategoryID] ASC);

GO
CREATE NONCLUSTERED INDEX [IX_FK_y_Product_Master_y_vendor_master]
    ON [dbo].[y_Product_Master]([VendorID] ASC);


Step:2 Create Entity Data Model to connect to database

Right-click on your project in Solution Explorer then click on ADD New ADO.NET Entity Data Model. name as "Product.edmx". Create database connection with the help of Entity framework
And drag & drop all three table in Entity modal design.



Step:3 Reffrence the AutoMapper DLL to your projects

Right Click on your project in Solution Explorer then select Manage NuGet Packages.search AutoMapper and install it.


Step:4 Add Model class

Here I created product modal partial class in Modal Folder with name Product.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace ViewModelProj.Models
{
    public partial class Product
    {
        public string Name { get; set; }
        public decimal Price { get; set; }
        public int CategoryID { get; set; }
        public int VendorID { get; set; }
 
    }

    public partial class Product
    {
        public string CategoryName { get; set; }
        public string VendorName { get; set; }
    }
}

Step:5 Add ViewModel class

Create new folder in project View_Model. In this folder right click and add class with name ProductViewModel.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using ViewModelProj.Models;
using System.Web.Mvc;

namespace ViewModelProj.View_Model
{
    public class ProductViewModel
    {
        public Product product { get; set; }
        public SelectList VendorList { get; set; }
        public SelectList CategoryList { get; set;}
    }
}


Step:6 Add Controller 
In Controller folder open the 'HomeController' and put the code given bellow.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using ViewModelProj.Models;
using ViewModelProj.View_Model;
using AutoMapper;

namespace ViewModelProj.Controllers
{
    public class HomeController : Controller
    {  
        TestEntities db = new TestEntities();
        public ActionResult Index()
        {
            List<Product> ProVModal = new List<Product>();
            using (TestEntities dc = new TestEntities())
            {
                var v = (from a in dc.y_Product_Master
                         join b in dc.y_category_master on a.CategoryID equals b.CategoryID
                         join c in dc.y_vendor_master on a.VendorID equals c.venderId
                         select new Product
                         {
                             Name = a.Name,
                             Price= (decimal)a.Price,
                             CategoryName= b.CategoryName,
                             VendorName = c.venderName
                         }).OrderBy(x => x.Name).ToList();
                ProVModal = v;
             
            }
            return View(ProVModal);
        }

        public ActionResult AddProduct()
        {
            ProductViewModel objProductViewModel = new ProductViewModel();
            var category = db.y_category_master;
            var vendor = db.y_vendor_master;

            objProductViewModel.CategoryList = new SelectList(category, "CategoryID", "CategoryName");
            objProductViewModel.VendorList = new SelectList(vendor, "venderId", "venderName");

            return View(objProductViewModel);
        }

        public ActionResult SaveProduct(ProductViewModel objProductViewModel)
        {        
            Mapper.CreateMap<Product,y_Product_Master>();
            y_Product_Master obj1 = Mapper.Map<Product, y_Product_Master>(objProductViewModel.product);
            db.y_Product_Master.Add(obj1);
            db.SaveChanges();

            return View();
        }

    }
}

Step:7 Adding View
Add three View against the controler. I added three view which given bellow as

Index.cshtml : This View showing all the product list in grid.
AddProduct.cshtml : This View use for add new product in system.
SaveProduct.cshtml : This View use shwoing Message to successfully product added.

@model IEnumerable<ViewModelProj.Models.Product>
@{
    ViewBag.Title = "Index";
}

<link href="~/Content/Bootstrap/bootstrap.css" rel="stylesheet" />

<h2 style="margin-left: 20px">All Product List</h2>
<p style="margin-left: 20px">
    @Html.ActionLink("Create New", "AddProduct")
</p>

 <div class="row" style="margin-left: 20px">
     <div class="form-group">
            <div class="col-md-6">
<table  class="col-md-12 table-bordered table-striped table-condensed cf" style="margin-left: 20px">
    <thead class="cf" style="border: 1px solid #ccc;">
    <tr>
        <th>
            @Html.DisplayNameFor(model => model.Name)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.Price)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.CategoryName)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.VendorName)
        </th>
        <th></th>
    </tr>
        </thead>
    <tbody style="border: 1px thin black">
@foreach (var item in Model) {
    <tr>
        <td>
            @Html.DisplayFor(modelItem => item.Name)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.Price)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.CategoryName)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.VendorName)
        </td>
        <td>
            @Html.ActionLink("Edit", "Edit", new { /* id=item.PrimaryKey */ }) |
            @Html.ActionLink("Details", "Details", new { /* id=item.PrimaryKey */ }) |
            @Html.ActionLink("Delete", "Delete", new { /* id=item.PrimaryKey */ })
        </td>
    </tr>
}
         </tbody>
</table>
</div>
         </div>
     </div>


AddProduct.cshtml
@model ViewModelProj.View_Model.ProductViewModel

@{
    ViewBag.Title = "AddProduct";
}

<h2 style="margin-left: 20px">AddProduct</h2>

@using (Html.BeginForm("SaveProduct","Home",FormMethod.Post)) {
    @Html.ValidationSummary(true)

    <div class="row" >
         <div class="col-xs-12 col-sm-12 col-md-12 ">
                    &nbsp;
                </div>
         <div>    
    </div>

         <div class="col-md-12">
        <table style="width:40%; margin-left: 20px" class="table-condensed" border="1">
        <tr>
            <td>
                <div class="row" >
                <div class="col-xs-12 col-sm-6 col-md-6">
                    <div class="editor-label">
                        Product Name:                    
                    </div>
                </div>
                <div class="col-xs-12 col-sm-6 col-md-6">
                    <div class="editor-field">
                        @Html.TextBoxFor(model => model.product.Name, new { @class="form-control", placeholder="Please Enter Product Name"})
                        @Html.ValidationMessageFor(model => model.product.Name, "Please Enter ProductName", new { @class = "text-danger" })
                    </div>
                </div>
              </div>

                <div class="row" >
               <div class="col-xs-12 col-sm-6 col-md-6">
                    <div class="editor-label">
                        Price:
                    </div>
                </div>
                <div class="col-xs-12 col-sm-6 col-md-6">
                    <div class="editor-field">

                        @Html.TextBoxFor(model => model.product.Price, new { @class="form-control", placeholder="Please Enter product Price"})
                        @Html.ValidationMessageFor(model => model.product.Price, "Please Enter product Price", new { @class = "text-danger" })
                     </div>
                </div>
                    </div>

                <div class="row" >
                <div class="col-xs-12 col-sm-6 col-md-6">
                    <div class="editor-label">
                     Select Category:
                    </div>
                </div>
                <div class="col-xs-12 col-sm-6 col-md-6">
                    <div class="editor-field">
                        @Html.DropDownListFor(model => model.product.CategoryID, Model.CategoryList, "-- Select One --" , new { @style = "width:100%", @class="dropdown-header" })
                        @Html.ValidationMessageFor(model => model.CategoryList, "Please Select Department Location", new { @class = "text-danger" })
                     </div>
                </div>
                    </div>

                <div class="row" >
                 <div class="col-xs-12 col-sm-6 col-md-6">
                    <div class="editor-label">
                      Select Vendor:
                    </div>
                </div>
                <div class="col-xs-12 col-sm-6 col-md-6">
                    <div class="editor-field">
                        @Html.DropDownListFor(model => model.product.VendorID, Model.VendorList, "-- Select One --" , new { @style = "width:100%", @class="dropdown-header" })
                        @Html.ValidationMessageFor(model => model.VendorList, "Please Select Department Location", new { @class = "text-danger" })
                     </div>
                </div>
                     </div>

                <div class="row" >
                <div class="col-xs-12 col-sm-12 col-md-12 " style="align-items:center">
                    <br />
                    <br />
                 
                     <button type="submit"  value="SAVE"  class="btn btn-success btn-group-lg"  >
                            <span class="glyphicon glyphicon-plus"></span> SAVE
                      </button>      
                </div>
              </div>
            </td>
        </tr>
    </table>
 </div>
</div>
}
 <br />
<div>
    <div class="row" >
                <div class="col-xs-12 col-sm-12 col-md-12 " style="margin-left: 20px" >
                           @Html.ActionLink("Back to List", "Index")
                    </div>
        </div>
    </div>

@section Scripts {
    @Scripts.Render("~/bundles/jqueryval")
}


SaveProduct.cshtml
@{
    ViewBag.Title = "SaveProduct";
}

<h2>Product Saved Successfully</h2>

<p>
    @Html.ActionLink("List of Prduct", "Index")
</p>


Conclusion : 
                     In this way you can use viewmodal class in mvc. Hope this article will helpful for you.

Tuesday 18 April 2017

HTML5 interview questions Part -3

1. Ques: What is HTML Local Storage ?
Answer:
With local storage, web applications can store data locally within the user's browser.
Before HTML5, application data had to be stored in cookies, included in every server request. HTML5 Local storage is more secure, and large amounts of data can be stored locally, without affecting website performance.
Unlike cookies, the storage limit is far larger (at least 5MB) and information is never transferred to the server.
Local storage is per origin (per domain and protocol). All pages, from one origin, can store and access the same data.


2. Ques: What is the Geolocation API and why would you use it?
Answer:
HTML Geolocation API is used to get the geographical position of a user.Since this can compromise privacy, the position is not available unless the user approves it.

The HTML5 Geolocation API allows users to share their location with a website. This is a useful feature that asks a user permission to share their latitude and longitude with the app to receive the benefits of location-aware features, such as the ability to present the landing page of the business closest to the user’s location.

Sunday 16 April 2017

Bootstrap Interview Question Part - 1

1. Ques: What is Bootstrap ? Why we use Bootstrap ?
Answer:
Bootstrap is an open-source Javascript framework developed by the team at Twitter.  It is a combination of HTML, CSS, and Javascript code designed to build user interface components.It used for building the rich web applications with minimal effort. Bootstrap was also programmed to support both HTML5 and CSS3.  Also it is called Front-end-framework.Current Version of Bootstrap is v3.3.7

Bootstrap is a free collection of tools for creating a websites and web applications.It powerful mobile first front-end framework for faster and easier web development.

It contains HTML and CSS-based design templates for typography, forms, buttons, navigation and other interface components, as well as optional JavaScript extensions.

Some Reasons for programmers preferred Bootstrap Framework
  • Easy to get started
  • Great grid system
  • Base styling for most HTML elements(Typography,Code,Tables,Forms,Buttons,Images,Icons)
  • Extensive list of components
  • Bundled JavaScript plugins
  • Browser Support
  • Responsive features
  • Mobile-first approach


2. Ques: What are the key components of Bootstrap?
Answer:
CSS : It comes with plenty of CSS files
Scaffolding : It provides a basic structure with Grid system , link styles and background
Layout Components : List of layout components
JavaScript Plugins: It contains many jQuery and JavaScript plugins
Customize: To get your own version of framework you can customize your components
glyphicons: a font (an icon font set)


3. Ques: Explain Bootstrap Grid System?
Answer:
Bootstrap's grid system allows up to 12 columns across the page. Bootstrap includes a responsive, mobile first fluid grid system that appropriately scales up to 12 columns as the device or viewport size increases. It includes predefined classes for easy layout options, as well as powerful for generating more semantic layouts.


4. Ques:  What are different types of layout available in Bootstrap?
Answer:
  • Fluid Layout: Fluid layout adapts itself to different browser. Means design automatic adjust according to browser size.
  • Fixed Layout:Fixed layout doesn’t adapts itself to different browser but it can be responsive.


5 . What do you mean by responsive layout?
Answer:
Responsive layout which is able to adapt itself to different sizes as well, but when resizing, the number of columns changes according to the available space.responsive layout it is easy reading and navigation with a minimum of resizing, panning, and scrolling across a wide range of devices (from mobile phones to desktop computer monitors)


6 . What is Jumbotron?
Answer:
Jumbotron is used for content that you want to highlight like some slogan OR marketing headline.
Its indicates a big box for calling extra attention to some special content or information.
A jumbotron is displayed as a grey box with rounded corners. It also enlarges the font sizes of the text inside it.


7 . What is Bootstrap Container in Bootstrap?
Answer:
container is used to set the content's margins dealing with the responsive behaviors of your layout. It contains the row elements and the row elements are the container of columns (known as grid system).
The container class is used to create boxed content.

There are two container classes in Bootstrap:
container
container-fluid

Thursday 13 April 2017

Paging and Sorting in MVC4 Using PagedList



In this tutorials i am going to showing Paging and Sorting in MVC4 Using PagedList . For this  Am using 

Step i am going to do here

  1. using Visual studio 2012 MVC 4 version.
  2. Sql Server 2012.
  3. For css using bootstrap and jquery
  4. Entity framework (4.4.0.0) references  
  5. Reffrence the PagedList.mvc in project

Step:1 

Create a table in sql server database and create store procedure (script given bellow)

CREATE TABLE [dbo].[DepartmentLocation](
[LocationId] [int] IDENTITY(1,1) NOT NULL,
[LocationName] [nvarchar](50) NULL,
[Address] [nvarchar](50) NULL,
[City] [nvarchar](50) NULL,
[Pincode] [nvarchar](50) NULL,
[PhoneNo] [nvarchar](50) NULL,
[CountryID] [nvarchar](50) NULL,
PRIMARY KEY CLUSTERED 
(
[LocationId] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]

GO

Create PROCEDURE [dbo].[Sp_Get_DepartmentList]
AS
Begin
SELECT DL.LocationId,
      DL.LocationName,
  DL. Address,
  DL.City,
  DL.Pincode,
  DL.CountryID,
      C.CountryName
from Country C inner join DepartmentLocation DL On C.CountryID=DL.CountryID

End

Step:2 Create Entity Data Model to connect to database

Right-click on your project in Solution Explorer then click on ADD New ADO.NET Entity Data Model. name as "MyContactBookEntities" ...



Step:3 Reffrence the Pagedlist dll and css to your projects

on your project in Solution Explorer then select Manage NuGet Packages.search Pagedlist.mvc  and install it.





Step:3

Add new Controller with name 'DepartmentLocationController.cs' and put the code given bellow.

DepartmentLocationController.cs

using AutoMapper;
using MVCContactBook.ViewModel;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using PagedList;

namespace MVCContactBook.Controllers
{
      public class DepartmentLocationController : BaseController
          {
           public ActionResult GetDepartmentLocationList(string sortOn, string orderBy, string                                pSortOn, int? page)
           {          
            int recordsPerPage = 10;
            if (!page.HasValue)
            {
                page = 1; // set initial page value
                if (string.IsNullOrWhiteSpace(orderBy) || orderBy.Equals("asc"))
                {
                    orderBy = "desc";
                }
                else
                {
                    orderBy = "asc";
                }
            }          
            if (!string.IsNullOrWhiteSpace(sortOn) && !sortOn.Equals(pSortOn, StringComparison.CurrentCultureIgnoreCase))
            {
                orderBy = "asc";
            }

            ViewBag.OrderBy = orderBy;
            ViewBag.SortOn = sortOn;
        
            MyContactBookEntities dc = new MyContactBookEntities();
            var list = dc.Sp_Get_DepartmentList().AsQueryable();
                     
            switch (sortOn)
            {
                case "LocationName":
                    if (orderBy.Equals("desc"))
                    {
                        list = list.OrderByDescending(p => p.LocationName);
                    }
                    else
                    {
                        list = list.OrderBy(p => p.LocationName);
                    }
                    break;
                case "Address":
                    if (orderBy.Equals("desc"))
                    {
                        list = list.OrderByDescending(p => p.Address);
                    }
                    else
                    {
                        list = list.OrderBy(p => p.Address);
                    }
                    break;
                case "City":
                    if (orderBy.Equals("desc"))
                    {
                        list = list.OrderByDescending(p => p.City);
                    }
                    else
                    {
                        list = list.OrderBy(p => p.City);
                    }
                    break;                
                default:
                    list = list.OrderBy(p => p.LocationId);
                    break;
            }

            var finalList = list.ToList().ToPagedList(page.Value, recordsPerPage);
            return View(finalList);
        }
 }

}

Step:4

Add View against the action method name 'GetDepartmentLocationList' and put the code given bellow.

View
GetDepartmentLocationList.cshtml

@using PagedList;
@using PagedList.Mvc;
@model IPagedList<MVCContactBook.Sp_Get_DepartmentList_Result>
@{
    ViewBag.Title = "GetDepartmentLocationList";
}

<script src="~/Scripts/jquery-3.1.1.js"></script>
    <script src="~/Scripts/bootstrap.min.js"></script>
    <script>
        $(document).ready(function () {
            hideColumn = function (column) {
                $('tr').each(function () {
                    $(this).find('td,th').eq(column).hide();
                });
            };
            hideColumn(0);

        });
    </script>


<h2>Department Location List</h2>

<p>
    @Html.ActionLink("Create New", "AddNewLocation")
</p>

 <div id="no-more-tables">
<table  class="col-md-12 table-bordered table-striped table-condensed cf">
     <thead class="cf" style="border: 1px solid #ccc;">
    <tr>
        <th  class="numeric">
            @*@Html.DisplayNameFor(model => model.LocationId)*@
        </th>
        <th  style="text-align:center;">
            
            @Html.ActionLink("Location", "GetDepartmentLocationList", new { sortOn ="LocationName", orderBy = ViewBag.OrderBy, pSortOn = ViewBag.SortOn })
        </th>
         <th style="text-align:center;">
            @Html.ActionLink("Address", "GetDepartmentLocationList", new { sortOn ="Address", orderBy = ViewBag.OrderBy, pSortOn = ViewBag.SortOn })
        </th>
         <th style="text-align:center;">
            @Html.ActionLink("City", "GetDepartmentLocationList", new { sortOn ="City", orderBy = ViewBag.OrderBy, pSortOn = ViewBag.SortOn })
        </th>
        <th style="text-align:center;">
            Pincode
        </th>
      
        <th style="text-align:center;">
            Country
        </th>
        <th>Edit</th>
        <th>Delete</th>
    </tr>
         </thead>
      <tbody style="border: 1px thin black">

         
@foreach (var item in Model)
{
    <tr>
        <td>
            @Html.DisplayFor(modelItem => item.LocationId)
        </td>
        <td style="text-align:center;">
            @Html.DisplayFor(modelItem => item.LocationName)
        </td>
        <td style="text-align:center;">
            @Html.DisplayFor(modelItem => item.Address)
        </td>
        <td style="text-align:center;">
            @Html.DisplayFor(modelItem => item.City)
        </td>
        <td style="text-align:center;">
            @Html.DisplayFor(modelItem => item.Pincode)
        </td>
      
        <td style="text-align:center;">
            @Html.DisplayFor(modelItem => item.CountryName)
        </td>
        <td style="text-align:center;">
            @Html.ActionLink(" ", "Edit", new { id = item.LocationId }, new { @class = "glyphicon glyphicon-edit", title = "Edit" }) 
            </td>

            <td style="text-align:center;">
            @Html.ActionLink(" ", "Delete", new { id = item.LocationId }, new { @class = "glyphicon glyphicon-trash", title = "Delete" })        
            
        </td>
    </tr>

}
          </tbody>
 </table>
    <div class="pagedList">
        @Html.PagedListPager(Model, page => Url.Action("GetDepartmentLocationList", new { page,
sortOn = ViewBag.SortOn, orderBy = ViewBag.OrderBy, pSortOn = ViewBag.SortOn }), PagedListRenderOptions.ClassicPlusFirstAndLast)
    </div>
   </div>

Monday 10 April 2017

jQuery attribute Selector

  • The [attribute] selector selects each element with the specified attribute.
Syntax

$('[attribute]')
$('[attribute="value"]')

Ex:
$('[title]') :-  Selects all elements that have title attribute.
$('div[title]'):-  Selects all div elements that have title attribute.
$('[title="divtitle"]') :-  Selects all elements that have title attribute value - divtitle.
$('div[title="divtitle"]') :-  Selects all div elements that have title attribute value - divtitle.
$('[title^='Ajay']') :- Selects  all elements with a title attribute value starting with "Ajay".
$("[title~='welcome']") :- Selects  all elements with a title attribute value containing the specific word "welcome".
$("[title*='welcome']") :- Selects all elements with a title attribute value containing the word "welcome".


$('[title]') :-  Selects all elements that have title attribute.

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>

<script type="text/javascript">
        $(document).ready(function () {
            $('[title]').css('border', '5px solid red');
        });
    </script>

  </head>
      <body>    
      <div title="dvTitle">
        DIV with Title
    </div>
    <br />
    <div title="dvTitle1">
        DIV with another Title
    </div>
      <span title="spanTitle">
        SPAN element
    </span>
    <p>I live in Mumbai.</p>
    </body>
</html>

output:



$('div[title]'):-  Selects all div elements that have title attribute.
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>

<script type="text/javascript">
        $(document).ready(function () {
            $('div[title]').css('border', '5px solid red');
        });
    </script>

  </head>
      <body>    
      <div title="dvTitle">
        DIV with Title
    </div>
    <br />
    <div title="dvTitle1">
        DIV with another Title
    </div>
      <span title="spanTitle">
        SPAN element
    </span>
    <p>I live in Mumbai.</p>
    </body>
</html>

output:

Thursday 6 April 2017

JQuery interview questions Part - 4

1. Ques: Write a code for get the text value of a selected option?

<select id="ddl">
   <option value="1">Employee</option>
   <option value="2">Manager</option>
   <option value="3">HR</option>
   <option value="4">Teacher</option>
</select>

Answer: $("#pcdsselect").val();


2. Ques: Write a code for check or unchecked a checkbox input or radio button?
Answer:
$('#pcds').attr('checked', true);
$('#pcds').attr('checked', false);


3. Ques: How do You disable or enable a form element?
Answer:
// Disable #pcds
$('#pcds').attr('disabled', true);
// Enable #pcds
$('#pcds').attr('disabled', false);


4. Ques: What is the Document Ready Event syntax ?
Answer:
$(document).ready(function(){

});

5. Ques: Write a code for hide method of different selector ?
Answer:
<p id="myherder" class="myherderclass">This is a paragraph Element in html.</p>

$(this).hide() -its  hides the current element.

$("p").hide() -its   hides all <p> elements.

$(".myherderclass").hide() -its  hides all elements with class="myherder".

$("#myherder").hide() - its  hides the element with id="myherder".


6. Ques: Explain the code syntax and example of  hide() and show() method in Jquery ?
Answer:
Syntax:  $(selector).hide(speed,callback);

Ex:
<p id="ParaId">This is a paragraph Element in html.</p>

$("#ParaId").click(function(){
    $("p").hide();
});

$("#ParaId").click(function(){
    $("p").show();
});

7. Ques: What are the use of jQuery toggle() method ?
Answer:
toggle() method just toggle between the hide() and show() methods in jQuery ?
Ex:
<script>
$(document).ready(function(){
    $("button").click(function(){
        $("p").toggle();
    });
});
</script>

Wednesday 29 March 2017

JQuery class Selectors

Class Selectors

  • class selector finds elements with a specific class.
  • period character use to find specific class.
  • In one page multiple controls or element have same class then select select all the element corresponding to that class.
Ex:  $(".cssclass")


<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script>
<script>
$(document).ready(function(){
    $("button").click(function(){
        $(".cssclass").hide();
    });
});
</script>
</head>
<body>

<p class="cssclass">This is a paragraph.</p>
<p class="cssclass">This is a paragraph.</p>
<p class="Param">This is another paragraph.</p>

<button>Click me</button>
</body>
</html>

Sunday 26 March 2017

JQuery Element Selectors

  • The Element Selectors selects all elements with the specific element name in html. 

ex:

$("element") 

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script>

$(document).ready(function()
{
    $("p").css("background-color", "red");
});
</script>
  </head>
      <body>
       <h1>Home</h1>
        <p class="intro">introduction </p>
        <p>I live in Mumbai.</p>
        <p>india is best country in the world.</p>

    Who is your favorite:
         <ul id="choose">
             <li>facebook</li>
             <li>whatapp</li>
             <li>twitter</li>
         </ul>
    </body>
</html>

OUTPUT:

jQuery id Selector

  • The id selector selects the element with specific id in html. 
  • It is work same as function as document.getelementbyid() in JavaScript
  • jQuery selectors start with the dollar sign and parentheses().

ex:
$("#id") 


<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
    $("#intro").css("background-color", "red");
});
</script>
</head>
<body>

<h1>Home</h1>
<p id="intro">This paragrap apply jquery css</p>
<p>This paragrap without css</p>
</body>
</html>


Output:


Saturday 25 March 2017

Insert, Update, Delete operation in MVC-4 with Entity Framework.

In This Session  I am going to describe Insert, Update, Delete operation in MVC-4 with Entity Framework.

Here I am using visual stdio 2012 (framework 4.5) , SQL server 2012 express and Entity Framework

So Lets start



Tuesday 21 March 2017

MVC interview questions Part-8

1. Ques: What is the strongly typed view in ASP.NET MVC? What are the main advantage of using strongly ?
Answer:
The view which bind with any model is called as strogly typed view. You  can bind any class as model to view.You can access model properties on  that view. You can use data associated with model to render controls.
You can bind custom types as well as primitive types like string, array, list etc.

public ActionResult View1()
{
  UserModel obj = new UserModel();
  return view(obj)
}

In view
  @Html.DisplayFor(modelItem => item.TotalWorkHours)

Again Main advantage of using strongly typed view is - You can same  object during posting view. So What ever values assigned to controls  associated models property. You can access in post action

Main advantage of using strongly typed view is -
  • You can use automatic scaffolding 
  • IntelliSense support 
  • Compile time type checking

2. Ques: What are the advantages of weak typing over strong typing?
Answer:
Weak Typing :
  • Requires less programing effort as the compiler or interpreter implicitly performs certain kinds of type conversions. So applications can be built in a rapid manner.
  • Fewer errors are caught at compile time. Many bugs are caught at run-time. Requires more discipline while coding.
Strong Typing:
  • Strong/Static types provide constraints which helps to catch errors during compile time
  • Strong typing provide more opportunities for performance enhancements
  • Strong typed code is easy to understand
  • Limits the developer programming expressiveness.
  • Application development go more slowly.

3. Ques:  What is UpdateModel() in mvc?
Answer:
UpdateModel() is a Controller helper method that attempts to bind a bunch of different input data sources (HTTP POST data coming from a View, QueryString values, Session variables/Cookies, etc.) to the explicit model object you indicate as a parameter.

UpdateModel method to fetch data from view to controller. UpdateModel is the method which is generics type and takes parameter of model type.


Monday 20 March 2017

ASP.NET interview questions Part-8

1. Ques: What are the difference between Web services and .Net Remoting ?
Answer:
Web services
  • Web Services are meant to be interoperable, meaning that they can be used across platforms. 
  • Web service create a Web service class derived from the System.Web.Services.WebService class and add the methods (functionality) with the WebMethod attribute. These methods can be invoked by sending HTTP requests using SOAP.
  • Web service create a proxy class for your Web service using either wsdl.exe utility or the Add Web Reference option in VS.NET. The Web service proxy hides all the network and marshaling plumbing from the application code, so using the Web service looks just like using any other local object
  • ASP.NET Web Services may be accessed using HTTP only.
  • Web Service is Stateless
Dot Net Remoting
  • The primary distinction is that .NET Remoting is only useful for .NET to .NET scenarios. 
  • the remote object is implemented in a class derived from System.MarshalByRefObject and MarshalByRefObject class provides the core foundation for enabling remote access of objects across application domains.
  • Remote object is confined to the application domain where it is created. In .NET remoting, a client doesn't call the methods directly; instead a proxy object is used to invoke methods on the remote object. Every public method that we define in the remote object class is available to be called from clients.
  • Remoting objects may be accessed over any protocol like TCP, SMTP, and HTTP. 
  • Remoting has support for both stateless and with-state environment, which is achieved using Singleton and Singlecall activation 

2. Ques:  What is the purpose of HTTP, SOAP in web-service ?
Answer:
HTTP(Hyper Text Transfer Protocol) is the set of slandered for the web requests. SOAP ( Simple Object Access Protocol) is the message format which is used to send and receive data in the specific message format in case of services.
Web Service transmits and receive the data in form of Message and each message should have some format so that it will be understandable by the browser and getting the responses in the same format. SOAP defines the common format of the messages which is XML format and understandably by all the technologies(as XML is platform independent).


3. Ques: What is  absolute expiration and sliding-time expiration ? What is the difference between them ?
Answer:
ASP.NET provides the functionality to create cache. It also provides the option to set the expiration time after which the cache would no longer be available. This is called "Time Based Expiration".
This expiration is of 2 types: 1. Absolute Expiration 2. Sliding ExpirationIn

Absolute Expiration the cache will be expired after a particular time irrespective of the fact whether it has been used or not in that time span. Whereas, in Sliding Time Expiration, the cache will be expired after a particular time only if it has not been used during that time span.The syntax to declare them are as follow:string cacheData = "Let's cache this data";
//Absolute Expiration Cache.Insert("AbsoluteCacheKey", cacheData, null,DateTime.Now.AddMinutes(1), System.Web.Caching.Cache.NoSlidingExpiration);
//Sliding Expiration Cache.Insert("SlidingExpiration", cacheData, null, System.Web.Caching.Cache.NoAbsoluteExpiration, TimeSpan.FromMinutes(1));

Ex: I have created the a string to be cache that can be any serialized data. In the absolute expiration you can see that it will expires after one minute whether its accessed or not. While in sliding expiration it will expire cache if cache is not accessed within specified time like one minute.

Absolute expiration
It will expire the entry after a set amount of time.

sliding-time expiration
It will expire the entry if it hasn't been accessed in a set amount of time.


4. Ques:  What are the important Namespaces in Asp.net ?
Answer:
Namespaces in Asp.net  given as
System.Web 
System.web namespace holds some basic ingredients which includes classes and built-in Objects like
  • Server
  • Application
  • Request
  • Response
And Classes used for managing
  • Cookies
  • Configuring page caching
  • Tracing Implementation
  • Retrieving Information of Web Server and client browser
System.Web.services 
The System.Web.services namespace is a initial point for creating the web services. It contains web service classes , which allow to create XML web services using Asp.Net . XML web services provides feature to exchange messages in loosely coupled environment. using protocol like SOAP , HTTP , XML .

Some classes are as
  • WebMethodAttribute
  • Webservice
  • WebServiceAttribute
  • WebServiceBindingAttribute
System.web.UI.WebControls 
he System.web.UI.WebControls namespace contains classes that provides to create web server controls on web pages. These controls run on the server so we can programmaticaly control elements
Some classes are as follows
  • Calendar
  • Check Box
  • Button
  • Base Data Bound Control
System.web.UI 
The System.web.UI namespace includes classes that allows to create server controls with data- binding functionality , which has ability to save view state of given control and pages (.aspx pages) .
Many of these types allows to support for controls System.web.UI .Html controls. It is a base class for all HTML ,Web, and User Controls. Every aspx pages comes under it. Control classes provides common set of functionslity

System.web.sessionstate
Session state management comes under The System.web.sessionstate namespace . That enable storage of data specific to a single client with in a web application on the server. Session state is ideal for sensitive data such as mailing address , credit card number , password , important numbers etc. Sesssion state can be used with clients that do not support cookies.

Some classes are as follows
  • HttpSessionState
  • HttpSessionStateContainer
  • SessionIDManager
  • SessionStateModule etc


5. Ques: What are different types of directives in .NET? Explain each of them .
Answer:
@Page
@Control
@Import
@Implements
@Register
@Assembly
@MasterType
@Output Cache
@PreviousPageType
@Reference
@Master

 @Page Directive
This directive use for page-specific attributes by the ASP.NET page parser and compiler. Can be included only in .aspx files and also define the page language used just like c#,VB etc.

<%@Page Language="C#" AutoEventWIreup="false" CodeFile="Default.aspx.cs" Inherits="_Default"%>

@Control
control-specific attributes used by the ASP.NET page parser and compiler. Can be included only in .ascx files.
This directive also define the view state of page. <%@ Control Language="VB" EnableViewState="false" %>

@Import
It is Explicitly imports a namespace into a page or user control. The Import directive cannot have more than one namespace attribute. To import multiple namespaces, use multiple @Import directives.Its helps in importing of files. <% @ Import Namespace="System.web" %>

@Register 
when we create a user control and you drag that user control onto your page then you will see the @Register directive. This directive registers your user control on the page so that the control can be accessed by the page.
<%@ Register TagPrefix="MayTag Namespace="MyName.MyNameSpace" Assembly="MyAssembly"%>

@Assembly 
The @Assembly Directive attaches assemblies to the page or an ASP.NET user control thereby all the assembly classes and interfaces are available to the class. 
 <%@ Assembly Name="MyAssembly" %>
 <%@ Assembly Src="MySource.vb" %>

@Previouspagetype
This directive specifies the page from which any cross-page posting originates.

@Implements
The @Implements Directive gets the ASP.NET pages to implement .Net framework interfaces. This directive only supports a single attribute interface.
<%@Implements Interface="System.Web.UI.IValidator"%>

@MasterType 
The @MasterType Directive connects a class name to the ASP.NET page for getting strongly typed references or members contained in the specified Master Page. This directive supports the two attributes Typename and virtualpath. Typename sets the name of the derived class from which to get the strongly typed or reference members and virtualpath sets the location of the page from which these are retrieved.
<%@MasterType VirtualPath="/MasterPage1.master"%>

@output cache
It controls the output caching policies of an ASP.NET page.
<%@ OutputCache Duration ="180" VaryByParam="None"%>