Академический Документы
Профессиональный Документы
Культура Документы
b. Reference types: This type does not hold the data directly. They hold the address
on which the actual data present. They stored in heap memory, Can have default
values.
We can make and work with null reference type.
6. Boxing and Unboxing: Terminology, Advantages and Disadvantages.
A. Converting the Value type data into the Reference type is called as Boxing.
byte b= 45;
Object o = b.Tostring();
Converting the Reference type data and keep its value to stack is called as
the Unboxing.
Object o=10;
Int i= Convert.ToInt32(o.ToString());
The Advantage of boxing and unboxing is that we can convert one type of the object
to another type. The disadvantage is that it requires lot of memory and CPU cycles
to convert from one type to another type.
7. What is Type Safety?
A. TypeSafe is a way through which the application or framework that the memory
will not be leaked to outside environment. E.g. C# is the type safe language where
you must have to assign any object before using it. In VB.Net it will take the default
value. So C# is the type safe language while VB.Net is not.
8. What is Strong Name?
A. Strong Name (SN) is used to make the dll as the unique not by its name but by its
version as:
SN -k fileName.dll
Now it will have the unique name with respect to the version. This assembly when
placed in the GAC, it will treat as the unique with its version number and other
details. 2 assemblies with the same name can exist in the GAC but both will have
different version. The CLR takes the latest version assembly while running the
application.
9. What are Extensions, modules and handlers?
A. HttpModule and HttpHandler are the utilities which are used in the HttpPipeline
under the ASP.Net page life cycle. When the request received to Http Pipeline, the
HttpModule checks for the Authentication of the request and then it route the
request to the respective handler. After that HttpHandler takes that request and
process it. Once the request is processed through handler, again the HttpModule
takes the response and send it back to the worker process and finally to the user.
10. What is worker process?
A. Worker process (w3wp.exe) is an executable which is also called as the
Application Factory. This is used for the execution of the request and handling of the
request for the web pages.
11. CLR and DLR?
A. CLR (Common Language Runtime) is the utility in the .Net framework to run the
application. It is the runtime engine which actually executes the application with
many responsibilities like taking care of memory management, versioning, CasPol
etc.
DLR is new with .Net 4.0 which is the Dynamic Language Runtime and used to run
the application on the fly wherever required. CLR runs as statically while DLR runs
dynamically.
12. In case more than one dll versions of an installable is installed, which version is
invoked by default?
A. By default the CLR will take and invoke the latest version of the dll and execute it
accordingly. There could be the same name assemblies exists in the GAC but they
will have different versions altogether for their uniqueness.
So while running the application, CLR takes the latest version assembly and use in
the application.
13. What are Globalization and localization? How to implement them?
A. Globalization is the concept of developing the application in more than one
language while the Localization is used for a particular language. Like if we develop
the application in more than one language we need to create the resource files
(.resx) by using System. Globalization and when we open the application in a
particular language, then the localizations used to convert that application to the
selected language.
14. What is assembly, GAC? Where they are physically located?
A. Assembly is the collection of classes, namespaces, methods, properties which
may be developed in different language and packed as a dll. So we can say that dll
is also called as assembly.
There are 3 types of assemblies- Private Assembly, Shared Assembly, and Satellite Assembly.
GAC (Global Assembly Cache)- When the assembly is required by more than one
project or application, we need to make the assembly with strong name and keep it
in GAC or in Assembly folder by installing the assembly with the GACUtil command.
To make the assembly with strong name:
SN -k MyDll.dll
A. Inproc and Outproc is the types of Sessions where the session data can be stored
in the process memory of the application server(IIS) and in the separate state
server.
When the session data is stored in the process memory(AppDomain) of the
server(IIS), the session is called as the Inproc server. In this case when the server is
restarted, the session data will be lost. So In the Inproc session mode, the session
data stores in the memory object in AppDomain in Application Worker
Process(AspNet_wp.exe)
When the session data is stored in the separate server like in state server or in Sql
Server, the type of session is called as the Outproc session. In this case, if the
server where the application is running is restarted, the session will be still remain
in the separate servers.
So in the inproc session state, the session data is stored in the Process memory of
the Server where the application is running.
In the Outproc session state, the session data is stored in the separate server- may
be state server or in sql server.
17. When the View state is saved, and when is it loaded? How to enable/ disable
View states?
A. View State data is stored in the current page in base64 encoded format. It gets
loaded with the page and displays the values to the controls after the decoded.
Internally it actually saves the check-sum of all the control data where the view
state is enabled.so that when the page gets loaded due to any post back, it again
finds the check-sum and then decodes the Base64 encoded string and gets back the
same data to the controls. We can see the view state base64 encoded string in View
Source of the page. It will be
like _VIEWETATE="DSDSDF8DGDGDFGFD5FDGGDJFF23BNN457M9UJOG"this.
View state won't take the client or server memory to keep the view state data.
18. Difference between GET and POST. Which one is more secure?
A. GET and POST methods are used for the data transfer between the web pages.
GET mainly used for small data which is not secure because in case of GET method,
the data which we are passing will be visible in the url so we can't keep the secure
data which will be visible in the url. There is also limited data which can be passed
in case of GET method (max 255 character).
POST is used for transferring the huge data between the pages where we can keep
the secure data and can transfer it. In case of using the POST method, the data
which is transferring between the pages will not be visible so it is more secure than
the GET method. Also there is no limit for POST method to post the data to the next
page.
POST is more secure.
19. What are Razor engine? How is it different from ASPX Engines?
A. Razor engine is the new execution engine in the ASP.Net MVC 3 which is mainly
used to convert the razor syntax views to HTML page in the MVC applications. It
takes the cshtml pages as the input for the ASP.Net MVC application and then
render to the HTML as the output. The ASPX engine takes the aspx code and then
renders to the HTML.
20. Pros and cons of JavaScript and AJAX.
A. JavaScript is a scripting language and mainly used for client side validation. We
can validate the client side data before sending to the server. So by this we can
improve the performance of the application.
Ajax is Asynchronous JavaScript and XML which is used for the Asynchronous calls
to the server. It uses the JavaScript/JQuery for making the call and use XML for the
Data Transfer. It basically uses the XmlHttpRequest for the asynchronous calls to
the server and communicates with the XML data which is platform independent. So
Ajax can be used with any technology.
21. In how many different ways JavaScript code can be used/called in an
application?
A. JavaScript can be used for Client Side validation, can also be used for calling of
server side methods and functions, can be used for calling the web services, WCF
service, Web API's, Calling the Controller and Action methods in ASP.Net MVC etc.
22. What needs to be done to call a JavaScript function from code behind?
A. If we want to call the JavaScript function from the code behind, we need to
attach the JavaScript to the events in the page_load event as:
protected void btnSave_cliekc9object sender, EventArgs e)
{
btnSave.Attributes.Add("onclick,"JavaScript: retrun Validatedata();");
}
Here ValidateData is the JavaScript function which can be used to validate the page
data and if validation fails, it will return and will not execute the server side
btnSave_click event.
23. Difference between Server Controls and User controls?
A. User controls are used for the re-usability for the controls in the application. By
using the Web User Control template, we create the new user controls and then we
can use the same control in the various pages. User controls can be created by
combining more than one control to extend the functionality of the existing
controls. To use the user controls, first we need to register them in the web page
where we want to use that control. A separate copy is needed in each page where
we want to use the user control. User controls can't be included into the toolbox.
Web Server controls are those controls which can be found in the toolbox and can
be directly drag to the application like other controls textbox, button etc. For the
web server control, only 1 copy of the control is needed irrespective of the number
of web pages. If we want 10 text-boxes to be added in our web page, we need only
1 copy of the textbox in the toolbox and can be dragged 10 times.
Here the myVar is the var type variable which is used to store the string array. Like
this we can store any type of data into the var.
Object is the type which is used to store the objects of any kind. These objects
need to be type cast when used.
Like object myObject = "Hello"
Here the myObject variable of object type is used to keep the string variable. Now
when we want this variable value, we need to typecast it like
string strvar= (string) myobject;
Var is the compile time where the type of the var variable gets defined at the
compilation of the program. Once we define the type during compilation, we cant
make the changes of the type during run time or at the later stages.
Let's say, if we define like
var myVar = new String[] {"hello", "world!!"} ;
so here myVar variable will be of string array. Now after this, I can;t make it like:
var myVar = 10 ;
Now the myVar type will be used as string type. So we can change the type in case
of dynamic.
The difference between the var and dynamic is that the dynamic variable uses the
same memory location to store the object and not changes throughout the
application.
25. Difference between Functions and methods.
A. In.Net terminology, both function and method are same. In general, we use
method in server side code of .Net but in scripting language we use function like
JavaScript function.
Here the difference can be function always returns a value whereas method may or
may not. It depends upon the return type of the method.
26. Difference between Abstract classes and Interface. Explain with scenario where
to implement one?
A. Abstract Class: Collection of the Abstract (Incomplete) and Concrete (complete)
members is called as the Abstract class. If there is at least one abstract member in
Now in the child class, lets say i have a circle class and want to calculate the area
of the circle:
public class Circle: MyAbstractClass
{
public override void Area()
{
// calculate the area of the circle
}
}
Now as this is the generic functionality and can be implemented in any of the class
so we have taken it as interface. We can implement this functionality into any page
like:
class MyClass: System.Web.UI.Page, Inf
{
public void Print()
{
// implement details about the Print method
}
// Here we can implement any kind of print-like print to excel, xml, word all depends on the
our decision.
}
Overriding: When the runtime (CLR) find the behavior of class members at the
runtime of the program, it is called as the AdHoc polymorphism or Overriding. In
this, the method name as well as the prototype (method + parameters) is same but
they are implemented in the different class. We use virtual keyword in the base
class method to override in the child class using the override keyword.
e.g.
public class MyBaseClass
{
public virtual void Show(string message)
{
Console.WriteLine(Your message is : + message);
}
}
public class MyChildClass: MyBaseClass
{
public override void Show(string message)
{
Console.WriteLine(Your new message is : + message);
}
}
Abstract keyword is also used to get the abstraction behavior. We can use Abstract
Class and Interface to implement Abstraction.
28. What are Delegates and Events?
A. A Delegate is an object, which points to another method in the application.
Delegate holds- name of the method, arguments of the method (if any) and the
return type of the method.
See the below points regarding the Delegate:
delegate keyword is sealed type in System. Multicast namespace.
Delegate hides the actual information which is written inside the method
definition.
There are 2 types of delegate- Single cast delegate (hold single function) and
- Multicast delegate(hold multiple functions).
Addition and subtraction are allowed for the delegates but NOT
multiplication and division. It means, we can add delegates, subtract delegates etc.
e.g. To create a single cast delegate, first we can create a class with a method as:
public class DelegateDemo
{
public void Show(string msg)
{
Console.WriteLine(msg);
}
}
Now we can call the method Show using the delegate as:
public delegate void MyDelegate(string message); //declare delegate
now we need to create the object of the delegate with the address of the method
as:
DelegateDemo obj = new DelegateDemo();//class object
MyDelegate md= new MyDelegate(obj.Show(Hello World!!));
md(); // call the delegate
We can create the events and event handler by using delegate with the below
syntax:
public delegate void textChangedEventHandler(Object sender, TextEventArgs e);
This event handler will be used to handle the textbox textchanged event.
More details about the delegate and events can be found at the below link:
http://msdn.microsoft.com/en-in/library/orm-9780596521066-01-17.aspx
You can go to the below link for more details with the examples that how we can
use the covariance and contrvariance to implicate reference conversion:
http://blogs.msdn.com/b/csharpfaq/archive/2010/02/16/covariance-and-contravariancefaq.aspx
In order to extract the matched rows from both the tables and unmatched rows
from the second table, right Outer join is used. The syntax for right outer join
condition is:
T1.Col1 = *T2.Col1
In order to extract the matched rows from both the tables and unmatched rows
from the first table and then unmatched row from the second table, full join is used.
The syntax for full join condition is:
T1.Col1* = *T2.Col1
b. Temp tables are only visible to the current sessions of the sql server instance.
When the session end, these table data automatically drops.
c. We cant join the temp tables as they dont allow the foreign key constraints.
d. Temp tables are created in TempDB database.
e. We can use the same temp table name for the different user sessions.
f. Mostly used in stored procedure to handle the intermediate data.
41. What does @ and @@ suffixed by property names specify?
A. @- This is used for the variable declaration
e.g. @name varchar2(50)
@@- This is used for the Global variable declaration
e.g. @@Error=0
42. Self-join queries.
A. Self-Join is a type of join which is used to join the same table by creating the
multiple instances of the same table. So we can join 2 instances of the same table
in case of self-join. This type of join is used when there is the requirement to get
the referenced data which is available in the same table.
e.g. A table contains EmpId, Ename and ManagerId
As the manager is also an employee. Now if we want that who is the manager of
which employee. In this situation, we need to create the instance of the same table
and get the required data as:
SELECT EMPID, ENAME, ENAME AS [MANAGER NAME]
FROM EMP E1, EMP E2
WHERE E1.EMPID= E2.MANAGERID
one of the normalization rule, we have to create primary key for the table to make
the rows unique.
Unique Key:- (Primary Key + Not null) is called as unique key. Unique key is also
used to make the rows as unique in a table. The only difference between primary
key and unique key is that primary key does not allow null value while the unique
key allow. The limitation of the null in unique key is that it allows only one Null
value. So only in one row, we can make the key as null for the unique key.
Candidate key- The key other than primary key, to make the rows as unique is
called as candidate key. In candidate key, we take the columns which are not in the
primary key and make the key for uniqueness of the row.
45. What is the default value for Datetime. What are Min and Max values for Date in
2008.
A. The default value of Date is CURRENT_TIMESTAMP
Below are the new date and time values in Sql Server 2008:
In SQL Server 2008:
1. DateTime2
Min Value: 0001-01-01 00:00:00.0000000
Max Value: 9999-12-31 23:59:59.9999999
2. Date
Min Value: 0001-01-01
Max Value: 9999-12-31
You can go through the below link for couple of work around:
http://dhaneenja.blogspot.in/2008/06/minimum-year-value-in-sql-server.html
WCF
46. What is WCF also known as?
A. WCF (Windows Communication Foundation) is also know as Indigo by its code
name.
47. Difference between WCF and Web Services?
A. Below are the main differences between the WCF and Web Service:
Web Service:
a. Can be hosted in IIS only
b. Only two types of operations affects- One-Way, Request-Response
c. To serialize the data use System.Xml.Serialization
d. To encode the data use- XML 1.0, MTOM, DIME, Custom
e. Web Service can be accessed through HTTP channel.
WCF service:
a. Can be hosted in IIS, Self Hosting, WAS, Windows Services etc
b. Three types of operations affects- One-Way, Request-Response and Duplex
c. To serialize the data use System.Runtimel.Serialization
d. To encode the data use- XML 1.0, MTOM,Binary, Custom
e. WCF Service can be accessed through HTTP, TCP, Named pipes, MSMQ,P2P etc.
48. What are Endpoints?
A. The collection of Address, Binding and Contract is called as End Point. In Sort,
EndPoint = A+B+C
Address (Where)- It means where the service is hosted. URL of the service shows
the address.
Binding (How)- How to connect to the service, is defined by the Binding. It basically
has the definition of the communication channel to communicate to the WCF service
Contract (what)- It means what the service contains for the client. What all the
methods are implemented in the WCF service is implemented in the Contract.
49. What are Behavior and Bindings?
A. Binding mainly describes about the communication of the client and service. For
this, there are protocols corresponding to the binding behavior which will take care
of the communication channel. There are different protocols which we use for the
different types of bindings. E.g. HTTP, TCP, MSMQ, Named Pipes etc.
Behavior is used for the common configurations that could be for endpoints. When
we use the common behavior, they affect to all the end points. Adding the service
behavior affect the service related stuff while the endpoint related behavior affects
the end points. Also operations level behavior affects the operations.
50. What are different types of Contracts supported?
A. There are mainly 5 type of contracts used in WCF service:
a. Service Contract
b. Operation Contract
c. Data Contract
d. Message Contract
e. Fault Contract
51. What is the difference between Transport and Message Security mode?
A. WCF supports 2 types of security- Transport Level Security and Message Level
Security
Transport Level Security- In this type of security, we make the transport channel as
secure so that the data flows in that channel will be automatically secured. For
HTTP channel, we use the client certificate for the security of the web address. SSL
is used for the HTTP channel security. As we dont need to secure each of the
messages which are floating between the client and the service, the speed is faster
as direct message is going to the client from the service.
Message level security- This type of security in WCF is used where we don't have
the fixed transport medium and we need to secure each message which is floating
between the server and the client. In this type of security we use certain algorithms
for making the message as secure message. We use some extra bits and send with
the message. We also use some encryption techniques like SHA1 or MD5 which
make the proper security for our message. As each message needs to be secured,
this type of security makes some delay in the process of sending and receiving the
messages.
52. How to configure WCF security to support Windows authentication?
A. To support the WCF security in Windows Authentication, we need to add the
ClientCredetialType attribute to Windows under the security tab element:
transport clientCredentialType="Windows"
53. How to use Fault Contract?
A. Fault Contract is mainly used for viewing and displaying the errors which
occurred in the service. So it basically documents the error and the error message
can be shown to the user in the understandable way. We cant use here the
try.catch block for the error handling because the trycatch is the technology
specific (.Net Technology). If we use the try...catch block for handling the errors,
the error will not be reached to the client who is consuming the
service. Because this error will not be included in the message. So we use the Fault
contract for the error handling.
e.g. To use the Fault contract, we can simply write like the below:
public int Add(int number1,int number2)
{
// write some implementation
throw new FaultException (Error while adding data..);
}
Here the fault Exception method is the inbuilt method which will throw the
exception and display the message . We can use the custom class so that the
message can be customized and the customized message can be sent to the client.
So we can create a clss like:
public Class CustomException
{
public int ID {get;set;}
public string Message {get;set;}
public string Type{get;set;}
}
Now this custom type we can use with the Operation Contract as:
[ServiceContract]
public interface IMyInterface
{
[OperationContract]
[FaultContract(typeOf(CustomException))]
int Add(int num1,int num2);
}
Now while implementation of the Add method, we can assign the class properties.
WPF
54. Diff between XML and XAML.
A. XAML is the declarative XML based language which is used to define the objects
and properties. XAML document is loaded by XAML parser. So XAML Parser initiates
the objects and set those properties. XAML is mainly used in creating the objects in
WPF and Silverlight applications.
For more detailed explanation, you can go through the below link:
http://www.differencebetween.net/technology/software-technology/differencebetween-xml-and-xaml/
55. Stack Panel and Wrap Panel.
A. StackPanel is one of layout control in WPF. We can place the child controls inside
the stackpanel either horizontally or vertically. So it provides two types of
orientations- Horizontal Orientation and Vertical orientation.
You can go through the below link for more detailed explanation and the code
snippet:
http://wpftutorial.net/StackPanel.html
Wrap panel is another layout control which is similar to the StackPanel. Wrap panel
not only keep the control in horizontal and vertical orientation but also wrap
them into new line if there is no space. Here also the orientation can be set as
Horizontal or Vertical. Its main use is to arrange the tabs in the tab control, menu
control or in toolbar items.
You can go through the below link for more details:
http://wpftutorial.net/WrapPanel.html
57. Virtualization.
A. This is the feature in WPF which increases the efficiency of the programs when
there are the large data objects. If the WPF ItemsControl is bound with the large
collection data source object and we enabled the virtualization, then the controls
will show only the data which is in the visual container for those items which are
visible currently. This visual data is only the small part of the large data object. Now
when the user will scroll down or up, the rest of the data will be visible and previous
data will be hidden again. So this is increase the efficiency of the program from the
UI prospective.
58. Events and Routed Events.
A. Routed event is special type of event which can invoke and handle multiple
events from different objects rather than the event which is coming from one
object. So it generally handles the object from the element tree. So whatever the
elements inside the element tree and if they generate the event-may be multiple
events, the routed event is capable of handling those events.
The routed event can be invoked in both the directions but in general it comes from
the source element and then bubbled up in the element tree until the root element.
59. Bubbling and Tunneling.
A. Bubbling: When the events are raised form the innermost element in the visual
tree and comes up towards the root element, is called as bubbling.
Tunneling: It is the opposite process of Bubbling where the events fired by the root
element goes down towards the last child element control.
Please go through the below link for more details:
http://www.dotnetspider.com/forum/130497-event-bubbling-event-tunneling.aspx
A. For the details about the dependency injection, you can follow the below link:
http://wpftutorial.net/ReferenceArchitecture.html
EventAggregator : It is the utility service which contains the events and allows the
decouple the publisher and subscriber so that they can be buildup independently.
Decouple is primarily useful when a new module needs to be added or removed or
modified. The new module can be added as per the event fired and defined in the
shell.
For more details about the Event Aggregator, you can follow the below link:
http://msdn.microsoft.com/en-us/library/ff921122(v=pandp.20).aspx
http://msdn.microsoft.com/en-us/library/ff921139(v=pandp.20).aspx
Region and Region Managers: This is concept of Prism framework. We define the
region through XAML code and once a region is defined, automatically it will be
registered with the RegionManager. Actually the Bootstrapper registers a service
called the RegionManager at run time. RegionManager is a dictionary where the key
is name of the region. The value of the key is the reference of the IRegion interface.
RegionAdapter is used to create the instance reference of the IRegion interface.
You can go through the below link for more details about the Region and Region
Manager:
http://msdn.microsoft.com/en-us/magazine/cc785479.aspx#id0090091
http://msdn.microsoft.com/en-us/library/dd460648.aspx
65. How to navigate to another page?
A. There is a class NavigationService which can be used for navigation of the WPF
window:
this.NavigationService.GoForward();
//or
this.NavigationService.Navigate("MysecondPage.xaml")
Most Interesting Questions in C#, ASP.Net and SQL Server, WCF, ASP.Net MVC
Hello Guys,
In this article, we will see the most interesting questions in Microsoft Technologies like in
C#, ASP.Net, Sql Server, WCF services, ASP.Net MVC.
Q 1. I have logged in to the ASP.Net website using my credential for the login page. Now I
want that when my session is expired, it should logout the application and show the login
page. With that It should also logged out from the Windows and I should use the Windows
credentials again to reach to my application again. How do you think it can be done?
Ans. This question is related to the Sessions in ASP.Net where the session time out is
configured for the current user. And when the session gets expired, we need to set so that it
should automatically come back to login page and user need to enter the credentials again.
the child class memory so when the object of the child class get created, it will call first the
abstract class constructor and then then it will call the child class constructor.
Yes, We can write the Static members(Methods and Properties) inside the abstract class
where
the static members can be called based on the class name. ClassName.MethodName(),
ClassName.PropertyName etc.
Yes, Inheritance between the abstract classes is possible where we have both base class and
inherited class both are abstract classes. So if we have an abstract method in the abstract
base class and then we are inheriting this base class to the abstract child class,
the abstract method can be overridden in the child abstract class but it is not mandatory to
implement it there. We can also implement the abstract base class method to the last child
class. So we can write the virtual, abstract as well as override methods inside the abstract
class.
Q.4 Can we write properties inside interfaces? If so then what is the syntax to write
a property in the Interface if the name of the property is ID and return type is integer?
Ans. Yes, We can define the public properties inside the Interface but as in interface all the
members are public so we don't need to define the property as public.
Syntax: int ID {get; set;}
Q. 5 By default all the members of the Interface are public abstract. Can we
write explicitly the 'Public' for the method? Do you think now my program will compile or will
give a warning message? If it will give the warning message, then what the text for the
warning message. If it will give the compilation error then what error you will get?
Ans. No, We can't write the explicitely 'Public' access specifier inside the interface. If we
write the 'public' access specifier inside the interface, it will throw error during the
compilation of the program that 'no access specifier are allowed inside the interface'.
What is MVC?
Ans. MVC (Model View Controller) is one of the Software Architectural pattern which is built
on 3 layers. So it is the pattern which basically talks about the separation of concern for a
project. Here the 3 parts are having their own roles like:
a. Model - It is used as the Data Container or it can also have the business rules, functions,
logic's etc.
b. View - It is mainly the UI (User Interface) part which is the main application built using
the Web technologies like ASP.Net etc. It consists of the User Interface
Design, representation of the information for the end users etc.
c. Controller - It is the mediator between the View and Model and used to control the
requests and responses floating through the views and Model. The command, Actions,
Events are the part of Controller in MVC. All the communication is done via Controller so we
can say that Controller is the heart of MVC.
2.
Ans. ASP.Net MVC is the Microsoft product based on the core MVC pattern. The Microsoft has
taken the core concept of MVC and Designed the ASP.Net MVC structure for the Visual
Studio which helps the developers to get the automated structure and on it, they can built
the applications.
ASP.Net MVC provides the structure with the separation of concerns where each part
of ASP.Net MVC application is separate and has no link among them. Apart from the
separation of concerns, the Microsoft has provided the way to communicate between the
separate components by using the other additional logic and libraries. These libraries
supports in the connection, communication between the components, databases and other
external components as well with small effort.
3.
Ans. ASP.Net MVC is the inherited form of Core MVC where Microsoft has designed their MVC
patterns based on the original core MVC concept. The Microsoft also provided the new MVC
structure (ASP.Net MVC) which has the inbuilt capabilities of communication with
their components, connection with the database etc. The ASP.Net MVC has the good support
for creating mobile application. We can create the Mobile applications in ASP.Net MVC using
the predefined template.
4.
Ans. There are few major changes happened in the version MVC2. The Microsoft has more
concentrated on the HTML Helpers, Validations support, Async controllers etc.Below are the
few point which distinguishes the ASP.Net MVC 2 different than the previous versions:
a. New HTML Helpers with Strongly Typed
b. Model based validations- This is very useful feature where the validation is done in the
Model and will be used throughout the application.
c. Automatic scaffolding feature also got introduces with this version.
d. Asynchronous controller support which enables the multiple tasks to run simultaneously.
e. Html.RenderAction introduced to render the section/part of the page.
The main objective of the MVC design pattern is to separate the logic with the UI. So the
separation of Concerns is one of the biggest advantage of the MVC design pattern where the
UI is separate with business logic.
The user sends the request and the request is taken by the Controller which is heart of the
MVC model and takes care of all the actions and events happens in the View. The controller
checks whether the request required the Model intervention and if so then call the model to
serve the database operations and get the result back. Based on the Model data, the View
will be populated. So the Model and View are nothing but the mapping of each other. View is
always gets populated based on the Model and not rendered.
6.
7.
8.
9.
Ans. The application life cycle of ASP.net MVC includes the request, processing, filtering and
execution and then finally the response back to the requester. The request first goes to URL
routing module(HTTP Module) and there it gets decided that whether this is MVC request
and will be handled or not. Now if the request is for MVC application, the URL routing
module selects the first route which is satisfying the requested URL. As soon as the first
match found for the requested URL, the process for the execution begins with the Controller
and Model(if any) and the response sends back to the browser.
To Specify a route, we need Name and URL of the route. The default URL contains the
Controller Name, Action name and the id(if required). By this route, the actual URL gets
mapped and if it maps correctly, the view will get displayed, else it shows the 404 error (file
not found).
16. How can you do authentication and authorization in ASP.Net MVC?
Ans. Windows and Form Authentication are available for the Authentication & Autherization
in ASP.Net MVC.
17. How to implement Windows authentication for ASP.Net MVC?
Ans. To Implement the Windows Authentication, it is similar to other application where we
can define the authentication mechanism in the config file. In the same way, we can
implement the Windows Authentication & Authorization using the below snippet:
Now, we can retrict the particualr use to access the controller as below:
We can also restrict the action methods by using the same attribute.
18. How do you implement Forms authentication in ASP.Net MVC? Mention some of the
return types of a controller action method.
Ans. The Form Authentication implementation is similar to the ASP.Net form authentication
where we need to check the user credentials in each forms to validate the user and then
provie the access.
For this, we need to first define the Form Authentication Mode in Web.Config file as:
Now once we define the Form Authentication, we can check the user and set the cookies as:
19. Is ASP.Net MVC suitable for both Windows and web applications?
Ans. No, ASP.Net MVC is primarility made for the Web Applications development. For the
Windows Application, MVC is most suitable.
20. What are the benefits of using ASP.Net MVC?
Ans. The major benefits using ASP.Net MVC are:
a. Separation of concern- separate code behind file
b. Automated testing - testing of the logic with no UI
30. How can we restrict MVC actions to be invoked only by GET or POST?
Ans. We can restrict the actions to be called by GET or POST by decorating the action
method by HttpGet or HttpPost as below:
36. Can we display all errors in one go? or Validation summery in ASP.Net MVC.
Ans. Html helper class contains a method with the name sas ValidationSummary which can
be used to show all the errors in one go.
e.g. Html.ValidationSummary()
37. How can we enable data annotation validation on the client side?
Ans. To enable the Data Annotations at the client side, first we need to include the JQuery
validation file and then call the Html.EnableClientValidation() method.
38. What is Razor in MVC?
Ans. Razor is the new engine to parse the MVC code. From ASP.Net MVC 3, Microsoft has
introduces this engine. So in ASP.Net MVC 3, there are 2 View Engines- Razor and ASPX
39. Why Razor when we already have ASPX?
Ans. The Razor view Engine is lightweight as compare to the ASPX view engine. Razor
engine has quite readable and simple syntaxes.
40. How to implement AJAX in MVC
Ans. There are 2 ways to implement AJAX in MVC:
a. By using JQuery
b. By using Ajax Libraries
41. What kind of events can be tracked in AJAX?
Ans.
42. What is the difference between ActionResult and ViewResult?
Ans.
43. What are the different types of results in MVC?
Ans.
44. What are ActionFilters in MVC?
Ans.
45. Can we create our own custom view engine using MVC?
Ans.
46. How to send result back in JSON format in MVC
Ans.
47. What is WebAPI?
Ans.
48. But WCF SOAP also does the same thing, so how does WebAPI differ? With WCF you can
implement REST, so why WebAPI?
Ans.
49. How can we detect that a MVC controller is called by POST or GET?
Ans.
50. What is Bundling and Minification in MVC?
Ans.
This post is regarding the Most Confusing Questions in .Net, C#.Net, ASP.Net and Sql
Server. As I have seen that lot of people whether they are searching for jobs, already in the
job or they try to understand the things, gets lot of confusions and there are very rare sites
where they explain the things in more detailed and example way.
So I thought to write such post which will be helpful for all of us to try to understand the
things in better manner and it will be helpful whether we are in search of job or in actual
implementation in our projects:
1. Abstract classes provide a simple and easy way to version your components. By updating
the base class, all inheriting classes are automatically updated with the change. How?
Ans. Abstract class is the collection of abstract and concrete members. I am not calling here
method or function but members because members can be methods or properties or
indexers etc.
A concrete member means non-abstract or general members.
Versioning of a class means adding or removing the members from the class.
So as per question statement, in abstract class we can add or remove the members and it
will not impact your classes which are inherited by the abstract class. The only thing is if the
class doesn't contain non-abstract members. As the abstract class can contain both abstract
and concrete members so it hardly matters to add or remove any non-abstract members.
So we can make another version of the class by adding or removing members in the class.
So if we update the base class or the abstract class by adding or removing any non-abstract
member, the child class will have no impact, it will be automatically inheriting the new
members.
public abstract class MyClass
{
public abstract void Show();
public int Add(int a, int b)
{
return a+b;
}
}
This is the abstract class and we can inherit it to the child classes.
Lets say:
class ChildClass:MyClass
{
public override void Show()
{
// some implementation
}
}
Now we can create another version of abstract class by adding an extra method;
public abstract class MyClass
{
public abstract void Show();
public int Add(int a, int b)
{
return a+b;
}
public int Sub(int a, int b)
{
return a-b;
}
}
Now it hardly matters for the child class to modify anything.
2. If a new version of an interface is required, you must create a whole new interface.
Ans. For interface which is the collection of abstract members is less flexible. Because when
we need to create another version of interface, means adding or removing a member which
is abstract so we need to change all the child class either remove or adding override
members.
Let's see with the example:
interface MyInf
{
void Show();
void Print();
}
Now use this interface in our class:
class ChildClass: MyInf
{
public void Show()
{
// some implementation
}
public void Print()
{
// some implementation
}
}
Now if we add another member in the interface, we need to implement it to all our child
classes so it is preferable to create another interface and inherit that as below:
interface MyInf2
{
void Display();
}
Use this in the class:
class ChildClass: MyInf,MyInf2
{
public void Show()
{
// some implementation
}
public void Print()
{
// some implementation
}
public void Display()
{
// some implementation
}
}
3. What are the advantages of properties (get, set)? When we go for properties? What is the
difference with using properties and without using properties?
Ans: Properties are the way to carry the data from one class to another class, from one
application to another application etc.
When we want to send the data from one class to another class or event one application to
another application, we can set the value and get its value to another place.
We can do our tasks without using the properties and in that case we need to send our data
as the parameters and get it to another class as below:
class A
{
public int IsValid(int val1, int val2, string val3, string val4)
{
B objB = new B();
int result= objB.Validate(val1,val2,val3,val4);
}
}
Now in the class B, we will have the Validate method and will do the validation based on the
input values:
class B
{
public int Validate(int val1, int val2, string val3, string val4)
{
// some processing
}
return true;
}
here we can see that we have not used the properties for sending the data from class A to
class B. And it will work fine.
Now we will try the same task using the properties. We will create a class which will contain
all the properties as below:
public class MyProperties
{
public int Val1{get;set;}
public int Val2{get;set;}
public string Val3{get;set;}
public string Val4{get;set;}
}
Now we will try to set these value and pass this whole object to another class:
class A
{
public int IsValid(int val1, int val2, string val3, string val4)
{
var objMyProperties= new MyProperties()
{
Val1 = val1,
Val2 = val2,
Val3 = val3,
Val4 = val4,
};
B objB = new B();
int result= objB.Validate(objMyProperties);
}
}
And your B class will be:
class B
{
public int Validate(MyProperties objProperties)
{
var value1 = objProperties.Val1;
var value2 = objProperties.Val2;
var value3 = objProperties.Val3;
var value4 = objProperties.Val4;
// some processing
}
return true;
}
Here we can see that if we are adding additional properties or removing the existing
properties, our call will not affect in class A and then method signature will also be same in
class B.
But in the first case, if we remove one parameter or add additional parameter, we need to
make the changes in the Class A calling method as well as the method signature in the
Class B also.
If we try to do, it will show the compile time error saying "Control cannot leave the body of
finally clause".
17 September 2014
This article is related to ASP.Net MVC. Here we will see what all the new features available in
terms of ASP.Net MVC 5 under the Visual Studio 2013 IDE. I have tried to explain the
default template structure which gets created when we start a new project of ASP.Net MVC
5 in Visual Studio 2013.
In this article, I also tried to create a new small application by making use of existing
template and the application will have the functionality of CRUD operations for each of the
menu items.
In this article, i am using the Code First Approach to create the application so it will be
helpful for those who wants to know about the Code First Approach and creating the
database automatically by using the Model classes. We will see each of these things step by
step from the installation of Visual Studio 2013 express edition free and then we will go on
to create the new application. I also explained the new feature of Visual Studio 2013 in
terms of ASP.Net MVC so it will be helpful for all of those guys who are looking out for the
same.
Below is the link where you can see the step by step approach of creating the new
application in ASP.Net MVC 5 with Visual Studio 2013.
http://www.dotnetspider.com/resources/45899-Creating-application-using-ASPNet-MVC-5with-Visual-Studio-2013.aspx
Do you have fear of thinking the layered architecture?? How to create it? What kind of
project we need to include for creating layers?? How the layer communicates to each
other??
How we can create the architecture by our own. Is this the job of architect? What all the
things we should be consider while creating the layered applications. How the layers will talk
to each other etc.
All of these questions come to our mind when we think about the layers architecture. So
Today I am going to show all of these things in my article.
You will see the practical implementation of all including the coding with the standards so
that you can adapt the similar things when writing the actual code in the projects.
below is the link where you can find the detailed description with the snapshots for all the
steps of create in the windows application using 3 -tier architecture:
http://www.dotnetspider.com/resources/45768-Windows-Application-using-3-tierarchitecture.aspx
B. Not only that, hosting is also one of the powerful feature in WCF where the service can be
hosted in Self Hosting, Hosting in Windows Services, Hosting on another Service etc.
C. Supports DataContractSerializer which is fast and can serialize fields and properties.
D. Integrated Logging mechanism.
C. Satellite Assembly
6. What is a strong name and how do you give a strong name to an assembly?
Ans.
Unique identification of an assembly called as strong name. By strong name we can
differentiate the assemblies which are having the same name.
We can generate the Strong name using the command:
SN -K dllName
7. What is InsteadOf trigger.
Ans.
To update the Views, InsteadOf trigger is used. This is the only use of InsteadOf trigger.
There is no use except this.
9. What are abstract classes and Interface and what the difference between the two.
Ans.
When the class does not provides the full functionality, the class must be declared as the
abstract class.
There are 2 types of abstract classesA. Partial Abstract Class (Abstract Class)- Class which can support the abstract
members(methods, properties) as well as concrete members(methods, properties), the
class can be declared as the abstract class.
Abstract class works based on the child class memory. We can't create the object of the
abstract class, only the reference can be created for the abstract class.
All the abstract members must be overrides in the child class using the Override keywords.
When you have limited scope for the functionality, Abstract class is better but when there is
the requirement to implement the global functions, interface is best way to do.
e.g. When u have some feature which can be implemented in several classes and classes
are interrelated, use Abstract class but when the feature can be application level and used
by various independent classes, use Interface.
12. What kind of authentication mechanism you have used in your WCF project.
Ans.
There are various authentication modes which can be used for the WCF service likeA. No Authentication- When the service doesn't requires any authentication and its public to
access and use, this type of authentication mode is used.
B. Windows Authentication This type of service depends on the windows credential so if
the user is having the windows credentials, they can use and access the service.
C. Form Authentication This type of authentication requires certain and valid user name
and password to access the service.
D. Certificate Based There are the secure cervices where each request needs certain
authentication mechanism which can be the 3rd party like .X509 certificates to validate the
access requests.
E. Custom Authentication- This can be mixed with two or more authentication mechanism.
F. Token Based Authentication Depends on the token provided by the service provider. So
based on the token, the client can access the service.
16. How is var keyword used in .NET.Difference between var and dynamic keywords.
Ans.
var keyword is newly introduces with the .net 3.5 and it is used to make the assignment for
any type of data. It can store any type of data irrespective of its datatype.
So when we don't know that what type of data, the certain process will return, we can use
the var keyword.
e.g.
var connection = new SqlConnection(connectionString);
Here the connection variable can store the SQLConnection type.
Dynamic keyword is newly introduces with the .net 4.0 version and is used to keep not only
the any type of data but also the reference will be constant.
For the var, the type is made at the compile time while in case of Dynamic; the type is
inferred in runtime.
e.g.
var customer = new Customer();
customer.GetCustomers();
Here the compiler will check for the GetCustomers()method. If the GetCustomers() method
doesn't exists, it will show error during the compilation.
But for the dynamic,
dynamic customer = new Customer();
customer.GetCustomers();
Here the compiler will not check for the GetCustomers() method during the compilation. But
at the run-time, if the method is not available, it will throw error.
So the main use of dynamic is when we don't want the compiler should check for certain
errors during compilation. It will skip the error if they are of dynamic type.
Stored Procedure and Functions are the database objects which are the pre-compiled names
SQL statements.
A. Stored procedure can take in as well as Out parameters while function can take only in
parameters'.
B. Stored Procedure may or may not return the value while the Function must return a
value. Returning a value in stored procedure depends on the input parameter. If the input
parameter is of type out, then it will return the value.
C. We can use the function inside the stored procedure but stored procedure can't be used
inside a function.
19. What is the static variable and what are the static variables in dot net.
Ans.
When the variable is shared by multiple class members (method, properties etc), we can
make that variable as Static (in VB.Net Shared). To access these variables, we don't need to
create the object of the class. We can directly call the static class members using the Class
name. These variables get loaded when the class gets loaded in to the memory.
20. If I have 2 interfaces with same method same parameter and same return type. Both
interface implemented from one Class. Then how can i call to these methods.
Ans.
Two interfaces with the same methods and same parameters can be implemented using the
external interface functionality, rather than internal interface.
By default, when we implement the interface, we need to implement all the method to the
implemented class.
But if the methods are same, then we can take the help of explicit interface as:
interface inf1
{
void Print();
void Show();
}
interface inf2
{
void Print();
void Show();
}
Now we will implement these interfaces in a single class:
class MyChildClass: inf1, inf2
{
public void inf1.Print() // explicit interface call
{
//implement Print() method details for the first interface
}
public void inf1.Show()
{
//implement Show() method details for the first interface
}
public void inf2.Print()
{
//implement Print() method details for the second interface
}
public void inf2.Show()
{
//implement Show() method details for the second interface
}
}
21. Can method overloading and overriding possible in simultaneously in program.
Ans.
Yes, both overloading and overriding concept can be implemented simultaneously between
the parent can child classes as:
Class MyBaseClass
{
public void Print()
{
// Print method implementation
}
public void Print(string fileName) // overloaded method
{
// Print method implementation with the file name
}
public virtual void Print()
{
// Print method implementation
}
}
Class ChildClass:MyBaseClass
{
public override void Print() // overriding implementation
{
26 January 2014
about the answer of a particular question. With the hope that these questions and answers
will be helpful to you, I am posting them and will try to update and include more in the
future.
These questions are scenario based questions in .Net technologies which will help to prepare
for the interviews. Few questions are related to OOPs concepts, and then few on Garbage
Collector and memory related. So you can prepare them accordingly. These questions will be
useful for those who are having the 3+ years experience and looking out for the
opportunities in good companies.
1.
How the Encapsulation is different from Abstraction? I think both are used to hide the
unnecessary details? Then how they are different?
Ans.
Yes, Both Encapsulation and Abstraction do the same thing but with few differences.
Encapsulation mainly encapsulates the object and so hides the details as well as it binds the
data.
So Encapsulation = Hiding + Binding the data
How it hides the data? Real-time Example?
Take the example of n-Tier application where we have an additional layer called Business
Objects. This layer
contains all the entities with their properties. Take an entity name: Employee. This
Employee will have the
class name "EmployeeBO.cs" and contains the public properties like EmpId, EmpName, Sal
ets
EmployeeBO.cs
So this is the presentation of one property in the Business object class. Now wherever we
want this attribute,
We just need to create the object of this class and set/get the value of EmpId as:
// set the EmpId
EmployeeBo objEmployeeBO = new EmployeeBO();
objEmployeeBO.EmpId = 101;
The Run time polymorphism also named as the Overriding. This concept works in between
classes or multiple classes or parent child classes where the child class has to get the
behavior of the base class by inheriting the base class.
In this concept we generally have an abstract or virtual method in the base class and we
override that method in the child class by using the override method.
e.g.
So now we know the Compile Time polymorphism and Run Time polymorphism. The
compile time polymorphism uses the concept of early binding and Run time polymorphism
uses it as the late binding.
In early binding, the runtime (CLR) gets the behavior in the compilation of the program.
It means that the method behavior will get compiled before in the early binding.
In Late binding, like Overriding, the behavior of the class and methods gets by the CLR
when creating the object means at runtime. So, in the late binding the behavior of the class
members identified by the CLR at runtime.
Now come to the next part of the question-which is good?
One cant say about the answer of this question, there are the scenarios where the early
binding is good. When you have lot of objects and in that case, the early binding behavior
performs well. While the late binding will be good when we have less objects. Lets say you
want the dropdown list to be loaded when you click on it and not while the loading of the
page. So in some scenario, it will be good if we have while load and it will not be good when
you click.
So its all depends on how you have implemented and the form structure.
3. In garbage collection, how the object generations come in the picture? How many
generations an object can have? Please tell me the process of disposing the objects based
on the generations? Can an object move from one generation to another? If yes then why?
Whats the need to have different generations as we are going to dispose the objects which
are marked by the Garbage collector?
Ans.
Lets start with what is Garbage collection first and then we will come to our main
question of the post. As we know that all the objects created using the new operator gets
fits in to the Heap memory. So whenever a new object gets created, it tries to fit in the heap
memory. Now lets say the heap memory is full and there is no place to keep another newly
created object.
In that case the Garbage collector installed, which is the background process, runs
through CLR and take the unused objects memory. It mainly cleanup the heap memory and
the new objects get placed in to it.
Now the question comes that for which objects it reclaims for the memory? How the
object generations come in the picture?
It depends on the objects generations. The CLR finds out the objects which are no longer
used by the application since longer time and then the Garbage collection reclaim their
memory.
How many generations an object can have? Please tell me the process of disposing the
objects based on the generations?
Actually there are 3 generations exists for the objects which are written under the .Net
framework library. When a new object gets created, by default it moves to the generation 0.
Can an object move from one generation to another?
Now when the generation 0 objects gets occupied with the memory and garbage collector
gets called by the run-time. It checks the objects which are no longer used by the
application and mark them for deletion. After deleting or reclaim the memory, the older
objects moved to next generation i.e. Generation 1. Now the next time the CLR will check
for the Generation 1 object too and if it finds that in generation 1 if the objects are not used
since longer time, it will mark them for release and move the remaining objects to
generation 2.
In generation the objects which are under the main method, exists as they gets removed
either at the end of the program or when both the generation 0 and generation 1 objects
are using.
Whats the need to have different generations as we are going to dispose the objects
which are marked by the Garbage collector?
With the different generation, it improves the performance of the application as the
Garbage collector need not to check for each of the objects in the memory. It first checks
for the generation 0 objects and reclaim the memory. If still needs then goes to the
generation 1 and then 2.
4.
What is object graph in garbage collector? Is this the graph physically exists? Or how
this graph gets created?
Ans. When the Garbage Collector gets called by the CLR to DE-allocate the memory in the
heap, the Garbage Collector start finding the references of all the reachable objects which
are currently in use. So it find the objects which are used by the processes and for rest of
objects which are un-reachable or the Garbage collector is not able to find the references for
them, it marks them for deletion.
Here the Garbage collector makes an Object graph which keeps track of all the objects
which are marked for deletion. After the deleting the references for those objects, the heap
memory gets compacted and a new root becomes available to use by the new created
object.
Is this the graph physically exists? Or how this graph gets created?
No, this object graph creates virtually by the Garbage Collector to keep all the objects
and to make them for deletion. This is the Garbage Collector responsibility to create this
object graph and gets the references of each reachable object which are used by the
application
5.
Can we suppress the Garbage collector? If yes, then why do we need to suppress it as
it is used to reclaim the unused memory and which improve s the performance of our
application?
Ans. Yes, We can suppress the Garbage Collector. There is the Static method in GC class
called as SupressFinalize.
GC.SuppressFinalize(objectName);
This Static method takes a parameter for the object. So we can pass it to suppress the
claiming memory for this object.
Now the question comes "why do we need to suppress it as it is used to reclaim the
unused memory",
So, whenever we are using dispose method for class object,which is capable of disposing
the object and in that case we don't need to use this method to again reclaim the memory.
e.g.
public class DemoClass : IDisposable
{
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
}
As we have seen above,the DemoClass is inherited by IDisposable interface and which
have the Dispose method to implement.
Hence after implementation of Dispose() method, we need not to reclaim the memory
using the Garbage collector and so we can use the SuppressFinalize() for the current class
object.
6. We already have the Finalize method which reclaims the memory using the Garbage
collector. This is automatic process then why do we have the Dispose () method? Is this
method different from Finalize ()? What is the interface from which the Dispose () method
inherited?
Ans. Yes, We have the Finalize() method which is used to reclaim the memory for the
unused objects. The Finalize() method is sufficient to release the memory from heap for the
un-referenced object but it is only for the managed objects. So Finalize() method can
reclaim the managed objects memory from the heap which are not used since longer time.
Then what about the objects which are unmanaged? The objects which are out of .Net
CLR? The objects where the CLR can't be used to manage? Dispose() method is used for all
those objects which do not comes under CLR or under the Managed heap. Dispose() method
can be overrides and can be written to reclaim the object of those classes. Dispose()
method is implemented by using the IDisposable interface.
e.g.public class TestClass : IDisposable
{
public void Dispose()
{
Dispose(true);
}
}
7.
Can we call the Finalize() method to be executed explicitly when we want that
particular object memory to be reclaim by the Garbage Collector? If yes, then where do we
need to write the code? If no then why?
Ans. No, the Finalize() method can't be called as Explicitly. The Garbage collector calls it
when the Heap memory is having no space to allocate the new object in the heap.
Finalize() method is mainly used to perform the cleanup on the unmanaged resources
which are held by the current object.
Working Finalization: Until the Finalize method is overrides, the Garbage
collection doesn't mark the object to claim its memory.Internally the Finalization Queue
keep each of the objects which are marked for deletion by GC and then the Finalize()
method gets called.
The Object must be inaccessible(no reference found) to put or keep in the Finalization
Queue.
Limitations: There are the limitation for Finalization:
a. Un-Deterministic - it is hard to find that when the Finalize() method will be called.
b. There is no guarantee that which object will be disposed first.
The C# compiler doesn't allow the overriding of Finalize() method an due to that we need
to write the Destructor of the class.
As the GC is non-Deterministic so we can implement the Dispose() method explicitly to
claim the unused memory by the Garbage collection.
For More details on GC, check the link:
GC Internal
8.
Can we inherit child class from 2 base classes? If yes then how? If not then why? What
is this scenario called as in OOPs? How to implement this kind of scenario where we need to
inherit the methods from more than one base class?
Ans. No, We can't inherit more than one base class in to child class. This leads to the
Multiple Inheritance where the child class can inherit more than one base class and the
Multiple Inheritance doesn't support in .Net.
So this scenario is called as Multiple inheritance(a type of inheritance in OOPs).
If you do so, you will see the error 'Interface name expected.' as below:
To implement these kind of scenarios, we need the help of Interfaces, Where we can
convert the second base class to Interface and then we can inherit one base class and
second Interface.
9.
How the Virtual methods are different from General methods? Can we have a method
in the base class and then in the child class can we write the same method? If not? Why?
What is the error we will get if we write the same method in the child class with the same
name as the parent class method name?
Ans. Yes, Virtual methods are different from the general method. The Virtual
methods
are the special type of methods which can be overrides in the
child class and then the
child class method will be the output or the default
result.
And when creating the child class object, it will take the child class method
preference as below:
as the
Now, if we have the same method in the child class as base class then it
will hide the
base class method by default and what ever is implemented in the child class will get
executed.
So here we can see that the error will not come but it will show the warning
'new' operator instead to hide the base class method. This scenario is called
as Shadowing in the OOPs.
to use the
10. Why do we need abstract class or abstract members? Cant we simply write the general
methods and fulfill our requirements? Can we get any advantage by implantation of abstract
members? As per the abstract class scenario, lets say we have an abstract method called
Show () in the abstract base class. Now if I am inheriting this base class to a child class, we
need to override this abstract method to the child class. And then we will call this method by
creating instance of child class.Now if we only have the method in the child class and then
create the instance and call the same method? Then why abstract class method? Is that
method doing anything here?
Ans. Abstract class or abstract members(methods, properties) are those which
are not
complete. So when the class contains at-least one abstract
member,the
class must be defined with abstract class.
We can also say that 'When the class does not provides the full
functionality, we can declare the class as abstract'. the abstract class
works
based on the child class memory. Due to that we cant create the
object of Abstract class, instead we can create the reference of the
abstract
class.
11. How abstract class and interfaces are different? Cant we create an abstract class by
having all the members as abstract members and wherever required inherit and implement
its members? Then why interface? I think interface is also doing the same thing? Then how
they are different?
12. Can we have abstract properties in Interface? If yes, then how to write the syntax for
the abstract property which is having the return type string?
13. Can we write static methods inside a non-static class? Is it possible to call a non-static
method inside the static method? If yes then how?
15. When we inherit a class which is having the private members. Are the private members
also gets inherited? If yes? Why cant we get them by the class object? If no then why?
16. What is the Difference between Coupling and Cohesion? If the components are more
cohesive the software is good? Or vice versa?
17. See the below code snippet and think about the output.
18. What is the Difference between HTTP enabled WCF Service and Web Services? I think if
we restrict the WCF service just for the HTTP communication, both WCF and Web Service
will have the same behavior. Then why still people prefer to have the WCF service rather
than the Web Service. What all the things which can be achieved through HTTP enabled
WCF service and cant be just from Web Service.
19. What is the Difference between SOAP enabled Services and ReST Services? Which one
is preferred and why?
class Mybase
{
int i, j;
float z;
}
class MyChild: Mybase
{
// no need to declare again the above variables
// as they will be automatically inherited.
}
As we need not to declare the variables again in the child class, so we have saved here 4 + 4 + 8 =
16 bytes of memory for the child class.
Main usage of inheritance is 'Re-usability'. No need to declare variables, methods again.. If u want,
then use them from base class. It reduce your code from complexity.
2. Why C# does not support Multiple Inheritance.
Ans. Multiple Inheritance is the situation in which when there are 2 base class and a single child class
is trying to inherit the members from both of them then there is the confusion that which base class
member should be inherited?
e.g.
class MyClass1
{
public void Show()
{
// something
}
}
class MyClass2
{
public void Show()
{
// something else
}
}
class MyChildClass: MyClass1, MyClass2
{
// not possible
}
Due to this, the architecture of .Net framework doesn't support such situation and will throw the
compile time error.
In C++, it is possible because there both the base class methods will have in different memory
locations and the methods will be accessed through the memory location. But in Java or .Net the
method is accessed through the class members objects.
It is quite difficult to implement multiple inheritance in C#. But we can do this through Interfaces. In
the above scenario, if we can change the second class as interface and then implement them as
below:
interface MyInterface
{
void Show();
}
class MyChildClass: MyClass1, MyInterface
{
public void Show()
{
// do something
}
public void MyInterface.Show()
{
// do something else
}
}
3. Why we used virtual keyword.
Ans. If we want to override the members of the base class, we can make them as virtual. The virtual
members have the capability to override them in the child class. If they are not overridden, the base
class implementation will be executed.
It is not the mandatory to override the virtual members of the class.
e.g.
class MybaseClass
{
public virtual void Show()
{
Console.WriteLine("hey..I am in base class");
}
}
class MyChild: MyBaseClass
{
public override void Show()
{
Create
return
as
Select
Create
return
as
Select
function
int[/Table]
FirstName+ LastName from Emp where EmpId = 101;
Function
Table
* from Emp;
7. If we have one Master Page , one aspx page and one ascx page then which one will called 1st while
page_load event and which one called 1st while page_Unload event.
Ans. If the content page contains the user controls then below will be the calling routeMaster Page Load event --> Content Page Load event --> User control page Load event
While unloading:
Content page Unload --> user control unload --> Master page unload event
8. What is Indexers and please give the description with example.
Ans. Indexer are the objects which doesn't need to be initialized and we can use them as it is for the
storing and retrieving the data in to pages.
Indexer is represented as []. So we can use them in Session, Application types of objects when
keeping the state management data.
e.g.
ViewState["UserName"] = txtUserName.Text;
Session["UserName"] = txtUserName.Text;
Application["UserName"] = txtUserName.Text;
To retrieve these data, we can simply type cast them as :
interface inf
{
void Print(); // abstract method
}
internal class MyClass: inf
{
public void Print()
{
// functionality to print to PDF document
}
}
internal class MyTest: inf
{
public void Print()
{
// functionality to print to tiff document
}
}
internal Class MyTest: inf
{
public void Print()
{
// functionality to print to .jpg format
}
}
We can see here we have separate classes and the implementation of the Print method is different
without making any changes in our interface.
So if we want to implement something global, we can use the Interface, for local or limited to class,
we can use the abstract class.
11.Why we use Method Overloading
Ans. To reduce the memory and the good readability, we use the Overloading. This is the concept
where we can have the same method name for similar work with different behavior.
Let's say we want to get the Database connection based on the provider name to connect with
different databases, we can use the overloaded methods like:
class Test
{
private string _name;
public string Name
{
set _name= value;
return _name;
}
}
Here the _name is the private which is not accessible so hiding the data. All the data will be binded to
the private variable as per the statement
class MyBaseClass
{
public abstract void Displaye();
}
class MyChildClass: MyBaseClass
{
public override void Display()
{
// do something
}
}
Here the essential things is the abstract method which must be overridden. If we add any number of
non-abstract method, the child class wont care. So Getting the essential information is Abstraction.
14. In which case we can use Abstract class in our project.
Ans. Abstract class is always used when we have the limited scope or the objects are of similar types.
e.g. Lets suppose we want to get the area of few objects. This is not the global where we need to do.
So we can create the abstract method to calculate the area and then according to shape, we can
override them. So here the scope is limited and will not be used throughout the application.
15 September 2013
This post is regarding the main OOPs concepts and what is there use and when its good to
use them.
Encapsulation
Abstraction
Overloading
Method Overriding
Constructor
Interface
Inheritance
Abstract class
These OOPs concepts you can use while implementing the functionality of your projects
in accordance with the requirements and situations.
Hope it will be useful to learn and in the implementation of the projects.
1) In which situation encapsulation is used in your project?
Encapsulation is hiding and binding of the data.
Accessing the public properties by using private variables is one of the good examples of
Encapsulation in all the projects.
e.g.
private string _name;
public String Name
{
get{return _name}
set{_name= value;}
}
Here you are not able to access the private variable _name but its value can be accessible
by the public property Name. So a kind of Encapsulation here. Namespace is also an
example of Encapsulation which is encapsulating the classes, methods, properties etc.
This is the runtime behaviour of an entity.
2) In which situation abstraction is used in your project?
Hiding the behaviour and showing the necessary things regards an entity can be called as
Abstraction. Like for a Car, showing the method like Clutch, Gear etc but hiding its internal
functions can be an example of Abstraction. This is the compile time behaviour of the
entities.
When there are the specific requirements and that can be flown to their child, then we can
use abstraction. it means whatever is essential, we implement to its child classes, else will
be inherited automatically.
e.g.
class A
{
public abstract void Add(int a, int b);
protected int x;
public string Name{get; set;};
}
Class B: A
{
public override void Add(int a, int b)
{
Console.WriteLine("Sum of two numbers is:" + int. Parse(a + b).toString());
}
}
Here the essential method Add is implemented to the child class B. rest all the members will
be inherited accordance to their protection levels.
Now according to our requirement, we can call the respective method with its arguments.
Here all the methods are doing sum of the numbers, but their behaviour are different- the
first method will give the sum of 2 number while the next one will give the sum of 3 number
and the final method will give the sum of 4 numbers.
4) In which situation method overriding is used in your project?
Class ExcelClass:Inf
{
public override void Print()
{
//Write code to print in excel
}
}
So you can go through the link to get the fair idea about its implementation:
http://www.dotnetspider.com/forum/ViewForum.aspx?ForumId=295763&
With lot of encouragement and support, I am posting the Part II of the questions and
answers for 3-6 years experienced people. These questions will be helpful for those who are
preparing for the interview or attending the interviews. This will be helpful for the last
minute preparation in quickest way.
If anyone has better answer, please reply to this post and I will include them.
C# / ASP.net/ .Net framework / other .Net related questions:
1. What is the difference between IEnumerable and IQueryable?
Ans. IEnumerable and IQueryable are used to query data from collections and database.
The IEnumerable is basically inherited from IQueryable, so its having all the features of the
IQueryable in addition to its having additional own features.
S.No
IEnumerable
IQueryable
1.
Exists in System.Collections
Namespace
2.
3.
4.
5.
6.
In the first example (By using the IEnumerable), the generated SQL is as below:
In the second example (By using the IQueryable), the generated SQL is as below:
We can see that by using the IQueryable, the performance will increase as it has the TOP
clause in the query.
2. What is cross site scripting? (XSS)
Ans. Cross-site scripting is the way to attacks and insert the vulnerabilities in Web page.
This attack is injected by client-side code. The script which is inject by the client can embed
itself in response data. The response data which send back to the malicious user. The
browser cant recognize the scripts as it is responded from the trusted source.
The cross-site scripting attacks also work on the HTTP and HTTPS.
There are 2 ways to prevent the cross site scripting attack:
Constrain input- Validate the input length, type, formatting, range etc
Encode output- Send the input data with encode e.g. Encode to HTML
To prevent the cross-site attack, we can set the below attributes in web.config file:
3. If I want to see my website similar in all the browsers then what I need to do for that?
Ans. If you want to see the website with the same look and feel then you need to write the
common css style which should be same for all browsers. Actually every browser will not
support every css elements so it is not possible to use the same css to support all the
browsers. You need to write the common css elements in the file and then apply it across
the website. Else you need to write the separate css file as per the browser.
4. If say 1 Lac users are using any particular website then what you will do to prevent
crashing of server? Which care you will take at the time of coding?
Ans. There are the ways like we can have multiple servers to handle the requests from the
users. In this, we can have the Web Gardening concept where we can have the multiple web
servers and then one main server to handle the number of requests and switch the requests
to other servers.
5. Why to use design patterns?
Ans. Design Pattern is the way to solve the recurring problems which occur during the
designing of the applications. As the requirements increases, the projects becomes complex
and due to the complexity, its difficult to maintain it.
With the help of design patterns, we can reduce the complexity and with the help of OOPs
paradigm, we can make our applications more efficient in all the ways.
According to the GoF (Gang of Four) company, the Design Patterns can be classified to 3
ways:Creational Design Pattern
Behavioral Design Pattern
Structural Design pattern
6. If I have a class C and two interfaces I1 and I2 and I have 'Add' method inside I1 and I2
then how to specify which one has to be called?
Ans. By using the explicit implement interface, we can implement the same method which is
defined in both the interfaces.
e.g.
7. Garbage collection uses which type of algorithm? How it will find which object is unused?
Ans. Mark-And-Release is the algorithm which the garbage collection uses to reclaim the
memory of the unreferenced objects which are no longer used.
The algorithm Mark-and-Release work in 2 steps:a. In the first steps, it marks all the accessible objects of the heap memory. This is called
as mark phase.
b. In the second step, scan the heap and reclaim all the unmarked objects by the Garbage
Collection algorithm. This step is called as sweep phase.
Below are the algorithm steps:
There is another way to return multiple values like using Tuple class (newly introduced in
.Net 4.0). The tuple class can return the object which can contain multiple values in it.
10. Is it possible to use .js files used under script will be in body and not in header? Why?
Ans. The .js file is used in header because first the .js file should be loaded to the
application and then rest of the content should be load.
11. What is Expression Tree in C#? How to use Express Trees to create Dynamic LinQ
queries?
Ans. Expression Tree is used to create Dynamic Linq query. Sometimes, when the specific
criterias' can't be defined at compile time, Expression tree is useful to generate the Linq
query at the runtime.
For E.g. In an application, the filter criteria is based on some user actions and is generated
dynamically. In this case, we can use the Expression Tree which will generate the criteria at
runtime and then we can use that criteria to filter the records from the IQueryable
collection.
System.Linq.Expressions is the namespace required to work with the Expression Tree. Here
we need to create the predicates using expressions, which will be used in the query.
1 February 2013
Model classes and generate the Views automatically through the Razor Engine.
The article is written with all the steps used to create the MVC3 application
with ASP.Net.
Hope this article will be useful for those who are looking forward to create
the applications in MVC3 (MVC with Razor) pattern.
Please go through the below link to get the details about creating the
MVC3 application in ASP.Net:
http://www.dotnetspider.com/resources/44324-MVC3-MODEL-VIEW-CONTROLLERA-NEW-MVC-FRAMEWORK-WITH-RAZOR-ENGINE-BY-MICROSOFT.aspx
5 January 2013
create the application with source code and creating the setup so that it can be run
on any machine just by copying and pasting of the setup file. The end user canenter
any number in the given textbox and click on the Convert to Spelling button. The
converted spellings will be displayed in the label. The Program is written in such a
way that it can handle the negative numbers also.The validation part is also
included in the program so that it will allow the user to accept only the numbers.
You can go through the below link for the detailed explanation of the application
including the setup
file:
Convert Numbers to Spellings- C# Windows Application
24 March 2012
Today I was thinking that many times, we are having doubt in writing the
connection string in the web.config file. Whether the connection string is correct or
not? Is it case sensitive? Is the User Id or userid is correct? Can we write pwd in
place of password or Password?
As we can't check it in compile time, so all the error we get at the run time and
then we try to replace the attributes of confile file by making the cap-locks to small
or vice versa.
So I though to write an article which will be useful for we all who are working in
Microsoft Technologies with the database.
As it will help to create all type of connection strings for their respective providers,
so we need not to worry that it is applicable only to SQL Server.
You can go through the below link for the details with the screenshots where i have
explained that how you can create and test your connection string before putting in
the configuration file.
http://www.dotnetspider.com/resources/43107-How-write-connection-stringplace.aspx
Hope it will help to all the members...
Cheers!!!
18 March 2012
// Date
By Version Description
// 03/18/2012 PA 1.0
Business Objects of CTS invoice
//
//
//==================================================
Then i created a snippet file and added to my visual studio IDE and now i don't
need to write all this code manually. There are few place holders which we need to
update and rest all code and other format will be done automatically.
Guys you can follow the below link where you can get the detailed description of
how we can create this Code snippet and how can we attach it with our Visual
Studio IDE and also how to create the shortcut's for it.
http://www.dotnetspider.com/resources/43654-Creating-Code-snippet-file-withshortcut.aspx.
Hope it will be helpful for most of the programmer who work in the maintenance
projects where they need to define such kind of header for the file..
Cheers!!!
29 November 2011
15 September 2011
3-Tier Architecture
Hai Friends,
This is the post which will define the small demo regarding the 3-tier architecture where i
have explained all the layers- Application layer, Business Logic Layer and Data Access Layer
and their interaction to perform the architecture of tried.
See the below link:
http://www.dotnetspider.com/forum/ViewForum.aspx?ForumId=295547&
Hai Friends,
As we know in ASP.Net, that there is no Built in control in which can display only the time
(We have datetime picker in windows application where we can choose the enum value as
time only to show the time).
So in this article we will take help of ASP.Net Dropdown list to show the time only to fulfill
our requirements.
See the below link:
http://www.dotnetspider.com/resources/43254-ASP-Net-Display-only-time-dropdownlist.aspx
Date-Time functions
Hai Friends,
This article will describe all the date time functions which are introduced in the
latest version of SQL Server (SQL Server 2008R2) including all the previous
functions.
This post is useful to all those who work in Sql server database domain.
See the link below:
http://www.dotnetspider.com/resources/43248-Date-Time-Functions-SQL-ServerR.aspx
9 September 2011
N-Tier Architecture
Hai Friends,
This is the post which is showing the n-tier architecture using the GridView implementation.
Here in this article I am showing how these layers interact with each other through code
implementation.
It will be useful for all those who are new learner of the architectures.
31 August 2011
This is article which is very useful in day-to-day coding implementation for those who are in
Microsoft .Net technology and using Visual studio for their development.
This article contains all the shortcuts which can be used while writing the code in .Net. It
includes all the shortcuts which can really increase the utilization of the resource and can
improve the performance.
Now you dont need to remember all the syntax which is required to write the loops,
properties, events, delegates, dependency properties etc.
So use this resource and improve the productivity.
The class which derives functionality from a base class is called a derived class. If Class Y
derives from Class X, then Class Y is a derived class.
What is inheritance?
Inheritance represents the relationship between two classes where one type derives
functionality from a second type and then extends it by adding new methods, properties,
events, fields and constants.
Implementation inheritance
Interface inheritance
In VB.NET you use the NotInheritable modifier to prevent programmers from using the class
as a base class. In C#, use the sealed keyword.
Define Overriding?
Overriding is a concept where a method in a derived class uses the same name, return type,
and arguments as a method in its base class. In other words, if the derived class contains
its own implementation of the method rather than using the method in the base class, the
process is called overriding.
What is an Interface?
An interface is a standard or contract that contains only the signatures of methods or
events. The implementation is done in the class that inherits from this interface. Interfaces
are primarily used to set a common standard or contract.
When should you use abstract class vs interface or What is the difference between
an abstract class and interface?
I would suggest you to read this. There is a good comparison given over here.
What is a component?
Component is a group of logically related classes and methods. A component is a class that
implements the IComponent interface or uses a class that implements IComponent
interface.
What is a control?
A control is a component that provides user-interface (UI) capabilities.
What is a stack? What is a heap? Give the differences between the two?
Stack is a place in the memory where value types are stored. Heap is a place in the memory
where the reference types are stored.
What is instrumentation?
It is the ability to monitor an application so that information about the applications
progress, performance and status can be captured and reported.
What is logging?
Logging is the process of persisting information about the status of an application.
What is a Form?
A form is a representation of any window displayed in your application. Form can be used to
create standard, borderless, floating, modal windows.
What is BLOB ?
A BLOB (binary large object) is a large item such as an image or an exe represented in
binary form.
What is ClickOnce?
ClickOnce is a new deployment technology that allows you to create and publish selfupdating applications that can be installed and run with minimal user interaction.
A user control cannot be added to the toolbox whereas a custom control can be.
A separate copy of a user control is required in every application that uses it whereas since
custom controls are stored in the GAC, only a single copy can be used by all applications.
What is Boxing/Unboxing?
Boxing is used to convert value types to object.
E.g. int x = 1;
object obj = x ;
Unboxing is used to convert the object back to the value type.
E.g. int y = (int)obj;
Boxing/unboxing is quiet an expensive operation.
What is globalization?
Globalization is the process of customizing applications that support multiple cultures and
regions.
What is localization?
Localization is the process of customizing applications that support a given culture and
regions.
What is MIME?
The definition of MIME or Multipurpose Internet Mail Extensions as stated in MSDN is MIME
is a standard that can be used to include content of various types in a single message. MIME
extends the Simple Mail Transfer Protocol (SMTP) format of mail messages to include
multiple content, both textual and non-textual. Parts of the message may be images, audio,
or text in different character sets. The MIME standard derives from RFCs such as 2821 and
2822. Quoted from here.