asp.net vs asp.net mvc

. Sunday, July 10, 2011
0 comments

Difference between Asp.net and Asp.net mvc
HI guys, Today I will discuss some of the major differences between asp.net and asp.net mvc

1)in asp.net each control on page is associated with its code behind so all time you have to
  take care of its code behind with UI,whereas in asp.net MVC view is completely independent from
  its source code so view can be implemented separately this thing known as soc(separation of concerns).

2)whenever httprequest is made for asp.net it passes through its UI and then to code behind( ie .aspx then .aspx.cs)
  whereas in asp.net mvc each request first passes through controller and then its associated action's view loaded.

3)asp.net is good to develop applications which uses lots of asp.net controls(easily drag & drop) whereas asp.net MVC
  separates each implementation logic so its good for large apps in which each developer can work on model,view,controller
  separately.

4)asp.net is fast to develop but less in terms of testability and maintainability where as mvc requires time to develop
  its apps but very much better in testability and maintainability.

5)asp.net is good to develop small and middle level apps whereas asp.net MVC is made for large aps with higher level of implementation
  logic. 

State Management Technique-View State

. Monday, May 16, 2011
0 comments


Hi Guys today i am going to tell you about view state.

What is a View State in asp.net ?

View state is a mechanism to preserve data across postbacks.

where Viewstate resides ? 

view state resides within a page in hidden field with value equals to _VIEW_STATE,and its in encoded string.
whenever you request for a page the web server proceeds the request and send response with aspx page and during this process view state is view state decoded and sent to client's browser.

why to use a view state ? 

it want to preserve your information on certain postback,then you need to use viewstate.let me explain how?suppose you bind a drop down with items fetched from database.Now if you do this activity on each time when the page is post back means on each fresh http request then you will slow down your page speed because each time you will interact with db and retrieve all records and bind them.Instead of doing so,just bind the records for the first httprequest and then for all other request use view state of this instead.you can do this as follows:

if (!Page.IsPostBack)
{

//your db stuff here.

}

now if your page is post back again & again you don't need to perform db stuff.

enableviewstate ? in page directive if you set this attribute to true then viewstate will be enabled for whole page,for control specific you can change this to false or true.

What is the role of enableViewStateMac ? well MAC  tends to message authentication code,lets understand use of enableviewstateMac with an example,suppose you have filled a form and its asked for ccnumber,if someone has enabled viewstate on this field and you fill the form in a usual way. after filling up form and checkout but someone decoded this viewstate string and fill the form again,now he is having you creditcard number because he decoded the string,now other field are set to his own. now message authentication code compare both of the string and then if the difference found(as in our case) then all the viewstate is replaced with the older one and this attach will not affect the transaction.

Can we allow viewstate to be encrypted ? yes. setting validation to 3DES(Encryption algo.)  in machine key(inside system.web element in web.config) you can allow you view state to be encrypted.benefit of this is that this won't be decrypted without decryption key.

an example of machine key

<machine key validation="3DES|SHA1|MD5" decryption key=.... validation key=..... />
validation key is used to validate the view state and determines is view state has been tempered.

  • (SHA1 and MD5 are encoding algo. but SHA1 generates long encoded string so more preferable.)


Persistent Machine key : suppose you are in a web farm scenario where apps is maintained on more than one server.suppose there are two server A,B. now user are not aware of whether this response is coming from web server A or B. so when ViewState is decrypted on server A its served to user but when some part of apps served from server B the dynamically generated decryption key/validation key will not decrypt/validate the view state and hence ViewState_Error will be occur. to avoid this error use a persistent machine key.

Extension methods -asp.net mvc

. Wednesday, May 4, 2011
0 comments


Extension Methods in asp.net mvc

why to use extension method ?

well, in a simple statement I would say extension methods are used to get rid of writing html source code for views in asp.net mvc

let's take an example

suppose you are building a html table with several rows and cols in view
eg:

<table><tr><td>...</td></tr></table>
now you need to use table structure in various places in your application so without re writing this just create one extension method and put you structure over there
like this :

namespace ExtensionMethods.Common
{
public static class Helpers
    {

        public static string table(this HtmlHelper helper, string itemfirst, string itemsecond)
        {
            return String.Format("<table><tr><td>{0}</td></tr><tr><td>{1}</td></tr></table>", itemfirst, itemsecond);
        }
      
}
}
note:static class only can have static functions.
so now when you implement table structure into your view,you just need to add appropriate namespace for my case this was
"ExtensionMethods.Common".

as shown below :

















Now whenever you need this structure just imports the appropriate namespace and then call extension method by passing parameters within it.

and you will see items witin table structure in your application.


outputcaching with authorize filter

.
0 comments


Hi guys,after a long time I am back to blogging,today I am going to explain about how to use outputcaching with authorizefilter.

for outputcaching you can refer by previous blog.
(outputcaching is also a kind of filter)

Filters in asp.net mvc : 

Authorize filter
Raises before any action execute and authorize the current user.
Action filter
two method overridden from actionfilterattribute class
onactionexecuting : before action get executed.
onactionexecuted : after action get executed.
Result Filter
two method overriden from actionfilterattribute class
onresultexecuting : before result get executed,
eg: when you return view() from any action this method executed before this.
onresultexecuted : after result get executed.

Exception filter
whenever action throws any exception.
class for this filter is HandleErrorAttribute.

Note: controller inherited from controllerbase class in which it implements filter attribute so ultimately your controller can also implement these attributes.
Eg:

[Athorize]
your action..

Using outputcaching with Authorize filter :

Problem : 

if we use both of these filters in the worst case the unauthorize users even can view the cached content of authorize users,to avoid we need to use a custom class which

implements authorizefilterattribute class.

public class EnhancedAuthorizeAttribute : AuthorizeAttribute
{
public bool AlwaysAllowLocalRequests = false;
protected override bool AuthorizeCore(System.Web.HttpContextBase httpContext)
{
if (AlwaysAllowLocalRequests && httpContext.Request.IsLocal)
return true;
// Fall back on normal [Authorize] behavior
return base.AuthorizeCore(httpContext);
}
}

[EnhancedAuthorize(Roles = "admin", AlwaysAllowLocalRequests = true)]
Now, this will grant login only for admin roles and not to any other role.

but I achieve this wtih athorize attribute

eg:
 [Authorize(Roles="admin")]
 [OutputCache(Duration=30,VaryByParam="None")]

note : order is a property of filter base class which defines the order of filter execution but by default filter are put on stack for execution which means the last one will be executed first.

using delegates and events in c#

. Thursday, April 7, 2011
3 comments


What is a delegate ? 
Delegate is a function pointer means it can point to those function which are having identical signature with delegate.
you can also call delegate as a interface of methods as this acts same as interface in c# but that implemented for classes and this is implemented for methods.

Process to create a delegate:
1)declaration
2)instantiation
3)invocation

Example :

Consider the following code:

  delegate string StrDelegate();//declaration
   public class Custom
    {
        public string strmethod()
        {
            return "This is string ";
        }
    }
    class Program
        {
        static void Main(string[] args)
        {
            Custom objcustom = new Custom();
            StrDelegate strdelegate = new  StrDelegate(objcustom.strmethod); //instantiation
            string message=strdelegate(); //invocation
            Console.Write(message);
            Console.Read();
        }
       }
so what happened in this above code,well first we define a delegate with its signature,in this case its return type is string and no arguments. then we create instance of delegate which is strdelegate now this can point to (reference to) all those function which having same signature as in our case function is strmethod() and at the last we invoke this and receive this in message.

Advantages:
The main advantage of delegate is multi cast.
you can call number of function with matching singature with single instance of delegate but point to remember is that its return type should be void because there are many

methods and if we pass return type then each one will return some value and finally delegate instance will hold the last one method's value.

example

in our previous example i added the following :

        public void strmethodmulticast()
        {
           console.write("This is string multicast");

        }

in set of methods and

StrDelegate strdelegate = null;
            strdelegate += new StrDelegate(objcustom.strmethod);
            strdelegate += new StrDelegate(objcustom.strmethodmulticast);

this in Static Void Main

also changed the return type of delegate to void.


What are events 
event is a way for a class to provide notifications to clients of that class when some interesting thing happens to an object of that class.
you can also consider events as variable type of delegates ? why lets look at event declaration.

public event StrDelegate customevent;

Just need to put event keyword before delegate name and your event created.
events are handled by delegates which are called event handlers.

consider the following code:

 btnsubmit.Click+=new EventHandler(custommethod);

I created a button on form and its object 'btnsubmit' now avaiable on code behind as you know, now when click event raises in above it is being handled by EventHandler
delegate and method  'custommethod'  do the desire operation which is having the same signature as in EventHandler delegate (object sender//to raise event,Eventargs e// to receive other information)

public void custommethod(object sender, EventArgs e)
    {
        txtsubmit.Text = "This is called on button click";

    }

and hence on click event of button the above method is called which changes the text of txtsubmit.

dropdown not working in ie7 and ie8

. Tuesday, April 5, 2011
0 comments

If you have created dropdownlist and either its not visible or not visible onchange event of other dropdown
Then one of possible solution this is as follows:

Possible Cause :
if you use firebug and see html for dropdown you will notice that 'option' is not well formed in html for this dropdown.

One of Solution to Resolve this Problem:

If you have used something like this

for (i = 1; i <= day_length; i++)
{

doc.innerHTML += "<OPTION value=\"" + i + "\">" + i + "</OPTION>";
}
and adding items to dropdown (doc) dynamically with some values(eg: i in this case) replace this with


addOption(doc, i, i);

function addOption(selectbox,text,value )
{
var optn = document.createElement("OPTION");
optn.text = text;
optn.value = value;
selectbox.options.add(optn);
}

this add option adds all of those values which you want (eg: i ) and this will event work in ie 7 ,ie8.

It worked for me hope same would for you..
Cheers...

Error 3205 Too Many Backup Devices Specified.

. Thursday, March 31, 2011
0 comments

Cause:
This error occured because of you sqlserver is not compatiable with current backup version



Solution:

1)first run SELECT @@version and find the version

2)exit from current sqlserver and connect with other server for which your backup file(.bak) is compatiable.