Friday, August 20, 2010

What is MVC in .net

Model View Controller architecture (or pattern) allows us to separate different parts of our applications into tiers to fulfill this need.

MVC Overview

Model View Controller architecture aims to separate an application into three parts:

Model: It is the business logic of an application. From an object oriented perspective it would consist of a set of classes that implement the critical functionality of an application from a business point of view.

View: It can consist of every type of interface given to the user. In ASP.NET the view is the set of web pages presented by a web application.

Controller: This part of the architecture is the most difficult to explain, hence the most difficult to implement in many platforms. The controller is the object that allows the manipulation of the view. Usually many applications implement Model-Controller tiers that contain the business logic along with the necessary code to manipulate a user interface. In an ASP.NET application the controller is implicitly represented by the code-behind or the server side code that generates the HTML presented to the user.

Implementing MVC in ASP.NET

A basic diagram that would help us understand perfectly the specific parts that implement the Model View Controller architecture in an ASP.NET application is presented below:

MVC implementation in ASP.NET

MVC Model Implementation

When implementing the business logic of an application it is a must to use a Class Library project in order to generate a .dll file that will encapsulate all the functionality. This is critical as we as professional developers would not like to jeopardize the source code of a software product by placing the actual .cs files as a reference in a web application.

This type of project can be easily created in Visual Studio 2005 under the Visual C# or Visual Basic tabs:

Creating a Class Library Project

As a tutorial example we will develop a simple calculator under a new namespace we will call "Math".

Once the project is created we will add a class called Calculator:

Adding Calculator class

As the code is very simple and a sample is provided in this tutorial we will not get into much detail as far as how it is developed. The only important thing we need to mention is the way errors have to be handled in this class. Take a look at the following code:

1. protected float Divide(float fNumber1, float fNumber2)
2. {
3. if (fNumber2 == 0)
4. {
5. throw new Exception( "Second number cannot be equal to zero.");
6. }

7. return (fNumber1 / fNumber2);
8. }

When implementing the Divide function we need to ensure that the user would not be able to set the "fNumber2" parameter (line 1) to zero as a division between zero does not exist. The validation statement in lines 3-6 takes care of this case but the important fact we need to notice is that this class will NEVER use specific methods to present errors like message boxes or writing into labels. Errors captured in the model part of the architecture ALWAYS have to be presented in the form of exceptions (line 5). This will allow us to use this object in several types of applications like ASP.NET applications, Windows applications, Web services, etc.

Once we have finished coding our Calculator class the project has to be built in order to get the .dll file we will use in our Web application.

MVC View-Controller Implementation

The View and the Controller objects will be implemented by using a common ASP.NET Website. Once we have created our project we need to add the reference to the .dll file we created before.

The option to do this can be found in the context menu when right-clicking the project in the solution explorer:

Adding the a reference

We can find the file in the path "\bin\Release" (or "\bin\Debug" depending on how you build your class library) inside our main folder containing the math class library project:

Adding Math.dll reference

Once we have referenced our library we will create a simple web page that will allow us to choose between the four basic arithmetic operations and type two different numbers to operate.

The web page will look like this:

Calculator Web page

In the code behind we need to reference the Math namespace in order to use our Calculator class. The following statement will do that:

using Math;

As the code for this application is also simple we will only explain the method called when the "Operate!" button is clicked:

1. protected void btnOperate_Click(object sender, EventArgs e)
2. {
3. if (pbValidateNumbers())
4. {
5. Calculator cOperator = new Calculator();
6. try
7. {
8. txtResult.Text = cOperator.Operate(float.Parse(txtNumber1.Text.Trim()),float.Parse(txtNumber2.Text.Trim()), Convert.ToInt16(rblOperations.SelectedValue)).ToString();
9. lbError.Text = "";
10. }
11. catch (Exception ex)

12. {
13. txtResult.Text = "";
14. lbError.Text = ex.Message;
15. }
16. }
17.}

In line 3 we call the bool function "pbValidateNumbers" that will return true if the numbers typed in both textboxes are valid. These types of validations have to be performed by the controller object as they allow the interface to work properly and have nothing to do with the business logic.
In line 5 we create an instance of our Calculator class so we can perform the arithmetic operation. We call the method "Operate" (line 8) and return the value in another textbox. An important thing to mention is that we have to use a try-catch statement (lines 6-15) to handle any exception that could be thrown by our method "Operate" as every error caught in our Calculator class is handled by throwing a "digested" exception that is readable to the user.

In the code above we can appreciate how well encapsulated the business logic is, hence it can be reused in several applications without having to code it again.

Advantages of using MVC in ASP.NET

  • There's no duplicated code.

  • The business logic is encapsulated; hence the controller code is transparent and safer.

  • The business logic can be used in several front ends like Web pages, Web services, Windows applications, services, etc.

  • Exception handling is well managed showing the user only digested error messages.

  • Testing every part of an application is easier as it can be done separately using automated methods.

  • Application changes are easier to apply as they are focused in one part of the architecture only.


For More Click Here>>>

Tuesday, August 17, 2010

SQL Server Questions

What are the OS services that the SQL Server installation adds?
MS SQL SERVER SERVICE, SQL AGENT SERVICE, DTC (Distribution transac co-ordinator)
What is an execution plan? When would you use it? How would you view the execution plan?
An execution plan is basically a road map that graphically or textually shows the data retrieval methods chosen by the SQL Server query optimizer for a stored procedure or ad-hoc query and is a very useful tool for a developer to understand the performance characteristics of a query or stored procedure since the plan is the one that SQL Server will place in its cache and use to execute the stored procedure or query. From within Query Analyzer is an option called “Show Execution Plan” (located on the Query drop-down menu). If this option is turned on it will display query execution plan in separate window when query is ran again.
Which virtual table does a trigger use?
Inserted and Deleted.
How to know which INDEX a table is using in SQL SERVER?
SELECT table_name,index_name FROM user_constraints
What is Cross Join in SQL Server?
A cross join that does not have a WHERE clause produces the Cartesian product of the tables involved in the join. The size of a Cartesian product result set is the number of rows in the first table multiplied by the number of rows in the second table. The common example is when company wants to combine each product with a pricing table to analyze each product at each price.
What is Self Join in SQL Server?
This is a particular case when one table joins to itself, with one or two aliases to avoid confusion. A self join can be of any type, as long as the joined tables are the same. A self join is rather unique in that it involves a relationship with only one table. The common example is when company have a hierarchal reporting structure whereby one member of staff reports to another.
What is the basic functions for master, msdb, model, tempdb databases?
The Master database holds information for all databases located on the SQL Server instance and is the glue that holds the engine together. Because SQL Server cannot start without a functioning master database, you must administer this database with care.

The msdb database stores information regarding database backups, SQL Agent information, DTS packages, SQL Server jobs, and some replication information such as for log shipping.

The tempdb holds temporary objects such as global and local temporary tables and stored procedures.

The model is essentially a template database used in the creation of any new user database created in the instance.
What is the REPLACE function in SQL?
REPLACE function replaces all occurrences of the second given string expression in the first string expression with a third expression.
Syntax REPLACE(string_expression, search_string, replacement_string), where every incidence of search_string found in the string_expression will be replaced with eplacement_string.
Note: Returns NULL if any of the arguments is NULL.
What is the difference between CAST and CONVERT in SQL?
Both CAST and CONVERT perform datatye conversions. In most respects, they both do the same thing, with the exception that CONVERT also does some date formatting conversions that CAST doesn't offer.
Note:- If CONVERT does everything that CAST does, and CONVERT also does date conversions, then why would ever use CAST? Simple answer for that - ANSI compliance. CAST is ASNI-compliant, and CONVERT isn't.
How to use EXISTS operator OR
How to use subqueries with the EXISTS operators?
A subquery can be used with the EXISTS operator as "EXISTS (subquery)", which returns true if the subquery returns one or more rows. Example -
Select custID, CompanyName from Customers cu where EXISTS (Select OrderID from Orders o where o.custID = cu.custID)
Note:- When you use EXISTS, you don't really return data - instead, you return a simple TRUE/FLASE regarding the existence of data that meets the criteria established in the query that the EXISTS statement is operating against.
How to SELECT TOP N records from mytable without using TOP keyword?
SET ROWCOUNT N
select * from mytable
SET ROWCOUNT 0

To turn this option off (so that all rows are returned), specify SET ROWCOUNT 0.
What is the advantage of SET NOCOUNT ON?
When we use SELECT and DML statement in SQL. SQL SERVER return a message which specify the number of rows affected by these statements. This information helps developer when they are debugging the code other-wise this is not useful. We can disable this by typing SET NOCOUNT ON. Setting SET NOCOUNT ON for stored procedure contains lots of statements, loops increases the performance and boost network traffic.
What are the types of constraints in SQL Server?
There are three types of constraints in SQL Server -

1. Domain Constraint - deals with one are more columns.
2. Entity Constraint - are all about individual rows.
2. Referential Integrity Constraint - are created when a value in one column must match the value in another column - in either the same table or in a different table.

What is the CASCADE action in SQL Server?
Bu default, you can not delete a record or update the referenced column in a referenced table if that record is referenced from the dependent table. If you want to be able to delete or update such records, then you need to set up a CASCADE action for the delete and/or update.
What is the primary key in SQL Server?
Primary keys are the unique identifiers for each row in a table. They must contains unique values (and hence can not be NULL). Because of their importance in the relational database, primary keys are the most fundamental of all keys and constraints.

A table can a maximum of one primary key. A primary key ensures uniqueness within the columns declared as being part of that primary key and that unique value serve as an identifier for each row.

For Read More Click Here>>

SQL Server Questions

What are the OS services that the SQL Server installation adds?
MS SQL SERVER SERVICE, SQL AGENT SERVICE, DTC (Distribution transac co-ordinator)
What is an execution plan? When would you use it? How would you view the execution plan?
An execution plan is basically a road map that graphically or textually shows the data retrieval methods chosen by the SQL Server query optimizer for a stored procedure or ad-hoc query and is a very useful tool for a developer to understand the performance characteristics of a query or stored procedure since the plan is the one that SQL Server will place in its cache and use to execute the stored procedure or query. From within Query Analyzer is an option called “Show Execution Plan” (located on the Query drop-down menu). If this option is turned on it will display query execution plan in separate window when query is ran again.
Which virtual table does a trigger use?
Inserted and Deleted.
How to know which INDEX a table is using in SQL SERVER?
SELECT table_name,index_name FROM user_constraints
What is Cross Join in SQL Server?
A cross join that does not have a WHERE clause produces the Cartesian product of the tables involved in the join. The size of a Cartesian product result set is the number of rows in the first table multiplied by the number of rows in the second table. The common example is when company wants to combine each product with a pricing table to analyze each product at each price.
What is Self Join in SQL Server?
This is a particular case when one table joins to itself, with one or two aliases to avoid confusion. A self join can be of any type, as long as the joined tables are the same. A self join is rather unique in that it involves a relationship with only one table. The common example is when company have a hierarchal reporting structure whereby one member of staff reports to another.
What is the basic functions for master, msdb, model, tempdb databases?
The Master database holds information for all databases located on the SQL Server instance and is the glue that holds the engine together. Because SQL Server cannot start without a functioning master database, you must administer this database with care.

The msdb database stores information regarding database backups, SQL Agent information, DTS packages, SQL Server jobs, and some replication information such as for log shipping.

The tempdb holds temporary objects such as global and local temporary tables and stored procedures.

The model is essentially a template database used in the creation of any new user database created in the instance.
What is the REPLACE function in SQL?
REPLACE function replaces all occurrences of the second given string expression in the first string expression with a third expression.
Syntax REPLACE(string_expression, search_string, replacement_string), where every incidence of search_string found in the string_expression will be replaced with eplacement_string.
Note: Returns NULL if any of the arguments is NULL.
What is the difference between CAST and CONVERT in SQL?
Both CAST and CONVERT perform datatye conversions. In most respects, they both do the same thing, with the exception that CONVERT also does some date formatting conversions that CAST doesn't offer.
Note:- If CONVERT does everything that CAST does, and CONVERT also does date conversions, then why would ever use CAST? Simple answer for that - ANSI compliance. CAST is ASNI-compliant, and CONVERT isn't.
How to use EXISTS operator OR
How to use subqueries with the EXISTS operators?
A subquery can be used with the EXISTS operator as "EXISTS (subquery)", which returns true if the subquery returns one or more rows. Example -
Select custID, CompanyName from Customers cu where EXISTS (Select OrderID from Orders o where o.custID = cu.custID)
Note:- When you use EXISTS, you don't really return data - instead, you return a simple TRUE/FLASE regarding the existence of data that meets the criteria established in the query that the EXISTS statement is operating against.
How to SELECT TOP N records from mytable without using TOP keyword?
SET ROWCOUNT N
select * from mytable
SET ROWCOUNT 0

To turn this option off (so that all rows are returned), specify SET ROWCOUNT 0.
What is the advantage of SET NOCOUNT ON?
When we use SELECT and DML statement in SQL. SQL SERVER return a message which specify the number of rows affected by these statements. This information helps developer when they are debugging the code other-wise this is not useful. We can disable this by typing SET NOCOUNT ON. Setting SET NOCOUNT ON for stored procedure contains lots of statements, loops increases the performance and boost network traffic.
What are the types of constraints in SQL Server?
There are three types of constraints in SQL Server -

1. Domain Constraint - deals with one are more columns.
2. Entity Constraint - are all about individual rows.
2. Referential Integrity Constraint - are created when a value in one column must match the value in another column - in either the same table or in a different table.

What is the CASCADE action in SQL Server?
Bu default, you can not delete a record or update the referenced column in a referenced table if that record is referenced from the dependent table. If you want to be able to delete or update such records, then you need to set up a CASCADE action for the delete and/or update.
What is the primary key in SQL Server?
Primary keys are the unique identifiers for each row in a table. They must contains unique values (and hence can not be NULL). Because of their importance in the relational database, primary keys are the most fundamental of all keys and constraints.

A table can a maximum of one primary key. A primary key ensures uniqueness within the columns declared as being part of that primary key and that unique value serve as an identifier for each row.

For Read More Click Here>>

ASP.Net Questions

Can I lock a configuration setting so that a Web.config file that appears lower in the hierarchy cannot override it?
Yes. By setting the location element Override attribute to false, you can lock a specific setting so that it does not inherit settings from below.
How are ASP.Net configuration files secured against unauthorized access?
ASP.Net configures IIS to deny access to any user that requests access to the Machine.config or Web.config files.
Where are the ASP.Net configuration files stored?
System-wide configuration settings and some ASP.NET schema settings are stored in a file named Machine.config, which is located in the %SystemRoot%\Microsoft .NET\Framework\versionNumber\CONFIG directory. This directory also contains other default settings for ASP.NET Web applications in a file that is referred to as the root Web.config file. ASP.NET configuration files for individual Web sites and applications, which are also named Web.config files, can be stored in any Web site root directory, application root directory, application subdirectory, or all of these.
How is ASP.Net configuration data formatted?
ASP.Net configuration data is encoded in XML and stored as plaintext files. You can access these files programmatically by using administration tools or by using a text editor
Do I have to use one programming language for all my Web pages?
No. Each page can be written in a different programming language if you want, even in the same application. If you are creating source code files and putting them in the \Code folder to be compiled at run time, all the code in must be in the same language. However, you can create subfolder in the \Code folder and use the subfolders to store components written in different programming languages.
Are ASP.NET pages XHTML compatible?
Yes. Individual controls render markup that is compatible with the XHTML 1.1 standard. It is up to you, however, to include the appropriate document type declaration and other XHTML document elements. ASP.NET does not insert elements for you to ensure XHTML compatibility.
Which page code model is preferable, single-file or code-behind?
Both models function the same and have the same performance. The choice of using single-file pages versus code-behind pages is one of personal preference and convenience.
Why is there no DataGrid control on the Toolbox?
The DataGrid control has been superseded by the GridView control, which can do everything the DataGrid control does and more. The GridView control features automatic data binding; auto-generation of buttons for selecting, editing, and deleting; automatic sorting; and automatic paging. There is full backward compatibility for the DataGrid control, and pages that use the DataGrid will continue to work as they did in version 1.0 of ASP.Net.
Can I still use the DataList and Repeater controls?
Absolutely. You can use them the way you always have. But note that the controls have been enhanced to be able to interact with data source controls and to use automatic data binding. For example, you can bind a DataList or Repeater control to a SqlDataSource control instead of writing ADO.Net code to access the database.
Can System.Net.Mail read email?
No. System.Net.Mail can only send email. To read email you either need a Mime parsing component such as aspNetMime or a POP3 component such as aspNetPOP3.
What is System.Web.Mail?
System.Web.Mail (SWM) is the .Net namespace used to send email in .Net Framework applications. SWM contains three classes:
MailMessage – used for creating and manipulating the mail message contents.
MailAttachments – used for creating a mail attachment to be added to the mail message.
SmtpMail – used for sending email to the relay mail server.
Note: More information on the System.Web.Mail Namespace can be found on MSDN here:http://msdn.microsoft.com/library/default.asp?url=/library/en-us/cpref/html/frlrfsystemwebmail.asp
What is System.Net.Mail?
System.Net.Mail is the namespace used to send email if you are using the .Net 2.0 (or higher) Framework.
How do you turn off cookies for one page in your site?
Use the Cookie.Discard Property which Gets or Sets the discard flag set by the server. When true, this property instructs the client application not to save the Cookie on the hard disk when a session ends.
How do you define the lease of the object?
The lifetime of the server object is determined by the lifetime lease. This is defined by implementing ILease interface when writing the class code.

OR

You can define the lease of the object by implementing the ILease interface at the code time.
What is ASP.Net?
ASP.Net is a server side scripting technology that enables scripts (embedded in web pages) to be executed by an Internet server.

1. ASP.Net is a Microsoft Technology
2. ASP stands for Active Server Pages
3.ASP.Net is a program that runs inside IIS
4.IIS (Internet Information Services) is Microsofts Internet server


Frequently Asked Questions

What is the GAC? What problem does it solve?
GAC stands for Global Access Cache where shareable/public assemblies (DLL)
stored to be used by multiple programs.It gives a shared platform for programs
to use single assembly and can store same assembly (of same name)with different
versions and can help to solve DLL HELL.
What is the difference between an .EXE and a .DLL?
Exe is executable and independent program/process to run which has its own
reserved memory space whereas DLL (Dynamic Link Library) is neither executable
and not even independent,it used by other DLL/program.
Are private class-level variables inherited?
Yes, but they are not accessible, so looking at it you can honestly say that they
are not inherited. But they are.
What is the difference between .dll extension and .exe extension?
The main difference between .dll and .exe is

.dll is the In process component where it take up the client's memory space to run.
So the communication between the application and component(dll) is very fast.

.EXE is the Out of process component.
It uses its own memory(not application memory) to run the component.
the communication between the application and component is slow when compared to .dll
Explain the 3 types of properties in C# (c-sharp)?
1. Read Only Properties: Properties without a set accessor are considered read-only.
2. Write Only Properties: Properties without a get accessor are considered write-only.
3. Read Write Properties: Properties with both a get and set accessor are considered read-write properties.
What are the advantages of properties in C# (c-sharp)?
1. Properties can validate data before allowing a change.
2. Properties can transparently expose data on a class where that data is actually retrieved from some
other source such as a database.
3. Properties can take an action when data is changed, such as raising an event or changing the value
of other fields.
Is it possible to use multiple inheritance in .Net?
Multiple Inheritance is an ability to inherit from more than one base class i.e. ability of a class
to have more than one super class, by inheriting from different sources and thus combine
separately-defined behaviours in a single class.
There are two types of multiple inheritance: multiple type/interface inheritance
and multiple implementation inheritance.
C# & VB.NET supports only multiple type/interface inheritance,
i.e. you can derive a class/interface from multiple interfaces.
There is no support for multiple implementation inheritance in .Net.
That means a class can only derived from one class.
What are JIT compilers? How many are available in CLR?
Just-In-Time compiler- it converts the language that you write in .Net
into machine language that a computer can understand.
There are two types of JITs one is memory optimized & other is
performance optimized.
How do you inherit from a class in C#?
Place a colon and then the name of the base class. Notice that it’s double colon in C++.
What is Strong Data Typing?
One very important aspect of IL is that it is based on exceptionally Strong Data Typing.
That means that all variables are clearly marked as being of a particular,
specific data type (There is no room in IL, for example Variant data type recognized by
Visual Basic and scripting languages). In particular, IL does not normally permit any
operations that result in ambiguous data types.
In how many ways you can compare two strings in C# using overloaded
methods and operators?
There are three ways:

1. Overloaded Compare() method
2. Overloaded Equal() method
3. Overloaded == operator.

By default the member of the interface are public and abstract. true or false?
True
What is type safety?
Type safety is about increasing the opportunities for the compiler to detect your coding errors.
If you use interfaces instead of delegates the compiler will have more opportunities to detect
your coding errors.
What is the difference between Convert.ToInt32(string)
and Int32.Parse(string)?
The two give identical results, except where the string is null.
Convert.ToInt32(null) returns zero,
whereas Int32.Parse(null) throws an ArgumentNullException.
Can you write a class without specifying namespace?
Which namespace does it belong to by default?
Yes, you can, and then the class belongs to global namespace which has no name.
For commercial products, naturally,you would not want global namespace.


====================================================================