Thursday, 20 February 2014

Increase MVC Application Performace

A compiled list of possible sources of improvement are below:
General
·         Make use of a profiler to discover memory leaks and performance problems in your application. personally I suggest dotTrace
·         Run your site in Release mode, not Debug mode, when in production, and also during performance profiling. Release mode is much faster. Debug mode can hide performance problems in your own code.
Caching
·         Use CompiledQuery.Compile() recursively avoiding recompilation of your query expressions
·         Cache not-prone-to-change content using OutputCacheAttribute to save unnecessary and action executions
·         Use cookies for frequently accessed non sensitive information
·         Utilize ETags and expiration - Write your custom ActionResult methods if necessary
·         Consider using the RouteName to organize your routes and then use it to generate your links, and try not to use the expression tree based ActionLink method.
·         Consider implementing a route resolution caching strategy
·         Put repetitive code inside your PartialViews, avoid render it xxxx times: if you end up calling the same partial 300 times in the same view, probably there is something wrong with that. Explanation And Benchmarks
Routing
·         Use to Url.RouteUrl("User", new { username = "joeuser" }) to specify routes. ASP.NET MVC Perfomance by Rudi Benkovic
·         Cache route resolving using this helper UrlHelperCached ASP.NET MVC Perfomance by Rudi Benkovic
Security
·         Use Forms Authentication, Keep your frequently accessed sensitive data in the authentication ticket
DAL
·         When accessing data via LINQ rely on IQueryable
·         Profile your queries i.e. Uber Profiler
·         Consider second level cache for your queries and add them an scope and a timeout i.e. NHibernate Second Cache
Load balancing
·         Utilize reverse proxies, to spread the client load across your app instance. (Stack Overflow uses HAProxy (MSDN).
·         Use Asynchronous Controllers to implement actions that depend on external resources processing.
Client side
·         Optimize your client side, use a tool like YSlow for suggestions to improve performance
·         Use AJAX to update components of your UI, avoid a whole page update when possible.
·         Consider implement a pub-sub architecture -i.e. Comet- for content delivery against reload based in timeouts.
·         Move charting and graph generation logic to the client side if possible. Graph generation is a expensive activity. Deferring to the client side your server from an unnecessary burden, and allows you to work with graphs locally without make a new request (i.e. Flex charting, jqbargraph, MoreJqueryCharts).
·         Use CDN's for scripts and media content to improve loading on the client side (i.e. Google CDN)
·         Minify -Compile- your JavaScript in order to improve your script size
·         Keep cookie size small, since cookies are sent to the server on every request.
Global configuration
·         If you use Razor, add the following code in your global.asax.cs, by default, Asp.Net MVC renders with an aspx engine and a razor engine. This only uses the RazorViewEngine.
ViewEngines.Engines.Clear(); ViewEngines.Engines.Add(new RazorViewEngine());
·         Add gzip (HTTP compression) and static cache (images, css, ...) in your web.config <system.webServer> <urlCompression doDynamicCompression="true" doStaticCompression="true" dynamicCompressionBeforeCache="true"/> </system.webServer>
·         Remove unused HTTP Modules
·         Flush your HTML as soon as it is generated (in your web.config) and disable viewstate if you are not using it <pages buffer="true" enableViewState="false">



Use Sprites : Sprites is a great thing to reduce request, you merge all your images into a single one and use css to get to good part of the sprite, Microsoft provides a good library to do it : Sprite and Image Optimization Preview 4.
Cache Your server object : If you have some references lists or datas which will change rarely, you can cache them into memory instead of querying database everytime.
Use ADO.Net instead of Entity Freamework : EF4 or EF5 are great to reduce developement time but it will be painfull to optimize. It's more simple to optimize a stored procedure than Entity Framework. So you should use Store procedure as much as possible. Dapper provides a simple way to query and map SQL with very good performance.
Cache Page or partial page: MVC Provides some easy filter to cache page according to some parameters, so use it.
Reduce Database calls: You can create a unique Database Request that return multiple object, check on Dapper website.
Always have a clean architecture: Have a clean n-tiers architecture, even on small project. It will help you to keep your code clean and it will be easier to optimize it if needed.

You can take a look at this template "Neos-SDI MVC Template" which will create for you a clean architecture with lots of performance improvements by default (check MvcTemplate website).

AJAX

How Ajax Works

At the heart of Ajax is the ability to communicate with a Web server asynchronously without taking away the user’s ability to interact with the page. The XMLHttpRequest is what makes this possible. Ajax makes it possible to update a page without a refresh.

What are Common Steps that AJAX Application Follows

The JavaScript function handEvent() will be invoked when an event occurred on the HTML element. In the handEvent() method, an instance of XMLHttpRequest object is created.

How Ajax Works in the Code

our DOM object is (input type="text" id="lblTime") which we have to refresh without refreshing the whole page. This will be done when we press the event of a button, i.e. onclick.

What is Ajax
Ajax (Asynchronous Javascript and XML ) is a technology used to load or retrieve the data from server without reloading or refreshing the Web page. Its a very good option in programming.
Example of Ajax

Google uses this ajax in each and every page. 
For example if you type some words in Google search box it shows some list of suggestion keywords. Listen how Google dynamically displaying the data when a user types in it, without reloading or refreshing the page?. 


Browser Support for AJAX?

Ajax can run in all type of browsers but their is a conflict in older (IE 5 and IE 6), and newer browsers (Mozilla, Netscape, IE 8, Chrome, Safari, Opera).
It can be rectified by checking the older and newer browser and implementing the below code.
For New Browsers: xmlhttp=new XMLHttpRequest();
For older Browsers: xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");


ASP.NET Question

1. Describe the role of inetinfo.exe, aspnet_isapi.dll and aspnet_wp.exe in the page loading process.

inetinfo.exe is the Microsoft IIS server running, handling ASP.NET requests among other things. When an ASP.NET request is received (usually a file with .aspx extension),the ISAPI filter aspnet_isapi.dll takes care of it by passing the request to the actual worker process aspnet_wp.exe.

2. What’s the difference between Response.Write() and Response.Output.Write()?

The latter one allows you to write formatted output.

3. What methods are fired during the page load?

Init() - when the page is instantiated,
Load() - when the page is loaded into server memory,
PreRender() - the brief moment before the page is displayed to the user as HTML,
Unload() - when page finishes loading.

4. Where does the Web page belong in the .NET Framework class hierarchy?
System.Web.UI.Page

5. Where do you store the information about the user’s locale?
System.Web.UI.Page.Culture

6. What’s the difference between Codebehind="MyCode.aspx.cs" and Src="MyCode.aspx.cs"? CodeBehind is relevant to Visual Studio.NET only.

7. What’s a bubbled event?
When you have a complex control, like DataGrid, writing an event processing routine for each object (cell, button, row, etc.) is quite tedious. The controls can bubble up their event handlers, allowing the main DataGrid event handler to take care of its constituents.

8. Suppose you want a certain ASP.NET function executed on MouseOver over a certain button. Where do you add an event handler?
It’s the Attributes property, the Add function inside that property. So btnSubmit.Attributes.Add("onMouseOver","someClientCode();")

9. What data type does the RangeValidator control support?
Integer, String and Date.

10. Explain the differences between Server-side and Client-side code?
Server-side code runs on the server. Client-side code runs in the clients’ browser.

11. What type of code (server or client) is found in a Code-Behind class?
Server-side code.

12. Should validation (did the user enter a real date) occur server-side or client-side? Why?
Client-side. This reduces an additional request to the server to validate the users input.

13. What does the "EnableViewState" property do? Why would I want it on or off?
It enables the viewstate on the page. It allows the page to save the users input on a form.

14. What is the difference between Server.Transfer and Response.Redirect? Why would I choose one over the other?

Server.Transfer is used to post a form to another page. Response.Redirect is used to redirect the user to another page or site.

15. Can you explain the difference between an ADO.NET Dataset and an ADO Recordset?

• A DataSet can represent an entire relational database in memory, complete with tables, relations, and views.
• A DataSet is designed to work without any continuing onnection to the original data source.
• Data in a DataSet is bulk-loaded, rather than being loaded on demand.
• There's no concept of cursor types in a DataSet.
• DataSets have no current record pointer You can use For Each loops to move through the data.
• You can store many edits in a DataSet, and write them to the original data source in a single operation.
• Though the DataSet is universal, other objects in ADO.NET come in different versions for different data sources.

16. Can you give an example of what might be best suited to place in the Application_Start and Session_Start subroutines?
This is where you can set the specific variables for the Application and Session objects.

17. If I’m developing an application that must accommodate multiple security levels though secure login and my ASP.NET web application is spanned across three web-servers (using round-robin load balancing) what would be the best approach to maintain login-in state for the users?
Maintain the login state security through a database.

18. Can you explain what inheritance is and an example of when you might use it?
When you want to inherit (use the functionality of) another class. Base Class Employee. A Manager class could be derived from the Employee base class.

19. Whats an assembly?
Assemblies are the building blocks of the .NET framework. Overview of assemblies from MSDN

20. Describe the difference between inline and code behind.
Inline code written along side the html in a page. Code-behind is code written in a separate file and referenced by the .aspx page.

21. Explain what a diffgram is, and a good use for one?
The DiffGram is one of the two XML formats that you can use to render DataSet object contents to XML. For reading database data to an XML file to be sent to a Web Service.

22. Whats MSIL, and why should my developers need an appreciation of it if at all?
MSIL is the Microsoft Intermediate Language. All .NET compatible languages will get converted to MSIL.

23. Which method do you invoke on the DataAdapter control to load your generated dataset with data?
The .Fill() method

24. Can you edit data in the Repeater control?
No, it just reads the information from its data source

25. Which template must you provide, in order to display data in a Repeater control?
ItemTemplate

26. How can you provide an alternating color scheme in a Repeater control?
Use the AlternatingItemTemplate

27. What property must you set, and what method must you call in your code, in order to bind the data from some data source to the Repeater control?
You must set the DataSource property and call the DataBind method.

28. What base class do all Web Forms inherit from?
The Page class.

29. Name two properties common in every validation control?
ControlToValidate property and Text property.

30. What tags do you need to add within the asp:datagrid tags to bind columns manually?
Set AutoGenerateColumns Property to false on the datagrid tag

31. What tag do you use to add a hyperlink column to the DataGrid?
<asp:HyperLinkColumn>

32. What is the transport protocol you use to call a Web service?
SOAP is the preferred protocol.

33. True or False: A Web service can only be written in .NET?
False

34. What does WSDL stand for?
(Web Services Description Language)

35. Where on the Internet would you look for Web services?
(
http://www.uddi.org)

36. Which property on a Combo Box do you set with a column name, prior to setting the DataSource, to display data in the combo box?
DataTextField property

37. Which control would you use if you needed to make sure the values in two different controls matched?
CompareValidator Control

38. True or False: To test a Web service you must create a windows application or Web application to consume this service?
False, the webservice comes with a test page and it provides HTTP-GET method to test.

39. How many classes can a single .NET DLL contain?
It can contain many classes.


OOP Questions & Answers

Q. What is Object Oriented Programming?
A. Object-oriented programming (OOP) is a programming paradigm using “objects” (data structures consisting of data fields and methods together with their interactions) to design applications and computer programs.

Q. What is an Object?
A. An object is an instance of a class.

Q. What is a Class?
A class is the blueprint from which the individual objects are created. Class is composed of three things: a name, attributes, and operations.

Q. What is Encapsulation ?
Encapsulation implies that the non-essential details of an object are hidden from the user and an access its provided to its essential details.
Example : Computer games also use this feature. The user only needs to know how to play the game, the complex working of the game is hidden from the user.
Encapsulation is the feature that provides security to the data and the methods of a class.

Q. What is Abstraction ?
Abstraction is a process of hiding unwanted details from the user.
Abstraction also means ignoring the non-essential details of an object and concentrating on its essential details.

Q. What is Inheritance ?
Inheritance enables you to extend the functionality of an existing class.
When you create a class that inherits another existing class, it will inherit the attributes and behavior of that class, plus it can also have new attributes and behavior that are specific to that class.
Advantage : Code-Resuability which result in saving time and energy.

Q. What is Polymorphism ?
Polymorphism – Poly stands for many and morph means form. So any thing that exists in more than one form is known as polymorph.
In oops, polymorphism means assigning a different meaning to an entity in different context.

Q. What are the different types of Inheritance ?
There are 5 types of inheritance,
a. Single Inheritence – One Super Class and One Sub class.
b. Multiple Inheritance – More than One Super Class and One Sub class
c. Multi Level Inheritance – A Class which is a Sub class of One class, becomes a Super class for another class.
d. Hierarchical Inheritance – One Super Class and many Sub classes
e. Hybrid Inheritance – Multiple and Multi level combined.

Q. What are the different types of Polymorphism ?
There are two types of polymorphism
1. Run Time Polymorphism
2. Compile time Polymorphism

To achive the Compile Time polymorphism there two ways

Function Overloading
Operator Overloading

To achieve the Run time Polymorphism we need to use

Virtual functions

Q. What is a Virtual Function ?
Virtual functions are normal member functions of a class, which can be over-ridden in the derived classes. The whole functionality can be replaced in the over-riding function.
In C#, the virtual functions will be declared with a keyword ‘virtual’ and the over-riding functions will be declared with ‘override’ key word.

Q. What is Serialization and De-Serialization?
Serialization is the process of converting an object into a series of bytes for transmitting or storing purpose. Deserialization is a process, where these same bytes are converted back into objects.

Q. What is an Abstract Class ?
Abstract class is a class which cannot be instantiated but it is inherited by derived classes. This class contains abstract as well as non-abstract methods and members.
Any concrete class (i.e not abstract) inheriting an abstract class MUST implement ALL inherited abstract method.

Q. What is an Interface ?
Interface is a contract for what a class MUST do, but it does not specify the way it should be done.
An interface contains only the signatures of methods (only the declaration). A class implementing the interface must implement all the members of the interface (i.e provide the definations for those methods).
Interface separates the implementation and defines the structure, and this concept is very useful in cases where you need the implementation to be flexible.
Interfaces can inherit other (many) Interfaces.
A Class can implement many Interfaces.

Q. What is the difference between Abstract class and Interface ?
An abstract class can have abstract members as well non abstract members. But in an interface all the members are implicitly abstract and all the members of the interface must be overriden in its derived class.
A class can inherit one or more interfaces, but only one abstract class.
An abstract class can have 0 abstract method.
Abstract class can have fields (such as int, string etc) , whereas Interface cannot.

Q. What are the different accessibility levels that can be defined in .NET?
Private – Only members of class have access.
Protected – All members in current class and in derived classes can access the variables.
Friend (internal in C#) – Only members in current project have access to the elements.
Protected friend (protected internal in C#) – All members in current project and all
members in derived class can access the variables.
Public – All members have access in all classes and projects.

Q. What is the difference between Class and Structure?
Structs are value types and classes are reference types. The general different is that a reference type lives on the heap, and a value type lives inline, that is, wherever it is your variable or field is defined.
A struct’s members are public by default while a class’ members are private by default
Classes are reference types and structs are value types.

Q. What does virtual keyword mean?
A. It signifies that the method/property can be overridden.

Q. What are static variables?
A static member cannot be referenced through an instance. Instead it is referenced through the class name.

An instance of a class will contain a separate copy for each instance, whereas for static, there will be only one copy for each static field.

If static keyword is applied to a class then all members of the class must be static.

Q. What is Finalize method in .NET?
Allows an object to try and free resources and perform other clean up operations before it is reclaimed by garbage collection.

Q. What is Dispose method in .NET?
Dispose method belongs to ‘IDisposable’ interface. If any object wants to release its unmanaged code, it is a good practice to implement the ‘IDisposable’ interface and then override the Dispose() method.

Q. What is the use of “Overrides” and “Overridable” keywords?
Overridable is used in parent class to indicate that a method can be overridden. Overrides is used in the child class to indicate that you are overriding a method

Q. Where are all .NET Collection classes located?
System.Collection namespace

Q. What is an ArrayList?
An ArrayList is a data structure. It stores data in an array that can be dynamically resized. Array list can hold item of different types. You can access any item in array using the INDEX value of the array position.

Q. What is a HashTable?
Hashtable optimizes lookups. This type is used in the C# language. It computes a hash of each key you add. It then uses this hash code to look up the element very quickly. It is an older .NET Framework type. It is slower than the generic Dictionary type.
Code:
Hashtable hashtable = new Hashtable();
hashtable[1] = "One";
hashtable[2] = "Two";
hashtable[13] = "Thirteen";

foreach (DictionaryEntry entry in hashtable)
{
Console.WriteLine("{0}, {1}", entry.Key, entry.Value);
}

Q. What are Collections in .NET
List
First, the List type provides you with an efficient and dynamically-allocated array. It does not provide fast lookup in the general case, which you will want to use Dictionary for. It is excellent when used in loops.
Code:
// Use the List type.
List<string> list = new List<string>();
list.Add("cat");
list.Add("dog");

foreach (string element in list)
{
Console.WriteLine(element);
}

Dictionary
The Dictionary type in the base class library is one of the most important ones you need to use for your C# programs. It is an implementation of a hashtable, which is an extremely efficient way to store keys for lookup. The Dictionary in .NET is well-designed.
Code:
// Use the dictionary.
Dictionary<string, int> dict = new Dictionary<string, int>();
dict.Add("cat", 1);
dict.Add("dog", 4);

Console.WriteLine(dict["cat"]);
Console.WriteLine(dict["dog"]);

ArrayList
As shown in this program, the ArrayList is a collection found in System.Collections and it can store objects of any derived type. You don’t need to worry about the type of the elements, at least until you need to know their types to use them.
Code:
ArrayList list = new ArrayList();
list.Add("cat");
list.Add(2);
list.Add(false);

foreach (var element in list)
{
Console.WriteLine(element);
}

Hashtable
Hashtable optimizes lookups. This type is used in the C# language. It computes a hash of each key you add. It then uses this hash code to look up the element very quickly. It is an older .NET Framework type. It is slower than the generic Dictionary type. First, you can create a new Hashtable with the simplest constructor. When it is created, the Hashtable has no values. We directly assign values with the indexer, which uses the square brackets [ ]. The example adds three integer keys with one string value each.
Code:
Hashtable hashtable = new Hashtable();
hashtable[1] = "One";
hashtable[2] = "Two";
hashtable[13] = "Thirteen";

foreach (DictionaryEntry entry in hashtable)
{
Console.WriteLine("{0}, {1}", entry.Key, entry.Value);
}

Stack
Stack is a LIFO collection. It provides a powerful and simple last-in-first-out data structure. This can help you develop parsers quickly and also replace complex recursive algorithms. Stack is a generic type.

LIFO:
The last element added (with Push) to Stack is the first one removed (with Pop).
Code:
Stack<int> stack = new Stack<int>();
stack.Push(100);
stack.Push(1000);
stack.Push(10000);
return stack;

Queues
Queue is a FIFO collection. It helps when you have elements that you need to process in a first-in, first-out order. It processes the elements that you received longest ago first. We look at several examples of using Queue<T>. We think about some of the logic used for processing help requests in a C# application.

First-In-First-Out:
The queue data structure implements this algorithm. Queue is a generic type with one type parameter.
Code:
// New Queue of integers
Queue<int> q = new Queue<int>();

q.Enqueue(5); // Add 5 to the end of the Queue.
q.Enqueue(10); // Then add 10. 5 is at the start.
q.Enqueue(15); // Then add 15.
q.Enqueue(20); // Then add 20.


Q. What is an ENUM?
It is used to define constants. Enums store special values. They make programs simpler. If you place constants directly where used, your C# program becomes complex. It becomes hard to change. Enums instead keep these magic constants in a distinct type. They improve code clarity. They alleviate maintenance issues.
An enum type is a distinct value type that declares a set of named constants.

Q. What is a nested Classes?
Nested classes are classes within classes. In sample below “ClsNested” class has a “Child
Nested” class nested inside it.

The class B here is enclosed inside the declaration of class A. Class B is thus a nested class. Because it has a public accessibility modifier, it can be accessed in places other than class A’s scope. In the main entry point, we create an instance of A, and also an instance of A.B. The instance of A does not contain an instance of B; the reverse is also the case.

Program that shows nested class B [C#]

class A
{
public int _v1;
Code:
public class B
{
public int _v2;
}
}

class Program
{
static void Main()
{
A a = new A();
a._v1++;

A.B ab = new A.B();
ab._v2++;
}
}

Q. What is Operator overloading in .NET?
It provides a way to define and use operators such as +, -, and / for user-defined classes or
structs. It allows us to define/redefine the way operators work with our classes and structs. This allows programmers to make their custom types look and feel like simple types such as int and string.
Code:
using System;

class Widget
{
public int _value;

public static Widget operator +(Widget a, Widget b)
{
// Add two Widgets together.
// … Add the two int values and return a new Widget.
Widget widget = new Widget();
widget._value = a._value + b._value;
return widget;
}

public static Widget operator ++(Widget w)
{
// Increment this widget.
w._value++;
return w;
}
}

class Program
{
static void Main()
{
// Increment widget twice.
Widget w = new Widget();
w++;
Console.WriteLine(w._value);
w++;
Console.WriteLine(w._value);

// Create another widget.
Widget g = new Widget();
g++;
Console.WriteLine(g._value);

// Add two widgets.
Widget t = w + g;
Console.WriteLine(t._value);
}
}

Output
Quote:1
2
1
3


Q. What is the significance of Finalize method in .NET?
For the majority of the objects that your application creates, you can rely on the .NET Framework’s garbage collector to implicitly perform all the necessary memory management tasks. However, when you create objects that encapsulate unmanaged resources, you must explicitly release the unmanaged resources when you are finished using them in your application. The most common type of unmanaged resource is an object that wraps an operating system resource, such as a file, window, or network connection. Although the garbage collector is able to track the lifetime of an object that encapsulates an unmanaged resource, it does not have specific knowledge about how to clean up the resource. For these types of objects, the .NET Framework provides the Object.Finalize method, which allows an object to clean up its unmanaged resources properly when the garbage collector reclaims the memory used by the object. By default, the Finalize method does nothing. If you want the garbage collector to perform cleanup operations on your object before it reclaims the object’s memory, you must override the Finalize method in your class.

Q. What is the use of DISPOSE method?
Dispose method belongs to ‘IDisposable’ interface. We had seen in the previous section how bad it can be to override the finalize method for writing the cleaning of unmanaged resources. So if any object wants to release its unmanaged code best is to implement I Disposable and override the Dispose method of I Disposable interface. Now once your class has exposed the Dispose method it is the responsibility of the client to call the Dispose method to do the cleanup.

Q. In what instances you will declare a constructor to be private?
When we create a private constructor, we cannot create object of the class directly from a client.
Therefore, you will use private constructors when you do not want instances of the class to be created by any external client. Example UTILITY functions in project will have no instance and be used with out creating instance, as creating instances of the class would be waste of memory.

Q. Can two catch blocks be executed?
No, once the proper catch section is executed the control goes finally to block. So there will not be any scenarios in which multiple catch blocks will be executed.

Q. What is the difference between System.String and System.StringBuilder
System. String is immutable;
System.StringBuilder can have mutable string where a variety of operations can be performed.
Jquery Question Answers

Q1. What is Jquery in the context of web applications?
jQuery is nothing but a collection of well written JavaScript code.
In other words Jquery is ready made concise and fast JavaScript Library to be used.

Q2. What are the advantages of using jQuery over JavaScript in ASP.NET web application
Below are the advantages of using jQery over JavaScript

1.Jquery is well written optimised javascript code so it will be faster in execution unless we write same standard optimised javascript code.

2.Jquery is concise java script code ,means minimal amount of code is to be written for the same functionality than the javascript.

3.Javascript related Development is fast using Jquery because most of the functionality is already written in the library and we just need to use that.

4.Jquery has cross browser support ,so we save time for supporting all the browsers.

Q3. How to use jQuery in ASP.NET web application?
To use jQuery in ASP.NET web application follow the below steps:
a)Go to
http://jquery.com/(The official jQuery WebSite)

b)Download latest .js jQuery file from the website.

c)Put it the script(or other folder) in the root of your web application

d)Add the below tag on the page where you want to use Jquery script type="text/javascript" src="script/jQueryDownLoadedFileName.js" /script

Q4. What is the use of Jquery min js file in ASP.NET web application
JQuery min .js file is actully a minified version of Actual JQuery .js. The min files have less size but same content so this improves the performance.so You should prefer to use min files.

Q5. What is the advantages of use of document.ready functions in jQuery
Advantage of using $(document).ready(function () in jQuery is that the code inside this function will execute only when the full page has been loaded so that there will be no error like the DOM object on which the Jquery has to execute is not loaded.

Q6. Can we write more than one document.ready jQuery functions in one page
Yes we can write more than one jquery $(document).ready(function () in one page.This is helpful when you have large Jquery code and you want to split it in multiple files.

Q7. How to select an element with Id in Jquery
To select an element with Id write as below:
var divValue = $(''#sampleDivId'').val();

Q8. How to select an element with class in Jquery
To select an element with class write as below:
$(".sampleClass").css("border","2px solid blue");


Q9. What is the difference between jQuery find and children methods
The difference between find() and children() methods are that the children only travels a single level down the DOM tree while the find travels at all level down the DOM tree.

Q10. How to use length function in jQuery to text existence of an element by Id
To test if an element exists we can use length method in jQuery as below:
if $(''#mySampleDiv'').length )//Tests wheter the div with id mySampleDiv exists or not $(mySampleDiv).find(''div'');

Entity Framework Questions & Answers

What is Entity Framework?
Entity Framework is an additional layer between application and database that enables the developers to program against the conceptual application model instead of programming directly against the relational storage schema.

Will there be any issues adding a table without primary keys to a data model?
Every entity must have a key, even in the case where the entity maps to a view. When you use the Entity Designer to create or update a model, the classes that are generated inherit from EntityObject, which requires EntityKey. So, we have to have a primary key in the table to add it to the data model.

How do you truncate a table using entity data model?
Unfortunately Entity Framework doesn’t include anything straight forward to handle this. But we can still call a T-SQL statement using entity framework that will still minimizes the developers work. We can call ExecuteStoreCommand() methond on ObjectContext as shown below.
Code:
using (var context = new MyTestDbEntities())
{
    context.ExecuteStoreCommand("TRUNCATE table Dummy");
}

How do you query in entity model when the result has a join from from different database other than the entity model?
E.g.: SELECT t1.c1, t2.c2 FROM table1 AS t1 JOIN table2 t2 ON t1.c1 = t2.c1

As the entity model doesn’t support querying from any entity other
than the entities defined in Entity Data Model, we have to query aginst the data base using ExecuteStoredQuery of the context.

Following code snippet shows how to query when other databases are joined.
Code:
string query = "SELECT t1.c1, t2.c2 FROM table1 AS t1 JOIN table2 t2 ON t1.c1 = t2.c1";
using (var context = new SampleEntities())
{
  ObjectResult<DbDataRecord> records = context.ExecuteStoreQuery<DbDataRecord>(query);
  foreach (DbDataRecord record in records)
  {
    //Do whatever you want
  }
}


What is minimum requirement for Entity Framework applications to run?
The Entity Framework is a component of the .NET Framework so Entity
Framework applications can run on any computer on which the .NET
Framework starting with version 3.5 SP1 is installed.

What is CSDL?
Conceptual schema definition language (CSDL) is an XML-based language that describes the entities, relationships, and functions that make up a conceptual model of a data-driven application. This conceptual model can be used by the Entity Framework or WCF Data Services.

The metadata that is described with CSDL is used by the Entity
Framework to map entities and relationships that are defined in a
conceptual model to a data source.

What is SSDL?
Store schema definition language (SSDL) is an XML-based language that describes the storage model of an Entity Framework application.

In an Entity Framework application, storage model metadata is loaded from a .ssdl file (written in SSDL) into an instance of the System.Data.Metadata.Edm.StoreItemCollection and is accessible by using methods in the System.Data.Metadata.Edm.MetadataWorkspace class. The Entity Framework uses storage model metadata to translate queries against the conceptual model to store-specific commands.

What is MSL?
Mapping specification language (MSL) is an XML-based language that describes the mapping between the conceptual model and storage model of an Entity Framework application.

In an Entity Framework application, mapping metadata is loaded from an .msl file (written in MSL) at build time. The Entity Framework uses mapping metadata at runtime to translate queries against the conceptual model to store-specific commands.

What is Entity Data Model?
The Entity Data Model (EDM) is a set of concepts that describe the structure of data, regardless of its stored form. The EDM borrows from the Entity-Relationship Model described by Peter Chen in 1976, but it also builds on the Entity-Relationship Model and extends its traditional uses.

The EDM addresses the challenges that arise from having data stored in many forms. For example, consider a business that stores data in relational databases, text files, XML files, spreadsheets, and reports. This presents significant challenges in data modeling, application design, and data access. When designing a data-oriented application, the challenge is to write efficient and maintainable code without sacrificing efficient data access, storage, and scalability. When data has a relational structure, data access, storage, and scalability are very efficient, but writing efficient and maintainable code becomes more difficult. When data has an object structure, the trade-offs are reversed: Writing efficient and maintainable code comes at the cost of efficient data access, storage, and scalability. Even if the right balance between these trade-offs can be found, new challenges arise when data is moved from one form to another. The Entity Data Model addresses these challenges by describing the structure of data in terms of entities and relationships that are independent of any storage schema. This makes the stored form of data irrelevant to application design and development. And, because entities and relationships describe the structure of data as it is used in an application (not its stored form), they can evolve as an application evolves.

Which are the key concepts of Entity Data Model?
The Entity Data Model (EDM) uses three key concepts to describe the structure of data: entity type, association type, and property. These are the most important concepts in describing the structure of data in any implementation of the EDM.

1. Entity Type: The entity type is the fundamental building block for describing the structure of data with the Entity Data Model. In a conceptual model, entity types are constructed from properties and describe the structure of top-level concepts, such as a customers and orders in a business application.

2. Association Type: An association type (also called an association) is the fundamental building block for describing relationships in the Entity Data Model. In a conceptual model, an association represents a relationship between two entity types (such as Customer and Order).

3. Property: Entity types contain properties that define their structure and characteristics. For example, a Customer entity type may have properties such as CustomerId, Name, and Address.

What is .edmx file and what it contains?
An .edmx file is an XML file that defines a conceptual model, a storage model, and the mapping between these models. An .edmx file also contains information that is used by the ADO.NET Entity Data Model Designer (Entity Designer) to render a model graphically.

How can you tell EF to have a different table or column name than that defined for the class?
By convention, EF defines the table and column names based on your class and property names.
You can use the [Table] and [Column] annotations to tell EF to use different names.

How do you mark a property as required? For example, For a Project, the Name is a required field.
You use the [Required] attribute to mark a property as required.

What is use of EntityDataSource Control?
The ADO.NET EntityDataSource control supports data binding scenarios in Web applications that use the ADO.NET Entity Framework. Like the Entity Framework, the control is available as part of the .NET Framework 3.5, beginning with SP1. Like the other Web server data source controls, the EntityDataSource control manages create, read, update, and delete operations against a data source on behalf of data-bound controls on the same page. The EntityDataSource works with editable grids, forms with user-controlled sorting and filtering, dually bound drop-down list controls, and master-detail pages.

What is Model First Approach?
A new Model First approach was supported in Visual Studio 2010, which was released together with the second Entity Framework version (Entity Framework v4). In Model First approach the development starts from scratch. At first, the conceptual model is created with Entity Data Model Designer, entities and relations are added to the model, but mapping is not created.

After this Generate Database Wizard is used to generate storage (SSDL) and mapping (MSL) parts from the conceptual part of the model and save them to the edmx file. Then the wizard generates DDL script for creating database (tables and foreign keys)

If the model was modified, the Generate Database Wizard should be used again to keep the model and the database consistent. In such case, the generated DDL script contains DROP statements for
tables, corresponding to old SSDL from the .edmx file, and CREATE statements for tables, corresponding to new SSDL, generated by the wizard from the conceptual part. In Model First approach developer should not edit storage part or customize mapping, because they will be re-generated each time when Generate Database Wizard is launched.

What is Code First Approach?
Code First allows you to define your model using C# or VB.Net classes, optionally additional configuration can be performed using attributes on your classes and properties or by using a Fluent API. Your model can be used to generate a database schema or to map to an existing database.

What is Entity SQL?
Entity SQL is a SQL-like storage-independent language, designed to query and manipulate rich object graphs of objects based on the Entity Data Model (EDM).

What is LINQ To Entities?
LINQ to Entities provides Language-Integrated Query (LINQ) support for querying entities.

LINQ to Entities enables developers to write queries against the database using one of the supported .NET Framework programming languages such as Visual Basic or Visual C#.

What is EntityClient?
System.Data.EntityClient is a storage-independent ADO.NET data provider that contains classes such as EntityConnection, EntityCommand, and EntityDataReader. Works with Entity SQL and connects to storage specific ADO.NET data providers, such as SqlClient.

What is Deferred Loading(Lazy Loading)?
When objects are returned by a query, related objects are not loaded at the same time.

Instead they are loaded automatically when the navigation property is accessed. Also known as “lazy loading,”

What is Eager Loading?
The process of loading a specific set of related objects along with the objects that were explicitly requested in the query.

What is Complex Type?
A .NET Framework class that represents a complex property as defined in the conceptual model. Complex types enable scalar properties to be organized within entities. Complex objects are instances of complex types.

What is Conceptual Model?
An implementation of the Entity Data Model (EDM), specific to the Entity Framework, which represents an abstract specification for the data structures that define an entity-relationship representation of data in the domain of an application.

What is use of Entity Container?
Specifies entity sets and association sets that will be implemented in a specified namespace.

What is Explicit Loading?
When objects are returned by a query, related objects are not loaded at the same time. By default, they are not loaded until explicitly requested using the Load method on a navigation property.

What do you mean by Navigation Property?
A property of an entity type that represents a relationship to another entity type, as defined by an association. Navigation properties are used to return related objects as an EntityCollection or an EntityReference, depending on the multiplicity at the other end of the association.

What is scalar property?
A property of an entity that maps to a single field in the storage model.

What is split entity?
An entity type that is mapped to two separate types in the storage model.

What do you mean by table-per-hierarchy?
A method of modeling a type hierarchy in a database that includes the attributes of all the types in the hierarchy in one table.

What do you mean by table-per-type?
A method of modeling a type hierarchy in a database that uses multiple tables with one-to-one relationships to model the various types.

WCF Questions & Answer

Q1. What is WCF?
WCF stands for Windows Communication Foundation. It is a Software development kit for developing services on Windows. WCF is introduced in .NET 3.0. in the System.ServiceModel namespace. WCF is based on basic concepts of Service oriented architecture (SOA)

Q2. What is endpoint in WCF service?
The endpoint is an Interface which defines how a client will communicate with the service. It consists of three main points: Address,Binding and Contract.

Q3. Explain Address,Binding and contract for a WCF Service?
Address:Address defines where the service resides.
Binding:Binding defines how to communicate with the service.
Contract:Contract defines what is done by the service.

Q4. What are the various address format in WCF?
a)HTTP Address Format:--> http://localhost:
b)TCP Address Format:--> net.tcp://localhost:
c)MSMQ Address Format:--> net.msmq://localhost:

Q5. What are the types of binding available in WCF?
A binding is identified by the transport it supports and the encoding it uses. Transport may be HTTP,TCP etc and encoding may be text,binary etc. The popular types of binding may be as below:
a)BasicHttpBinding
b)NetTcpBinding
c)WSHttpBinding
d)NetMsmqBinding

Q6. What are the types of contract available in WCF?

The main contracts are:
a)Service Contract:Describes what operations the client can perform.
b)Operation Contract : defines the method inside Interface of Service.
c)Data Contract:Defines what data types are passed
d)Message Contract:Defines wheather a service can interact directly with messages

Q7. What are the various ways of hosting a WCF Service?
a)IIS b)Self Hosting c)WAS (Windows Activation Service)

Q8. WWhat is the proxy for WCF Service?

A proxy is a class by which a service client can Interact with the service.
By the use of proxy in the client application we are able to call the different methods exposed by the service


Q9. How can we create Proxy for the WCF Service?

We can create proxy using the tool svcutil.exe after creating the service.
We can use the following command at command line.
svcutil.exe *.wsdl *.xsd /language:C# /out:SampleProxy.cs /config:app.config

Q10.What is the difference between WCF Service and Web Service?
a)WCF Service supports both http and tcp protocol while webservice supports only http protocol.
b)WCF Service is more flexible than web service.

Q11.What is DataContract and ServiceContract?Explain
Data represented by creating DataContract which expose the
data which will be transefered /consumend from the serive
to its clients.

**Operations which is the functions provided by this
service.

To write an operation on WCF,you have to write it as an
interface,This interface contains the "Signature" of the
methods tagged by ServiceContract attribute,and all methods
signature will be impelemtned on this interface tagged with
OperationContract attribute.

and to implement these serivce contract you have to create
a class which implement the interface and the actual
implementation will be on that class.


Code Below show How to create a Service Contract:
Code:

[ServiceContract]
Public Interface IEmpOperations
{
[OperationContract]
Decimal Get EmpSal(int EmpId);

}

Class MyEmp: IEmpOperations
{
Decimal Get EmpSal()
{
// Implementation of this method.
}
}