Q. What is Overriding?
Overriding is a concept where a method in a derived class
uses the same name with the same return type and also the same 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.
Example:
1.
class BC
{
public void
Display()
{
System.Console.WriteLine("BC::Display");
}
}
class DC : BC
{
new public void
Display()
{
System.Console.WriteLine("DC::Display");
}
}
class TC : BC
{
new public void
Display()
{
System.Console.WriteLine("DC::Display");
}
}
class Demo
{
public static void
Main()
{
BC b;
b = new BC();
b.Display();
b = new DC();
b.Display();
b = new TC();
b.Display();
}
}
Output
BC::Display
BC::Display
BC::Display
2.
Solve Problem using Virtual and Override keyword.
class BC
{
public virtual
void Display()
{
System.Console.WriteLine("BC::Display");
}
}
class DC : BC
{
public override
void Display()
{
System.Console.WriteLine("DC::Display");
}
}
class Demo
{
public static
void Main()
{
BC b;
b = new BC();
b.Display();
b = new DC();
b.Display();
}
}
Output
BC::Display
DC::Display
2.What are events and
delegates?
Events are user actions
such as key press, clicks, mouse movements, etc., or some occurrence such as
system generated notifications. Applications need to respond to events when
they occur. For example, interrupts. Events are used for inter-process
communication.
Example:
using System;
namespace SimpleEvent
{
using System;
public class EventTest
{
private int value;
public delegate void NumManipulationHandler();
public event NumManipulationHandler ChangeNum;
protected virtual void OnNumChanged()
{
if (ChangeNum != null)
{
ChangeNum();
}
else
{
Console.WriteLine("Event fired!");
}
}
public EventTest(int n )
{
SetValue(n);
}
public void SetValue(int n)
{
if (value != n)
{
value = n;
OnNumChanged();
}
}
}
public class MainClass
{
public static void Main()
{
EventTest e = new EventTest(5);
e.SetValue(7);
e.SetValue(11);
Console.ReadKey();
}
}
}
When the above code is compiled and executed, it produces the
following result:
Event Fired!
Event Fired!
Event Fired!
Delegate :
A delegate in C# is similar to a function pointer in C or
C++. Using a delegate allows the programmer to encapsulate a reference to a
method inside a delegate object. The delegate object can then be passed to code
which can call the referenced method, without having to know at compile time
which method will be invoked.
Example:
using
System;
namespace Akadia.BasicDelegate
{
// Declaration
public delegate void SimpleDelegate();
class TestDelegate
{
public static void MyFunc()
{
Console.WriteLine("I was called by delegate ...");
}
public static void Main()
{
// Instantiation
SimpleDelegate simpleDelegate = new SimpleDelegate(MyFunc);
// Invocation
simpleDelegate();
}
}
}
namespace Akadia.BasicDelegate
{
// Declaration
public delegate void SimpleDelegate();
class TestDelegate
{
public static void MyFunc()
{
Console.WriteLine("I was called by delegate ...");
}
public static void Main()
{
// Instantiation
SimpleDelegate simpleDelegate = new SimpleDelegate(MyFunc);
// Invocation
simpleDelegate();
}
}
}
Compile
an test:
# csc SimpleDelegate1.cs
# SimpleDelegate1.exe
I was called by delegate .
# SimpleDelegate1.exe
I was called by delegate .
3.Can multiple catch blocks
be executed?
No, Multiple catch blocks can't be executed. Once the
proper catch code executed, the control is transferred to the finally block and
then the code that follows the finally block gets executed.
4. Difference between
public, static and void?
All these are access modifiers in C#. Public declared
variables or methods are accessible anywhere in the application. Static
declared variables or methods are globally accessible without creating an
instance of the class. The compiler stores the address of the method as the
entry point and uses this information to begin execution before any objects are
created. And Void is a type modifier that states that the method or variable
does not return any value.
5. Difference
between ref & out parameters?
An argument passed as ref must be initialized before
passing to the method whereas out parameter needs not to be initialized before
passing to a method
6. Can “this” be used
within a static method?
We can’t use ‘This’ in a static method because we can only
use static variables/methods in a static method.
7. What is
difference between constants and read-only?
Constant variables are declared and initialized at compile
time. The value can’t be changed after wards. Read-only variables will be
initialized only from the Static constructor of the class. Read only is used
only when we want to assign the value at run time.
8. What is an interface
class?
Interface is an abstract class which has only public
abstract methods and the methods only have the declaration and not the
definition. These abstract methods must be implemented in the inherited
classes.
9. What are value types and
reference types?
Value types are stored in the Stack whereas reference
types stored on heap. Following are some of the Value types:
int, enum, byte, decimal, double, float, long
Reference Types:
string, class, interface, object.
10. Different categories of
inheritance?
There are 4 types of Inheritance in Object Oriented
Programming and they are as follows
(i)Single inheritance : Have one base
class and one derived class.
(ii)Hierarchical
inheritance : Have one base class and multiple derived classes of the
same base class.
(iii)Multilevel inheritance : Have a class
derived from a derived class.
(iv)Multiple inheritance : Have several
base classes and a derived class.
11. Difference between
constants, readonly and, static ?
(i) Constants: Value can’t be changed.
(ii) Read-only: Value will be initialized only once from
the constructor of the class.
(iii)Static: Value can be initialized once.
12. What is multi cast
delegates?
Each delegate object holds reference to a single method.
However, it is possible for a delegate object to hold references of and invoke
multiple methods. Such delegate objects are called multicast delegates or
combinable delegates.
public partial class Form1 : Form
{
public delegate void MyDelegate();
private void Method1()
{
MessageBox.Show(“Method1 Invoked”);
}
//lock code start
private void Method2()
{
MessageBox.Show(“Method2 Invoked”);
}
//lock code End
private void button1_Click(object sender, EventArgs e)
{
//2.create delegate referance
MyDelegate myptr = null;
//3.point the referance to Add function
myptr += this.Method1;
////lock code start
myptr += this.Method2;
////lock code end
//4.invoke the method through delegate object
myptr.Invoke();
}
public Form1()
{
InitializeComponent();
}
}
13. What is data
encapsulation?
Encapsulation is hiding the code and data into a single
unit to protect the data from outer world. Data encapsulation, also referred to as data hiding, is the
mechanism whereby the implementation details of a class are kept hidden from
the user. The user can only perform a restricted set of operations on the
hidden members of the class by executing special functions called methods.
Abstraction:
Abstraction refers to the
act of representing essential features without including the background details
or explanations.
14. Is it possible to override
private virtual methods?
No. Private methods are not accessible outside the class.
15. Can you store
multiple data types in System.Array?
No.
16. What’s the
difference between the System.Array.CopyTo() and System.Array.Clone()?
The System.Array.CopyTo() a deep copy of the array, the System.Array.Clone() is shallow.
Q. How many ways of session
variable in asp.net ?
Basically two ways of seesion variable in asp.net like as :
1. InProc Session Variable
2. OutProc Session Variable
InProc Session Variable :
InProc Session
Variable are store Inside the IIS
memory itself(locally).
OutProc Session Variable :
OutProc Session
Variable either use SQL server or either use State Server.
Q. WCF ?
WCF (Windows Communication Framework) is Microsoft framework to
make inter-process communication easier. Through various means, it lets
you do the communication like MS messaging Queuing, Services, Remoting and so
on. It also allows you talk with other.NET apps, or non-Microsoft
technologies (like J2EE).
Explain the components
used in WCF?
Below are the
essential components of WCF –
- Service class
- End point
- Hosting Environment
Explain
“Address” property of endpoint in WCF?
“Address”
property is the part of endpoint defined in service level and this property is
used to determine the location if the service, where it is located.
Explain “Binding” property of endpoint in WCF?
“Binding”
property is the part of endpoint defined in service level and this property is
used to decide out the type protocols, encoding's and transport. These all
factors has been decided by both the parties who want to communicate each
other.
8) Explain
“Contract” property of endpoint in WCF?
It
is just an interface between client and server where client and server
communicate each other. Contracts are used to identify operations available.
9) Explain
the types of contracts available in WCF?
Below
are the list types of contracts available in WCF
- Data Contracts
- Service Contracts
- Message Contracts
- Fault Contracts
10) Explain
“Service Contracts” in WCF?
Service
Contracts attribute given at the service level for WCF service and it will give
you the list of operations that can be performed from that service. Service
Contracts can be defined like –
[ServiceContract]
11) Mention
the list of bindings supported by WCF?
Below
are the list of schemas supported by WCF –
- TCP
- HTTP
- MSMQ
- IPC
- Peer Network
12) Explain
the ways to host the WCF Service?
Below
are ways to host WCF Service –
- IIS
- Self Hosting
- WAS
Q. Define Aggregation,
Association and Composition.
Aggregation: - Aggregation means
both of objects are not same.
Example : Department and
teacher. A single teacher cannot belong to multiple departments, but if we
delete the department the teacher object will not be destroyed. We can think of
it as a “has-a” relationship.
Composition: - Composition means
both of objects are same.
Example: House can contain multiple rooms but there is no
independent life of a room and any room cannot belong to two different houses.
If we delete the house, the room will automatically be deleted.
Association
Association
is a relationship where all object have their own lifecycle and there is no
owner. Let’s take an example of Teacher
and Student. Multiple students can associate with a single teacher and a single
student can associate with multiple teachers, but there is no ownership between
the objects and both have their own lifecycle. Both can create and delete independently.
Q. Define Abstract Class
and Interface.
Abstract Class: We can not create an object of
an abstract class and can call the method of abstract class with the help of
class name only.
namespace
ConsoleApplication4
{
abstract class M1
{
public int add(int a, int b)
{
return (a + b);
}
}
class M2 :M1
{
public int mul(int a, int b)
{
return a * b;
}
}
class test
{
static void Main(string[] args)
{
M2 ob = new M2();
int result = ob.add(10, 20);
Console.WriteLine("the result is {0}", result);
Console.ReadLine();
}
}
}
{
abstract class M1
{
public int add(int a, int b)
{
return (a + b);
}
}
class M2 :M1
{
public int mul(int a, int b)
{
return a * b;
}
}
class test
{
static void Main(string[] args)
{
M2 ob = new M2();
int result = ob.add(10, 20);
Console.WriteLine("the result is {0}", result);
Console.ReadLine();
}
}
}
Interface:- An
interface is not a class. It is an entity that is defined by the word
Interface. An interface has no implementation; it only has the signature or in
other words, just the definition of the methods without the body. C# doesn't
support multiple inheritance, interfaces are used to implement multiple
inheritance.
namespace
ConsoleApplication3
{
interface MyInterface
{
void myMethod();
}
class MyClass : MyInterface
{
public static void Main()
{
MyClass cls = new MyClass();
cls.myMethod();
}
public void myMethod()
{
Console.WriteLine("welcome to MCN IT SOLUTION");
Console.ReadLine();
}
}
}
{
interface MyInterface
{
void myMethod();
}
class MyClass : MyInterface
{
public static void Main()
{
MyClass cls = new MyClass();
cls.myMethod();
}
public void myMethod()
{
Console.WriteLine("welcome to MCN IT SOLUTION");
Console.ReadLine();
}
}
}
Difference between Store
procedure and function .
Sr.No.
|
User Defined Function
|
Stored Procedure
|
1
|
Function must return a value.
|
Stored Procedure may or not return values.
|
2
|
Will allow only Select statements, it will not allow us to use
DML statements.
|
Can have select statements as well as DML statements such as
insert, update, delete and so on
|
3
|
It will allow only input parameters, doesn’t support
output parameters.
|
It can have both input and output parameters.
|
4
|
It will not allow us to use try-catch blocks.
|
For exception handling we can use try catch blocks.
|
5
|
Transactions are not allowed within functions.
|
Can use transactions within Stored Procedures.
|
6
|
We can use only table variables, it will not allow using
temporary tables.
|
Can use both table variables as well as temporary table in it.
|
7
|
Stored Procedures can’t be called from a function.
|
Stored Procedures can call functions.
|
8
|
Functions can be called from a select statement.
|
Procedures can’t be called from Select/Where/Having and so on
statements. Execute/Exec statement can be used to call/execute Stored
Procedure.
|
9
|
A UDF can be used in join clause as a result set.
|
Procedures can’t be used in Join clause
|
ASP.NET MVC
ASP.NET supports
three major development models: Web Pages, Web Forms and MVC (Model View
Controller). The ASP.NET MVC framework is a lightweight, highly testable
presentation framework that is integrated with existing ASP.NET features, such
as master pages, authentication, etc. Within .NET, this framework is defined in
the System.Web.Mvc assembly. The latest version of the MVC Framework is 5.0. We
use Visual Studio to create ASP.NET MVC applications which can be added as
template in Visual Studio.
ASP.NET MVC Features
The ASP.NET MVC
provides the following features:
- Ideal for developing complex but light weight applications
- It provides an extensible and pluggable framework which can be easily replaced and customized. For example, if you do not wish to use the in-built Razor or ASPX View Engine, then you can use any other third-party view engines or even customize the existing ones.
- Utilizes the component-based design of the application by logically dividing it into Model, View and Controller components. This enables the developers to manage the complexity of large-scale projects and work on individual components.
- The MVC structure enhances the test-driven development and testability of the application since all the components can be designed interface-based and tested using mock objects. Hence the ASP.NET MVC Framework is ideal for projects with large team of web developers.
- Supports all the existing vast ASP.NET functionalities such as Authorization and Authentication, Master Pages, Data Binding, User Controls, Memberships, ASP.NET Routing, etc.
- It does not use the concept of View State (which is present in ASP.NET). This helps in building applications which are light-weight and gives full control to the developers.
View Engine
As seen in the
initial introductory chapters, Views are the components involved with
application's User Interface. These Views are generally bind from the model
data and have extensions like html, aspx, cshtml, vbhtml, etc. In our First MVC
Application, we had used Views with Controller to display data to the final
user. For rendering these static and dynamic content to the browser, MVC Framework
utilizes View Engines. View Engines are basically markup syntax implementation
which are responsible for rendering the final HTML to the browser.
The MVC Framework
comes with two built-in view engines:
1. Razor Engine: Razor is a markup
syntax that enables the server side C# or VB code into web pages. This server
side code can be used to create dynamic content when the web page is being
loaded. Razor is an advanced engine as compared to ASPX engine and was launched
in the later versions of MVC.
Razor:
@Html.ActionLink("Create
New", "UserAdd")
2. ASPX Engine: ASPX or the Web
Forms engine is the default view engine that is included in the MVC Framework
since the beginning. Writing code with this engine is very similar to writing
code in ASP.NET Web Forms.
Following are small
code snippets comparing both Razor and ASPX engine.
ASPX:
<% Html.ActionLink("SignUp",
"SignUp") %>
Out of these two,
Razor is more advanced View Engine as it comes with compact syntax, test driven
development approaches, and better security features. We will use Razor engine
in all our examples since it is the most dominantly used View engine.
These View Engines
can be coded and implemented in following two types:
- Strongly typed
- Dynamic typed
These approaches are
similar to early-binding and late-binding respectively in which the models will
be bind to the View strongly or dynamically.
Introduction to Routing
ASP.NET MVC Routing enables use of URLs that are descriptive of the
user actions and are more easily understood by the users. At the same time,
Routing can be used to hide data which is not intended to be shown to the final
user. For example, in an application that does not uses routing, user would be
shown the URL as http://myapplication/Users.aspx?id=1 which would correspond to
the file Users.aspx inside myapplication path and sending id as 1 Generally we
would not like to show such file names to our final user.
To handle MVC URLs, the ASP.NET platform uses the routing system
which lets you create any pattern of URLs you desire, and express them in a
clear and concise manner. Each route in MVC contains a specific URL pattern.
This URL pattern is compared to the incoming request URL and if the URL matches
this pattern, it is used by the routing engine to further process the request.
MVC Routing URL Format
To understand the MVC routing, consider the following address URL:
http://servername/Products/Phones
In the above URL, Products is the first segment and Phone is the
second segment which can be expressed in the following format:
{controller}/{action}
The MVC framework automatically considers the first segment as the
Controller name and the second segment as one of the actions inside that
Controller. Note that if the name of your Controller is ProductsController, you
would only mention Prodcuts in the routing URL. The MVC framework automatically
understands the
Controller suffix.
public
class RouteConfig
{
public static void RegisterRoutes(RouteCollection
routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new {
controller = "Home", action = "Index", id = UrlParameter.Optional
}
);
}
}
Action Filters
In ASP.NET MVC, controllers define action methods and these action
methods generally have a one-to-one relationship with UI controls such as
clicking a button or a link, etc. For example in one of our previous examples,
the UserController class contained methods UserAdd, UserDelete, etc.
But many times we would like to perform some action before or after
a particular operation. For achieving this functionality, ASP.NET MVC provides
feature to add pre and post action behaviors on controller's action methods.
Types of Filters
ASP.NET MVC framework supports following action filters:
- Action Filters: Action filters are used to implement logic that gets executed before and after a controller action executes. We will look at Action Filters in detail in this chapter.
- Authorization Filters: Authorization filters are used to implement authentication and authorization for controller actions.
- Result Filters: Result filters contain logic that is executed before and after a view result is executed. For example, you might want to modify a view result right before the view is rendered to the browser.
- Exception Filters: Exception filters are the last type of filter to run. You can use an exception filter to handle errors raised by either your controller actions or controller action results. You also can use exception filters to log errors.
Action filters are one of most commonly used filters to perform
additional data processing, or manipulating the return values or cancelling the
execution of action or modifying the view structure at run time.
Action Filters
Action Filters are additional attributes that can be applied to
either a controller section or the entire controller to modify the way in which
action is executed. These attributes are special .NET classes derived from
System.Attribute which can be attached to classes, methods, properties and
fields.
ASP.NET MVC provides following action filters:
- Output Cache: This action filter caches the output of a controller action for a specified amount of time.
- Handle Error: This action filter handles errors raised when a controller action executes.
- Authorize: This action filter enables you to restrict access to a particular user or role.
Now we will see the code example to apply these filters on an
example controller ActionFilterDemoController. (ActionFilterDemoController is
just used as an example. You can use these filters on any of your controllers.)
Output Cache
E.g.: Specifies the return value to be cached for 10 seconds.
public class ActionFilterDemoController : Controller
{
[HttpGet]
OutputCache(Duration = 10)]
public string Index()
{
return DateTime.Now.ToString("T");
}
}
Handle Error
E.g.: Redirect application to a custom error page when an error is
triggered by controller
[HandleError]
public class ActionFilterDemoController : Controller
{
public ActionResult Index()
{
throw new NullReferenceException();
}
public ActionResult About()
{
return View();
}
}
With the above code, if any error happens during the action
execution, it will find a view named Error in the Views folder and render that
page to the user.
Authorize
E.g.: Allowing only authorized users to log in the application
public class ActionFilterDemoController: Controller
{
[Authorize]
public ActionResult Index()
{
ViewBag.Message = "This can be viewed only by authenticated users only";
return View();
}
[Authorize(Roles="admin")]
public ActionResult AdminIndex()
{
ViewBag.Message = "This can be viewed only by users in Admin role only";
return View();
}
}
Comments
Post a Comment