?

Log in

QuestPond’s Best Practices in ASP.NET MVC

What are best practices that need to be followed in ASP.NET MVC?

Whether it is ASP.NET MVC, WCF or ASP.NET Web Forms when it comes to best practices its endless.

Let me share couple of practices I followed during ASP.NET MVC development.

    1. Keep Model as separate class library.

    2. Implement Repository pattern to isolate Business layer from Data Access Layer.

    3. Follow MVC architecture properly
                  a. Controller should contain only user interaction logic
                  b. View should contain only UI Design

    4. Use ViewModel and isolate View from presentation and Data Transformation logic.

    5. Always have base controller created. Means make sure your controllers are not directly inheriting from
         Controller class instead there should be an intermediate base controller
         Example:
         public class BaseController: Controller{….}
         public class CustomerController:BaseController{}

    6. For Generating input controls in view always use Html helper class methods.

   7. Always put appropriate Http verbs on action methods. Example: If it is a post action
        HttpPost and if it is Get put HttpGet action. By default it will be both and it should not be.

   8. Strictly follow the traditional best practice, avoid magic strings. Magic strings means
        writing something in Double quotes.

   9. If there is an action method which returning same result many times, apply caching into it.

10. Action methods with HttpGet attribute attached should not be performing an operation.
       Example: it should not delete, update any record. In short Get methods should perform
       anything which looks like Post.

11. Avoid putting hardcoded Action URIS.
       Example :
       Instead of
                        Html.Form(“~/MyController/MyAction”,FormMethod.Post”)
       Use
                        Html.Form(“ActionName”,”ControllerName”,ForMethod.Post)        

12. Always include bundling and Minification in your application.

13. All your view should be strongly typed

14. Use Model Binder for updating Model class object with posted data instead of manual update.

So the story of best practices doesn’t ends here we have more complete detailed article on best practices in .NET

For technical trainings on various topics like WCF (Windows Communication Foundation), MVC (Model View Controller), Business Intelligence, Design Patterns, WPF, TFS and Basic fundamentals feel free to contact SukeshMarla@Gmail.com or visit www.sukesh-marla.com

For more stuff like this, click here. Subscribe to article updates or follow at twitter @SukeshMarla
Copy right www.questpond.com

Multi Targeting in .NET

From VS 2008 they have added multi-targeting feature. You can use same visual studio with different versions of .NET framework. So in previous versions of Visual studio, every version was tied-up with its framework. For example VS 2003 only works with 1.1 framework whereas VS 2005 works with 2.0.

Project created in VS 2008 or after that onwards edition if you click on project properties you can now change the framework version to different types and check if your code is compatible with old version.

.net

Above is a brief explanation for Multi Targeting. Click to learn Multi Targeting topic in more detail.

Copy right www.questpond.com

What is Inversion of Control (IOC) and why it is required?

In order to understand Inversion of control let’s talk about a scenario.

Scenario: - We have Customer_Business_Logic class which is using FileLogger class internally for logging Exception inside file.

Understanding problems with this approach–


  • Now let’s say some time later our organization asks us to replace FileLogger with DBLogger
    so that error can be logged inside Database instead of File. In this case we
    will explicitly change the code written inside Business logic layer to achieve
    goal.
    Changes in the business logic may leads to error in business logic.

  • Testing of business logic in isolation is not possible because it is directly referencing FileLogger class.

  • FileLogger need to be available at compile time. Means we can start working on Business logic only after FileLogger is created.

Solution: - Move concrete type creating power to some external source. In short Business class won’t directly create FileLogger object rather someone else will does that and give it to business logic. This is called Inversion of control. Control of object creating is given to someone else.

How to implement Inversion of Control (IOC)?

IOC or Inversion control can be implemented using many ways like Factory Pattern, Dependency injection, Service Locator Pattern etc.

For technical trainings on various topics like WCF (Windows Communication Foundation), MVC (Model View Controller), Business Intelligence, Design Patterns, WPF, TFS and Basic fundamentals feel free to contact SukeshMarla@Gmail.com or visit www.sukesh-marla.com

For more stuff like this, click here. Subscribe to article updates or follow at twitter @SukeshMarla

See the following video on real time scenarios on Dependency Injection and Inversion of Control (DIIOC): -



Click and see here for more learning Inversion of Control(IOC) in .NET
Copy right www.questpond.com
How to write a FizzBuzz program in C#?

Ok first let me explain what is FizzBuzz, Fizz

"Write a c# program that prints numbers from 1 to 100. But for multiples of 3 print “Fizz” instead of the number and for the multiples of 5 print “Buzz”. For numbers which are multiples of both 3 and 5  print “FizzBuzz”.

for (int j = 1; j <= 100; j++)
 {
      string Output = "";

      if (j % 3 == 0) Output = "Fizz";// Divisible by 3 --> Fizz

      if (j % 5 == 0) Output += "Buzz"; // Divisible by 5 --> Buzz

      if (Output == "") Output = j.ToString(); // If none then --> number

      Console.WriteLine(Output); // Finally print the complete output
 }


Click and see here for more programming algorithm in .NET
Copy right www.questpond.com
How can we save all data from dataset?

Dataset has “AcceptChanges” method, which commits all the changes since last time “Acceptchanges” has been executed.

How can we check which rows have changed since dataset was loaded?

For tracking down changes, Dataset has two methods, which comes to rescue “Get Changes “and “Has Changes”.

Get Changes
Returns dataset, which are changed since it, was loaded, or since Accept changes was executed.

Has Changes
Or abandon all changes since the dataset was loaded use “Reject Changes This property indicates that has any changes been made since the dataset was loaded or accept changes method was executed.

How can we add/remove row is in “Data Table” object of “Dataset”?

“Data table” provides “NewRow” method to add new row to “Data Table”. “Data Table” has “DataRowCollection” object that has all rows in a “Data Table” object. Following are the methods provided by “DataRowCollection” object:-

Add
Adds a new row in Data Table

Remove
It removes a “Data Row” object from “Data Table”

Remove At
It removes a “Data Row” object from “Data Table” depending on index position of the “Data Table”.

How can we load multiple tables in a Dataset?

objCommand.CommandText = "Table1"
objDataAdapter.Fill(objDataSet, "Table1")
objCommand.CommandText = "Table2"
objDataAdapter.Fill(objDataSet, "Table2")


Above is a sample code, which shows how to load multiple “Data Table” objects in one “Dataset” object. Sample code shows two tables “Table1” and “Table2” in object ObjDataSet.


lstdata.DataSource = objDataSet.Tables("Table1").DefaultView

In order to refer “Table1” Data Table, use Tables collection of Datasets and the Default view object will give you the necessary output.

How can we add relation between tables in a Dataset?

Dim objRelation As DataRelation
objRelation=New
DataRelation("CustomerAddresses",objDataSet.Tables("Customer").Columns("Custid")
,objDataSet.Tables("Addresses").Columns("Custid_fk"))
objDataSet.Relations.Add(objRelation)


Relations can be added between “Data Table” objects using the “Data Relation” object. Above sample, code is trying to build a relationship between “Customer” and “Addresses” “Data table” using “Customer Addresses” “Data Relation” object.

See the following video on Dataset is a disconnect while datareader is connected: -



Click and see here for more step by step training in ADO.NET
Copy right www.questpond.com
What are Accessors and mutators in C#?

Look at the following example,

public class Customer
{
     publicint Age;
     .
     .
     .
 }


Now in the client code we will do something like this.

Customer c=new Customer();
c.Age=55;


But do you realize one thing even we can do something like this,

c.Age=563;
OR
c.Age=-65;


This is not a valid statement logically but it’s valid syntactically. Our program will just execute perfectly fine.

One of the pillar of Object oriented principle called Encapsulation let us protect our data by creating a wrapper around our data, logic etc. by means of functions, classes etc. In short Encapsulation also let us protects our data.

Usually we will do something like this.

public class Customer
{
       privateint Age; // data is private
       .
       .
       .
       publicintGetAge() // Data is exposed to outside world via public method
       {
               Return Age;
       }
       publicvoid SetAge(intpAge) // Updating of data is only possible via public method
       {
             If(pAge>0 &&pAge<100)
             {
                    Age=pAge;
             }
             else
             {
                   throw new Exception(“Invalid Age”);
             }
        }
 }


Now our data is protected.

Client code will look like this.

Customer c=new Customer();
c.SetAge(55);
Console.WriteLine(c.GetAge());

c.SetAge(965); // It will throw exception


In the above code snippet GetAge function which usually return the data is called Accessor method and SetAge function which updates data is called Mutator method.

Good news?

Now we are in C# things become much simpler. We can make use of properties instead of creating two functions.

public class Customer
{
       privateintpAge; .
       .
       .
       publicintAge()
       {
               get
               {
                    //Accessor
                    returnpAge;
               }
               set
               {
                   //Mutator
                   If(value>0 && value<100)
                   {
                           pAge=value;
                   }
                   else
                   {
                           throw new Exception(“Invalid Age”);
                   }
              }
        }
 }


Client code will look like this,

Customer c=new Customer();
c.Age=55;
Console.WriteLine(c.Age);

c.Age = 965; // It will throw exception


For technical trainings on various topics like WCF(Windows Communication Foundation), MVC, Business Intelligence, Design Patterns, WPF, TFS and Basic fundamentals feel free to contact SukeshMarla@Gmail.com or visit www.sukesh-marla.com

For more stuff like this, click here. Subscribe to article updates or follow at twitter @SukeshMarla

Click and see here for more .NET training.

Copy right www.questpond.com
How security works in WCF?

In WCF security is by default enabled in wsHttpBinding and NetHttpBinding.
Enabled means all three aspects of security (CIA) is automatically provided by bindings.


Let’s understand how.

1. C – Confidentiality – Data can be viewed by only intended recipient.
     It is done by means of encryption. Data (Messages) to be transferred will be encrypted.
     Even if someone get the message he will not be able to understand it.

2. I – Integrity – Data should not be tempered.
     It is done by means of signing. Data (messages) to be transferred will be signed. If
     someone modifies the data in between receiver easily come to know about that.

3. A – Authentication – User should validate his/her identity.
     By default all the binding except basic provides windows authentication. It means every
     service call will be authenticated automatically. While making call automatically clients
     windows credentials will be passed along which will be automatically get validated in
     service end. In case he is not a valid AD – Active directory user, his/her request won’t get
     processed.

For technical trainings on various topics like WCF(Windows Communication Foundation), MVC, Business Intelligence, Design Patterns, WPF, TFS and Basic fundamentals feel free to contact SukeshMarla@Gmail.com or visit www.sukesh-marla.com

For more stuff like this, click here. Subscribe to article updates or follow at twitter @SukeshMarla

See following video on WCF(Windows Communication Foundation) Concurency and throttling: -
Copy right www.questpond.com
How to invoke WCF service asynchronously?

As a service developer we just simply create the service, host it and expose the endpoints. Now whether those functions should be called synchronous or asynchronously is client’s lookout.

When the proxy class of our service get generated in the client side, async version of all our service methods also get generated automatically.
For example : If our service contain methods such as GetString, GetCustomer then our proxy class will contain four methods, GetString,GetCustomer,GetStringAsync,GetCustomerAsync.

There are two approaches normally a .net developer can follow,

  1. Event based approach

  2. Task based approach

1. Event based approach

Both the asynchronous methods will never return anything. Return type will be void. Instead on completion, some events will be raised.

Complete code:

privatevoid button1_Click(object sender, EventArgs e)
{
   FirstClient c = newFirstClient("WSHttpBinding_IFirst");
   c.GetStringCompleted += c_GetStringCompleted;
   c.GetStringAsync();
   .
   .
}
.
.
.
.
voidc_GetStringCompleted(object sender, GetStringCompletedEventArgs e)
{
label2.Text = e.Result;
}

2. Task based approach

In this approach C# 5.0 asycn await pattern will be used. Here asynchronous methods will return “Task” object instead of direct return value which can be awaited later

privateasyncvoid button1_Click(object sender, EventArgs e)
{
       FirstClient c = newFirstClient("WSHttpBinding_IFirst");
       Task<string> r=c.GetStringAsync();
   .
   .
   .
label2.Text += "\n" + await r;
}

For technical trainings on various topics like WCF, MVC, Business Intelligence, Design Patterns, WPF, TFS and Basic fundamentals feel free to contact SukeshMarla@Gmail.com or visit www.sukesh-marla.com

For more stuff like this, click here. Subscribe to article updates or follow at twitter @SukeshMarla

See following video on WCF concurrency and throttling: -



Click and see here for more step by step learning WCF(Windows Communication Foundation).
Copy right www.questpond.com
What is Namespace?

Namespace does two basic functionalities:-

  • It logically groupsclasses, for instance System.Web.UI logically groups UI related features like textboxes, list control etc.

  • In Object Oriented world, many times it is possible that programmers will use the same class name. Qualifying NameSpace with class names avoids this collision.

What is Difference between NameSpace and Assembly?

Following are the differences between namespace and assembly:

  • Assembly is physical grouping of logical units, Namespace, logically groupsclasses.

  • Namespace can span multiple assemblies while assembly is a physical unit like EXE , DLL etc.

What is ILDASM?

ILDASM is a simple tool which helps you to view IL code of a DLL or EXE. In order to view  IL code using ILDASM , go to visual studio command prompt and run “ILDASM.EXE”. Once ILDASM is running you view the IL code.

What is Manifest?

Assembly metadata is stored in Manifest. Manifest contains metadata which describes the following things :-

  • Version of assembly.

  • Security identity.

  • Scope of the assembly.

  • Resolve references to resources and classes.

The assembly manifest is stored in the DLL itself.

Where is the version information stored of an assembly?

Version information is stored in assembly inside the manifest.

Is versioning applicable to private assemblies?

Yes, versioning is applicable to private assemblies also.

See following video on to check assembly manifest for supported CLR version: -



Click and see here for more basics of .NET.
Copy right www.questpond.com
Tell me something about PerSession instance context mode in WCF?

When we set instance context mode as PerSession in WCF, for every channel object or proxy object client creates a dedicated service instance will be created.

What happens by that?

Our service become state full. Values of the variables updated during subsequent service call will be maintained.

Is it the default instance context mode?

Yes it is, considering binding supports session full endpoints. For example when your binding is netTcpEndpoint or wsHttpBindingPerInstance is default but when its basicHttpBinding default one will be percall because PerInstance is not supported over there?

Does WsHttpBinding supports sessions all the time?

No, it supports only if security is enabled. Best point is in case of WSHttpBinding security is be default turned on.

What if I don’t want security but wants session?

You have to enable reliable messaging at least. Reliable messaging is not enabled by default.

How the server differentiates between different sessions in case of per instance?

It will be with the help of sessionId. SessionId will be created for a client when he create the proxy or channel instance for first time.

Is it possible to get current session Id in service?

Yes, using OperationContext.Current.SessionId

For technical trainings on various topics like WCF, MVC, Business Intelligence, Design Patterns, WPF, TFS and Basic fundamentals feel free to contact SukeshMarla@Gmail.com or visit www.sukesh-marla.com

For more stuff like this, click here. Subscribe to article updates or follow at twitter @SukeshMarla

See following video on WCF concurrency and throttling: -



Click and see here for more advanced training in .NET on WCF(Windows Communication Foundation) .
Copy right www.questpond.com

Buy 600+ Real Time Interview Videos

Call +91-22-66752917 or mail us on questpond@questpond.com for more details on C#, .NET, ASP.NET, SQL Server interview question videos.

SQL Server interview question videos

Latest Month

August 2014
S M T W T F S
     12
3456789
10111213141516
17181920212223
24252627282930
31      

Tags

Powered by LiveJournal.com