Interview Question





1. What is .NET Framework?

 .NET Framework is a complete environment that allows developers to develop, run, and deploy the following applications:

  • Console applications
  • Windows Forms applications
  • Windows Presentation Foundation (WPF) applications
  • Web applications (ASP.NET applications)
  • Web services
  • Windows services
  • Service-oriented applications using Windows Communication Foundation (WCF)
  • Workflow-enabled applications using Windows Workflow Foundation (WF)


.NET Framework also enables a developer to create sharable components to be used in distributed computing architecture. NET Framework supports the object-oriented programming model for multiple languages, such as Visual Basic, Visual C#, and Visual C++. .NET Framework supports multiple programming languages in a manner that allows language interoperability. This implies that each language can use the code written in some other language.

2. What are the main components of .NET Framework?

  .NET Framework provides enormous advantages to software developers in comparison to the advantages provided by other platforms. Microsoft has united various modern as well as existing technologies of software development in .NET Framework. These technologies are used by developers to develop highly efficient applications for modern as well as future business needs. The following are the key components of .NET Framework:

  • .NET Framework Class Library
  • Common Language Runtime
  • Dynamic Language Runtimes (DLR)
  • Application Domains
  • Runtime Host
  • Common Type System
  • Metadata and Self-Describing Components
  • Cross-Language Interoperability
  • .NET Framework Security
  • Profiling
  • Side-by-Side Execution

3. List the new features added in .NET Framework 4.0?

The following are the new features of .NET Framework 4.0:

  • Improved Application Compatibility and Deployment Support
  • Dynamic Language Runtime
  • Managed Extensibility Framework
  • Parallel Programming framework
  • Improved Security Model
  • Networking Improvements
  • Improved Core ASP.NET Services
  • Improvements in WPF 4
  • Improved Entity Framework (EF)
  • Integration between WCF and WF

4. What is an IL?

     Intermediate Language is also known as MSIL (Microsoft Intermediate Language) or CIL (Common Intermediate Language). All .NET source code is compiled to IL. IL is then converted to machine code at the point where the software is installed, or at run-time by a Just-In-Time (JIT) compiler.

 5. What is Manifest?

 Assembly metadata is stored in Manifest. Manifest contains all the metadata needed to do the following things

  • Version of assembly.
  • Security identity.
  • Scope of the assembly.
  • Resolve references to resources and classes.

The assembly manifest can be stored in a PE file either (an .exe or) .dll with Microsoft 
intermediate language (MSIL code with Microsoft intermediate language (MSIL) code or in a 
stand-alone PE file, that contains only assembly manifest information.

 6. What are code contracts?

  Code contracts help you to express the code assumptions and statements stating the behavior of your code in a language-neutral way. The contracts are included in the form of pre-conditions, post-conditions and object-invariants. The contracts help you to improve-testing by enabling run-time checking, static contract verification, and documentation generation.


The System.Diagnostics.Contracts namespace contains static classes that are used to express contracts in your code.

7. Name the classes that are introduced in the System.Numerics namespace?

The following two new classes are introduced in the System.Numerics namespace:

  • BigInteger - Refers to a non-primitive integral type, which is used to hold a value of any size. It has no lower and upper limit, making it possible for you to perform arithmetic calculations with very large numbers, even with the numbers which cannot hold by double or long.
  • Complex - Represents complex numbers and enables different arithmetic operations with complex numbers. A number represented in the form a + bi, where a is the real part, and b is the imaginary part, is a complex number.

8. What is managed extensibility framework?

    Managed extensibility framework (MEF) is a new library that is introduced as a part of .NET 4.0 and Silverlight 4. It helps in extending your application by providing greater reuse of applications and components. MEF provides a way for host application to consume external extensions without any configuration requirement.

9. Explain memory-mapped files?

Memory-mapped files (MMFs) allow you map the content of a file to the logical address of an application. These files enable the multiple processes running on the same machine to share data with each Other. TheMemoryMappedFile.CreateFromFile() method is used to obtain a MemoryMappedFile object that represents a persisted memory-mapped file from a file on disk.

These files are included in the System.IO.MemoryMappedFiles namespace. This namespace contains four classes and three enumerations to help you access and secure your file mappings.

10. What is Common Type System (CTS)?

CTS is the component of CLR through which .NET Framework provides support for multiple languages because it contains a type system that is common across all the languages. Two CTS-compliant languages do not require type conversion when calling the code written in one language from within the code written in another language. CTS provide a base set of data types for all the languages supported by.NET Framework. This means that the size of integer and long variables is same across all .NET-compliant programming languages. However, each language uses aliases for the base data types provided by CTS. For example, CTS uses the data type system. int32 to represent a 4 byte integer value; however, Visual Basic uses the alias integer for the same; whereas, C# uses the alias int. This is done for the sake of clarity and simplicity.

 11. Give a brief introduction on side-by-side execution. Can two applications, one using private assembly and the other using the shared assembly be stated as side-by-side executables?

 Side-by-side execution enables you to run multiple versions of an application or component and CLR on the same computer at the same time. As versioning is applicable only to shared assemblies and not to private assemblies, two applications, one using a private assembly and other using a shared assembly, cannot be stated as side-by-side executables.

 12. Which method do you use to enforce garbage collection in .NET?

   The System.GC.Collect() method.

 

13. State the differences between the Dispose() and Finalize()?

   CLR uses the Dispose and Finalize methods to perform garbage collection of run-time objects of .NET applications.


 The Finalize method is called automatically by the runtime. CLR has a garbage collector (GC), which periodically checks for objects in heap that are no longer referenced by any object or program. It calls the Finalize method to free the memory used by such objects. The Dispose method is called by the programmer. Dispose is another method to release the memory used by an object. The Dispose method needs to be explicitly called in code to dereference an object from the heap. The Dispose method can be invoked only by the classes that implement the IDisposableinterface.

 14. What is code access security (CAS)?

 Code access security (CAS) is part of the .NET security model that prevents unauthorized access of resources and operations, and restricts the code to perform particular tasks.

 15. Differentiate between managed and unmanaged code?

  Managed code is the code that is executed directly by the CLR instead of the operating system. The code compiler first compiles the managed code to intermediate language (IL) code, also called as MSIL code. This code doesn't depend on machine configurations and can be executed on different machines.


  Unmanaged code is the code that is executed directly by the operating system outside the CLR environment. It is directly compiled to native machine code which depends on the machine configuration.
  In the managed code, since the execution of the code is governed by CLR, the runtime provides different services, such as garbage collection, type checking, exception handling, and security support. These services help provide uniformity in platform and language-independent behavior of managed code applications. In the unmanaged code, the allocation of memory, type safety, and security is required to be taken care of by the developer. If the unmanaged code is not properly handled, it may result in memory leak. Examples of unmanaged code are ActiveX components and Win32 APIs that execute beyond the scope of native CLR.

 16. What are tuples?

 Tuple is a fixed-size collection that can have elements of either same or different data types. Similar to arrays, a user must have to specify the size of a tuple at the time of declaration. Tuples are allowed to hold up from 1 to 8 elements and if there are more than 8 elements, then the 8th element can be defined as another tuple. Tuples can be specified as parameter or return type of a method.

 

17. How can you turn-on and turn-off CAS?

  You can use the Code Access Security Tool (Caspol.exe) to turn security on and off.


 To turn off security, type the following command at the command prompt:
caspol -security off 

 To turn on security, type the following command at the command prompt:
caspol -security on 

In the .NET Framework 4.0, for using Caspol.exe, you first need to set the <LegacyCasPolicy> element to true.

 18. What is garbage collection? Explain the difference between garbage collections in .NET 4.0 and earlier versions?

 Garbage collection prevents memory leaks during execution of programs. Garbage collector is a low-priority process that manages the allocation and deallocation of memory for your application. It checks for the unreferenced variables and objects. If GC finds any object that is no longer used by the application, it frees up the memory from that object.


GC has changed a bit with the introduction of .NET 4.0. In .NET 4.0, the GC.Collect() method contains the following overloaded methods:

GC.Collect(int)

GC.Collect(int, GCCollectionMode)

Another new feature introduced in .NET is to notify you when the GC.Collect() method is invoked and completed successfully by using different methods. The .NET 4.0 supports a new background garbage collection that replaces the concurrent garbage collection used in earlier versions. This concurrent GC allocates memory while running and uses current segment (which is 16 MB on a workstation) for that. After that, all threads are suspended. In case of background GC, a separate ephemeral GC - gen0 and gen1 can be started, while the full GC - gen0, 1, and 2 - is already running.

 19. How does CAS works?

 There are two key concepts of CAS security policy- code groups and permissions. A code group contains assemblies in it in a manner that each .NET assembly is related to a particular code group and some permissions are granted to each code group. For example, using the default security policy, a control downloaded from a Web site belongs to the Zone, Internet code group, which adheres to the permissions defined by the named permission set. (Normally, the named permission set represents a very restrictive range of permissions.)


Assembly execution involves the following steps:

1.     Evidences are gathered about assembly.
2.     Depending on the gathered evidences, the assembly is assigned to a code group.
3.     Security rights are allocated to the assembly, depending on the code group.
4.     Assembly runs as per the rights assigned to it.

20. What is Difference between NameSpace and Assembly?

 

Following are the differences between namespace and assembly: 

  • Assembly is physical grouping of logical units, Namespace, logically groups classes.
  • Namespace can span multiple assembly.
21. Mention the execution process for managed code?

 A piece of managed code is executed as follows:

  • Choosing a language compiler
  • Compiling the code to MSIL
  • Compiling MSIL to native code
  • Executing the code.

   22. Is there a way to suppress the finalize process inside the garbage collector forcibly in .NET?

  Use the GC.SuppressFinalize() method to suppress the finalize process inside the garbage collector forcibly in .NET.

 23. How can you instantiate a tuple?

  The following are two ways to instantiate a tuple:

  • Using the new operator. For example,

Tuple<String, int> t = new Tuple<String, int> ("Hellow", 2);

  • Using the Create factory method available in the Tuple class. For example,

Tuple<int, int, int> t = Tuple.Create<int, int, int> (2, 4, 5);

24. Which is the root namespace for fundamental types in .NET Framework?

System.Object is the root namespace for fundamental types in .NET Framework.

25. What are the improvements made in CAS in .NET 4.0?

  The CAS mechanism in .NET is used to control and configure the ability of managed code. Earlier, as this policy was applicable for only native applications, the security guarantee was limited. Therefore, developers used to look for alternating solutions, such as operating system-level solutions. This problem was solved in .NET Framework 4 by turning off the machine-wide security. The shared and hosted Web applications can now run more securely. The security policy in .NET Framework 4 has been simplified using the transparency model. This model allows you to run the Web applications without concerning about the CAS policies.


 As a result of security policy changes in .NET Framework 4.0, you may encounter compilation warnings and runtime exceptions, if your try to use the obsolete CAS policy types and members either implicitly or explicitly. However, you can avoid the warnings and errors by using the <NetFx40_LegacySecurityPolicy> configuration element in the runtime settings schema to opt into the obsolete CAS policy behavior.

 26. What is Microsoft Intermediate Language (MSIL)?

  The .NET Framework is shipped with compilers of all .NET programming languages to develop programs. There are separate compilers for the Visual Basic, C#, and Visual C++ programming languages in .NET Framework. Each .NET compiler produces an intermediate code after compiling the source code. The intermediate code is common for all languages and is understandable only to .NET environment. This intermediate code is known as MSIL.

 27. What is lazy initialization?

   Lazy initialization is a process by which an object is not initialized until it is first called in your code. The .NET 4.0 introduces a new wrapper class, System.Lazy<T>, for executing the lazy initialization in your application. Lazy initialization helps you to reduce the wastage of resources and memory requirements to improve performance. It also supports thread-safety.

 28. How many types of generations are there in a garbage collector?

  Memory management in the CLR is divided into three generations that are build up by grouping memory segments. Generations enhance the garbage collection performance. The following are the three types of generations found in a garbage collector:

  • Generation 0 - When an object is initialized, it is said to be in generation 0.
  • Generation 1 - The objects that are under garbage collection process are considered to be in generation 1.
  • Generation 2 - Whenever new objects are created and added to the memory, they are added to generation 0 and the old objects in generation 1 are considered to be in generation 2.

29. Explain covariance and contra-variance in .NET Framework 4.0. Give an example for each?

  In .NET 4.0, the CLR supports covariance and contravariance of types in generic interfaces and delegates. Covariance enables you to cast a generic type to its base types, that is, you can assign a instance of type IEnumerable<Tl> to a variable of type IEnumerable<T2> where, T1 derives from T2. For example,

IEnumerable<string> str1= new List<string> ();

IEnumerable<object> str2= str1;


Contravariance allows you to assign a variable of Action<base> to a variable of type Action<derived>. For example,

IComparer<object> obj1 = GetComparer()

IComparer<string> obj2 = obj1;

.NET framework 4.0 uses some language keywords (out and in) to annotate covariance and contra-variance. Out is used for covariance, while in is used for contra-variance.

Variance can be applied only to reference types, generic interfaces, and generic delegates. These cannot be applied to value types and generic types.

30. How do you instantiate a complex number?

 The following are the different ways to assign a value to a complex number:


By passing two Double values to its constructor. The first value represents the real, and the second value represents imaginary part of a complex number. 
For example,

Complex c1 = new Complex(5, 8); /* It represents (5, 8) */


By assigning a Byte, SByte, Intl6, UIntl6, Int32, UInt32, Int64, UInt64, Single, or Double value to aComplex object. The assigned value represents the real part of the complex number, and its imaginary part becomes0. For example, 

Complex c2 = 15.3; /* It represents (15.3, 0) */


By casting a Decimal or BigInteger value to a Complex object.
For example,

Complex c3 = (Complex) 14.7; /* It represents (14.7, 0) */


Assigning the value returned by an operator to a Complex variable. 
For example,

Complex c4 = c1 + c2; /* It represents (20.3, 8) */

 

31. What is Common Language Specification (CLS)?

 CLS is a set of basic rules, which must be followed by each .NET language to be a .NET- compliant language. It enables interoperability between two .NET-compliant languages. CLS is a subset of CTS; therefore, the languages supported by CLS can use each other's class libraries similar to their own. Application programming interfaces (APIs), which are designed by following the rules defined in CLS can be used by all .NET-compliant languages.

 32. What is the role of the JIT compiler in .NET Framework?

 The JIT compiler is an important element of CLR, which loads MSIL on target machines for execution. The MSIL is stored in .NET assemblies after the developer has compiled the code written in any .NET-compliant programming language, such as Visual Basic and C#.


JIT compiler translates the MSIL code of an assembly and uses the CPU architecture of the target machine to execute a .NET application. It also stores the resulting native code so that it is accessible for subsequent calls. If a code executing on a target machine calls a non-native method, the JIT compiler converts the MSIL of that method into native code. JIT compiler also enforces type-safety in runtime environment of .NET Framework. It checks for the values that are passed to parameters of any method. 

For example, the JIT compiler detects any event, if a user tries to assign a 32-bit value to a parameter that can only accept 8-bit value.

33. What is difference between System.String and System.StringBuilder classes?

 String and StringBuilder classes are used to store string values but the difference in them is that String is immutable (read only) by nature, because a value once assigned to a String object cannot be changed after its creation. When the value in the String object is modified, a new object is created, in memory, with a new value assigned to the String object. On the other hand, the StringBuilder class is mutable, as it occupies the same space even if you change the value. The StringBuilder class is more efficient where you have to perform a large amount of string manipulation.

 34. Describe the roles of CLR in .NET Framework?

 CLR provides an environment to execute .NET applications on target machines. CLR is also a common runtime environment for all .NET code irrespective of their programming language, as the compilers of respective language in .NET Framework convert every source code into a common language known as MSIL or IL (Intermediate Language).


CLR also provides various services to execute processes, such as memory management service and security services. CLR performs various tasks to manage the execution process of .NET applications.

The responsibilities of CLR are listed as follows:

  • Automatic memory management
  • Garbage Collection
  • Code Access Security
  • Code verification
  • JIT compilation of .NET code
 35. What is the difference between int and int32.

 There is no difference between int and int32. System.Int32 is a .NET Class and int is an alias name forSystem.Int32.


36. 

Which of the following statements are TRUE about the .NET CLR?

ü  It provides a language-neutral development & execution environment.

ü  It ensures that an application would not be able to access memory that it is not authorized to   access.

ü  It provides services to run "managed" applications.

ü  The resources are garbage collected.

ü   It provides services to run "unmanaged" applications.




C# Code Optimization Tips

   Code optimization is the vital factor for any applications. Its importance is high. As a good professional programmer we should consider about that. This article describes how can we optimize a program? orcode optimization techniques. Summary of the article:

 v  What is Code Optimization?

v  Optimization of C# Code

 

What is Code Optimization?

   In computing technology, optimization is the process of modifying a system to improve its performance or efficiency. The system can be a single computer program, a collection of computers or internet. Good code optimization can makes the code to run faster and use fewer hardware resources. Even it can make easier to debug and maintain.

   In computer programming, code optimization is done by transforming the code to improve its performance (like code execution time, code size, minimum resources utilization). This transformation can be made either at a high level or at a low level.
The main point of code optimization is to improve the code. There are two parts:

ü  Make the program faster (in terms of execution times or steps)

ü  Make the program smaller (in terms of memory)

 Optimization of C# Code

  Code optimization is an important aspect of writing an efficient C# program. The following tips will helps to increase the speed and efficiency of C# code and application:

v  We should follow standard naming convention

v  The variables and methods/functions name should be relevant and small as far as possible

v  Use X++ instead of X=X+1. Both returns the same result but X++ use fewer characters

v  Remove codes and variables whose are not used

v  If possible remove white spaces (superfluous spaces, new lines, tabs, and comments etc). It increases the code sizes

v  Use List<> instead of ArrayList. Because List<> is less cost effective

v  Use ‘for’ Loop instead of ‘for-each’ Loop


SQL Queries Optimization Tips

    Every time we writes lot of SQL queries. But most of the time we don’t consider its efficiency. Query optimization is the vital process for any database related applications. Its importance is high. It can makes any complex application simple. This article describes how we can optimize SQL query? Summary of the article:

 v  What is SQL Query Optimization?

v  Some SQL Query Optimization Tips

 What is SQL Query Optimization?

  Query Optimization is the process to write the query in such a way that it execute quickly. It is very important for any standard application.

 Some SQL Query Optimization Tips

    All time we use lot of SQL queries in our application. But we don’t consider about its performance. If we follow some tips then our query will be more efficient. Some of them are.

v  Use views and stored procedures instead of heavy-duty queries.  It reduces network traffic

v  Try to use constraints instead of triggers, whenever possible.  Constraints are much more efficient than triggers and can boost performance

v  Use table variables instead of temporary tables

v  Try to use UNION ALL statement instead of UNION. The UNION ALL statement is much faster than UNION, because UNION ALL statement does not look for duplicate rows, and UNION statement does look for duplicate rows, whether or not they exist

v  Try to avoid using the DISTINCT clause

v  Try to avoid using SQL Server cursors, whenever possible. If required must use cursor standard way.

v  Try to avoid the HAVING clause

v  Include SET NOCOUNT ON statement into stored procedures. It shows the number of rows affected by a T-SQL statement. This can reduce network traffic, because your client will not want to see this

v  Try to return only the required column rather than all columns of a table

v  Don’t use unnecessary complex join

v  Don’t use more number of trigger

v  Use indexing in the table and follow its standard






ASP.NET 

1.       What Are The New Data Controls In Asp.net 2.0?

 

 Data access in ASP.NET 2.0 can be accomplished completely declaratively (no code) using the new data-bound and data source controls. There are new data source controls to represent different data backends such as SQL database, business objects, and XML, and there are new data-bound controls for rendering common UI for data, such as gridview, detailsview, and formview.


2.       What Are The New Navigation Controls In Asp.net 2.0?

 

 The navigation controls provide common UI for navigating between pages in your site, such as treeview, menu, and sitemappath. These controls use the site navigation service in ASP.NET 2.0 to retrieve the custom structure you have defined for your site.


3.      What Are The New Login Controls In Asp.net 2.0?

 

 The new login controls provide the building blocks to add authentication and authorization-based UI to your site, such as login forms, create user forms, password retrieval, and custom UI for logged in users or roles. These controls use the built-in membership and role services in ASP.NET 2.0 to interact with the user and role information defined for your site.


4.      What Are The New Web Part Controls In Asp.net 2.0 ?

 

Web parts are an exciting new family of controls that enable you to add rich, personalized content and layout to your site, as well as the ability to edit that content and layout directly from your application pages. These controls rely on the personalization services in ASP.NET 2.0 to provide a unique experience for each user in your application.


5.      What Are Master Pages?

 

 Master Page feature provides the ability to define common structure and interface elements for your site, such as a page header, footer, or navigation bar, in a common location called a "master page", to be shared by many pages in your site. In one simple place you can control the look, feel, and much of functionality for an entire Web site. This improves the maintainability of your site and avoids unnecessary duplication of code for shared site structure or behavior.


6.      What Are Themes And Skins In 2.0, Explain Usage Scenario?

 

 The themes and skins features in ASP.NET 2.0 allow for easy customization of your site's look-and-feel. You can define style information in a common location called a "theme", and apply that style information globally to pages or controls in your site. Like Master Pages, this improves the maintainability of your site and avoid unnecessary duplication of code for shared styles.


7.      What Is A Profile Object, Why Is It Used?

 

  Using the new personalization services in ASP.NET 2.0 you can easily create customized experiences within Web applications. The Profile object enables developers to easily build strongly-typed, sticky data stores for user accounts and build highly customized, relationship based experiences. At the same time, a developer can leverage Web Parts and the personalization service to enable Web site visitors to completely control the layout and behavior of the site, with the knowledge that the site is completely customized for them. Personalizaton scenarios are now easier to build than ever before and require significantly less code and effort to implement.


8.      What Is Configuration Api?

  ASP.NET 2.0 contains new configuration management API's, enabling users to programmatically build programs or scripts that create, read, and update Web.config and machine.config configuration files.


9.      What Is Mmc Admin Tool?

 

  ASP.NET 2.0 provides a new comprehensive admin tool that plugs into the existing IIS Administration MMC, enabling an administrator to graphically read or change common settings within our XML configuration files.


10.  Explain The Use Of Pre-compilation Tool?

 

    ASP.NET 2.0 delivers a new application deployment utility that enables both developers and administrators to precompile a dynamic ASP.NET application prior to deployment. This precompilation automatically identifies any compilation issues anywhere within the site, as well as enables ASP.NET applications to be deployed without any source being stored on the server (one can optionally remove the content of .aspx files as part of the compile phase), further protecting your intellectual property.


11.  How Is Application Management And Maintenance Improved In Asp.net 2.0?

 

  ASP.NET 2.0 also provides new health-monitoring support to enable administrators to be automatically notified when an application on a server starts to experience problems. New tracing features will enable administrators to capture run-time and request data from a production server to better diagnose issues. ASP.NET 2.0 is delivering features that will enable developers and administrators to simplify the day-to-day management and maintenance of their Web applications.


12.  What Are Provider-driven Application Services? Explain In Detail?

 

     ASP.NET 2.0 now includes built-in support for membership (user name/password credential storage) and role management services out of the box. The new personalization service enables quick storage/retrieval of user settings and preferences, facilitating rich customization with minimal code. The new site navigation system enables developers to quickly build link structures consistently across a site. As all of these services are provider-driven, they can be easily swapped out and replaced with your own custom implementation. With this extensibility option, you have complete control over the data store and schema that drives these rich application services.


13.  Explain Server Control Extensibility With Reference To Asp.net 2.0 ?

 

   ASP.NET 2.0 includes improved support for control extensibility, such as more base classes that encapsulate common behaviors, improved designer support, more APIs for interacting with client-side script, metadata-driven support for new features like themes and accessibility verification, better state management, and more.


14.  What Are The Data Source Controls?

 

   Data access in ASP.NET 2.0 is now performed declaratively using data source controls on a page. In this model, support for new data backend storage providers can be easily added by implementing custom data source controls. Additionally, the SqlDataSource control that ships in the box has built-in support for any ADO.NET managed provider that implements the new provider factory model in ADO.NET.


15.  What Are Compilation Build Providers?

 

   Dynamic compilation in ASP.NET 2.0 is now handled by extensible compilation build providers, which associate a particular file extension with a handler that knows how to compile that extension dynamically at runtime. For example, .resx files can be dynamically compiled to resources, .wsdl files to web service proxies, and .xsd files to typed DataSet objects. In addition to the built-in support, it is easy to add support for additional extensions by implementing a custom build provider and registering it in Web.config.


16.  What Is Expression Builders, Why Would You Use It?

 

   ASP.NET 2.0 introduces a declarative new syntax for referencing code to substitute values into the page, called Expression Builders. ASP.NET 2.0 includes expression builders for referencing string resources for localization, connection strings, application settings, and profile values. You can also write your own expression builders to create your own custom syntax to substitute values in a page rendering.


17.  Is Asp.net 64-bit Enabled? How?

 

   ASP.NET 2.0 is now 64-bit enabled, meaning it can take advantage of the full memory address space of new 64-bit processors and servers. Developers can simply copy existing 32-bit ASP.NET applications onto a 64-bit ASP.NET 2.0 server and have them automatically be JIT compiled and executed as native 64-bit applications (no source code changes or manual re-compile are required).


18.  Explain How Caching In Asp.net 2.0 Is Different From Caching In Asp.net 1.1?

 

  ASP.NET 2.0 also now includes automatic database server cache invalidation. This powerful and easy-to-use feature allows developers to aggressively output cache database-driven page and partial page content within a site and have ASP.NET automatically invalidate these cache entries and refresh the content whenever the back-end database changes. Developers can now safely cache time-critical content for long periods without worrying about serving visitors state data.


19.  Can We Bind Data To A Server Control Without Writing Code In .net?

 

   Yes, that is possible. ASP.NET 2.0 has the feature of declarative solution for data binding which requires no code at all for the most common data scenarios, such as:
*Selecting and displaying
*Data Sorting
*Paging and Caching
*Data Updating
*Inserting and Deleting Data


20.  What Is A Nested Masterpage In Asp.net 2.0? Can There Be A Master Page Inside A Masterpage?

 

   When a master page is placed inside the contentplaceholder of a masterpage, then the masterpage is said to be nested. In other words, there is one parent masterpage, and the child masterpage is inside the content placeholder of the parent masterpage.


21.  How To Sort The Contents Of A Gridview Control?

 

   The ASP.NET 2.0 GridView control is a powerful control, the enables sorting of the rows based on a column, all this possible, without writing code. Well thats what we call power.

The GridView control relies on the underlying data source control to whom this is bound for the sorting capability. The GridView needs to have an AccessDataSource or an SQlDataSource or an ObjectDataSource (if the SortParameterName property is set to a value allowed.

The AllowSorting property of the GridView control, when set to true, enables sorting of the GridView. A sortable GridView has the Header column represented as a LinkButton control. When this Link Button is clicked, the Sorting event of the GridView is raised server-side, which causes a postback and in turn, sorts the GridView control's records.



22.  What Does The Hotspot Class In .net Do? What Is An Imagemap In Asp.net?

 

   An ImageMap is an ASP.NET control that allows clicks inside a polygon like (called Hotspot) region in a webpage. Well, that actually means you may create a star-shaped or diamond shaped button.

There are several pre-defined shapes allowed inside an ImageMap for which templates may be used. For example, for a rectangle, an asp:RectangularHotSpot may be used. For a circle, an asp:CircleHotSpot may be used. And for creating stars & diamonds, an asp:PolygonHotSpot may be used. An image may also be put in an ImageMap which may be specified by its ImageUrl property.

In order to invoke an event, the HotSpotMode property needs to be set to PostBack. Further, if several HotSpots are placed inside an ImageMap, the event of the ImageMap may be passed a value using the PostBackValue property.

Code below shows how to create a Polygon HotSpot using an ImageMap.

<asp:ImageMap ID="ImageMap1" Runat="Server"
ImageUrl="Photo.gif" OnClick="SomeEvent"
AlternateText="Click Here"
HotSpotMode="Navigate">

<asp:PolygonHotSpot
AlternateText="Click Here Too!"
Coordinates="100,150, 250,350, 210,290, 90,350, 60,240"
NavigateUrl="http://www.asp.net"
Target="_blank"/>
</asp:ImageMap>


23.  How Do We Update And Delete Data In A Gridview? Datakeynames Property In .net?

 

   The best way to Update or Delete a record in a GridView control is to include a CheckBox column and a Submit Button.

The GridView has its own Delete and Edit functionality. If the GridView is populated with data using an SqlDataSource, checkout the wizard that comes along with the SqlDataSource. It may be used to automatically create an SQL Delete command and specify the delete parameters.

The DataKeyNames property of the GridView is set to a field name of the Table.


24.  What Is Asp.net?

 

  ASP.NET is a programming framework built on the common language runtime that can be used on a server to build powerful Web applications.


25.  Why Does My Asp.net File Have Multiple Tag With Runat=server?

 

   This means that ASP.Net is not properly registered with IIS. .Net framework provides an Administration utility that manages the installation and uninstallation of multiple versions of ASP.NET on a single machine. You can find the file in C:\WINNT\Microsoft.NET \Framework\v**\aspnet_regiis.exe
use the command: aspnet_regiis.exe -u ---> to uninstall current asp.net version.
use the command: aspnet_regiis.exe -i ---> to install current asp.net version.

For Windows Server 2003, you must use aspnet_regiis -i -enable This is because of the "Web Service Extensions" feature in IIS 6 (if you install VS.NET or the framework without IIS installed, and then go back in and install IIS afterwards, you have to re-register so that ASP.NET 'hooks' into IIS properly."


26.  How To Find Out What Version Of Asp.net I Am Using On My Machine?

 

VB.NET
Response.Write(System.Environment.Version.ToString())

C#
Response.Write(System.Environment.Version.ToString());


27.  Is It Possible To Pass A Querystring From An .asp Page To Aspx Page?

 

Yes you can pass querystring from .asp to ASP.NET page.asp <%response.redirect "webform1.aspx?id=11 " %> .aspx

VB.NET
Response.Write (Request("id").ToString())

C#
Response.Write (Request["id"].ToString());


28.  How To Comment Out Asp.net Tags?

 

<%--<asp:Label id="Label1" style="Z-INDEX: 101; LEFT: 8px; POSITION: absolute; TOP: 48px" runat="server"> Label</asp: Label>--%>


29.  What Is A Viewstate?

 

    In classic ASP, when a form is submitted the form values are cleared. In some cases the form is submitted with huge information. In such cases if the server comes back with error, one has to re-enter correct information in the form. But submitting clears up all form values. This happens as the site does not maintain any state (ViewState).

In ASP.NET, when the form is submitted the form reappears in the browser with all form values. This is because ASP.NET maintains your ViewState. ViewState is a state management technique built in ASP.NET. Its purpose is to keep the state of controls during subsequent postbacks by the same user. The ViewState indicates the status of the page when submitted to the server. The status is defined through a hidden field placed on each page with a <form runat="server"> control.

<input type="hidden" name= "_VIEWSTATE"  value="dDwyNTA 3OTU0NDM7Oz 7t5Tntzk OUeB0QVV6FT2hvQwtp"  Pw =="/>

If you want to NOT maintain the ViewState, include the directive <%@ Page Enable View State="false"%> at the top of an .aspx page If you do not want to maintain Viewstate for any control add the attribute Enable View State="false" to any control.


30.  Where Can I Get The Details On Migration Of Existing Projects Using Various Technologies To Asp.net?

 

  Microsoft has designed Migration Assistants to help us convert existing pages and applications to ASP.NET. It does not make the conversion process completely automatic, but it will speed up project by automating some of the steps required for migration. Below are the Code Migration Assistants
•ASP to ASP.NET Migration Assistant
•PHP to ASP.NET Migration Assistant
•JSP to ASP.NET Migration Assistant


31.  What Is The Equivalent Of Date() And Time() In Asp.net?

 

VB.NET
System.DateTime.Now.ToShortDateString()
System.DateTime.Now.ToShortTimeString()

C#
System.DateTime.Now.ToShortDateString();
System.DateTime.Now.ToShortTimeString();


32.   How To Prevent A Button From Validating It's Form?

 

Set the CauseValidation property of the button control to False.


33.  How To Get The Ip Address Of The Host Accessing My Site?

 

VB.NET
Response.Write (Request.UserHostAddress.ToString ())

C#
Response.Write (Request.UserHostAddress.ToString ());


34.  How To Access The Parameters Passed In Via The Url?

 

Call the Request.QueryStringmethod passing in the key. The method will return the parameter value associated with that key. VB.NET
Request.QueryString("id")

C#
Request.QueryString["id"];


35.  How To Display A Wait Page While A Query Is Running?

 

Refer Asynchronous Wait State Pattern in ASP.NET.


36.  How To Implement Form Based Authentication In Asp.net Application?

 

For
•VB.NET
•C#


37.  Is There A Method Similar To Response.redirect That Will Send Variables To The Destination Page Other Than Using A Query String Or The Post Method?

 

   Server.Transfer preserves the current page context, so that in the target page you can extract values and such. However, it can have side effects; because Server.Transfer doesnt' go through the browser, the browser doesn't update its history and if the user clicks Back, they go to the page previous to the source page.
Another way to pass values is to use something like a LinkButton. It posts back to the source page, where you can get the values you need, put them in Session, and then use Response.Redirect to transfer to the target page. (This does bounce off the browser.) In the target page you can read the Session values as required.


38.  What Are The Differences Between Html Versus Server Control?

 

Refer
•ASP.NET Server Controls Recommendations
•Introduction to ASP.NET Server Controls


39.  How Can I Change The Action Of A Form Through Code?

 

You cannot change it. The action attribute is owned by ASP.NET. Handle Events and Transfer.


40.  Is There Any Control That Allows User To Select A Time From A Clock - In Other Words Is There A Clock Control?

 

Peter Blum has developed some controls. Check out Peter's Date Package: TimeOfDayTextBox and Duration Text Box Controls.


41.  How To Work With Timespan Class?

 

VB.NET
Dim adate As DateTime = DateTime.Parse("06/24/2003")
Dim bdate As DateTime = DateTime.Parse("06/28/2003")
Dim ts As New TimeSpan(bdate.Ticks - adate.Ticks)
Response.Write(ts.TotalDays & "")
Response.Write(ts.TotalHours & ":" & ts.TotalMinutes & ":" & ts.Total Seconds & ":" & ts.TotalMilliseconds)

C#
DateTime adate = DateTime.Parse("06/24/2003");
DateTime bdate = DateTime.Parse("06/28/2003");
TimeSpan ts = new TimeSpan (bdate.Ticks - adate.Ticks);
Response.Write(ts.TotalDays.ToString () + "");
Response.Write(ts.TotalHours.ToString() + ":" + ts.Total Minutes. ToString() + ":" + ts.Total Seconds.ToString() + ":" + ts.Total Milli seconds.ToString() );


42.      Does Asp.net Still Recognize The Global.asa File?

 

ASP.Net does not recognize the standard ASP global.asa file. Instead it uses a file named global.asax with the same - plus additional - functionality


43.      How Should I Destroy My Objects In Asp.net?

 

 ASP.Net actually has very solid internal garbage collection. So this is not an issue as it was in previous versions of Active Server Pages.


44.      Are There Resources Online With Tips On Asp To Asp.net Conversions?

 

  Microsoft has deisnged The ASP to ASP.NET Migration Assistant help us convert ASP pages and applications to ASP.NET. It does not make the conversion process completely automatic, but it will speed up project by automating some of the steps required for migration. The following Code Migration Assistants are discussed in the link below.
•ASP to ASP.NET Migration Assistant
•PHP to ASP.NET Migration Assistant
•JSP to ASP.NET Migration Assistant


45.      How Do I Publish My Asp.net Application To My Isp's Web Server?

 

 Your ISP must first create an IIS application and apply the Front Page Server Extensions to it. Then in Visual Studio.NET, select the "Project | Copy Project" menu. Then enter the URL and select the FrontPage web access method. The "Copy Project" feature copies all of the necessary files to your ISP's machine for your ASP.NET application to run.

You can also FTP your files to your ISP web server. But you must know which files to upload. 


46.      Why Do I Get Error Message "could Not Load Type" Whenever I Browse To My Asp.net Web Site?

 

 Your code-behind files for either your .aspx or the global.aspx page have not been complied. Use Visual Studio .NET's "Build | Build Solution" menu, or run the command line compiler.


47.      Will The Webmatrix Sqldatasourcecontrol Work With A Mysql Connection?

 

 SqlDataSourceControl lets you connect and work with MS SQL DB, while AccessDataSourceControl do the same thing but for MS Access DB. Therefore SqlDataSourceControl can't help you in your MySql connectivity .
For Connectivity with MySql refer Accessing MySQL Database with ASP.NET.


48.      Can I Combine Classic Asp And Asp.net Pages?

 

No.

ASP pages can run in the same site as ASP.NET pages, but you can't mix in a page. Also ASP and ASP.NET won't share their session.


49.      What Is The Difference Between Src And Code-behind?

 

 Src attribute means you deploy the source code files and everything is compiled JIT (just-in-time) as needed. Many people prefer this since they don't have to manually worry about compiling and messing with dlls -- it just works. Of course, the source is now on the server, for anyone with access to the server -- but not just anyone on the web.

CodeBehind attribute doesn't really "do" anything, its just a helper for VS.NET to associate the code file with the aspx file. This is necessary since VS.NET automates the pre-compiling that is harder by hand, and therefore the Src attribute is also gone. Now there is only a dll to deploy, no source, so it is certainly better protected, although its always decompilable even then.


50.      How Can I Get The Value Of Input Box With Type Hidden In Code-behind?

 

  You can set the runat= server for the hidden control and you can use ControlName.Value to get its value in CodeBehind file.


51.      I Have Created A .net User Control Page (.ascx) But I Cannot Compile And Run It.

 

User control (ascx) can't be run on it own, but you can drag it onto any web page (aspx) and then run it.


52.      What Is A .resx File?

 

The .resx resource file format consists of XML entries, which specify objects and strings inside XML tags. This is useful for localization. 


53.      Is It Possible To Use A Style Sheet Class Directly On A Control Instead Of Using Inline Or Page-level Formatting ?

 

Every WebControl derived control has a CssClass property which allows you to set it's format to a style sheet.


54.      Can I Recieve Both Html Markup For Page And Code In The Asp.net Web Page's Source Code Portion In The Web Browser?

 No.

The Web browser recieves only HTML markup,No source code or web control syntax is passed back to the web browser.


55.      Why Can't I Put <%@ Page Language="c " %> Where At The Top Of An Aspx File And Write My Server-side Scripts In C ?


The parsers ASP.NET uses to extract code from ASPX files understand C#, Visual Basic.NET, and JScript.NET. You can write server-side scripts in any language supported by a .NET compiler.


56.      Asp Pages That Worked Pefectly On Windows 2000 Server And Iis 5.0 Do Not Work On Windows 2003 Server With Iis 6.0. Asp.net Pages Work Fine. Why?

 

Start -> Settings -> Control Panel -> Administrative Tools -> and double clicking IIS Manager.
Go to the Web Service Extensions tab, click Active Server Pages, then press the "Allow" button on the left.


57.      Why Do I Get Error Message "error Creating Assembly Manifest: Error Reading Key File 'key.snk' -- The System Cannot Find The File Specified"?

 

Check the location of the key.snk file relative to the assembly file. Provide an explicit path or a relative path.
<Assembly: AssemblyKeyFileAttribute("Drive:\key.snk")>


58.      How To Get Url Without Querystring?

 

VB.NET
Dim stringUri As String = "http://www.syncfusion.com/?id=1&auid=16" Dim weburi As Uri = New Uri(stringUri)
Dim query As String = weburi.Query
Dim weburl As String = stringUri.Substring(0, stringUri.Length - query.Length)
Response.Write(weburl)

C#
string stringUri = "http://www.syncfusion.com/?id=1&auid=16"; Uri weburi = new Uri(stringUri);
string query = weburi.Query;
string weburl = stringUri.Substring(0, stringUri.Length - query.Length);
Response.Write (weburl);


59.      What Is The Best Way To Output Only Time And Not Date?

 

Use DateTime as follows VB.NET
Response.Write(DateTime.Now.ToString("hh:mm:ss"))

C#
Response.Write(DateTime.Now.ToString("hh:mm:ss"));


60.  Do I Have To Compile Code If I Am Changing The Content Of My Aspx.cs File?

 

Yes if you have used Codebehind="my.aspx.cs".

if not  you used src="my.aspx.cs" in your page declaration.


61.  How To Grab The Referring Url?

 

VB.NET
Response.Write ( Request.UrlReferrer.ToString())

C#
Response.Write ( Request.UrlReferrer.ToString());


62.  My Asp Code Gives An Error "compiler Error Message: Bc30289: Statement Cannot Appear Within A Method Body. End Of Method Assumed" When Changed To .aspx?

 

Use a <script runat="server" type="text/javascript"> block instead of the <% %> syntax to define Subs.Make sure you have proper events associated with the code and have start and end of procedure or function wirtten properly.


63.  How Can I Save Images ?

 

You need a stream to read the response, WebResponse. GetResponse Stream(), and a stream to write it to the hard drive. FileStream should do the trick. You'll have to write to the filestream what you read from the response stream.


64.  How Can I Logout When Using Formsauthentication?

 

FormsAuthentication.SignOut().

 

65.  Why Do I Get A Blank Page When I Use Server.transfer("page1.htm") To Transfer To A Different Page?

 

Server.Transfer only works with .aspx pages You can't use Transfer method with HTML pages.


 66.  How To Detect The User's Culture?

VB.NET

Dim sLang As String
sLang = Request.UserLanguages(0)
Response.Write(sLang)

C#
string sLang ;
sLang = Request.UserLanguages[0];
Response.Write (sLang);


67.      What Is The Difference Between Currentculture Property And The Currentuiculture Property?

 

ü  CurrentCulture property : affects how the .NET Framework handles dates, currencies, sorting and formatting issues.

ü  CurrentUICulture property : determines which satellite assembly is used when loading resources.

 



68.      Can I Read The Hard Disk Serial # Of The Client Computer Using Asp.net?

 

No.

Such information is not passed to the server with a http request.

 

69.      What Is Xxx(src As Object, E As Eventargs)?

 

  xxx is an event handler src is the object that fires the event e is an event argument object that contains more information about the event An event handler is used when one object wants to be notified when an event happens in another object.


70.      What Is The Difference Between Absolute Vs Relative Urls?

 

Absolute /Fully Qualified URLs:

    1. Contain all information necessary for the browser(or other client program) to locate the resource named in the URL

                                                              i.      This includes protocol monitor used( i.e http://, ftp://..etc..), Server's Domain name or IP address and the file path

                                                            ii.      Absolute URL looks as http://localhost/megasolutions/page1.aspx Relative URLs:

    1. Only provide information necessary to locate a resourcerelative to the current document(document relative) or current server or domain(root relative)

                                                              i.      Document relative URL - page1.aspx

                                                            ii.      Root Relative URL - /megasolutions/Admin/pagelog.aspx








     Model-View-Controller (MVC) is an architectural pattern that separates an application into three main logical components: the model, the view, and the controller. Each of these components are built to handle specific development aspects of an application. MVC is one of the most frequently used industry-standard web development framework to create scalable and extensible projects.




MVC application life cycle below diagrams summarize it.


Any web application has two main execution steps first understanding the request and depending on the type of the request sending out appropriate response. MVC application life cycle is not different it has two main phases first creating the request object and second sending our response to the browser.

Creating the request object: -The request object creation has four major steps. Below is the detail explanation of the same.

Step 1 Fill route: - MVC requests are mapped to route tables which in turn specify which controller and action to be invoked. So if the request is the first request the first thing is to fill the route table with routes collection. This filling of route table happens in the global.asax file.

Step 2 Fetch route: - Depending on the URL sent “UrlRoutingModule” searches the route table to create “RouteData” object which has the details of which controller and action to invoke.

Step 3 Request context created: - The “RouteData” object is used to create the “RequestContext” object.

Step 4 Controller instance created: - This request object is sent to “MvcHandler” instance to create the controller class instance. Once the controller class object is created it calls the “Execute” method of the controller class.

Creating Response object: - This phase has two steps executing the action and finally sending the response as a result to the view.


MVC is an evolution of a three layered traditional architecture. Many components of the three layered architecture are part of MVC. So below is how the mapping goes.

Three Layered Architecture

MVC 6

v  ASP.NET MVC and Web API has been merged in to one.

v  Dependency injection is inbuilt and part of MVC.

v  Side by side - deploy the runtime and framework with your application

v  Everything packaged with NuGet, Including the .NET runtime itself.

v  New JSON based project structure.

v  No need to recompile for every change. Just hit save and refresh the browser.

v  Compilation done with the new Roslyn real-time compiler.

v  vNext is Open Source via the .NET Foundation and is taking public contributions.

v  vNext (and Rosyln) also runs on Mono, on both Mac and Linux today.

 MVC 5

v  One ASP.NET

v  Attribute based routing

v  Asp.Net Identity

v  Bootstrap in the MVC template

v  Authentication Filters

v  Filter overrides

MVC 4

v  ASP.NET Web API

v  Refreshed and modernized default project templates

v  New mobile project template

v  Many new features to support mobile apps

v  Enhanced support for asynchronous methods

MVC 3 

v  Razor

v  Readymade project templates

v  HTML 5 enabled templates

v  Support for Multiple View Engines

v  JavaScript and Ajax

v  Model Validation Improvements

MVC 2

v  Client-Side Validation

v  Templated Helpers

v  Areas

v  Asynchronous Controllers

v  Html.ValidationSummary Helper Method

v  DefaultValueAttribute in Action-Method Parameters

v  Binding Binary Data with Model Binders

v  DataAnnotations Attributes

v  Model-Validator Providers

v  New RequireHttpsAttribute Action Filter

v  Templated Helpers

Display Model-Level Errors

v  

MVC Flow Diagram

Flow Steps

Step 1 − The client browser sends request to the MVC Application.

Step 2 − Global.ascx receives this request and performs routing based on the URL of the incoming request using the RouteTable, RouteData, UrlRoutingModule and MvcRouteHandler objects.

Step 3 − This routing operation calls the appropriate controller and executes it using the IControllerFactory object and MvcHandler object's Execute method.

Step 4 − The Controller processes the data using Model and invokes the appropriate method using ControllerActionInvoker object

Step 5 − The processed Model is then passed to the View, which in turn renders the final output.


1. What are the 3 main components of an ASP.NET MVC application?

1. M - Model

2. V - View

3. C - Controller

 

2. In which assembly is the MVC framework defined?

System.Web.Mvc

 

3. Is it possible to combine ASP.NET webforms and ASP.MVC and develop a single web application?

Yes, it is possible to combine ASP.NET webforms and ASP.MVC and develop a single web application.

 

4. What does Model, View and Controller represent in an MVC application?

Model: Model represents the application data domain. In short the applications business logic is contained with in the model.

 

View: Views represent the user interface, with which the end users interact. In short the all the user interface logic is contained with in the UI.

 

Controller: Controller is the component that responds to user actions. Based on the user actions, the respective controller, work with the model, and selects a view to render that displays the user interface. The user input logic is contained with in the controller.

 

5. What is the greatest advantage of using asp.net mvc over asp.net webforms?

It is difficult to unit test UI with webforms, where views in mvc can be very easily unit tested.

 

6. Which approach provides better support for test driven development - ASP.NET MVC or ASP.NET Webforms?

ASP.NET MVC

7. What are HTML helpers in MVC?

 HTML helpers help you to render HTML controls in the view. For instance if you want to display a HTML textbox on the view , below is the HTML helper code.

<%= Html.TextBox("LastName") %>

For checkbox below is the HTML helper code. In this way we have HTML helper methods for every  HTML control that exists.

<%= Html.CheckBox("Married") %>


8. What are the advantages of ASP.NET MVC?

v  Extensive support for TDD. With asp.net MVC, views can also be very easily unit tested.

v  Complex applications can be easily managed

v  Seperation of concerns. Different aspects of the application can be divided into Model, View and Controller.

v   v  ASP.NET MVC views are light weight, as they donot use viewstate.


9. Is it possible to unit test an MVC application without running the controllers in an ASP.NET process?

Yes, all the features in an asp.net MVC application are interface based and hence mocking is much easier. So, we don't have to run the controllers in an ASP.NET process for unit testing.


10. Is it possible to share a view across multiple controllers?

Yes, put the view into the shared folder. This will automatically make the view available across multiple controllers.

 

11. What is the role of a controller in an MVC application?

The controller responds to user interactions, with the application, by selecting the action method to execute and alse selecting the view to render.

 

12. Where are the routing rules defined in an asp.net MVC application?

 In Application_Start event in Global.asax


13. Name a few different return types of a controller action method?

  The following are just a few return types of a controller action method. In general an action method can return an instance of a any class that derives from ActionResult class.

v  ViewResult

v  JavaScriptResult

v  RedirectResult

v  ContentResult

v  JsonResult


14. What is the significance of NonActionAttribute?

 In general, all public methods of a controller class are treated as action methods. If you want prevent this default behaviour, just decorate the public method with NonActionAttribute.

 

15. What is the significance of ASP.NET routing?

 ASP.NET MVC uses ASP.NET routing, to map incoming browser requests to controller action methods. ASP.NET Routing makes use of route table. Route table is created when your web application first starts. The route table is present in the Global.asax file.

What are the 3 segments of the default route, that is present in an ASP.NET MVC application?

v  1st Segment - Controller Name

v  2nd Segment - Action Method Name

v  3rd Segment - Parameter that is passed to the action method


Example: http://HumanResource/Employee/Details/5

Controller Name = Customer

Action Method Name = Details

Parameter Id = 5


16. ASP.NET MVC application, makes use of settings at 2 places for routing to work correctly. What are these 2 places?

v  Web.Config File : ASP.NET routing has to be enabled here.

v  Global.asax File : The Route table is created in the application Start event handler, of the Global.asax file.


17. What is the adavantage of using ASP.NET routing?

In an ASP.NET web application that does not make use of routing, an incoming browser request should map to a physical file. If the file does not exist, we get page not found error.

 An ASP.NET web application that does make use of routing, makes use of URLs that do not have to map to specific files in a Web site. Because the URL does not have to map to a file, you can use URLs that are descriptive of the user's action and therefore are more easily understood by users.


18. What are the 3 things that are needed to specify a route?

v  URL Pattern - You can include placeholders in a URL pattern so that variable data can be passed to the request handler without requiring a query string.

v  Handler - The handler can be a physical file such as an .aspx file or a controller class.

v  Name for the Route - Name is optional.


19. Is the following route definition a valid route definition?

{controller}{action}/{id}

 No, the above definition is not a valid route definition, because there is no literal value or delimiter between the placeholders. Therefore, routing cannot determine where to separate the value for the controller placeholder from the value for the action placeholder.


20. What is the use of the following default route?

{resource}.axd/{*pathInfo}

 This route definition, prevent requests for the Web resource files such as WebResource.axd or ScriptResource.axd from being passed to a controller.


21. What is the difference between adding routes, to a webforms application and to an mvc application?

To add routes to a webforms application, we use MapPageRoute() method of the RouteCollection class, where as to add routes to an MVC application we use MapRoute() method.


22. How do you handle variable number of segments in a route definition?

Use a route with a catch-all parameter. An example is shown below. * is referred to as catch-all parameter.

controller/{action}/{*parametervalues}

 

23. What are the 2 ways of adding constraints to a route?

v  Use regular expressions

v  Use an object that implements IRouteConstraint interface

 

24. Give 2 examples for scenarios when routing is not applied?

v  A Physical File is Found that Matches the URL Pattern - This default behaviour can be overriden by setting the RouteExistingFiles property of the RouteCollection object to true.

v  Routing Is Explicitly Disabled for a URL Pattern - Use the RouteCollection.Ignore() method to prevent routing from handling certain requests.

 

25. What is the use of action filters in an MVC application?

 Action Filters allow us to add pre-action and post-action behavior to controller action methods.

 26. If I have multiple filters impleted, what is the order in which these filters get executed?

v  Authorization filters

v  Action filters

v  Response filters

v  Exception filters

 27. What are the different types of filters, in an asp.net mvc application?

v  Authorization filters

v  Action filters

v  Result filters

v  Exception filters

28. Give an example for Authorization filters in an asp.net mvc application?

v  RequireHttpsAttribute

v  AuthorizeAttribute

 29. Which filter executes first in an asp.net mvc application?

      Authorization filter

 30, What are the levels at which filters can be applied in an asp.net mvc application?

v  Action Method

v  Controller

v  Application

v  [b]Is it possible to create a custom filter?[/b]

v  Yes

 31. What filters are executed in the end?

Exception Filters

 32. Is it possible to cancel filter execution?

       Yes

 33. What type of filter does OutputCacheAttribute class represents?

        Result Filter

34. What are the 2 popular asp.net mvc view engines?

v  Razor

v  .aspx

 35. What symbol would you use to denote, the start of a code block in razor views?

@

36. What symbol would you use to denote, the start of a code block in aspx views?

       <%= %>

 37. In razor syntax, what is the escape sequence character for @ symbol?

     The escape sequence character for @ symbol, is another @ symbol

 38. When using razor views, do you have to take any special steps to proctect your asp.net mvc application from cross site scripting (XSS) attacks?

  No, by default content emitted using a @ block is automatically HTML encoded to protect from cross site scripting (XSS) attacks.

 39. When using aspx view engine, to have a consistent look and feel, across all pages of the application, we can make use of asp.net master pages. What is asp.net master pages equivalent, when using razor views?

To have a consistent look and feel when using razor views, we can make use of layout pages. Layout pages, reside in the shared folder, and are named as _Layout.cshtml

 40. What are sections?

   Layout pages, can define sections, which can then be overriden by specific views making use of the layout. Defining and overriding sections is optional.

 41. What are the file extensions for razor views?

v  .cshtml - If the programming lanugaue is C#

v  .vbhtml - If the programming lanugaue is VB

 42. How do you specify comments using razor syntax?

   Razor syntax makes use of @* to indicate the begining of a comment and *@ to indicate the end. An example is shown below.

   @* This is a Comment *@

43. What is the difference between “HTML.TextBox” vs “HTML.TextBoxFor”?

 Both of them provide the same HTML output, “HTML.TextBoxFor” is strongly typed while “HTML.TextBox” isn’t. Below is a simple HTML code which just creates a simple textbox with “CustomerCode” as name.

Html.TextBox("CustomerCode")

Below is “Html.TextBoxFor” code which creates HTML textbox using the property name ‘CustomerCode” from object “m”.

 Html.TextBoxFor(m => m.CustomerCode)

In the same way we have for other HTML controls like for checkbox we have “Html.CheckBox” and “Html.CheckBoxFor”.

44. What is the difference between tempdata, viewdata, and viewbag?


Difference between tempdata, viewdata, and viewbag

Temp data - Helps to maintain data when you move from one controller to another controller or from one action to another action. In other words when you redirect, tempdata helps to maintain data between those redirects. It internally uses session variables.

View data - Helps to maintain data when you move from controller to view.

View Bag - It’s a dynamic wrapper around view data. When you use Viewbag type, casting is not required. It uses the dynamic keyword internally.

                                                                                            Dynamic keyword

Session variables - By using session variables we can maintain data from any entity to any entity.

Hidden fields and HTML controls - Helps to maintain data from UI to controller only. So you can send data from HTML controls or hidden fields to the controller using POST or GET HTTP methods.

Below is a summary table which shows the different mechanisms for persistence.

Maintains data between

ViewData/ViewBag

TempData

Hidden fields

Session

Controller to Controller

No

Yes

No

Yes

Controller to View

Yes

No

No

Yes

View to Controller

No

No

Yes

Yes


45. What is routing in MVC?

  Routing helps you to define a URL structure and map the URL with the controller.

For instance let’s say we want that when a user types “http://localhost/View/ViewCustomer/”, it goes to the “Customer” Controller and invokes the DisplayCustomer action. This is defined by adding an entry in to the routes collection using the maproute function. Below is the underlined code which shows how the URL structure and mapping with controller and action is defined.

routes.MapRoute(

               "View", // Route name

               "View/ViewCustomer/{id}", // URL with parameters

               new { controller = "Customer", action = "DisplayCustomer",

id = UrlParameter.Optional }); // Parameter defaults   


46. Where is the route mapping code written?

The route mapping code is written in "RouteConfig.cs" file and registered using "global.asax" application start event.  


47. Can we map multiple URL’s to the same action?

Yes, you can, you just need to make two entries with different key names and specify the same controller and action.


48. Explain attribute based routing in MVC?

 This is a feature introduced in MVC 5. By using the "Route" attribute we can define the URL structure. For example in the below code we have decorated the "GotoAbout" action with the route attribute. The route attribute says that the "GotoAbout" can be invoked using the URL structure "Users/about".

public class HomeController : Controller

{

       [Route("Users/about")]

       public ActionResult GotoAbout()

       {

           return View();

       }

}


49. What is the advantage of defining route structures in the code?

   Most of the time developers code in the action methods. Developers can see the URL structure right upfront rather than going to the “routeconfig.cs” and see the lengthy codes. For instance in the below code the developer can see right upfront that the “GotoAbout” action can be invoked by four different URL structure.

 This is much user friendly as compared to scrolling through the “routeconfig.cs” file and going through the length line of code to figure out which URL structure is mapped to which action.

public class HomeController : Controller

{

       [Route("Users/about")]

       [Route("Users/ContactUs")]

       [Route("Users/Result")]

       [Route("Users/Company")]

       public ActionResult GotoAbout()

       {

           return View();

       }

}


50. How can we navigate from one view to another using a hyperlink?

By using the ActionLink method as shown in the below code. The below code will create a simple URL which helps to navigate to the “Home” controller and invoke the GotoHome action.

<%= Html.ActionLink("Home","Gotohome") %>


51. How can we restrict MVC actions to be invoked only by GET or POST?

  We can decorate the MVC action with the HttpGet or HttpPost attribute to restrict the type of HTTP calls. For instance you can see in the below code snippet the DisplayCustomer action can only be invoked by HttpGet. If we try to make HTTP POST on DisplayCustomer, it will throw an error.

[HttpGet]

public ViewResult DisplayCustomer(int id)

{

    Customer objCustomer = Customers[id];

    return View("DisplayCustomer",objCustomer);

}

52. How can we maintain sessions in MVC?

Sessions can be maintained in MVC by three ways: Temp Data, View Data, and View Bag.


53. What is difference between TempData and ViewData ?

 TempData maintains data for the complete request while ViewData maintains data only from Controller to the view.


54. Does TempData preserve data in the next request also?

 TempData is available through out for the current request and in the subsequent request it’s available depending on whether TempData is read or not. So if TempData is once read it will not be available in the subsequent request.


55. What is the use of Keep and Peek in TempData?

  Once TempData is read in the current request it’s not available in the subsequent request. If we want TempData to be read and also available in the subsequent request then after reading we need to call Keep method as shown in the code below.

@TempData["MyData"];

TempData.Keep("MyData");

 The more shortcut way of achieving the same is by using Peek. This function helps to read as well advices MVC to maintain TempData for the subsequent request.

string str = TempData.Peek("Td").ToString();


56. What are partial views in MVC?

  Partial view is a reusable view (like a user control) which can be embedded inside other view. For example let’s say all your pages of your site have a standard structure with left menu, header, and footer as shown in the image below.

Partial views in MVC

  For every page you would like to reuse the left menu, header, and footer controls. So you can go and create partial views for each of these items and then you call that partial view in the main view.

57. How can we do validations in MVC?

 One of the easiest ways of doing validation in MVC is by using data annotations. Data annotations are nothing but attributes which can be applied on model properties. For example, in the below code snippet we have a simple Customer class with a property customercode.

This CustomerCode property is tagged with a Required data annotation attribute. In other words if this model is not provided customer code, it will not accept it.

public class Customer

{

    [Required(ErrorMessage="Customer code is required")]

    public string CustomerCode

    {

        set;

        get;

    }

In order to display the validation error message we need to use the ValidateMessageFor method which belongs to the Html helper class.

<% using (Html.BeginForm("PostCustomer", "Home", FormMethod.Post))

{ %>

<%=Html.TextBoxFor(m => m.CustomerCode)%>

<%=Html.ValidationMessageFor(m => m.CustomerCode)%>

<input type="submit" value="Submit customer data" />

<%}%>

Later in the controller we can check if the model is proper or not by using the ModelState.IsValid property and accordingly we can take actions.

public ActionResult PostCustomer(Customer obj)

{

    if (ModelState.IsValid)

    {

        obj.Save();

        return View("Thanks");

    }

    else

    {

        return View("Customer");

    }

}

Below is a simple view of how the error message is displayed on the view.



58. Can we display all errors in one go?

Yes, we can; use the ValidationSummary method from the Html helper class.

<%= Html.ValidationSummary() %>

 

59. What are the other data annotation attributes for validation in MVC?

If you want to check string length, you can use StringLength.

[StringLength(160)]

public string FirstName { get; set; }

 

In case you want to use a regular expression, you can use the RegularExpression attribute.

[RegularExpression(@"[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4}")]public string Email { get; set; }

 

If you want to check whether the numbers are in range, you can use the Range attribute.

[Range(10,25)]public int Age { get; set; }

Sometimes you would like to compare the value of one field with another field, we can use the Compare attribute.

public string Password { get; set; }

[Compare("Password")]

public string ConfirmPass { get; set; }

In case you want to get a particular error message , you can use the Errors collection.

var ErrMessage = ModelState["Email"].Errors[0].ErrorMessage;

If you have created the model object yourself you can explicitly call TryUpdateModel in your controller to check if the object is valid or not.

TryUpdateModel(NewCustomer);

In case you want add errors in the controller you can use the AddModelError function.

ModelState.AddModelError("FirstName", "This is my server-side error.");


60. How can we enable data annotation validation on client side?

 It’s a two-step process: first reference the necessary jQuery files.

<script src="<%= Url.Content("~/Scripts/jquery-1.5.1.js") %>" type="text/javascript"></script>

<script src="<%= Url.Content("~/Scripts/jquery.validate.js") %>" type="text/javascript"></script>

<script src="<%= Url.Content("~/Scripts/jquery.validate.unobtrusive.js") %>" type="text/javascript"></script>

The second step is to call the EnableClientValidation method.

<% Html.EnableClientValidation(); %>


61. What is Razor in MVC?

  It’s a light weight view engine. Till MVC we had only one view type, i.e., ASPX. Razor was introduced in MVC 3. Razor is clean, lightweight, and syntaxes are easy as compared to ASPX. For example, in ASPX to display simple time, we need to write:

v  <%=DateTime.Now%>

v  @DateTime.Now


62. What is the difference between ActionResult and ViewResult?

  ActionResult is an abstract class while ViewResult derives from the ActionResult class. ActionResult has several derived classes like ViewResult, JsonResult, FileStreamResult, and so on.

 ActionResult can be used to exploit polymorphism and dynamism. So if you are returning different types of views dynamically, ActionResult is the best thing. For example in the below code snippet, you can see we have a simple action called DynamicView. Depending on the flag (IsHtmlView) it will either return a ViewResult or JsonResult.

public ActionResult DynamicView()

{

   if (IsHtmlView)

     return View(); // returns simple ViewResult

   else

     return Json(); // returns JsonResult view

}

63. What are the different types of results in MVC?

   It’s difficult to remember all the 12 types. But some important ones you can remember for the interview are ActionResult, ViewResult, and JsonResult. Below is a detailed list for your interest:

There 12 kinds of results in MVC, at the top is the ActionResult class which is a base class that can have 11 subtypes as listed below.

v  ViewResult - Renders a specified view to the response stream

v  PartialViewResult - Renders a specified partial view to the response stream

v  EmptyResult - An empty response is returned

v  RedirectResult - Performs an HTTP redirection to a specified URL

v  RedirectToRouteResult - Performs an HTTP redirection to a URL that is determined by the routing engine, based on given route data

v  JsonResult - Serializes a given ViewData object to JSON format

v  JavaScriptResult - Returns a piece of JavaScript code that can be executed on the client

v  ContentResult - Writes content to the response stream without requiring a view

v  FileContentResult - Returns a file to the client

v  FileStreamResult - Returns a file to the client, which is provided by a Stream

v  FilePathResult - Returns a file to the client


64. What are ActionFilters in MVC?

 ActionFilters help you to perform logic while an MVC action is executing or after an MVC action has executed.

Action filters are useful in the following scenarios:

v  Implement post-processing logic before the action happens.

v  Cancel a current execution.

v  Inspect the returned value.

v  Provide extra data to the action.

You can create action filters by two ways:

v  Inline action filter.

v  Creating an ActionFilter attribute.

 To create an inline action attribute we need to implement the IActionFilter interface. The IActionFilter interface has two methods: OnActionExecuted and OnActionExecuting. We can implement pre-processing logic or cancellation logic in these methods.

public class Default1Controller : Controller , IActionFilter

{

    public ActionResult Index(Customer obj)

    {

        return View(obj);

    }

    void IActionFilter.OnActionExecuted(ActionExecutedContext filterContext)

    {

        Trace.WriteLine("Action Executed");

    }

    void IActionFilter.OnActionExecuting(ActionExecutingContext filterContext)

    {

        Trace.WriteLine("Action is executing");

    }

}



65. How to send result back in JSON format in MVC

In MVC, we have the JsonResult class by which we can return back data in JSON format. Below is a simple sample code which returns back a Customer object in JSON format using JsonResult.

 

public JsonResult getCustomer()

{

    Customer obj = new Customer();

    obj.CustomerCode = "1001";

    obj.CustomerName = "Prem";

    return Json(obj,JsonRequestBehavior.AllowGet);

}

Below is the JSON output of the above code if you invoke the action via the browser.




66. What is WebAPI?

 HTTP is the most used protocol. For the past many years, browser was the most preferred client by which we consumed data exposed over HTTP. But as years passed by, client variety started spreading out. We had demand to consume data on HTTP from clients like mobile, JavaScript, Windows applications, etc.

 WebAPI is the technology by which you can expose data over HTTP following REST principles.

 But WCF SOAP also does the same thing, so how does Web API different?

    


67. With WCF you can implement REST, so why Web API?

 WCF was brought into implement SOA, the intention was never to implement REST. Web API is built from scratch and the only goal is to create HTTP services using REST. Due to the one point focus for creating REST service, Web API is more preferred.

 How to implement Web API in MVC

 Below are the steps to implement Web API.

 Step 1 : Create the project using the Web API template.


Step 2 : Once you have created the project you will notice that the controller now inherits from ApiController and you can now implement POST, GET, PUT, and DELETE methods of the HTTP protocol.

public class ValuesController : ApiController

{

    // GET api/values

    public IEnumerable<string> Get()

    {

        return new string[] { "value1", "value2" };

    }

    // GET api/values/5

    public string Get(int id)

    {

        return "value";

    }

    // POST api/values

    public void Post([FromBody]string value)

    {

    }

    // PUT api/values/5

    public void Put(int id, [FromBody]string value)

    {

    }

    // DELETE api/values/5

    public void Delete(int id)

    {

    }

}

Step 3 : If you make an HTTP GET call you should get the below results.

68. How can we detect that an MVC controller is called by POST or GET?

   To detect if the call on the controller is a POST action or a GET action we can use the Request.HttpMethod property as shown in the below code snippet.

 

public ActionResult SomeAction()

{

    if (Request.HttpMethod == "POST")

    {

        return View("Employee");

    }

    else

    {

        return View("Department");

    }

}

69. What is bundling and minification in MVC?

 Bundling and minification helps us improve request load times of a page thus increasing performance.




   ASP.NET Core is a cross-platform, high-performance, open-source framework for building modern, cloud-based, Internet-connected applications. ASP.NET Core 3.0 is the latest version of ASP.NET Core. You can develop Web Applications, Cloud based application, IoT Applications, and also Mobile applications. ASP.NET Core 3.0 is open source and cross platform. So, you it supports Windows, Mac and Linux.





1. What is the ASP.NET Core?

  ASP.NET Core is not an upgraded version of ASP.NET. ASP.NET Core is completely rewriting that work with .net Core framework. It is much faster, configurable, modular, scalable, extensible and cross-platform support. It can work with both .NET Core and .net framework via the .NET standard framework. It is best suitable for developing cloud-based such as web application, mobile application, IoT application.

 

2. What are the features provided by ASP.NET Core?

Following are the core features that are provided by the ASP.NET Core

v  Built-in supports for Dependency Injection

v  Built-in supports for the logging framework and it can be extensible

v  Introduced new, fast and cross-platform web server - Kestrel. So, a web application can run without IIS, Apache, and Nginx.

v  Multiple hosting ways are supported

v  It supports modularity, so the developer needs to include the module required by the application. However, .NET Core framework is also providing the meta package that includes the libraries

v  Command-line supports to create, build and run the application

v  There is no web.config file. We can store the custom configuration into an appsettings.json file

v  There is no Global.asax file. We can now register and use the services into startup class

v  It has good support for asynchronous programming

v  Support WebSocket and SignalR

v  Provide protection against CSRF (Cross-Site Request Forgery)


3. What are the advantages of ASP.NET Core over ASP.NET?

 There are following advantages of ASP.NET Core over ASP.NET :

v  It is cross-platform, so it can be run on Windows, Linux, and Mac.

v  There is no dependency on framework installation because all the required dependencies are ship with our application

v  ASP.NET Core can handle more request than the ASP.NET

v  Multiple deployment options available withASP.NET Core


4. What is Metapackages?

  The framework .NET Core 2.0 introduced Metapackage that includes all the supported package by ASP.NET code with their dependencies into one package. It helps us to do fast development as we don't require to include the individual ASP.NET Core packages. The assembly Microsoft.AspNetCore.All is a meta package provide by ASP.NET core.


5. Can ASP.NET Core application work with full .NET 4.x Framework?

 Yes. ASP.NET core application works with full .NET framework via the .NET standard library.


6. What is the startup class in ASP.NET core?

 Startup class is the entry point of the ASP.NET Core application. Every .NET Core application must have this class. This class contains the application configuration rated items. It is not necessary that class name must "Startup", it can be anything, we can configure startup class in Program class.


7. What is the use of ConfigureServices method of startup class?

 This is an optional method of startup class. It can be used to configure the services that are used by the application. This method calls first when the application is requested for the first time. Using this method, we can add the services to the DI container, so services are available as a dependency in controller constructor.


8. What is the use of the Configure method of startup class?

 It defines how the application will respond to each HTTP request. We can configure the request pipeline by configuring the middleware. It accepts IApplicationBuilder as a parameter and also it has two optional parameters: IHostingEnvironment and ILoggerFactory. Using this method, we can configure built-in middleware such as routing, authentication, session, etc. as well as third-party middleware.


9. What is middleware?

It is software which is injected into the application pipeline to handle request and responses. They are just like chained to each other and form as a pipeline. The incoming requests are passes through this pipeline where all middleware is configured, and middleware can perform some action on the request before passes it to the next middleware. Same as for the responses, they are also passing through the middleware but in reverse order.

Create a middleware pipeline with IApplicationBuilder


Middleware order

MVC Endpoint (Call By Endpoint Middleware)


10. What is the difference between IApplicationBuilder.Use() and IApplicationBuilder.Run()?

 We can use both the methods in Configure methods of startup class. Both are used to add middleware delegate to the application request pipeline. The middleware adds using IApplicationBuilder.Use may call the next middleware in the pipeline whereas the middleware adds using IApplicationBuilder.Run method never calls the subsequent ore next middleware. After IApplicationBuilder.Run method, system stop adding middleware in request pipeline.

 

11. What is the use of "Map" extension while adding middleware to ASP.NET Core pipeline?

 It is used for branching the pipeline. It branches the ASP.NET Core pipeline based on request path matching. If request path starts with the given path, middleware on to that branch will execute.


12. What is routing in ASP.NET Core?

 Routing is functionality that map incoming request to the route handler. The route can have values (extract them from URL) that used to process the request. Using the route, routing can find route handler based on URL. All the routes are registered when the application is started. There are two types of routing supported by ASP.NET Core.

v  The conventional routing

v  Attribute routing

 The Routing uses routes for map incoming request with route handler and Generate URL that used in response. Mostly, the application having a single collection of routes and this collection are used for the process the request. The RouteAsync method is used to map incoming request (that match the URL) with available in route collection.

 

13. How to enable Session in ASP.NET Core?

 The middleware for the session is provided by the package Microsoft.AspNetCore.Session. To use the session in ASP.NET Core application, we need to add this package to csproj file and add the Session middleware to ASP.NET Core request pipeline.


14. What are the various JSON files available in ASP.NET Core?

      There are following JSON files in ASP.NET Core :

v  global.json

v  launchsettings.json

v  appsettings.json

v  bundleconfig.json

v  bower.json

v  package.json

 

15. What is tag helper in ASP.NET Core?

  It is a feature provided by Razor view engine that enables us to write server-side code to create and render the HTML element in view (Razor). The tag-helper is C# classes that used to generate the view by adding the HTML element. The functionality of tag helper is very similar to HTML helper of ASP.NET MVC.


16. How to disable Tag Helper at element level?

 We can disable Tag Helper at element level using the opt-out character ("!"). This character must apply opening and closing the Html tag.

  Example :

17. What are Razor Pages in ASP.NET Core?

 This is a new feature introduced in ASP.NET Core 2.0. It follows a page-centric development model just like ASP.NET web forms. It supports all the feature of ASP.NET Core.

 Example :


  The Razor pages start with the @page directive. This directive handle request directly without passing through the controller. The Razor pages may have code behind file, but it is not really code-behind file. It is class inherited from PageModel class.


18. How can we do automatic model binding in Razor pages?

  The Razor pages provide the option to bind property automatically when posted the data using BindProperty attribute. By default, it only binds the properties only with non-GET verbs. we need to set SupportsGet property to true to bind a property on getting request.

19. How can we inject the service dependency into the controller?

There are three easy steps to add custom service as a dependency on the controller.

 Step 1: Create the service



Step 2: Add this service to Service container (service can either added by singleton, transient or scoped)


Step 3: Use this service as a dependency in the controller


20. How to specify service lifetime for register service that added as a dependency?

 ASP.NET Core allows us to specify the lifetime for registered services. The service instance gets disposed of automatically based on a specified lifetime. So, we do not care about the cleaning these dependencies, it will take care by ASP.NET Core framework. There is three type of lifetimes.

21. Explain Session and State management in ASP.NET Core.

  As we know HTTP is a stateless protocol. HTTP requests are independent and does not retain user values. There are different ways to maintain user state between multiple HTTP requests.

v  Cookies

v  Session State

v  TempData

v  Query strings

v  Hidden fields

v  HttpContext.Items

v  Cache

 

22. Describe the ASP.NET Core MVC.

  ASP.NET Core MVC is a framework to build web applications and APIs. It's based on Model-View-Controller (MVC) Design Pattern. This design pattern separate an application into three main components known as Model, View and Controller. It also helps to achieve SoC (Separation of Concern) design principle.

ASP.NET Core MVC is light weight, open-source and testable framework to build web applications and services.

 

23. Explain the Model, View and Controller.

ASP.NET MVC has three main group of components Model, View and Controller, Each one has his own responsibilities as below.

v  Model - It contains the business logic and represents the state of an application. It also performs the operation on the data and encapsulates the logic to persist an application state. Strongly-typed Views use View-Model pattern to display the data in the view.

v  View - It's responsible to present the content via User interface. It does not contain much logic and use Razor View Engine to embed .NET code into view. If you need to perform much logic to display the data then prefer to use View Component, View Model or View Template for simplify view.

Controller - It's responsible to handle user interactions, It works with model and select the view to display. Controller is the main entry point that decides the model with which it works and decide which view it needs to display. Hence it's name - Controller means controls user inputs and interactions.

24. Explain Strongly-typed views.

 Strongly-typed views are tightly bound to a model. for example, In above question if you want to pass the author data to view then you need to write below code for type checking in your view. @model Author. Controller can pass strongly type model to view that enables type checking and intelliSense support in view.


25. Describe the Dependency Injection.

 Dependency Injection is a Design Pattern that's used as a technique to achieve the Inversion of Control (IoC) between the classes and their dependencies.

ASP.NET Core comes with built-in Dependency Injection framework that makes configured services available throughout the application. You can configure the services inside ConfigureServices method as below.

services.AddScoped();

 A Service can be resolved using constructor injection and DI framework is responsible for the instance of this service at run time.


26. What is difference between .NET Core and .NET framework?

 There are the following some differences between .NET Core and .NET framework.

v  .NET Core is the latest of .NET framework.

v  .NET Core is cross platform, but .NET framework is not.

v  .NET Core compatible with xamarin to develop mobile application. But .NET framework doesn’t have any tools to simplify mobile application.

v.NET Core is more effective than .NET framework


27. Explain the ASP.NET page life cycle in brief.

 ASP.NET goes through a series of stages in the life cycle of each page.

v  Page request : The user requests a page. ASP.NET decides whether to compile it or serve it from a cache.

v  Page Start : The Request and Response objects are created.

v  Page Initialization : All page controls are initialized, and any themes are applied.

v  Page Load : ASP.NET uses the view state and control state properties to set the control properties. Default values are set in the controls.

v  Postback : event handling. This event is triggered if the same page is loaded again.

v  Rendering : ASP.NET saves the view state for the page and writes the output of rendering to the output stream. It happens just before the complete web page is sent to the user.

Unload : The rendered page gets sent to the client. ASP.NET unloads page properties and performs cleanup. All unwanted objects are removed from memory. 


Singleton

ASP.NET Core will create and share a single instance of the service through the application life. The service can be added as a singleton using AddSingleton method of IServiceCollection. ASP.NET Core creates service instance at the time of registration and subsequence request use this service instance. Here, we do not require to implement Singleton design pattern and single instance maintained by the ASP.NET Core itself.

Example :

Scoped

 ASP.NET Core will create and share an instance of the service per request to the application. It means that a single instance of service available per request. It will create a new instance in the new request. The service can be added as scoped using an AddScoped method of IServiceCollection. We need to take care while, service registered via Scoped in middleware and inject the service in the Invoke or InvokeAsync methods. If we inject dependency via the constructor, it behaves like singleton object.


  ASP.NET Core versions starting from 1.0 to 3.0 and will help .NET developers who are looking for a change or want to make a bright future in ASP.NET Core technology.

v  ASP.NET Core features details.

v  How to configure middleware and routing.

v  How to enable session and configure your application environment.

v  A JS framework like a way to write server-side code to create and render the HTML using Tag Helper.

v  How to reuse your code using Partial views and view component.

v  Different ways to apply validations and binding data to server-side action methods.

v  How to implement localization and globalization.

v  Handle exceptions and logging errors.

v  Dependency Injection implementation.

v  Ways to secure your application and using filters.

v  Using Unit testing frameworks and running tests.

v  Various Deployment options


Table of Content

v  Introducing ASP.NET Core.

v  Middleware and Routing

v  Session and Environment Settings

v  Areas and Tag Helpers

v  Razor Pages and View Component

v  Model Binding and Validations

v  Globalization and Localization

v  Exception Handling and Logging Framework

v  Dependency Injection

v  Security and Filters

v  Unit Testing

Deployment








1. Blazor is a .NET web framework to build client web apps with C#.

  Blazor lets you build interactive web UIs using C# instead of JavaScript. Blazor apps are composed of reusable web UI components implemented using C#, HTML, and CSS. Both client and server code is written in C#, allowing you to share code and libraries. 

v  Efficient and fast :  The Wasm stack machine is designed to be encoded in a size- and load-time-efficient binary format. WebAssembly aims to execute at native speed by taking advantage of common hardware capabilities available on a wide range of platforms.

v  Safe : WebAssembly describes a memory-safe, sandboxed execution environment that may even be implemented inside existing JavaScript virtual machines. When embedded in the web, WebAssembly will enforce the same-origin and permissions security policies of the browser.

v  Open and debuggable : WebAssembly is designed to be pretty-printed in a textual format for debugging, testing, experimenting, optimizing, learning, teaching, and writing programs by hand. The textual format will be used when viewing the source of Wasm modules on the web.

v  Part of the open web platform : WebAssembly is designed to maintain the versionless, feature-tested, and backwards-compatible nature of the web. WebAssembly modules will be able to call into and out of the JavaScript context and access browser functionality through the same Web APIs accessible from JavaScript. WebAssembly also supports non-web embeddings.




2. What’s this WebAssembly?

 WebAssembly (abbreviated Wasm) is a binary instruction format for a stack-based virtual machine. Wasm is designed as a portable compilation target for programming languages, enabling deployment on the web for client and server applications.


3. Is Microsoft Blazor Framework faster than other SPA frameworks for example Angular, React or Vue compiled in JavaScript?

Blazor uses web assembly, On paper web assembly should be faster than any JavaScript library, however not all browsers have a mature web assembly parser yet. So you might find that browsers will not run web assembly in an optimal speed as of now.

 You can create a small blazor app and run it in Firefox, chrome or edge. In most cases Firefox runs blazor apps much faster than chrome or edge, which implies that browser makers still need to improve, even Firefox can improve.

 If your app needs to access DOM frequently, then definitely web assembly / Blazor will be slower compared to any JS libraries since web assembly can’t directly access DOM.

 By itself, WebAssembly cannot currently directly access the DOM; it can only call JavaScript, passing in integer and floating point primitive data types. Thus, to access any Web API, WebAssembly needs to call out to JavaScript, which then makes the Web API call.

Additionally, current implementation Blazor has its own MSIL engine on top of the browsers web assembly Engine, which means there are two interpreters working to run a Blazor project, Like two translators interpreting a conversation instead on one. Currently Microsoft is working on an AOT compiler, which is not yet release. Once its release Blazor will be much faster than the current implementation.

 We can safely assume that the web assembly is the future of web development, but at the moment we can’t say anything about Blazor’s future. On paper Blazor can be faster than any framework out there, however we need commitment from web assembly maintainers, Browser developers, Microsoft and the communities to make the theories practical.


4. What’s this Blazer framework?

  Blazor is basically an SPA framework, but not a typical one like Angular or React that uses JavaScript or TypeScript. This one is built on .Net that runs in the browser.

 

5. How to run a .Net in the browser?

 We can run a .Net in the browser using WebAssembly. Basically, we use a .Net runtime called Mono that most of you might have heard. We compile it to WebAssembly, and then run the compiled binary in the browser.


6. How does Routing Work?

 If you look at the top of the “Counter.cshtml” you can see the @page directive that specifies that this component is a page to which requests can be routed.

 That means any requests that are sent to “/Counter” will be handled by this “Counter” component. If you don’t have this “page” directive at the top of the component, that component will not handle any requests at all on its own but that component can be used by other components as a subcomponent.


7. How do I add a new component?

 It is very simple. Under the pages folder, create a new .cshtml file and add the route you like at the top of the page like the following:

@page "/customer"

<h1> Customer Page</h1>

This means that our route for the new component is “/customer”


8. What is difference between Blazor WebAssembly App (with Asp.Net Core Hosted) and Blazor Server App?

 There are two hosting models: Server-Hosted, and Client-Hosted. The difference is whether the app is hosted in server, or in client.

v  Server-Hosted Model

Server hosted model means your app logic runs in the server (you can think of it similar to what Web Forms is), you click on a button, an “Ajax” call sends the request, the server receives the request, and sends back the updated page. However, here it uses SignalR not Ajax, which is a low level socket communication (read efficient). And instead of updating a whole page, it updates only the relevant parts (thus it is a single page application).

v  Client-Hosted Model

Client hosted model means your logic runs within the browser. Think of it as if your C# logic is converted into JavaScript, and it is embedded in the page. So the logic runs in the browser. This could be possible after the introduction of WebAssembly.

v  WebAssembly App (with Asp.Net Core Hosted)

This options means having Blazor to include ASP.NET Core runtime. This is because you can write an offline app (e.g. calculator app) that does not need any kind of connection to external services, making ASP.NET Core irrelevant. However, you might want to write an online app that accesses online DB, external APIs, do verification, etc. For these kind of apps, you will need an ASP.NET Core stack to support your app.


9. How can I access the browser’s localStoarge in Blazor?

There are couple of options available to achieve this functionality. But I will explain two best approaches here.

Approach #1

 You can use Blazored.LocalStorage awesome library by Chris for accessing localStorage in Blazor applications. It can be installed from NuGet via Visual Studio Package manager or using below command.

 Install-Package Blazored.LocalStorage

 How to Setup

  For using in Blazor Server project, You will need to register the local storage services with the IServiceCollection _under _ConfigureServices _method in _Startup.cs file.

 


 For using in Blazor WebAssembly project, You will need to register in Program.cs file.



 How to Use

To use it wither in Blazor WebAssembly project or in Blazor Server project, you will need to inject the ILocalStorageService:


 There is another option of synchronous API to use local storage in Blazor WebAssembly project only. You can use _ISyncLocalStorageService _instead of _ILocalStorageService _that allows you to avoid use of async/await.


  Approach #2

 There is another NuGet package provided by Microsoft Blazor Team named Microsoft.AspNetCore.ProtectedBrowserStorage that provides Data Protection for localStoarge and sessionStorage.

Important : Microsoft.AspNetCore.ProtectedBrowserStorage is an unsupported experimental package unsuitable for production use at this time. It may be in future.


10. How to store Session data in Blazor application?

 You can use another NuGet library called Blazored.SessionStorage by Chris for providing access to session storage in Blazor applications. It can be installed from NuGet via Visual Studio Package manager or using below command .

  Install-Package Blazored.SessionStorage

 How to Setup

 For using in Blazor Server project, You will need to register the local storage services with the IServiceCollection under ConfigureServices method in Startup.cs file.


  For using in Blazor WebAssembly project, You will need to register in Program.cs file.

 


 How to Use

To use it wither in Blazor WebAssembly project or in Blazor Server project, you will need to inject the ISessionStorageService.


 There is another option of synchronous API to use local storage in Blazor WebAssembly project only. You can use ISyncSessionStorageService instead of ISessionStorageService that allows you to avoid use of async/await.

 



11. How to debug Blazor WebAssembly application?

 To enable debugging for a Blazor WebAssembly app, follow the below steps –

 Step 1. Update the launchSettings.json file with the following highlighted “_inspectUri_” field and value.

 


 Once updated, the launchSettings.json file should look similar to the following code 


Step 2. Set the breakpoints in the any razor component C# code section (or in partial class). For example. In the following example, I have set on the Increment method.


Step 3. Press F5 to run the app and navigate to the Counter tab and click the “Click Me” button to hit the break point.



12. How to get current URL in a Blazor application?

   You can use Uri property of NavigationManager class to get the current URL.

 How to use

 Inject NavigationManager class using @inject directive into razor component or using [Inject] attribute, if using code-behind approach of creating components.

 Check out my article here to know about 4 different methods of creating Blazor components.

 To inject inside component, use @inject directive like below

 


 To inject NavigationManager in code-behind file, use [Inject] attribute like below –


 Now you have injected NavigationManager, so you need to Uri property to get current URL.

 



13. How to Preserve State in Server-side Blazor application?

You can find the best answer of this question from here given by Steve Sanderson (Creator of Microsoft Blazor Framework).

 

14. How to get IPAddress and UserAgent in Blazor server application?

  You can get user information using IHttpContextAccessor in Blazor server app.  

  • Add the following line in the ConfigureServices method inside Startup.cs file.
    • Inject IHttpContextAccessor in blazor component using @inject directive or using [Inject] attribute in code-behind file.


    • Get UserAgent and IPAddress value using _httpContextAccessor object.

    Using JavaScript Interop

    To get UserAgent information using JavaScript Interop, follow below steps.

      ·   Add a JavaScript file under wwwroot folder named “userinfo.js” and add the following code


    ·      Add JS file in _Host.cshtml file (in case of Blazor server) OR in index.cshtml file (in case of Blazor WebAssembly) just before the body closing tag


    ·         Now to invoke a JS function from any Blazor component, Inject IJSRuntime using @inject directive


    ·         Now you can invoke JS function and get the UserAgent information here in component using following code


    15. How to download file in Blazor application?

    You can use JSInterop feature for downloading file in Blazor application. Use the following steps to do this work.

    ·     Create a JavaScript file named “download.js” under wwwroot folder and add the following code to it


    ·         Add this JS file in _Host.cshtml file in Blazor Server app or in Index.html file in Blazor WebAssembly app just before the body closing tag.


    ·         Now invoke saveAsFile JavaScript function inside any Blazor component using IJSRuntime


    16. How to disable anchor <a> link’s href disable if there is an onclick method on it in Blazor?

    OR

    How to use preventDefault (just like in JavaScript) to prevent the default action for an event in Blazor?

    You can use @on{EVENT}:preventDefault directive attribute to prevent the default action for an event.

    For example, I have an anchor link with href attribute and an onclick event handler in a Blazor component.


    When you will run the Blazor application and click on this anchor link, you will be redirected to google.com along with the doClick handler execution.

    Solution -: To stop navigation (redirection to href link), you need to use  @onclick:preventDefault  directive attribute like below



    17. How to stop event propagation or event bubbling in Blazor?

    You can use @on{EVENT}:stopPropagation directive attribute to stop event propagation in Blazor.

      For Example, I have multiple nested <div> elements (each with onclick event) or multiple <button> elements with onclick event nested inside a <div> element in a Blazor component. In the following example, I am showing this with a single <button> element nested inside a <div> element, where <div> and <button> both elements have onclick event.



     When you run the blazor application and click on button, button onclick handler (IncrementCount method) along with parent <div> element onclick handler (divClickIncrementCount method) will be executed that means currentCount value will be incremented twice with a single button click.

      Event Bubbling means When an event happens on an element, it first runs the handler on it, then on its parent, then all the way up on other ancestors.

      Solution -: To stop event bubbling, you need to use @onclick:stopPropagation=”true” directive attribute in Blazor. This way currentCount value will be increment on individual click on child and parent element.


    18. How to pass arguments to @on{EVENT} handler in Blazor?

      For passing argument to a handler of an event in Blazor, you can use lambda.

     For example. If you have a button in a Blazor component and you want to pass arguments to its onClick (or onmouseover or any event) handler like below.

     

      This code won’t work because we’re just binding the onclick event with the returning result of OnButtonClick method. Rather we need to attach method itself with the help of lambda.

     

    Now run the application and you can get both argument values inside the handler.


    19. How to create Custom InputSelect element which supports System.Guid or any data type in Blazor?

    OR

    How to fix the error “System.InvalidOperationException: Microsoft.AspNetCore.Components.Forms.InputSelect`1[System.Guid] does not support the type ‘System.Guid”’?

      By default, InputSelect Blazor control supports only String and Enum data type.  For supporting other data types, you need to create your custom InputSelect control.

    Replicating the issue with existing InputSelect element

    First of all, let implement a simple example in which we will a EmployeeList with two properties Id (System.Guid) and Name (String) and we will this list of employees with existing InputSelect element.

    Create a model class called Employee with two properties.

      Now create a Blazor component called BindGuidToInputSelect.razor and add the following code into the component.


         In the above example, I have binded EmployeeList to InputSelect element where EmployeeId (which is a GUID value) binds to its value and EmployeeName (which is a string value) for displaying names in the dropdown.

     Let’s run the application and change the employee from InputSelect control. As you change selection, you will get the following exception –

    Error: System.InvalidOperationException: Microsoft.AspNetCore.Components.Forms.InputSelect`1[System.Guid] does not support the type ‘System.Guid’ at Microsoft.AspNetCore.Components.Forms.InputSelect`1.TryParseValueFromString(String value, TValue& result, String& validationErrorMessage) at Microsoft.AspNetCore.Components.Forms.InputBase`1.set_CurrentValueAsString(String value).

     Reason of exception

       The reason of exception is that by default, InputSelect element does not support other data type than System.String. To support other data types, you need to create your own custom InputSelect.

     

    Creating a Custom InputSelect

    Create a class file named CustomInputSelect.cs and add the following code to it.


     In the above code, CustomInputSelect class is inherited from InputSelect base type. I did the implementation of supporting of System.Guid & System.Int datatypes as of now. If you want to add more data type support, you can enhance the existing class.

    Let’s change the InputSelect element with the CustomInputSelect element in the same example above explained.


    Now run the application and try changing employee from the dropdown.

    You can check out of the box Blazor InputSelect supported datatype and source code using this link.


    20. How to show Confirm box before deleting record in Blazor?

    You can achieve this functionality using JavaScript Interop feature. Let’s see an example how we can achieve that.

    Create a component called EmployeeList.razor just to display employees and add the following code.

    EmployeeList.razor



     In the above code, I fetched a list of employee from EmployeeService and displayed all employees on the page using Bootstrap table. There is a button called Delete, added with each record. Now when user will click to this button, a dialog will be open to confirm just before deleting that user.

     This is JavaScript confirm dialog which has been called using IJSRuntime object in this component. Let’s run the application and see the output.


    21. How to Pass data from Parent component to Child Component in Blazor?

    For passing data from parent component to child component, there are mainly three methods in Blazor.

    Using Parameters       

    A component can receive data from its parent component using [Parameter] attribute. Meaning You can use component [Parameter] attribute to pass data from parent to child component in Blazor.

    Using Cascading Value and Parameters

    Blazor introduced another way for passing data from parent to child components.

     For example. Component C can be nested inside component B and that component B can be nested inside another component A and so on. It means there can be several layers of components in a hierarchy in a real-time blazor application.

    As I explained above, there is one way to pass data from an ancestor component (component A) to its descendant components (component B & C and more in hierarchy) using Component Parameters. But using this way, it’s tedious to pass data to all descendant components. That’s why Blazor introduced cascading values and parameters that allows any data cascaded down to its all descendant components in components hierarchy.

    Using Route Parameters

     You can pass string data as a route parameter from the parent component (navigating from) to child component (navigated to). In the page you are navigating to, you need to add a property (with the same name as route parameter) decorated with parameter attribute.

    Suppose you want to pass data from component 1 to component 2, the you need to

    • Inject NavigationManager class to the component 1 page


    • Call NavigateTo method of NavigationManager to move to the component 2 with name

    • In component 2, add @page directive with route and parameter

    • Now add a property decorated with [Parameter] attribute


    • Now you can this parameter value in OnParameterSet lifecycle method


    22. How to Pass data from Child component to Parent Component in Blazor?

     You can use EventCallBack in Blazor for passing data from child component to parent component. An EventCallBack is a special type of delegate which is used in a common scenario with nested components to execute a parent component method when a child component event occurs.

    We can say that for passing any data from child component to parent component when any event is occurred inside child component, blazor provides us a special type of delegate called EventCallBack.


    23. What is JavaScript Interoperability (JS interop)?

       Blazor app can invoke JavaScript functions from .NET methods and .NET methods from JavaScript functions. This scenario is called JavaScript Interoperability (JS Interop).

     

    24. How to call JavaScript functions from .NET methods in Blazor?

    To call into JavaScript from .NET, use the IJSRunime abstraction. To invoke JS functions, you need to inject IJSRuntime into your Blazor component.

    IJSRuntime has following two methods named InvokeVoidAsync and InvokeAsync for calling JavaScript functions from .NET. These methods take first parameter as identifier for JavaScript function.

    InvokeVoidAsync : This method is used when JavaScript function doesn’t return any value.

    InvokeAsync : This method is used when JavaScript function returns any value after execution.

    Calling JS function that doesn’t return any value

    Create a JavaScript file called JsInteropTest.js (you can give any name) and add the following code to file.


    Add this JS file to _Host.cshtml (in case of Blazor WebAssembly Project) file OR index.cshtml file (in case of Blazor Server project) just before the body closing tag.


    Now add a Blazor component called CallingJSFunctionsFromDotnet.razor and add the following code.


    In the above example, I have used InvokeVoidAsync method of IJSRuntime because doLog JS function doesn’t return anything, just log a message to console.

    Now run the application, click the button and open the developer tools window. You can check message is logged to the console.

    Calling JS function that returns a value and accepts the arguments

     Let use the same JS file and add the following code. In the following code, I am calling a JavaScript function that opens a JavaScript prompt window with a question. User just need to put answer and hit okay button.

    JsInteropTest.js


    CallingJSFunctionsFromDotnet.razor


    As you can see, I have used InvokeAsync this time because JS function will return prompt result.

    Run the application and hit the button. You will get a prompt with question “What’s your name?”. Put the answer and hit Okay button. You’ll get the result.

    Calling JavaScript function that returns Object

    You can return object also from JS function which you can get and deserialize in Blazor like below.

    JsInteropTest.js


    CallingJSFunctionsFromDotnet.razor


    Employee.cs


    25. How to call C# static methods from JavaScript in Blazor?

    You can invoke .NET static methods from JavaScript in Blazor using DotNet.invokeMethod or DotNet.invokeMethodAsync functions.

    Calling Static .NET methods from JavaScript

     To invoke a static .NET method from JavaScript, use the DotNet.invokeMethod or DotNet.invokeMethodAsync functions. First argument passed into these method is name of assembly containing the .NET method and second argument is method name itself.

    The .NET method being invoked from JavaScript must be public, static and decorated with [JSInvokable] attribute.

    CallingDotnetMethodsFromJSFunctions.razor


    JsInteropTest.js


       In above code, C# method is public, static and decorated with [JSInvokable] attribute and in JS code, DotNet.invokeMethodAsync function is used to invoke where first parameter passed as BlazorApp (which is assembly name), second argument passed as C# method name and third argument is passed a name value which is being return from C# code.

    DotNet.invokeMethodAsync function returns a promise which will display returned email when promise is resolved.


    26. How to call C# instance methods from JavaScript in Blazor?

      You can also invoke .NET non-static or instance methods from JavaScript in Blazor. To invoke a .NET instance method from JavaScript, you need to pass the .NET instance by reference to JavaScript using DotNetObjectReference.Create method.

    Calling Instance .NET methods from JavaScript

    CallingDotnetMethodsFromJSFunctions.razor


    JsInteropTest.js


     
      In the above example, I have created an instance method in component called PassComponentInstanceToJS in which a JavaScript function named callDotnetnstanceMethod is invoked and passing current component instance to JS using DotNetObjectReference.Create(this) method. Since current component instance is passed to JS, so now I can call GetWindowSize method from JS, which is a .NET instance method inside current component.


    No comments:

    Post a Comment