Monday, 3 November 2014

SQL Server 2012 Magic

1)Unusual Sort Orders
         (Order by Contain Case)

SELECT  certificate_id,
                certificate_name,
                certificate_code,
                type_id,
               date_position
                              FROM tbl_sref_train_certificate
                             ORDER BY
                                     CASE
date_position WHEN NULL
                                        THEN type_id
                                   ELSE  date_position  END

2) NULLIF,COALESCE

ISNULL : Returns a null value if the two specified expressions are equal.

SELECT NULLIF(2,2)

Result
----------------------------------------
 NULL

SELECT NULLIF(2,3) 
Result
----------------------------------------
2

COALESCE : coalesce returns the first non-null expression among its arguments.

Example 1
SELECT COALESCE(NULL, NULL, NULL, GETDATE()) 

Result
----------------------------------------
2014-11-02 22:48:40.780

The above example may have single value or four values. If it has single value, then it fills null values with remaining attributes.

---------------------------------------------------------------
column 1              |     column1
----------------------------------------------------------------
 Abc                          NULL
NULL                      Efg
--------------------------------------------------------------

Example 2
 SELECT COALESCE(column 1, column1 )

Result
----------------------------------------
  Abc
 Efg

Example 3
Concatination

---------------------------------------------------------------
Country              |     Currency
----------------------------------------------------------------
India                          Rupee
Japan                         Yen
--------------------------------------------------------------


SELECT  Country ,
                 Currency,
                 COALESCE(Country,Currency)  As Country_Currency

---------------------------------------------------------------
Country              |     Currency     | Country_Currency
----------------------------------------------------------------
India                          Rupee           India Rupee          
Japan                         Yen               Japan Yen                              
--------------------------------------------------------------

3) UNION AND UNION Goof Exapmle

DECLARE @test1 TABLE
(
  ID INT,
  NAME VARCHAR(200)
)
DECLARE @test2 TABLE
(
  ID INT,
  NAME VARCHAR(200)
)

INSERT INTO @test1 VALUES (1,NULL),(2,'India'),(3,'Japan'),(4,NULL)
INSERT INTO @test1 VALUES (1,NULL),(2,'USA'),(3,'Braziln'),(4,NULL),(1,'India')

SELECT ID,NAME FROM @test1
UNION
SELECT ID,NAME FROM @test2

SELECT ID,NAME FROM @test1
UNION ALL
SELECT ID,NAME FROM @test2

Result
----------------------------------------
ID NAME
-----------------------------------------
1    NULL
1    India
2    India
2    USA
3    Braziln
3    Japan
4    NULL

Result
----------------------------------------
ID NAME
-----------------------------------------
1    NULL
2    India
3    Japan
4    NULL
1    NULL
2    USA
3    Braziln
4    NULL
1    India

4)Random Rows Return

SELECT  member_id,
        last_name,
        first_name
 FROM tbl_member
 TABLESAMPLE SYSTEM (1 PERCENT);

Result (1st Execution)
----------------------------------------
102  rows

Result (2st Execution)
----------------------------------------
106  rows

So on...

5)Overriding an IDENTITY Column

CREATE TABLE TEST
(
    ID INT IDENTITY  ,
    COUNTRY VARCHAR(200)
)

INSERT INTO TEST (COUNTRY) VALUES ('India'),('Brazil'),('China')

SELECT * FROM TEST

Result
----------------------------------------
ID NAME
-----------------------------------------
1    India
2    Brazil
3    China



SET IDENTITY_INSERT [Database].TEST
INSERT INTO TEST (COUNTRY) VALUES (4,'Pakistan'),(5,'Irac')


----------------------------------------
ID NAME
-----------------------------------------
1    India
2    Brazil
3    China
4   Pakistan
5   Irac


6) Deleting Rows and Returning the Deleted Rows

CREATE TABLE TEST
(
    ID INT IDENTITY  ,
    COUNTRY VARCHAR(200)
)

INSERT INTO TEST (COUNTRY) VALUES  ( 'India' ),( 'Brazil'  ),(  'China'  ),(  'Nepal'  )

DELETE
FROM TEST
OUTPUT deleted.COUNTRY
WHERE ID=4

7) Inserting Rows and Returning the Inserted Rows

CREATE TABLE TEST
(
    ID INT  ,
    COUNTRY VARCHAR(200)
)

INSERT INTO TEST (ID,COUNTRY)
OUTPUT INSERTED.COUNTRY,INSERTED.ID
VALUES       (1,'India')  ,  (2,'Brazil')  ,  (3,'China')  ,  (4,'Nepal')

8)Updating Data and Returning the Affected Rows

CREATE TABLE TEST
(
    ID INT  ,
    COUNTRY VARCHAR(200)
)

INSERT INTO TEST (ID,COUNTRY)
VALUES (1,'India') , (2,'Brazil') , (3,'China') , (4,'Nepal')


CREATE TABLE TEST1
(
    ID INT  ,
    COUNTRYX VARCHAR(200) NULL
)

INSERT INTO TEST1
VALUES (1,NULL),(2,NULL),(3,NULL),(4,NULL)

SELECT * FROM TEST1

UPDATE A
           SET A.COUNTRYX=B.COUNTRY
           OUTPUT INSERTED.COUNTRYX
FROM  TEST1 A
INNER JOIN TEST B
ON A.ID=B.ID

SELECT * FROM TEST1


9) SoundIndex ...Sound Like

DROP TABLE TEST

CREATE TABLE TEST
(
    ID INT  ,
    COUNTRY VARCHAR(200)
)

INSERT INTO TEST (ID,COUNTRY)
VALUES (1,'India'   )  ,
                (2,'Brazil'  )  ,
                (3,'China'  )  ,
                (4,'Nepal'  )  ,
                (5,'ian'      )  ,
                (6,'en'       )  ,
                (7,'an'       )  ,
                (8,'am'      ) ,
                (9,'em'      ),
                (10,'am'    )



SELECT  top 5 COUNTRY
FROM TEST
WHERE  SOUNDEX(COUNTRY)=SOUNDEX('inI')

Result
----------------------------------------
COUNTRY
-----------------------------------------
ian


10) Merger Statement

CREATE TABLE TEST
(
    ID INT  ,
    COUNTRY VARCHAR(200)
)

INSERT INTO TEST (ID,COUNTRY)
VALUES    (1,'India'),
                   (2,'Brazil'),
                   (3,'China'),
                   (4,'Nepal'),
                   (5,'ian'),
                   (6,'en'),
                   (7,'an'),
                   (8,'am'),
                   (9,'em'),
                   (10,'am')


CREATE TABLE TEST1
(
    ID INT  ,
    COUNTRYX VARCHAR(200) NULL
)


MERGE INTO TEST1 AS C
USING TEST AS CT
        ON C.ID = CT.ID
WHEN MATCHED THEN
    UPDATE SET
      C.COUNTRYX = CT.COUNTRY    
WHEN NOT MATCHED THEN
      INSERT (ID,COUNTRYX)
      VALUES (CT.ID, CT.COUNTRY);
     
SELECT * FROM TEST1

---------------------------------------------------------------------------------
ID COUNTRYX
----------------------------------------------------------------------------------
1    India
2    Brazil
3    China
4    Nepal
5    ian
6    en
7    an
8    am
9    em
9    am

11) Sring Operation 

LEFT & RIGHT

SELECT LEFT  (  'India Govt has started clean india mission.' , 10)
SELECT RIGHT ( 'India Govt has started clean india mission.' , 10) ;

Result
----------------------------------------
(No column name)
-----------------------------------------
 India Govt


Result
----------------------------------------
(No column name)
-----------------------------------------
a mission.


UPPER & LOWER 

SELECT UPPER ( 'India Govt has started clean india mission. '  )
SELECT LOWER 'India Govt has started clean india mission.'  )

Result
----------------------------------------
(No column name)
-----------------------------------------
 INDIA GOVT HAS STARTED CLEAN INDIA MISSION.


Result
----------------------------------------
(No column name)
-----------------------------------------
india govt has started clean india mission.


12) Date Function

ISDATE :valid date or not

 SELECT MyDate ,ISDATE(MyDate) AS IsValiDate
                                    FROM (
                                                 VALUES 'IsValiDate'   ),
                                                                (  '2012-02-14' ),
                                                                (  '2012-01-01T00:00:00'  ),
                                                                (  '2014-12-31T23:59:59.9999999' )
                                               )   dt(MyDate)

 
Result
--------------------------------------------------------------------------------------------
MyDate                                    |                    IsValiDate
-------------------------------------------------------------------------------------------
 IsValiDate                                                              0
2012-02-14                                                             1
2012-01-01T00:00:00                                            1
2014-12-31T23:59:59.9999999                             0

13) @@IDENTITY && SCOPE_IDENTITY 

@@IDENTITY returns the last identity value generated by any table in the current session. If the insert statement fires a trigger that inserts into another table with an identity column, the value returned by @@IDENTITY will be that of the table inserted into by the trigger.
SCOPE_IDENTITY returns the last identity value generated by any table in the current session and scope. In the previous scenario, SCOPE_IDENTITY returns the identity value returned by the first insert statement, not the insert into the second table from the trigger.

CREATE TABLE TEST
(
    IDX INT IDENTITY ,
    ID INT  ,
    COUNTRY VARCHAR(200)
)

INSERT INTO TEST (ID,COUNTRY)
VALUES    (1  ,  'India'  ),
                   (2  ,  'Brazil' ),
                   (3  ,  'China' ),
                   (4  ,  'Nepal' ),
                   (5  ,  'ian'     ),
                   (6  ,  'en'      ),
                   (7  ,  'an'     ),
                   (8  ,  'am'    ),
                   (9  ,  'em'   ),
                   (10 , 'am'   )

 SELECT @@IDENTITY, SCOPE_IDENTITY(), IDENT_CURRENT('dbo.TEST');

14) ESCAPE 

 SELECT access_name FROM tbl_user
 WHERE  access_name LIKE  '%%%' 












all ,value return , no match for wildcard %

Instead, you can try one of the following solutions:

SELECT access_nameFROM tbl_userWHERE 
    access_name LIKE  '%[%]%' 
 

SELECT access_name FROM tbl_user  WHERE
    access_name LIKE '%\%%' ESCAPE '\'







Wednesday, 3 September 2014

CLASS

1) What is Class ?
           A class is the blueprint from which individual objects.

2) What is constructor ?
A constructor in a class is a special type of subroutine called to create an object. It prepares the new object for use

 class Sample
{
             public string param1, param2;
             public Sample()     // Default Constructor
            {
              param1 = "Welcome";
              param2 = "Aspdotnet-Suresh";
            }
}
 
class Program
{
           static void Main(string[] args)
            {
                      Sample obj=new Sample();   // Once object of class created automatically constructor will be called
                    Console.WriteLine(obj.param1);
                    Console.WriteLine(obj.param2);
                    Console.ReadLine();
            }
}


3) Private & Public & Protected ?

Private :Variables and methods declared with private visibility are not accessible in the child class

Public :Variables and methods declared with public visibility are accessible; but public variables violate our goal of encapsulation

Protected : Variables and methods declared with protected visibility in a parent class are only accessible by a child class or any class derived from that class

4) What is Inheritance ?

Inheritance is when an object or class is based on another object or class, using the same implementation

public class ParentClass
{
           public ParentClass()
           {
           }

           public void print()
           {
        Console.WriteLine("I'm a Parent Class.");
         
} 

}

 public class ChildClass : ParentClass
{
    public ChildClass()
    {
        Console.WriteLine("Child Constructor.");
    }

    public
static void Main()
    {
        ChildClass child =
new ChildClass();
        child.print();
    }
}


5) What is sealed class ?
A sealed class is a class that cannot be inherited. Sealed classes are used to restrict the inheritance


    sealed class SealedClass
    {
        public int x;
        public int y;
    }


6)What is interface ?

An interface contains only the signatures of methods, properties, events or indexers. A class or struct that implements the interface must implement the members of the interface that are specified in the interface definition
 

Using interfaces we can invoke functions from different classes through the same Interface reference, whereas using virtual functions we can invoke functions from different classes in the same inheritance hierarchy through the same reference


interface ISampleInterface
{
    void SampleMethod();
}

class ImplementationClass : ISampleInterface
{
    // Explicit interface member implementation:  
    void ISampleInterface.SampleMethod()
    {
        // Method implementation.
    }

    static void Main()
    {
        // Declare an interface instance.
        ISampleInterface obj = new ImplementationClass();

        // Call the member.
        obj.SampleMethod();
    }
}

7)What is Abstact Class ?

They are classes that cannot be instantiated, and are frequently either partially implemented, or not at all implemented



//Abstract Class1
abstract class absClass1
{
    public abstract int AddTwoNumbers(int Num1, int Num2);
    public abstract int MultiplyTwoNumbers(int Num1, int Num2);
}

//Abstract Class2
abstract class absClass2:absClass1
{
    //Implementing AddTwoNumbers
    public override int AddTwoNumbers(int Num1, int Num2)
    {
        return Num1+Num2;
    }
}

//Derived class from absClass2
class absDerived:absClass2
{
    //Implementing MultiplyTwoNumbers
    public override int MultiplyTwoNumbers(int Num1, int Num2)
    {
        return Num1*Num2;
    } 
} 

8) Abstact Class Vs Interface



                     Interfaces

         Abstract Classes

 A class may inherit several interfaces.
A class may inherit only one abstract class.
Interfaces can only have consts and methods stubs
Abstract classes can have consts, members, method stubs and defined methods, whereas
All methods of an interface must be defined as public
Methods and members of an abstract class can be defined with any visibility
An interface cannot have access modifiers for the subs, functions, properties etc everything is assumed as public
An abstract class can contain access modifiers for the subs, functions, properties


9) Output Parameter C#


   public void getValues(out int x, out int y )
      {
          Console.WriteLine("Enter the first value: ");
          x = Convert.ToInt32(Console.ReadLine());
          Console.WriteLine("Enter the second value: ");
          y = Convert.ToInt32(Console.ReadLine());
      }
   

        /* local variable definition */
         int a , b;
         
         /* calling a function to get the values */
         n.getValues(out a, out b);


10) Event & Delegates

Delegate and Event concepts are completely tied together. Delegates are just function pointers, That is, they hold references to functions.


11) Override

override stands for use one's authority to reject or cancel

abstract class ShapesClass
{
    abstract public int Area();
}
class Square : ShapesClass
{
    int side = 0;

    public Square(int n)
    {
        side = n;
    }
    public override int Area()
    {
        return side * side;
    } 
} 

12)Overloading


mechanism to have more than one method with same name but with different signature (parameters). A method can be overloaded on the basis of following properties
  1. Have different number of parameter
  2. Having same number of parameters but of different type
  3. Having same number and type of parameters but in different orders

public class test
{
    public void getStuff(int id)
    {}
    public void getStuff(string name)
    {}
}

13)What is virtual keyword ?
 
            The virtual keyword is used to modify a method, property, indexer, or event declaration   and allow for it to be overridden in a derived class. For example, this method can be overridden by any class that inherits it.


      When a virtual method is invoked, the run-time type of the object is checked 
for an overriding member. The overriding member in the most derived class is 
called, which might be the original member, if no derived class has overridden 
the member.
 
        class A
        {
           public virtual void Test()
           {
         Console.WriteLine("A.Test");
           }
        }

         class B : A
         {
          public override void Test()
          {
     Console.WriteLine("B.Test");
          }
         }

14)

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?

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

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