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"%>

Sunday 19 March 2017

HTML5 interview questions Part 2

1. Ques: What are the new APIs provided by the HTML5  standard ?
Answer:
The HTML 5 standard comes with a new APIs.
  • Media API
  • Text Track API
  • Application Cache API
  • User Interaction
  • Data Transfer API
  • Command API
  • Constraint Validation API
  • History API

2. Ques:  How can  use Audio in HTML5 ?
Answer:
 HTML5 embedding audio files following way. Supported audio formats are MP3, Wav and Ogg.
<audio controls>
  <source src="moviessong.mp3" type="audio/mpeg">
  <embed height="60" width="100" src="horse.mp3">
</audio>


3. Ques:  How can  use Video in HTML5 ?
Answer:
 HTML5 embedding Video files following way. Supported video formats are MP4, WebM and Ogg.
<video width="500" height="400" controls>

  <source src="movies.mp4" type="video/mp4">

  Your browser does'nt support video embedding feature.

</video>




4. Ques: What are “web workers”  in  HTML5?
Answer:
A web worker is a script that runs in the background (i.e., in another thread) without the page needing to wait for it to complete. The user can continue to interact with the page while the web worker runs in the background. Workers utilize thread-like message passing to achieve parallelism.
Unlike JavaScript the Web worker doesn't interrupt the user and the web page remain responsive because they are running tasks in the background.


5. Ques: What is use of HTML Canvas?
Answer:
The HTML <canvas> element is used to draw graphics, on the fly, via JavaScript.
The <canvas> element is only a container for graphics. You must use JavaScript to actually draw the graphics.
Canvas has several methods for drawing paths, boxes, circles, text, and adding images.
Ex:
<canvas id="newcanvas" width="300" height="100"></canvas>


6. Ques: What is a SVG?
Answer:
SVG stands for Scalable Vector Graphics and it is a language for describing 2D-graphics and graphical applications in XML and the XML is then rendered by an SVG viewer. SVG is mostly useful for vector type diagrams like Pie charts, Two-dimensional graphs in an X,Y coordinate system etc.

Scalable Vector Graphics (SVG) is an XML-based vector image format for two-dimensional graphics with support for interactivity and animation. The SVG specification is an open standard developed by the World Wide Web Consortium (W3C) since 1999. SVG images and their behaviors are defined in XML text files.


7. Ques: What is the difference between Canvas and SVG?
Answer:
 Difference between Canvas and SVG given as
Canvas 
  • Canvas draws 2D graphics, on the fly (with a JavaScript). 
  • Canvas is a javascript API for drawing vector graphics to a bitmap of a specific size.
  • Pixel based (Dynamic .png)
  • Single HTML element.(Inspect element in Developer tool. You can see only canvas tag)
  • Modified through script only
  • Event model/user interaction is granular (x,y)
  • Performance is better with smaller surface, a larger number of objects (>10k), or both
SVG
  • SVG is XML based, which means that every element is available within the SVG DOM. You can attach JavaScript event handlers for an element. In SVG, each drawn shape is remembered as an object.
  • SVG is a document format for scalable vector graphics.
  • Shape based
  • Multiple graphical elements, which become part of the DOM
  • Modified through script and CSS
  • Event model/user interaction is abstracted (rect, path)
  • Performance is better with smaller number of objects (<10k), a larger surface, or both

8. Ques: What are the new input attributes in HTML5 ?
Answer:
Below are the new input attributes in HTML5 
  • AutoFocus
  • Form
  • FormMethod
  • FormNoValidate
  • Height and Width
  • Min and Max
  • Placeholder
  • Required

9. Ques: What methods are used to draw straight line using canvas?
Answer:
Below are the list of methods used to draw straight line 
  • moveTo(a,b)
  • lineTo(a,b)
  • stroke()

10. Ques: What is HTML5 Application Cache ?
Answer:
HTML5 introduces application cache, which means that a web application is cached, and accessible without an internet connection.
Application cache gives an application three advantages:
  • Offline browsing - users can use the application when they're offline
  • Speed - cached resources load faster
  • Reduced server load - the browser will only download updated/changed resources from the server

Saturday 18 March 2017

C# basic interview questions Part-8

1. Ques: What is the Environment Class in C#? 
Answer:
The System.Environment Class provides information about the current environment and platform. The System.Environment Class uses to retrieve Environment variable settings, Version of the common language runtime, contents of the call stack etc. This class cannot be inherited.

The Environment class use for getting and setting various operating system related information. You can use this class to retrieve information such as command-line arguments, exit codes, environment variable settings, contents of the call stack, time since last system boot in milliseconds (tick count), and version of the CLR.


2. Ques: What is an Exception in C#?
Answer:
 An exception is an error that occurs during program execution. Generally, an exception describes an unexpected event.

  • The advantage of using exceptions is that the program doesn’t terminate due to the occurrence of the exception.
  • Whenever an exception is occurred the .NET runtime throws an object of specified type of Exception.
  • The class ‘Exception’ is the base class of all the exceptions.

Exception handling is an in built mechanism in .NET framework to detect and handle run time errors. The .NET framework contains lots of standard exceptions. The exceptions are anomalies that occur during the execution of a program. They can be because of user, logic or system errors. If a user (programmer) do not provide a mechanism to handle these anomalies, the .NET run time environment provide a default mechanism, which terminates the program execution.

Here are a few common types of exceptions:

System.NullReferenceException Handles errors generated from deferencing a null object.
System.DivideByZeroException Handles errors generated from dividing a dividend with zero.
System.InvalidCastException  Handles errors generated during typecasting.


3. Ques:  What is the difference between system exceptions and application ?
Answer:
 System.SystemException -> This class is for exceptions that r usually thrown by the .net run time, or which r considered to be of a generic nature and must be thrown by almost any application. For example, StackOverflowException will be thrown by the .net run time if it detects the stack is full.

 System.ApplicationException-> This class is important, because it is the intended base for any class of exception defined by third parties. Hence, if u define any exceptions covering error conditions unique to your application, u should derive these directly or indirectly from System.ApplicationException.


4. Ques:  What is the difference between object pooling and connection pooling ?
Answer:
  • object pool implementation will increase the size of the pool up to the specified maximum. When the maximum is reached, unlike the example above, instead of throwing an exception, it makes the client wait until an object is returned to the pool, and then gives the newly returned object to the waiting client.
  • Connection pool implementation does not have a maximum size parameter - it will keep creating new connections to meet demand (eventually it will hit some system limit and the request will fail in some way that isn't specified).
  • With object pooling, you maintain a pool of objects in memory.
  • Connection pooling does the same thing with connections to a database.

5. Ques:  What is Extension methods in C# ? What is Benefits of extension methods ?
Answer:
Extension methods enable you to add methods to existing types without creating a new derived type, recompiling, or otherwise modifying the original type. An extension method is a special kind of static method, but they are called as if they were instance methods on the extended

An extension method is a static method of a static class, where the "this" modifier is applied to the first parameter. The type of the first parameter will be the type that is extended.
Extension methods are only in scope when you explicitly import the namespace into your source code with a using directive.

Important points for the use of extension methods are given as
  • An extension method must be defined in a top-level static class.
  • An extension method with the same name and signature as an instance method will not be called.
  • Extension methods cannot be used to override existing methods.
  • The concept of extension methods cannot be applied to fields, properties or events.
  • Overuse of extension methods is not a good style of programming.
Benefits of extension methods
  • Extension methods allow existing classes to be extended without relying on inheritance or having to change the class's source code.
  • If the class is sealed than there in no concept of extending its functionality. For this a new concept is introduced, in other words extension methods.
  • This feature is important for all developers, especially if you would like to use the dynamism of the C# enhancements in your class's design.

6. Ques:  What is Marshalling?
Answer:
Marshaling is the process of creating a bridge between managed code and unmanaged code; it is the homer that carries messages from the managed to the unmanaged environment and reverse. It is one of the core services offered by the CLR (Common Language Runtime.)


7. Ques:  What is difference between Serialization and Marshaling ?
Answer:
Serialization
Serialization is the process of converting a data structure or object into a sequence of bits so that it can be stored in a file, a memory buffer, or transmitted across a network connection to be "resurrected" later in the same or another computer environment. And this sequence of bits can be of any format the user chooses; however, they are usually formed as XML or binary.

Serialization comes in many forms in .NET Framework, it can be observed in ADO.NET, Web services, WCF services, Remoting, and others.

For example, calling the WriteXml() function of a DataSet serializes this DataSet into a XML file.

ds.WriteXml("data.xml");

Marshaling
Marshaling is the process of converting managed data types to unmanaged data types. There're big differences between the managed and unmanaged environments. One of those differences is that data types of one environment is not available (and not acceptable) in the other.

For example, you can't call a function like SetWindowText() -that sets the text of a given window- with a System.String because this function accepts LPCTSTR and not System.String. In addition, you can't interpret (handle) the return type, BOOl, of the same function, that's because your managed environment (or C# because of the context of this writing) doesn't have a BOOL, however, it has a System.Boolean.


8. Ques:  What are the New Features in C# 6.0 ?
Answer:
The New Features in C# 6.0 listed bellow
  • using Static.
  • Auto property initializer.
  • Dictionary Initializer.
  • nameof Expression.
  • New way for Exception filters.
  • await in catch and finally block.
  • Null – Conditional Operator.
  • Expression – Bodied Methods
  • Easily format strings – String interpolation

9. Ques:  What is Dynamic language runtime (DLR) in Dot net ?
Answer:
The dynamic language runtime (DLR) is a runtime environment that adds a set of services for dynamic languages to the common language runtime (CLR). The DLR makes it easier to develop dynamic languages to run on the .Net Framework and to add dynamic features to statically typed languages."

The dynamic language runtime (DLR) is a runtime environment that adds a set of services for dynamic languages to the common language runtime (CLR). The DLR makes it easier to develop dynamic languages to run on the .NET Framework and to add dynamic features to statically typed languages.
Dynamic languages can identify the type of an object at run time, whereas in statically typed languages such as C# and Visual Basic (when you use Option Explicit On) you must specify object types at design time. Examples of dynamic languages are Lisp, Smalltalk, JavaScript, PHP, Ruby, Python, ColdFusion, Lua, Cobra, and Groovy.

Advantages of dynamic languages 
  • The ability to use a rapid feedback loop (REPL, or read-evaluate-print loop). This lets you enter several statements and immediately execute them to see the results.
  • Support for both top-down development and more traditional bottom-up development. For example, when you use a top-down approach, you can call functions that are not yet implemented and then add underlying implementations when you need them.
  • Easier refactoring and code modifications, because you do not have to change static type declarations throughout the code.

10. Ques: What is type-safe in .net?
Answer:
Type-safe code accesses only the memory locations it is authorized to access. For example, type-safe code cannot read values from another object's private fields. It accesses types only in well-defined, allowable ways.

During just-in-time (JIT) compilation, an optional verification process examines the metadata and Microsoft intermediate language (MSIL) of a method to be JIT-compiled into native machine code to verify that they are type safe. This process is skipped if the code has permission to bypass verification

Verification of type safety is not mandatory to run managed code, type safety plays a crucial role in assembly isolation and security enforcement. When code is type safe, the common language runtime can completely isolate assemblies from each other. This isolation helps ensure that assemblies cannot adversely affect each other and it increases application reliability.

Friday 17 March 2017

Linq interview questions Part-2

1. Ques: What is difference between IEnumerable and IQueryable ?
Answer:
Difference between IEnumerable and IQueryable
IEnumerable
  • IEnumerable exists in System.Collections Namespace.
  • IEnumerable can move forward only over a collection, it can’t move backward and between the items.
  • IEnumerable is best to query data from in-memory collections like List, Array etc.
  • While query data from database, IEnumerable execute select query on server side, load data in-memory on client side and then filter data.
  • IEnumerable is suitable for LINQ to Object and LINQ to XML queries.
  • IEnumerable supports deferred execution.
  • IEnumerable doesn’t supports custom query.
  • IEnumerable doesn’t support lazy loading. Hence not suitable for paging like scenarios.
  • Extension methods supports by IEnumerable takes functional objects.
IQueryable
  • IQueryable exists in System.Linq Namespace.
  • IQueryable can move forward only over a collection, it can’t move backward and between the items.
  • IQueryable is best to query data from out-memory (like remote database, service) collections.
  • While query data from database, IQueryable execute select query on server side with all filters.
  • IQueryable is suitable for LINQ to SQL queries.
  • IQueryable supports deferred execution.
  • IQueryable supports custom query using CreateQuery and Execute methods.
  • IQueryable support lazy loading. Hence it is suitable for paging like scenarios.
  • Extension methods supports by IQueryable takes expression objects means expression tree.

2. Ques: What is the difference between Linq to Object and Linq to SQL ?
Answer:
LINQ to Objects queries operate on IEnumerable collections. The query iterates through the collection and executes a sequence of methods (for example, Contains, Where etc) against the items in the collection. 

LINQ to SQL queries operate on IQueryable collections. The query is converted into an expression tree by the compiler and that expression tree is then translated into SQL and passed to the database. 


3. Ques: What is the difference between First() and Single() extension methods in LINQ ?
Answer:
First(): Use Single to retrieve the first (and only) element from a sequence that should contain one element and no more. If the sequence has more than on element your invocation of Single will cause an exception to be thrown since you indicated that there should only be one element.

Single(): Use First to retrieve the first element from a sequence that can contain any number of elements. If the sequence has more than on element your invocation of First will not cause an exception to be thrown since you indicated that you only need the first element in the sequence and do not care if more exist.


4. Ques: What are Quantifiers in Linq ?
Answer:
 Quantifier Operators return the Boolean value (either True or false) if some or all the elements in a sequence satisfy a condition.

1)All
2)Any
3)Contains
4)SequenceEqual

example:
int[] arr={10,20,30};
var b=arr.All(a=>a>20);


5. Ques:  What are the different implementations of LINQ ?
Answer:
Following are the different implementations of LINQ:

LINQ to SQL : This component was introduced in .Net framework version 3.5 that gives a run-time mechanism to manipulate relational data as objects.

LINQ to DataSet : This component facilitates to run simpler and faster query over data which is cached in the DataSet object.

LINQ to XML : Provides an in-memory XML programming interface.

LINQ to Objects : It provides the use of LINQ queries with any IEnumerable or IEnumerable(T)collection directly, without the use of an middle LINQ provider or API, like LINQ to SQL or LINQ to XML.


6. Ques:  What is DataContext class ?
Answer:
The DataContext class is a LINQ to SQL class that acts as a conduit between a SQL Server database and the LINQ to SQL entity classes mapped to that database. This class contains the connection string information and the methods for connecting to a database and manipulating the data in the database. It is configured with connection information provided by the first item that is dragged onto the design surface.

DataContext class performs the following three tasks:
  • Create connection to database.
  • It submits and retrieves object to database.
  • Converts objects to SQL queries and vice versa.

7. Ques:  What is a LinqDataSource control?
Answer:
The LinqDataSource control enables you to use LINQ. in an ASP.NET Web page by setting the properties in the markup text. You can use the control retrieve or modify data. It is similar to the SqIDataSource andObjectDataSource controls in the sense that it can be used to declaratively bind other ASP.NET controls on a page to a data source. The difference is that instead of binding directly to a database or to a generic class, theLinqDataSource control is designed to bind a LINQ enabled data model.


8. Ques: What is Action in LINQ?
Answer:
Action are generic delegates provided by base class library of .NET. In Action delegate we can only store those methods that have only input parameters and void return types. We can specify upto 16 parameters.
Below is the example of Action delegate:

func f1 = (a, b) => a + b;

Action<int> printAction = (a) => Console.WriteLine(a);
printAction(f1(1, 3));


9. Ques: What is Predicate delegate in LINQ ?
Answer:
Predicate is a feature that returns true or false.This concept has come in .net 2.0 framework. Predicate is a delegated provided by base class library of NET.
In Predicate delegate we can only store those method which have one input parameter and a bool return type.
Predicate delegates are mainly used in filtering scenarios in LINQ where we have to filter some list.
It is being used with lambda expression (=>). It takes generic type as an argument.
It allows a predicate function to be defined and passed as a parameter to another function

 Example of Predicate delegate given bellow

Predicate<string> isStringStartWithMChar = (a) => a.StartsWith("m");
Console.WriteLine(isStringStartWithMChar("msmd"));


10. Ques:  What is Func Delegates ?
Answer:
Func delegates are pointers to methods that take one or more parameters and must return a value. There are many overloaded Func delegates. Please see the documentation for a better understanding of those. In this article let's have a general idea of how to use it programmatically.

Usage
  Generelly it's used with anonymous methods.
Example:
Func<int, int, int, long> add = delegate(int a, int b, int c) { return a + b + c; };
 Console.WriteLine(add(2, 3, 4)); 

Thursday 16 March 2017

Linq interview questions Part-1

1. Ques: What is LINQ ? What are the types of LINQ ?  What are the Advantages and Disadvantages of LINQ ?
Answer:
LINQ stands for Language Integrated Query, is the collection of standard query operators which provides query facilities into.NET framework language like C#, VB.NET.

Types of  LINQ  are 
  • LINQ to Objects
  • LINQ to XML
  • LINQ to Dataset
  • LINQ to SQL
  • LINQ to Entities
Advantages
  • Quick turn around for development
  • Queries can be dynamically
  • Tables are automatically created into class
  • Columns are automatically created into properties
  • Relationship are automatically appeaded to classes
  • Lambda expressions are awesome
  • Data is easy to setup and use
Disadvantages
  • No clear outline for Tiers
  • No good way of view permissions
  • Small data sets will take longer to build the query than execute
  • There is an overhead for creating queries
  • When queries are moved from sql to application side, joins are very slow
  • DBML concurrency issues

2. Ques: What are Lambda expressions ? 
Answer:
A lambda expression is an anonymous function that can contain expressions and statements, and can be used to create delegates or expression tree types. 
All lambda expressions use the lambda operator =>, which is read as "goes to". The left side of the lambda operator specifies the input parameters (if any) and the right side holds the expression or statement block. 

The => operator has the same precedence as assignment (=) and is right-associative. 

Lambdas are used in method-based LINQ queries as arguments to standard query operator methods such as Where and Where(IQueryable, String, array[]).

Ex:
class Program
  {
     delegate int del(int i);
     static void Main(string[] args)
     {
        del myDelegate = y => y * y;
        int j = myDelegate(5);
        Console.WriteLine(j);
        Console.ReadLine();
     }
  }


3. Ques:  What is PLINQ?
Answer:
PLINQ stands for Parallel Language Integrated Query. It is the parallel implementation of LINQ, in which a query can be executed by using multiple processors. PLINQ ensures the scalability of software on parallel processors in the execution environment. It is used where data grows rapidly, such as in telecom industry or where data is heterogeneous.

PLINQ also supports all the operators of LINQ. In addition, you can query 'collections by using PLINQ. It can also run several LINQ queries simultaneously and makes use of the processors on the system. Apart from this, PLINQ uses parallel execution, which helps in running the queries quickly. Parallel execution provides a major performance improvement to PLINQ over certain types of legacy code, which takes too much time to execute.


4. Ques:  What is the difference between the Take and Skip clauses?
Answer:
Take clauses
The Take clause will give you a predefined number of elements.
if you want to return two elements from an array then you can use Take clause.

Skip clauses
The Skip clause will skip the predefined number of elements in the query and returns the remaining elements.
if you want to skip first five strings in an array of strings and want to retrieve the remaining string then you can use Skip clause.


5. Ques:  What is the difference between the Select clause and SelectMany() method in LINQ?
Answer:
Difference between the Select clause and SelectMany clause given as
 Select clause
  • Select operator is used to select value from a collection and 
  • Select operator produce one result value for every source value 
Select Many 
  • SelectMany operator is used to select values from a collection of collection i.e. nested collection.
  • SelectMany produce a single result that contains a concatenated value for every source value.
  • Actually, SelectMany operator flatten IEnumerable<IEnumerable<T>> to IEnumrable<T> i.e. list of list to list.

6. Ques: What are the advantages of LINQ over stored procedure?
Answer:
Advantages of LINQ over stored procedure?

  • Debugging – LINQ supports .Net debugger, so we can easily debug a LINQ query using .NET debugger but it is not supported by SQL stored procedure so it is hard to debug the stored procedure.
  • Deployment – To deploy stored procedure it is necessary to write one more script to run them, while LINQ will complie by a single DLL statement and so the deployment will be simple.
  • Type Safety - As LINQ supports type safety so errors can be type checked in LINQ queries in compile time.It is better to use LINQ as it enable us to identify the errors while compilation rather than runtime execution.

7. Ques: What is the difference between first() and single() extension methods in linq ?
Answer:

First()
It returns First element value from collection of elements or a sequence. It also returns first element of sequence when you specified condition. If result has no element than it will throws InvalidOperationException.

FirstOrDefault( )
FirstOrDefault()  is just like First() except that, if no element match the specified condition than it returns default value of underlying type of generic collection. It does not throw InvalidOperationException if no element found. But collection of element or a sequence is null than it throws an exception.


8. Ques: What is difference between LINQ and Stored Procedures?
Answer:

  • Stored procedures normally are faster as they have a predictable execution plan. Therefore, if a stored procedure is being executed for the second time, the database gets the cached execution plan to execute the stored procedure.
  • LINQ supports type safety against stored procedures.
  • LINQ supports abstraction which allows framework to add additional improvements like multi threading. It’s much simpler and easier to add this support through LINQ instead of stored procedures.
  • LINQ allows for debugging using .NET debugger, which is not possible in case of stored procedures.
  • LINQ supports multiple databases against stored procedures which need to be re-written for different databases.
  • Deploying LINQ based solution is much simpler than a set of stored procedures

SQL Server interview question Part 7

1. Ques: What is BCP utility in SQL SERVER ?
Answer:
BCP (Bulk Copy Program) is a command line utility by which you can import and export large amounts of data in and out of SQL SERVER database.
 With BCP, you can import and export large amounts of data in and out of SQL Server databases quickly and easily.

We can run a bcp command (along with the appropriate arguments) at a Command Prompt window. The command should conform to the following syntax:

bcp {table|view|"query"}
    {out|queryout|in|format}
    {data_file|nul}
    {[optional_argument]...}

As you can see, a bcp command requires three arguments. The first (table|view|“query”) represents the data source or destination in a SQL Server database. You can use the bcp utility to export data from a table or view or through a query. If you specify a query, you must enclose it in quotation marks. In addition, you can import data into a table or view. If you import into a view, all columns within the view must reference a single table.

out: The command exports data from a table or view into a data file.
queryout: The command exports data retrieved through a query into a data file.
in: The command imports data from a data file into a table or view.
format: The command creates a format file based on a table or view.


2. Ques: What is SQL Server log shipping? what are the Advantages and disadvantages of log shipping ?
Answer:
log shipping is a technique which involves two or more SQL Server instances and copying of a transaction log file from one SQL Server instance to another. The process of transferring the transaction log files and restoring is automated across the SQL Servers. As the process result there are two copies of the data on two separate locations

A log shipping session involves the following steps:

Backing up the transaction log file on the primary SQL Server instance
Copying the transaction log backup file across the network to one or more secondary SQL Server instances
Restoring the transaction log backup file on the secondary SQL Server instances


Advantages and disadvantages of using SQL Server log shipping

SQL Server log shipping is primarily used as a disaster recovery solution. Using SQL Server log shipping has multiple benefits: it’s reliable and tested in details, it’s relatively easy to set up and maintain, there is a possibility for failover between SQL Servers, data can be copied on more than one location etc.

Log shipping can be combined with other disaster recovery options such as AlwaysOn Availability Groups, database mirroring, and database replication. Also, SQL Server log shipping has low cost in human and server resources

The main disadvantages in the SQL Server log shipping technique are: need to manage all the databases separately, there isn’t possibility for an automatic failover, and secondary database isn’t fully readable while the restore process is running

Wednesday 15 March 2017

WPF interview question Part 3

1. Ques: What are the difference Between WPF and Silverlight ?
Answer:
  • Silverlight is simply a subset of WPF.
  • Silverlight is meant to be used online, while WPF is for local use.
  • You can use Silverlight applications regardless of the operating system you use, while WPF applications are restricted to later versions of the Windows operating system.
  • Silverlight lacks access to local resources, while WPF can utilize local resources.
  • Silverlight only has perspective 3D support, while WPF is capable of full 3D images.
  • WPF you can create Windows App, Navigation app and XBAP (IE based) application With Silverlight you can create only XAP (Browser based application.).
  • WPF supports 3 types of routed events (direct, bubbling, and tunneling). Silverlight supports direct and bubbling only.
  • Silveright does not support MultiBinding.
  • Silverlight supports the XmlDataProvider but not the ObjectDataProvider. WPF supports both.


2. Ques: What is use of resources in WPF  ? How many types of resources in WPF ?
Answer:
Resources in WPF allow you to set the properties of multiple controls at a time. For example you can set the background property on several elements in a WPF application using a single resource.

There are two types of resource in wpf 
Static Resource
Dynamic Resource

Static Resource:The value of StaticResource is determined at the time of loading.

Ex: in Window1.xaml file inside the Grid

<Grid.Resources>
            <SolidColorBrush x:Key="lblbgcolor" Color="Blue"/>
</Grid.Resources>
       <Label Name="lbl" Margin="71,44,77,0" Background="{StaticResource lblbgcolor}" Height="49" />


Dynamic Resource: Dynamic Resource we use in a situation where we want to change the value of property at run time.
EX:  Window1.xaml file inside 
<Window.Resources>
        <SolidColorBrush x:Key="brush" Color="Red" />
</Window.Resources>
    <Button x:Name="btn" Content="Click Me" Click="Button_Click" Background="{DynamicResource brush}" Height="100" Width="100" />

In Code behind
private void Button_Click(object sender, RoutedEventArgs e)
{
    this.btn.SetResourceReference(BackgroundProperty, "brush");
}


3. Ques: What is the INotifyPropertyChanged Interface?
Answer:
The INotifyPropertyChanged interface is used to notify clients, typically binding clients, that a property value has changed.

For example, consider a Person object with a property called FirstName. To provide generic property-change notification, the Person type implements the INotifyPropertyChanged interface and raises a PropertyChanged event when FirstName is changed.


4. Ques: What are the Advantages of dependency properties in WPF ?
Answer:
Advantages of a Dependency Property given bellow

Less memory consumption
The Dependency Property stores the property only when it is altered or modified. Hence a huge amount of memory for fields are free.

Property value inheritance 
It means that if no value is set for the property then it will return to the inheritance tree up to where it gets the value.

Change notification and Data Bindings
Whenever a property changes its value it provides notification in the Dependency Property using INotifyPropertyChange and also helps in data binding.

Participation in animation, styles and templates 
A Dependency Property can animate, set styles using style setters and even provide templates for the control.

CallBacks 
Whenever a property is changed you can have a callback invoked.

Resources 
You can define a Resource for the definition of a Dependency Property in XAML.

Overriding Metadata 
You can define certain behaviors of a Dependency Property using Property Metadata. Thus, overriding a metadata from a derived property will not require you to redefine or re-implement the entire property definition.


5. Ques:  What are the core WPF assemblies?
Answer:
The core WPF assemblies are
  • WindowsBase.dll: This is the core types constituting the infrastructure of WPF API.
  • PresentationCore.dll: It defines numerous types constituting foundation of WPF GUI layer.
  • PresentationFoundation.dll: It defines WPF control types, animation & multimedia support, databinding suport and other WPF services.
  • Besides these three libraries WPF also uses an unmanaged binary called milcore.dll which acts as abridge between WPF assemblies and DirectX runtime laye

6. Ques: What are the types of binding in WPF?
Answer:
There are four types of data binding modes in WPF.
One-Way
Two-Way
OneWayToSource
OneTime

OneWay: The target property will listen to the source property being changed and will update itself. If you programmatically change the ViewwModel's UserName property, it will reflect in the text box. This is of intermediate cost as the binding system watches only Source for changes.

TwoWay: The target property will listen to the source property being changed and will update itself. AND The source property will listen to the target property being changed and will update itself. Both the TextProperty and the UserName property will remain in sync and will update each other if one changes. This is most costly as the binding system has to watch both sides for change.

OneWayToSource: The Source property will change if the target property is changed. If the user changes the TextProperty, the UserName property will take up the changed value. This again is of intermediate cost as the binding system watches only Target for changes.

OneTime: This happens only once during the lifetime of Binding, the Target property will be updated with the Source property when the Binding happens. This is least costly and is advisable for scenarios where you have static data to be shown e.g. Label, TextBlock etc.


7. Ques: What are Triggers and its type in WPF?
Answer:
The WPF styling and templating model enables you to specify Triggers within your Style.
Triggers are objects that enable you to apply changes when certain conditions (such as when a certain property value becomes true, or when an event occurs) are satisfied.

There are three types of trigger in wpf
  • Property triggers 
  • Data triggers 
  • Event triggers
Types of triggers:
1) Property triggers get active when a property gets a specified value.
2) Data triggers get active when a specified event is fired.
3) Event triggers get active when a binding expression reaches a specified value.


8. Ques:  How to Creating Windows Forms Controls Dynamically in WPF ?
Answer:
Step to Creating Windows Forms Controls Dynamically

1.)Import the following namespaces:
     using System.Windows.Forms;
     using System.Windows.Forms.Integration;

2) Create the windows forms control and set its properties and event handlers.
3) Add the control to the 'Child' property of 'WindowsFormsHost' object.
4) Add the host object to the 'Children' collection of the panel.

HTML5 interview questions Part 1

1. Ques: What is HTML5?
Answer:
HTML5 is the latest version of Hypertext Markup Language, the code that describes web pages. It's actually three kinds of code: HTML, which provides the structure; Cascading Style Sheets (CSS), which take care of presentation; and JavaScript, which makes things happen.

HTML5 has new features like Drawing, Animation, Video and Audio etc. It is used to solve some common structural problems encountered with HTML 4.1. It gives more flexibility to both the web developers, the web designers and enables more exciting and interactive websites in addition to more powerful and efficient applications.

HTML5 brings a whole new dimension to the web world. It can embed video on the web-pages without using any special software like Flash. Firefox, Chrome, Opera, Safari and Internet Explorer all support <! doctype html>.


2. Ques:  What are the new features in HTML5 ?
Answer:
Following are new features in HTML5
  • Local storage.
  • New form controls like calendar, date, time, email, URL and search etc.
  • canvas element is provided for 2D drawing.
  • video and audio elements for media playback.
  • New elements are provided. For e.g. article, header, footer, nav, section.

3. Ques: What are the various elements provided by HTML5 for media content?
Answer:
audio - It defines sound content.
video - It defines a video. 
source - This tag defines the source of video and audio.
embed - It provides a container for an external application. 
track - It defines text tracks for video and audio.


4. Ques:  What are the diffrent types of storage in html5 ?
Answer:
HTML5 offers two new objects for storing data on the client

LocalStorage – stores data with no time limit
<script type=“text/javascript”>
localStorage.lastname=“ZAG”;
document.write(localStorage.lastname);
</script>
SessionStorage – stores data for one session.The data is deleted when the user closes the browser window.
<script type=“text/javascript”>
sessionStorage.lastname=“ZAG”;
document.write(sessionStorage.lastname);
</script>


5. Ques: Differentiate between Canvas and SVG ?
Answer:
Differences between Canvas and SVG are given bellow

  • Canvas is resolution dependent while SVG is not.
  • Canvas does not provide any support for event handlers while SVG does.
  • Canvas is suitable for graphic-intensive games while SVG is not suitable for gaming.
  • Canvas is suitable for small rendering areas while SVG is suitable for large rendering areas like Google maps.

6. Ques: What are the new input types provided by HTML 5 for forms ?
Answer:
New input types for forms provided by HTML 5 are given bellow

  • color – Used for fields that should contain color.
  • date – Allows the user to select a date.
  • datetime - Allows the user to select a date and time (with time zone).
  • datetime-local - Allows the user to select a date and time (without time zone).
  • email - Used for input fields that should contain an e-mail address.
  • month - Allows the user to select a month and year.
  • number - Used for input fields that should contain a numeric value. Restrictions on type of numbers accepted can be set.
  • range - Used for input fields that should contain a value from a range of numbers. Restrictions on type of numbers accepted can be set here as well.
  • search - Used for search fields.
  • tel - Defines a field for entering a telephone number.
  • time - Allows the user to select a time.
  • url - Used for input fields that should contain a URL address.
  • week - Allows the user to select a week and year.


7. Ques: What is HTML5 Web Storage?
Answer:
With HTML5, it is possible for the web pages to store the data locally in the user's browser. This web storage is much faster and secured than the cookies. Also, a larger amount of data can be stored without causing any adverse effect to the performance of the website.
The data here is not included with every server request. It is used ONLY when it is asked for. It is only that particular web page that can access the data stored by itself.


8. Ques: What is the use of Canvas element in HTML5?
Answer:
The canvas element is used to draw graphics by making use of JavaScript. It is defined with the <canvas> tag. We write the following code.
This tag is nothing but a container for graphics. We need to use a script to provide the structure or shapes of the graphics.

We can have multiple Canvas elements in one HTML page.
The real power of the Canvas element is the scripting for which use JavaScript.
For the complete functionality of the HTML5 Canvas tag, we require an API which is made by writing JavaScript code that provides access to Canvas element functionality.

Tuesday 14 March 2017

MVC interview questions Part 7

1. Ques: What is the Entity Framework in .NET ?
Answer:
Entity Framework (EF) is an object-relational mapper that enables .NET developers to work with relational data using domain-specific objects. It eliminates the need for most of the data-access code that developers usually need to write.
                                                               OR

Entity framework is an Object/Relational Mapping (O/RM) framework. It is an enhancement to ADO.NET that gives developers an automated mechanism for accessing & storing the data in the database.

Entity framework is useful in three scenarios. First, if you already have existing database or you want to design your database ahead of other parts of the application. Second, you want to focus on your domain classes and then create the database from your domain classes. Third, you want to design your database schema on the visual designer and then create the database and classes.

The following figure illustrates the above scenarios.

 Entity Framework overview
As per the above figure, EF creates data access classes for your existing database, so that you can use these classes to interact with the database instead of ADO.Net directly.

EF can also create the database from your domain classes, thus you can focus on your domain-driven design.

EF provides you a model designer where you can design your DB model and then EF creates database and classes based on your DB model.

2. Ques:  Explain the entity framework architecture ?
Answer:
The architecture  of  Entity Framework given bellow . Let discuss  the components of the architecture individually:


Entity Framework Architecture
EDM (Entity Data Model): EDM consists of three main parts - Conceptual model, Mapping and Storage model.

Conceptual Model: The conceptual model contains the model classes and their relationships. This will be independent from your database table design.

Storage Model: Storage model is the database design model which includes tables, views, stored procedures, and their relationships and keys.

Mapping: Mapping consists of information about how the conceptual model is mapped to the storage model.

LINQ to Entities: LINQ to Entities is a query language used to write queries against the object model. It returns entities, which are defined in the conceptual model. You can use your LINQ skills here.

Entity SQL: Entity SQL is another query language just like LINQ to Entities. However, it is a little more difficult than L2E and the developer will have to learn it separately.

Object Service:Object service is a main entry point for accessing data from the database and to return it back. Object service is responsible for materialization, which is the process of converting data returned from an entity client data provider (next layer) to an entity object structure.

Entity Client Data Provider:The main responsibility of this layer is to convert L2E or Entity SQL queries into a SQL query which is understood by the underlying database. It communicates with the ADO.Net data provider which in turn sends or retrieves data from the database.

ADO.Net Data Provider:This layer communicates with the database using standard ADO.Net.


3. Ques: What is an entity in a database ?
Answer:
An entity is any object in the system that we want to model and store information about. Entities are usually recognizable concepts, either concrete or abstract, such as person, places, things, or events which have relevance to the database. Some specific examples of entities are Employee, Student, Lecturer.


4. Ques: How can you enhance the performance of Entity Framework?
Answer:
Following steps should follow, To enhance the performance of Entity Framework

  • Try to avoid to put all the DB objects into one single entity model
  • Disable change tracking for entity if not needed
  • Reduce response time for the first request by using pre-generating Views
  • If not required try to avoid fetching all the fields
  • For data manipulation select appropriate collection
  • Wherever needed use compiled query
  • Avoid using Views and Contains
  • While binding data to grid or paging, retrieve only required no of records
  • Debug and Optimize LINQ query


5. Ques: Explain the code first approach in mvc ? What are the advantages in code first approach ?
Answer:
Entity framework code first approach, we write model classes first and then generates database from the classes.

The Code first approach of the entity framework helps you to develop your application by Domain driven design approach. In domain driven design, developers can focus on core domain and domain logic and can start working with classes as per your domain requirement; no need to create the database first. It is different from data driven programming, in which data controls the business logic and complete application built around the database schema.


Advantage of code first approach:
  • No need to worry about database creation, you can focus on domain logic to solve the business problem
  • Faster coding – you can start coding even if the database is not ready or if you don’t have knowledge about database management.
  • The Code first API of entity framework will automatically create the database and map their relation with model classes.
  • It’s easy to make changes with model classes rather than to databases.
  • No need to edit and update the designer model (.edmx file) in visual studio.

6. Ques: What are new feature in Entity Framework 6 ?
Answer:
Let us take a some of the important features of Entity Framework 6:

Dependency Resolution 
Connection Resiliency
Multiple Contexts per Database
Code Based Configuration
Code First Mapping to Insert/Update/Delete Stored Procedures and many more.


7. Ques: What is the difference between LINQ to SQL and Entity Framework?
Answer:
LINQ to SQL
  • It works only with SQL Server Database
  • To maintain the relation it generates a .dbml
  • It cannot generate database from model
  • It permits one to one mapping between the entity classes and relational views/tables
  • It enables you to query data using DataContext
  • It provides tightly coupled approach
Entity Framework
  • It works with various database like DB2, MYSQL, SQL Server etc.
  • It creates an .edmx files initially and relation is maintained using 3 different files .msl, .csdl and .ssdl
  • It can generate database from model
  • Between the entity classes and relational tables, it permits one-to-one, one-to-many and many-to-many
  • It enables you to query data using EntitySQL, DBContext, and ObjectContext
  • It provides loosely coupled approach

8. Ques: What is Asynchronous controllers in MVC? 
Answer:
The asynchronous controller enables you to write asynchronous action methods. It allows you to perform long running operation(s) without making the running thread idle. 
Asynchronous action methods are useful when an action must perform several independent long running operations. 

Sunday 12 March 2017

MVC interview questions Part 6

1. Ques: How can we use two (multiple) models with a single view ?
Answer:
10 ways to bind multiple models on a single view given bellow

1. View Model
ViewModel is nothing but a single class that may have multiple models. It contains multiple models as a property. It should not contain any method.

2. View Bag
ViewBag is similar to ViewData and is also used to transfer data from the controller to the view. ViewBag is a dynamic property. ViewBag is just a wrapper around the ViewData.

3. View Data
ViewData is used to transfer data from the controller to the view. ViewData is a dictionary object that may be accessible using a string as the key. Using ViewData, we can pass any object from the controller to the view. The Type Conversion code is required when enumerating in the view.

4. Temp Data
TempData is also a dictionary derivative from TempDataDictionary class. TempData stored in short lives session. We can pass multiple models through TempData also.

5. Session
Session is used to pass data across controllers in MVC Application.Session data never expires (by default session expiration time is 20 minutes but it can be increased).Session is valid for all requests, not for a single redirect.

6. Dynamic Model
ExpandoObject (the System.Dynamic namespace) is a class that was added to the .Net Framework 4.0 that allows us to dynamically add and remove properties onto an object at runtime.

7. Tuples
A Tuple object is an immutable, fixed-size and ordered sequence object. It is a data structure that has a specific number and sequence of elements. The .NET framework supports tuples up to seven elements.

8. Render Action
A Partial View defines or renders a partial view within a view. We can render some part of a view by calling a controller action method using the Html.RenderAction method. The RenderAction method is very useful when we want to display data in the partial view. The disadvantages of this method is that there are only multiple calls of the controller.

9. JSON
We can Bind Multiple Models with the help of Json as well. We will retun JsonResult from action Method and on View through JQuery we can pasrse the JSON data and Bind on View.

10. Navigation Properties
If we have two related models then we can bind a model into another model as a property and can pass to a View.


2. Ques: What is csrf(Cross-Site Request Forgery) attack in mvc ? How Preventing (CSRF) Attacks ?
Answer:
CSRF (Cross site request forgery) is a method of attacking a website where the attacker imitates a.k.a forges as a trusted source and sends data to the site. CSRF stands for Cross site request forgery.

To Preventing CSRF attack  we need to add “@Html.AntiForgeryToken” in view with that we need to add this in controller also as a attribute [ValidateAntiForgeryToken] to validating this. Basically AntiForgeryToken is used in HTTPPost method.


3. Ques: What is diffrence between @Html.Action and @Html.RenderAction in mvc ?
Answer :

@Html.Action

This Html.Action renders partial view as an HTML string so we can store it in another string variable. It is string return type method so first it returns result as a string then renders result to response.

@Html.RenderAction

This is also same as Html.Action but main difference is that it renders result directly to response that’s why it is more efficient if the action returns a large amount of HTML over @Html.Action.


4. Ques: How can you remove default View Engine in ASP.NET MVC? ?
Answer:
We can customize view engines in ASP.NET MVC application. If you are not using any view engine like ASPX View Engine, better you remove it to improve the performance.

Removing the Web Form view engine is easy in MVC. We can remove all the view engines and add only Razor view engine by using Application_Start event of Global.asax.cs file like below.

protected void Application_Start()
{
//Remove All Engine
 ViewEngines.Engines.Clear();
 //Add Razor Engine
 ViewEngines.Engines.Add(new RazorViewEngine());
}

5. Ques:  What are Non Action methods in ASP.Net MVC?
Answer:
In ASP.Net MVC all public methods have been treated as Actions. So if you are creating a method and if you do not want to use it as an action method then the method has to be decorated with "NonAction" attribute as shown below :

[NonAction]
public void TestMethod()
{
// Method logic
}


6. Ques:  What is the "HelperPage.IsAjax" Property?
Answer:
The HelperPage.IsAjax property gets a value that indicates whether Ajax is being used during the request of the Web page.


7. Ques:  What is Attribute Routing in ASP.Net MVC?
Answer:
ASP.NET Web API supports this type routing. This is introduced in ASP.Net MVC5. In this type of routing, attributes are being used to define the routes. This type of routing gives more control over classic URI Routing. Attribute Routing can be defined at controller level or at Action level like :

[Route("{action = TestCategoryList}")] - Controller Level
[Route("customers/{TestCategoryId:int:min(10)}")] - Action Level


8. Ques:  What is ViewStart? What are the benifit for ViewStart ? 
Answer:
Razor View Engine introduced a new layout named _ViewStart which is applied on all view automatically. Razor View Engine firstly executes the _ViewStart and then start rendering the other view and merges them.

  • _ViewStart.cshtml page is a special view page containing the statement declaration to include the Layout page.
  • Instead of declaring the Layout page in every view page, we can use the _ViewStart page.
  • When a View Page Start is running, the “_ViewStart.cshtml” page will assign the Layout page for it.

ex:
_viewstart.cshtml
@{
        Layout = "~/Views/Shared/_Layout.cshtml";
 }

Benifit for ViewStart
Instead of declaring the Layout page individually in every page, we can include it on one place only.
So the application became maintainable.
You can still add another page as your Layout page to individual pages, regardless of your _ViewStart page.

9 .What is JSON?
Answer:
JSON full form is JavaScript Object Notation. JSON is a lightweight text-based open standard designed for human-readable data interchange. It is derived from the JavaScript programming language for representing simple data structures and associative arrays, called objects. And JSON is language-independent, with parsers available for virtually every programming language. Uses conventions that are familiar to programmers of the C-family of languages, including C, C++, C#, Java, JavaScript, Perl, Python,php  The JSON format is often used for serializing and transmitting structured data over a network connection. When third party data interchane(REST Services) then JSON may used there LIKE SHOP .It is primarily used to transmit data between a server and web application, serving as an alternative to XML.


10. What is JsonResultType in MVC?
Answer:
JsonResult is an ActionResult type in MVC. It helps to send the content in JavaScript Obect Notation (JSON) format.
Action methods on controllers return JsonResult that can be used in an AJAX application. This class is inherited from the "ActionResult" abstract class. Here Json is provided one argument which must be serializable. The JSON result object that serializes the specified object to JSON format.

public JsonResult JsonResultTest()
{
    return Json("Hello My Friend!");
}   

Friday 10 March 2017

AJAX interview questions Part-2

1. Ques:What are the differences between AJAX and JavaScript ?
Answer:
  • AJAX sends request to the server and will not wait for the response.
  • It will allow other operations on the page before it get response of previous request; whereas, JavaScript make a request to the server, will waits for response and will not allow other operation on the page during that time.
  • In AJAX, the page will not get refreshed for downloading the whole page while JavaScript manages and controls a Web page after being downloaded.
  • By using AJAX we can minimize the overload on the server because the script needs to request once while JavaScript posts the request that updates the script each time.


2. Ques: How many types of triggers are there in update panel?
Answer:
Triggers are the stored procedures used in the database. There are 2 types of triggers in update panel, which are as follows:

1. PostBackTrigger : This trigger is the internal trigger of the update control. It doesn’t work asynchronously. It short circuits the control to do synchronous post back. For example Update control panel

2. AsyncPostBackTrigger : This trigger is a control, that is external to update control. It works synchronously. It wires up the control to do asynchronous post back.


3. Ques: What is an Timer control in ajax?
Answer:
By using Timer control we can update the particular content of the page automatically without clicking the browser refresh button. The Timer control is used along with the Update Panel so the Contents put under the update panel are automatically updated according the timing set under the timer_click event.


4. Ques: How can we cancel the XMLHttpRequest in AJAX?
Answer:
Abort() method can be called to cancel the XMLHttpRequest in Ajax.


5. Ques: What are the security issues with AJAX?
Answer:
The Ajax calls are sent in plain text format, this might lead to insecure database access. The data gets stored on the clients browser, thus making the data available to anyone. It also allows monitoring browsing sessions by inserting scripts.

AJAX function calls are sent in plain text to server. These calls may easily reveal database details, variable names etc

Thursday 9 March 2017

AJAX interview questions Part-1

1. Ques: What is AJAX?
Answer
AJAX is an Asynchronous JavaScript and XML.AJAX is a new technique for creating better, faster, and more interactive web applications.With AJAX, a JavaScript script can communicate directly with the server, with the XMLHttpRequest object. With this object, a JavaScript can exchange data with a web server, without reloading the page.

AJAX uses asynchronous data transfer (HTTP requests) between the browser and the web server, allowing web pages to request small bits of information from the server instead of entire pages.
The AJAX technique makes Internet applications smaller, faster and more user-friendly.


2. Ques: What are the advantages of Ajax?
Answer:
Following are the advantages of Ajax:
  • AJAX technique makes Internet applications smaller, faster and more user-friendly.
  • Reduce the traffic travels between the client and the server.
  • Bandwidth utilization – It saves memory when the data is fetched from the same page.
  • Response time is faster so increases performance and speed.
  • You can use JSON (JavaScript Object Notation) which is alternative to XML.
  • You can use Firefox browser with an add-on called as Firebug to debug all Ajax calls.
  • Speeder retrieval of data

3. Ques: What are the disadvantages of Ajax?
Answer:
Following are the disadvantages of Ajax:
  • AJAX is dependent on JavaScript. If there is some JavaScript problem with the browser or in the OS, Ajax will not support
  • Ajax can be problematic in Search engines as it uses JavaScript for most of its parts.
  • Source code written in AJAX is easily human readable. There will be some security issues in Ajax.
  • Debugging is difficult
  • Increases size of the requests
  • Slow and unreliable network connection.
  • Problem with browser back button when using AJAX enabled pages.

3. Ques: What is Script Manager?
Answer:
Script Manager helps manage the client side script of AJAX. Script Manager acts as a mediator as AJAX depends on JavaScript. Every page that uses AJAX has a Script Manager to enable AJAX libraries. These Libraries in turn helps to implement the core Functionality of Ajax: Partial rendering. The Script Manager controls client script for ASP.NET AJAX pages. It also registers the script for the AJAX Library.


4. Ques: How many types of AJAX controls?
Answer:
  • ScriptManager
  • ScriptManagerProxy
  • Timer
  • UpdatePanel
  • UpdateProgress

ScriptManager :The ScriptManager control manages client script for AJAX-enabled ASP.NET Web pages. By default, the ScriptManager control registers the script for the Microsoft Ajax Library with the page. This enables client script to use the type system extensions and to support features such as partial-page rendering and Web-service calls.


5. Ques: What are the differences between the ScriptManager And ScriptManager Proxy ?
Answer:
ScriptManager
Script Manager is server control that makes script resources available to the browser, including the Microsoft AJAX Library and the functionality that enables partial-page rendering.

ScriptManager Proxy 
Script manager proxy is a server control that enable nested components to add script and service references if the page already contains a script manager control.

6. Ques: What is an UpdatePanel Control?
Answer:
An UpdatePanel control is a cover for server side controls which is to be partial postbacked on ajax enabled page. All controls included in the UpdatePanel will be partial postbacked.
ex:
<asp:ScriptManager runat=”server”>
</ asp:ScriptManager>
<asp:UpdatePanel runat=”server”>
<ContentTemplate>
<asp:Button runat=”server”></asp:Button>
</ContentTemplate>
</asp:UpdatePanel>


7. Ques: What is XMLHttpRequest  in Ajax? What are the main task of xmlhttprequest ?
Answer:
The XMLHttpRequest Object. The XMLHttpRequest object can be used to request data from a web server. he XMLHttpRequest object is used to exchange data with a server behind the scenes. This means that it is possible to update parts of a web page, without reloading the whole page.
Main task of xmlhttprequest
  • Update a web page without reloading the page
  • It send the request data from a server after the page has loaded
  • Receive data from a server after the page has loaded
  • Send data to a server in the background

8. Ques: What is readystate property holds the status of the XMLHttpRequest. 
Answer:
The readystate property holds the status of the XMLHttpRequest.
The onreadystatechange property defines a function to be executed when the readyState changes.

0: request not initialized
1: server connection established
2: request received
3: processing request
4: request finished and response is ready


9. Ques: What is JSON?
Answer:
JSON is a simple data exchange format. JSON means JavaScript Object Notation; it is language and platform independent.


10. Ques: What is use of JSON?
Answer:
When writing application based on JavaScript it uses JSON, which includes browser extension and websites
  • JSON is used for transmitting and serializing structured data over network connection
  • JSON is mainly used to transfer data between server and web application
  • Web service and API’s use JSON format to provide public data
  • JSON can be used with modern programming language