Thursday, 12 December 2013

.Net fundamental

1)Which ADO.NET object is very fast in getting data from database?

   DataReader is the  object which retrieve data from database verifiable.
   for example SqlDataReader , OledbDataReader

   DataReader is the object which was introduced in .net from earlier version. Even Dataset use
   DataReader  object internally for data retrieving.DataReader use connected data retrieval only
  
2)Explain about the relationship of XML and ADO.NET?

ADO.Net was intoduced in .net framework.ADO.Net dataset is a class for handling  data operation.Data fetch, update etc. ADO.Net dataset is of two type a)Typed and b)Untyped dataset.Both are derived from dataset class.

a)Typed dataset : It is derived from ADO.Net dataset and all method , event,property also from ADO.Net class.When a typed dataset is generated at design time, a dataset class and an associated XML Schema is created.XML Schemas define and validate the data being imported from XML streams or documents into typed datasets.

b)Untyped dataset : It is derived from ADO.Net also.

3)Explain about Data access objects or DAO?

4)How to add auto increment column in the DataTable?

It is a tricky question , asked by employer , to know in depth knowledge of a candidate.
Datatable also an inmemeory representation.Data table had a property called "AutoIncrement" 
thta is DataColumn.AutoIncrement 

DataTable table = new DataTable("mytable");
 
DataColumn mycolumn = new DataColumn();
column.DataType = System.Type.GetType("System.Int32");
column.AutoIncrement = true;
table.Columns.Add(mycolumn);
 
5)Stored procedure return more than one resut set and datareader used to fetch record, how you fetch 6)second result set using datareader?
7)What is the use of DataSet.HasChanges() Method?

Gets indicating whether the  dataset  has changes, including new, deleted, or modified rows.
   if(mydataSet.HasChanges()) return;

Sometimes programetically  we cange the value of a datatable , add new row, delete row, modify    value of column.Or some times add a new datatable added to dataset.

To determine if the value has change , HasChanges() property is used
  

8)What is the use of SqlCommandBuilder?
A Command object is used to execute scalar or non query commands to a Databse.

It comes under System.Data.Sqlclient.It is a sealed class.

SqlDataAdapter da = new SqlDataAdapter();
da.SelectCommand = new SqlCommand(myQueryString, connection);
SqlCommandBuilder builder = new SqlCommandBuilder(da );
builder.GetUpdateCommand(); 
 

9)What is the difference between Typed and UnTyped DataSets?
Dataset is derived from System.Data.DataSet.There are two type of dataset , Typed and untyped dataset.Both are dataset but have some major advantages of Typed dataset over untyped dataset.Mainly when we declare a dataset ,it is untyped dataset , but .Xsd file is a good example of typed dataset

untyped dataset
dataset ds=new dataset();

typed dataset is and .xsd file
now  what more on typed dataset ?
Typed dataset maintain schema .Foreign key and others reference,Relation between tables.
we can not violate the database integrity programetically form typed dataset
 

10)Differences between DataSet and DataReader

DataSet

DataReader

Can perform both Read/Write
Can perform only Read-only operation
Can return /contain multiple tables from different databases
Can read on a single result set of one database
Disconnected mode
Connected mode
Can bind to multiple controls
Can bind to a single control
Forward and backward scanning of data, any point of data can be access
Forward-only scanning of data
Slower access to data
Faster access to data
Greater overhead to enable additional features
Lightweight object with very little overhead
 Internally XML is used for storing of data.
No scope of storing of data.




11)How do you create a permanent cookie ?

It is also termed as persistent cookie or a stored cookie

cookie that is stored on a users hard drive until it expires or until the user deletes the cookie. This cookies are used to collect identifying information about the user, such as Web surfing behavior or user preferences for a specific Web site.Expire date are set to get expired

Add cookie
var myCookie = new HttpCookie("myCookie ");
myCookie .Values.Add("Id", "some_information");
panelIdCookie.Expires = DateTime.Now.AddMonths(2); 
Response.Cookies.Add(myCookie );
 
Read cookie
 var httpCookie = Request.Cookies["myCookie "];
 if (httpCookie != null)
 {
   myId = Convert.ToInt32(httpCookie["Id"]);
 }
 


12)What is gacutil.exe?

 gacutil stands for Global Assembly Cache (GAC),it is for the Common Language Infrastructure (CLI).It is automatically installed when a visual studio is installed,to run the tool we have to go to
"Command Prompt".gacutil accept three parameters

assemblyName,assemblyPath,assemblyListFile

we can see the gacutil.exe like the path
 %programfiles%\Microsoft Visual Studio .NET 2005\SDK\v1.1\Bin\gacutil.exe


13)Difference between Response.Expires and Response.ExpiresAbsolute?

Response.Expires
Specifies the number of minutes before a page cached in the browser expires . if the user returns to the same page before the specified number of minutes the cached version of the page is displayed.
Response.Expires = 40
Response.Cache.SetNoStore()
by this  cached in the browser expires in 40 minutes

Response.ExpiresAbsolute
This can set the date and/or time at which page cached in the browser expires.
 <% Response.ExpiresAbsolute=#May 31,2013 13:30:15# %>

14)What is CLR (Common Language Runtime)?

                                     It is a  run-time environment called the common language runtime, which runs the code and provides services that make the development process easier.
                                   The term service refers to as a collection of services that are required to execute a code. The beauty of CLR is that all .NET-supported languages can be executed under this single defined runtime layer. The spinal cord of CLR is represented by a library refers to as mscoree.dll (common object runtime execution engine). When an assembly is referenced for use, mscoree.dll is automatically loaded.
                                 The CLR first locates the referenced assembly, and then it loads it into memory, compiles the associated IL code into platform specific instructions, performs security related checks, and finally executes the code.
 
Role of CLR in DOT.NET Framework
Base Class Libraries: It provides class libraries supports to an application when needed.
Debug Engine: CLR allows us to perform debugging an application during runtime. Thread Support: Threads are managed under the Common Language Runtime
Manages memory: Allocation of Memory,De-Allocation of Memory (garbage collation)
Compilation

                                Common Language Runtime (CLR) is a language-independent runtime environment . The Common Language Runtime (CLR) environment is also referred to as a managed environment, because during the execution of a program it also controls the interaction with the Operating System


15)What is CTS?

                               CTS stands for Common Type System. It confirm how Type definitions and specific values of Types are represented in computer memory.Which establishes a framework that helps enable cross-language integration, type safety, and high-performance code execution.Provides an object-oriented model that supports the complete implementation of many programming languages
                            
                              The language interoperability, and .NET Class Framework, are not possible without all the language sharing the same data types.This is exactly what's done in the Common Type System (CTS). A fundamental part of the .NET Framework's Common Language Runtime (CLR), the CTS specifies no particular syntax or keywords, but instead defines a common set of types that can be used with many different language syntaxes. Each language is free to define any syntax it wishes, but if that language is built on the CLR, it will use at least some of the types defined by the CTS.
                            These types can be Value Types or Reference Types . The Value Types are passed by values and stored in the stack. The Reference Types are passed by references and stored in the heap. Common Type System (CTS) provides base set of Data Types which is responsible for cross language integration. The Common Language Runtime (CLR) can load and execute the source code written in any .Net language, only if the type is described in the Common Type System (CTS) .Most of the members defined by types in the 
                            
      


16)What is CLS?
17)What is MSIL?

Full form of  MSIL is Microsoft Intermediate Language.Also called  Intermediate Language (IL) / Common Intermediate Language (CIL). While compile , the compiler convert the source code into Microsoft Intermediate Language (MSIL).MSIL includes instructions for loading, storing, initializing, and calling methods on objects, as well as instructions for arithmetic and logical operations, control flow, direct memory access, exception handling, and other operations.
Combined with metadata and the common type system, MSIL allows for true cross- language integration Prior to execution, MSIL is converted to machine code. It is not interpreted.

18)What is Satellite Assembly?
19)Can you place two .dll files with the same name in GAC (Global Assembly Cache)?
20)What's the difference between private and shared assembly?

Private Assembly
                                A private assembly is normally used by a single application, and is stored in the application's directory, or a sub-directory beneath.
                               The disadvantage of using private assemblies is that they have to be copied into every application that uses it. This results in increased disk space requirements on the target machine - the same private assembly is copied to disk multiple times - and in memory requirements - the same DLL loaded from different locations is seen by Windows as a different module and is allocated separate physical memory.

Shared Assembly
                         A shared assembly is an assembly available for use by multiple applications on the computer.This type of assembly can be used in situations where it is not necessary to install a version of an assembly for each application that uses it


21)What is the location of Global Assembly Cache on the system.

22)What is JIT (Just-in-time) Compiler ?
A compiler that converts program source code into native machine code just before the program is run. Compilation is a executes in two-steps.It required an  Virtual Machine which is able to execute
execute your code.
Step 1
Convert  your program to a bytecode understandable by Virtual Machine. .NET  is called Common Intermediate Language or CIL. It is also known as Microsoft Intermediate Language (MSIL) or just Intermediate Language (IL)

Step 2
Virtual Machine  converts only executed MSIL  into CPU instructions at runtime.

23)What is Managed and Unmanaged code?
24)What is the difference between Namespace and Assembly?
25)What is Manifest?
26)What is Metadata?
27)What is CODE Access security?
28)What’s difference between System.SystemException and System.ApplicationException?
30)Dictionary objects 

Contain collection of keys and values.comes under System.Collections.Generic
Dictionary<TKey, TValue>()

Example
public class AClass
{
Dictionary<int, dynamic> sp = new Dictionary<int, dynamic>
{
{1, new {name="Ram", age="18"}}
{2, new {name="Sham", age="22"}}
}
}

Now how to read dictionary object?
 
AClass obj = new AClass(); 
 
foreach (var item in obj.sp)
{
    Console.Write(item.Key);
    Console.Write(item.Value.name);
    Console.Write(item.Value.age);
} 


31)What is ResolveUrl ?

Converts a URL into one that is usable on the requesting client .
For example i have a path
../event/play/sport.aspx
Now some other path , i have to redirect to the sport.aspx page
Say i am in a path
../event/study/class.aspx
i have to rend the redirect to
../event/play/sport.aspx

if i write  string postTo=ResolveUrl(`~/sport.aspx);
Response.write( postTo.totsring());
Result
../event/study/class.aspx 

MVC fundamental

1)  How to Rnder HTML to view pages from controller  ?
Example
<div>@Html.Raw(ViewBag.Message)</div> 

Here  Html.Raw is the command to render html to view .The Htnl soure can be database , or any other source.We can use Viewdata["example"] to render in the same manner.


2)MVC Routing 
http://www.codeproject.com/Articles/641783/Customizing-Routes-in-ASP-NET-MVC 



3)ViewData    ViewData is a dictionary object that is derived from ViewDataDictionary class.

    ViewData is used to pass data from controller to corresponding view.

    It’s life lies only during the current request.

    If redirection occurs then it’s value becomes null.

    It’s required typecasting for getting data and check for null values to avoid error.

ViewBag
    ViewBag is a dynamic property that takes advantage of the new dynamic features in C# 4.0.

    Basically it is a wrapper around the ViewData and also used to pass data from controller to corresponding view.

    It’s life also lies only during the current request.

    If redirection occurs then it’s value becomes null.

    It doesn’t required typecasting for getting data.
TempData

    TempData is a dictionary object that is derived from TempDataDictionary class and stored in short lives session.

    TempData is used to pass data from current request to subsequent request (means redirecting from one page to another).

    It’s life is very short and lies only till the target view is fully loaded.

    It’s required typecasting for getting data and check for null values to avoid error.

    It is used to store only one time messages like error messages, validation messages. To persist data with TempData refer this article

4)The Simplest way to Display text in MVC
     @Html.DisplayText("This MVC control For Display")



5) Html.Encode

HTML-encodes a string and returns the encoded string.

Result.Text = Server.HtmlEncode("<script>unsafe</script>");     

One of the best features in the Razor View Engine that I like most is "HTML Encoding". In many cases (like a comment form in a blog) we receive the data from users and he may be trying to harm us by sending some malicious scripts to cause cross-site script injection attacks (aka XSS attack).In ASP.NET Web Forms we have a couple of ways to do HTML encoding:

ASP.NET MVC Razor expressions are automatically HTML encoded. It is always a good practice to validate data received from a user before storing it in the database because the database can accept any malicious data, especially XSS data happily but if you are using Razor to display the data on the web page then you are still safe and you don't need any special care.

6)RenderBody, RenderPage ,RenderPaertial and RenderSection 

RenderBody

The page content will be rendered here. 
@RenderBody ()

@{
    Layout = "~/Views/Shared/_Layout.cshtml";
}
  
RenderPage 
The RenderPage method allows you to render code from an external page. It is useful if you want to keep the footer and header in separate pages and call them into the layout page. This avoids very long pages and keeps code neat. It is similar to the PHP include function.
  1. In the shared folder create two new files _Header.cshtml and _Footer.cshtml
  2. From the layout page copy and remove the content between the <header> tag and place it in the _Header.cshtml do the same for the footer.
@RenderPage("~/shared/_Header.cshtml")

 RenderSection
One of the drawbacks of the RenderPage method is that it cannot manage optional content for example you might have a sidebar but don’t want to render it on every page. Sections are a way around this.

The RenderSection method takes two arguments first is the section name and second one is Boolean which specifies if the section is required or not, default is true so it will be required. The diagram below shows how sections work, similar to layout pages.

<aside>
 @RenderSection("sidebar")
</aside>

@RenderSection("sidebar", false)

@section sidebar{

<ul>
<li>Coffee</li>
<li>Tea</li>
<li>Milk</li>
</ul>

}

7)Is there any difference between HTML.ActionLink vs Url.Action or they are just two ways of doing the same thing?

Yes, there is a difference. Html.ActionLink generates an <a href=".."></a> tag whereas Url.Action returns only an url.
For example:
@Html.ActionLink("link text", "someaction", "somecontroller", new { id = "123" }, null)
 
generates:
<a href="/somecontroller/someaction/123">link text</a>
 
and Url.Action("someaction", "somecontroller", new { id = "123" }) generates:
/somecontroller/someaction/123

8)Helper Classes

There are several Helper classes in MVC frame work.

1.Form Helper- Radio buttons, textboxes,list boxes etc.

2.URL helpers

3.HTML helpers- Encode, Decode, AttributeEncode, and RenderPartial.
 
9)@Url.Content 
 
Url.Content is used when you wish to resolve a url for any file or resource on your site and you would pass it the relative path:

@Url.Content("~/path/file.htm") Url.Action is used to resolve an action from a controller such as:

@Url.Action("ActionName", "ControllerName", new { variable = value })
 
You could create a URL that invokes the action with it like this:
Url.Action("YourAction", "YourController")
 
@Url.Content resolves a virtual path into an absolute path. Example:
Url.Content("~/images/image.jpg")

10)What is the difference between  @Html.Action & @Html.RenderAction ?

@Html.RenderAction(Action, Controller, Route)

@Html.Action("Breadcrumb", "Navigation", new {SeoUrl = Model.CarlineBucket.SEOURLName})

@Html.RenderAction("Breadcrumb", "Navigation", new {SeoUrl = Model.CarlineBucket.SEOURLName})

The difference between the two is that Html.RenderAction will render the result directly to the Response (which is more efficient if the action returns a large amount of HTML) whereas Html.Action returns a string with the result.

11) What is the difference between @Html.Parcial and @Html.Renderparcial

The code below demonstrates the call to render the featured product partial view.
<div>
  @Html.Partial("_FeaturedProduct")
</div>

Partial views can be rendered inside a Layout Page (or if using MVC 2/3 w/ASPX, the Master Page) as well as regular views.

There are some cases where you might like to step aside and write directly to the HTTP Response stream rather than having a partial view render the results (partials/views use MvcHtmlString/StringWriter). To do so, use the Html.RenderPartial helper.

As with strongly typed views, strongly typed partial views also support dot notation syntax and access to the model, ViewBag, ViewData and other classes specifically designed for sharing data.

For Example
   <div>
        <div>
            <h2>Our Featured product:<br />
                 @ViewBag.FeaturedProduct.Name
           </h2>
    </div>   <div>
<h3>
 Now discounted to $@String.Format("{0:F}", ((decimal)ViewBag.FeaturedProduct.Price)-100)
 </h3>
 </div>


 12) MVC Points to ponder

Html.RenderPartial

  1. This method result will be directly written to the HTTP response stream means it used the same TextWriter object as used in the current webpage/template.
  2. This method returns void.
  3. Simple to use and no need to create any action.
  4. RenderPartial method is useful used when the displaying data in the partial view is already in the corresponding view model.For example : In a blog to show comments of an article, we would like to use RenderPartial method since an article information with comments are already populated in the view model.
    1. @{Html.RenderPartial("_Comments");}
  5. This method is faster than Partial method since its result is directly written to the response stream which makes it fast.

Html.RenderAction

  1. This method result will be directly written to the HTTP response stream means it used the same TextWriter object as used in the current webpage/template.
  2. For this method, we need to create a child action for the rendering the partial view.
  3. RenderAction method is useful when the displaying data in the partial view is independent from corresponding view model.For example : In a blog to show category list on each and every page, we would like to use RenderAction method since the list of category is populated by the different model.
    1. @{Html.RenderAction("Category","Home");}
  4. This method is the best choice when you want to cache a partial view.
  5. This method is faster than Action method since its result is directly written to the HTTP response stream which makes it fast.

Html.Partial

  1. Renders the partial view as an HTML-encoded string.
  2. This method result can be stored in a variable, since it returns string type value.
  3. Simple to use and no need to create any action.
  4. Partial method is useful used when the displaying data in the partial view is already in the corresponding view model.For example : In a blog to show comments of an article, we would like to use RenderPartial method since an article information with comments are already populated in the view model.
    1. @Html.Partial("_Comments")

Html.Action

  1. Renders the partial view as an HtmlString .
  2. For this method, we need to create a child action for the rendering the partial view.
  3. This method result can be stored in a variable, since it returns string type value.
  4. Action method is useful when the displaying data in the partial view is independent from corresponding view model.For example : In a blog to show category list on each and every page, we would like to use Action method since the list of category is populated by the different model.
    1. @{Html.Action("Category","Home");}
  5. This method is also the best choice when you want to cache a partial view.
13) MVC Razor - Custom Html Helper Calsses . Point to ponder

                  i. All Html helper classes are static.
                 ii. All helper methods are static.
                iii. One of the parameters of helper method should be HTMLHelper object.
                iv. The return type of every Html helper method will be "MVCHtmlString"
                 v. Add the reference of Helper class project to current MVC project. Include the namespace of html helper class in web.config of MVC app.

14) Advantages of MVC Pattern

·         It provides a clean separation of concerns.
·         It is easier to test code that implements this pattern.
·         It promotes better code organization, extensibility, scalability and code re-use.
·         It facilitates de-coupling the application's layers.

15) Mention some of the return types of a controller action method ?

An action method is used to return an instance of any class which is derived from ActionResult class.
Some of the return types of a controller action method are:
i) ViewResult : It is used to return a webpage from an action method
ii) PartialViewResult : It is used to send a section of a view to be rendered inside another view.
iii) JavaScriptResult : It is used to return JavaScript code which will be executed in the user’s browser.
iv) RedirectResult : Based on a URL, It is used to redirect to another controller and action method.
v) ContentResult : It is an HTTP content type may be of text/plain. It is used to return a custom content type as a result of the action method.
vi) JsonResult : It is used to return a message which is formatted as JSON.
vii) FileResult : It is used to send binary output as the response.
viii) EmptyResult : It returns nothing as the result.



16)Explain about 'page lifecycle' of ASP.NET MVC ?

The page lifecycle of an ASP.NET MVC page is explained as follows:

i) App Initialisation
In this stage, the aplication starts up by running Global.asax’s Application_Start() method.
In this method, you can add Route objects to the static RouteTable.Routes collection.
If you’re implementing a custom IControllerFactory, you can set this as the active controller factory by assigning it to the System.Web.Mvc.ControllerFactory.Instance property.

ii) Routing
Routing is a stand-alone component that matches incoming requests to IHttpHandlers by URL pattern.
MvcHandler is, itself, an IHttpHandler, which acts as a kind of proxy to other IHttpHandlers configured in the Routes table.

iii) Instantiate and Execute Controller
At this stage, the active IControllerFactory supplies an IController instance.

iv) Locate and invoke controller action
At this stage, the controller invokes its relevant action method, which after further processing, calls RenderView().

v) Instantiate and render view
At this stage, the IViewFactory supplies an IView, which pushes response data to the IHttpResponse object.

17) Explain about the formation of Router Table in ASP.NET MVC ?

The Router Table is formed by following the below procedure:

In the begining stage, when the ASP.NET application starts, the method known as Application_Start() method is called.
The Application_Start() will then calls RegisterRoutes() method.
This RegisterRoutes() method will create the Router table.

18) Explain about default route, {resource}.axd/{*pathInfo} ...

With the help of this default route {resource}.axd/{*pathInfo}, you can prevent requests for the web resources files such as WebResource.axd or ScriptResource.axd from being passed to a controller.


19)Is the route {controller}{action}/{id} a valid route definition or not and why ?

{controller}{action}/{id} is not a valid route definition.
The reason is that, it has no literal value or delimiter between the placeholders.
If there is no literal, the routing cannot determine where to seperate the value for the controller placceholder from the value for the action placeholder.








20) Difference between Viewbag and Viewdata in ASP.NET MVC ?

Both are used to pass the data from controllers to views.
The difference between Viewbag and Viewdata in ASP.NET MVC is explained below:

View Data:
In this, objects are accessible using strings as keys.

Example:

In the Controller:
public ActionResult Index()
{
var softwareDevelopers = new List<string>
{
"Brendan Enrick",
"Kevin Kuebler",
"Todd Ropog"
};
ViewData["softwareDevelopers"] = softwareDevelopers;
return View();
}

In the View:
<ul>
@foreach (var developer in (List<string>)ViewData["softwareDevelopers"])
{
<li>
@developer
</li>
}
</ul>

An important note is that when we go to use out object on the view that we have to cast it since the ViewData is storing everything as object.

View Bag:
It will allow the objectto dynamically have the properties add to it.

Example:

In the Controller:
public ActionResult Index()
{
var softwareDevelopers = new List<string>
{
"Brendan Enrick",
"Kevin Kuebler",
"Todd Ropog"
};
ViewBag.softwareDevelopers = softwareDevelopers;
return View();
}

In the View:
<ul>
@foreach (var developer in ViewBag.softwareDevelopers)
{
<li>
@developer
</li>
}
</ul>

An important point to note is that there is no need to cast our object when using the ViewBag. This is because the dynamic we used lets us know the type.

@Html.Partial
@Html.Partial
 
1)What is Model view controller ?
2)Where is the route mapping code written?
3)How to implement AJAX in MVC
4)How do we implement minification?
5)What is Razor in MVC?
6)Can we map multiple URLs to the same action?
7)So which is a better fit, Razor or ASPX?

বাঙালির বেড়ানো সেরা চারটি ঠিকানা

  বাঙালি মানে ঘোড়া পাগল | দু একদিন ছুটি পেলো মানে বাঙালি চলল ঘুরতে | সে সমুদ্রই হোক , পাহাড়ি হোক বা নদী হোক। বাঙালির ...