June 2009


NET Webforms

In general, choosing between ASP.NET MVC and ASP.NET can be based on the following ive criteria:

  • Are you considering test-driven development (TDD)?
  • TDD enables you to write tests for an application irst, after which the application logic is developed. An ASP.NET Webforms application uses only one class to display output and handle user input. Automated testing of this class is complex as you are required to load the full ASP.NET stack into a separate process (for example, in IIS). The MVC framework allows the testing of each component separately, without requiring the full ASP.NET stack. For example, you can test your model separately from your controller without requiring a view. If you are considering TDD, the ASP.NET MVC framework will be the better choice.

  • Is             there     a              need     for          fine        control  over       HTML    markup?
  • ASP.NET Webforms automatically inserts hidden HTML markup, IDs, JavaScript, and so on, into your page’s HTML output because of its event-driven architecture and its use of ViewState. The ASP.NET MVC framework allows for 100% control over the HTML output. If you require full control over your HTML markup, the ASP.NET MVC framework will be the better choice.

  • Is the application heavily data-driven?
  • If you are developing an application that is heavily data-driven and is using grids or a lot of master-detail editing of data, ASP.NET Webforms may be the better choice as it provides a lot of controls that will aid you in the development of these kind of applications. Of course, you can use the ASP.NET MVC framework for these tasks too, but you will be required to write more code to achieve the same goal.

  • Is there a need for a Winforms-like development approach?
  • Does your development team write Winforms code? Is there a need for an event-driven programming approach? In these cases, consider ASP.NET Webforms in favor of ASP.NET MVC.

  • Is there a need for a rapid application development (RAD)  development approach?
  • Does your client expect a quick prototype of an application? Is the use of drag-and-drop development using pre-created web controls required? If so, consider ASP.NET Webforms in favor of ASP.NET MVC.

if it is helpful, plese dont forget to leave a comment.
Advertisements

The ASP.NET MVC framework offers the following advantages:

  • Complexity of application logic is made easier to manage because of the separation of an application into model, view, and controller.
  • It allows for easier parallel development; each developer can work on a separate component of the MVC pattern.
  • It provides good support for TDD, mocking, and unit testing frameworks.
  • TDD enables you to write tests for an application irst, after which the  application logic is developed.
  • It does not use ViewState or server-based forms, which allows you to have full control over the application’s behavior and HTML markup.
  • It uses RESTful interfaces for URLs, which is better for SEO (Search Engine Optimization). REST is short for REpresentational State Transfer—the concept of using URLs as the link to a resource, which can be a controller action method, rather than to physical iles on the web server.A typical page size is small, because no unnecessary data is transferred in the form of hidden ViewState data. It integrates easily with client-side JavaScript frameworks such as jQuery  or ExtJS.

ASP.NET Webforms offers the following advantages:

  • It offers an event model over HTTP that is familiar to any developer. This event model also beneits the creation of business web applications.
  • It provides a lot of controls that are familiar to any developer—data components such as data grids and lists, validation controls, and so on.  These components are highly integrated in the development environment.
  • There are numerous third-party control vendors that can deliver almost any possible control.Being familiar to developers allows ASP.NET Webforms to facilitate rapid application development.
  • Functionality is concentrated per page. It uses ViewState and server-based forms, which makes state management easier.

if it is helpful, plese dont forget to leave a comment.

<%@ Page Language="C#" MasterPageFile="~/MasterPage.master" Title="Untitled Page" %>

<script runat="server">
    protected void Page_Load(object sender, EventArgs e)
    {
        StringBuilder str = new StringBuilder();
        str.Append("function test() { alert('Close!');}\n");
        str.Append("window.onunload=test;");
        string str2 = Convert.ToString(str);
        Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "clientscript", str2, true);
    }
</script>

<asp:Content ID="Content1" ContentPlaceHolderID="head" Runat="Server">
</asp:Content>

<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" Runat="Server">Test Page.
</asp:Content>

.

if it is helpful, plese dont forget to leave a comment.

Choosing a UI Pattern (MVC, MVP, and ASP.Net MVC)

This particular post assumes you already know about the MVC and the MVP pattern. Of course they stand for Model View Controller and Model View Presenter. And the MVP is basically the MVC pattern, but it gives less control to the view and puts most of the responsibility in the presenter. It is an attempt to make all logic part of the presenter, thus the view is “passive”. The MVP pattern is even broken down into two other patterns, passive view and supervising controller, to even more decide on how much authority the view has. This post also assumes you at least understand the basics of the ASP.Net MVC framework (i.e.: it is a framework based around the MVC pattern). I am not going to explain the patterns or frameworks in this post as I believe that information is already widely available on the internet.

First of all, let me be clear – MVC and MVP are patterns and ASP.Net MVC is a framework around a pattern.

Also, let me be clear – this post is just my opinions, this is not any official way to think based off of Microsoft recommendations. These are just the opinions I have generated after buiding many sites with and without patterns and learning the “hard way” about why patterns are that important.

The first decision you have to make is – are you doing a winform or a webform. Unless you have a specific requirement for an application to be on the web, a winform or WPF is usually your best choice. A lot of companies are trying to do everything on the web now a days and I don’t agree with that. Deployment of winforms is easier than ever (with Click Once) and when working within a business domain environment a winform can be your best friend because of performance and ease of use. So, I will break down my recommendations first based on this.

Winform
I almost always choose the MVP pattern when building winforms. This provides me the best separation of UI from business as well as the best testability coverage of my view. Of course the MVP pattern is broken down into supervising controller and passive view. I tend to lean more towards the passive view, but I understand it is very restricting. If I have to do a lot of grid binding I see that the supervising controller can be a more flexible pattern, but you lose a little bit of testability that you would get with the passive view.

Very rarely will I recommend the MVC for a Winform application. The only times I will agree to this is if the timeline is very short and the initial setup of a good MVP pattern cannot be implemented in the time allotted. It is important to point out, a good controller pattern is key to a good system. So, if you don’t feel you can implement an MVP pattern, a MVC pattern will work just fine. At least you have testability over all your business function calls, by going through the controller, in this pattern.

Winform and Webform (cross-boundary application)
These are applications that need to be built to run on a web page as well as a winform. Good examples of these are applications where 100% of the functionality is available in house, on a winform, and 90% of the functionality is available on a webpage to external users. In these cases the MVP passive view pattern should always be used. The reason is the presenter is always responsible for everything. Thus, all you have to do is build respective UIs (that implement a particular interface) and you can resuse the whole M and P from the MVP model. It provides great reuse of code.

Webpages
Webpages (in .net) can now be broken down into two separate things – WebForms(classic ASP.Net) and ASP.Net MVC. Deciding on which one to use depends on a few parameters.

ASP.Net MVC
It is important to understand that ASP.Net MVC is not a replacement for WebForms, it is just an alternative.

It provides a few great advantages:

  1. Built in MVC Pattern
  2. Front Controller pattern (implemented with Routing). Please note: routing is not an ASP.Net MVC pattern. It is a new functionality, of .net, that the ASP.Net MVC framework takes advantage of.
  3. Mock testing – using a Mock framework like RhinoMock, the ASP.Net MVC allows us to mock up website objects such as server, context, etc… This is a great advantage because we don’t have to have a website actually running to do our testing.
  4. No postbacks or viewstate. This really makes .net development more web-centric and really cleans up the html page that is ultimately created (because the viewstate is not in the webpage anymore)
  5. Great for Agile development. It really forces you to create end to end segments, one at a time.

However, it also has some disadvantages:

  1. Still in CTP – not even a beta release yet
  2. No postbacks or viewstate. Yes, I know I listed this as an advantage, but it is a disadvantage also. The reason is a lot of people have learned to work with postbacks and are going to have a hard time working without them.
  3. Controls support – controls that take advantage of postbacks or viewstate will not work. These include the grid control and the AJAX Update Panel. However, I am sure Microsoft will release similar controls for the ASP.Net MVC framework – eventually.
  4. Not great for design driven or waterfall development of large, business applications. Using something like an MVP pattern in a Webform will allow you to create interfaces and business layers completely before building any UI or View code. With ASP.Net MVC, you should create you views and test them from the beginning.

So, my conclusion to the question of “When to use ASP.Net MVC” is: use it in small to medium size applications when using agile development and when you need good test driven development. Or, use it if you are not a fan of the postback/viewstate implementation of WebForms.

WebForms (classic ASP.Net)
Webforms have not gone away now that ASP.Net MVC is here. It is still a very valid alternative. Before jumping into when to use this, a little history is in order. Microsoft built WebForms at an attempt to mimic Winform development. If you remember Classic ASP you will remember it was very hard, maybe impossible, to separate the business from the UI. So, Microsoft built WebForms to be more like Winforms. The business is seperated from the UI with code behind. Plus, it is an event-driven model, just like Winforms. When I say event-driven, I mean if you double click on a control it build an associated event in the code behind. It can do all this because of postbacks and viewstate.

When building a Webform you should still implement an MVC or MVP pattern. Preferably an MVP (supervising controller seems to work the best with Webforms) if you have enough time to build it out. You will be responsible for building this pattern out correctly however, so set some time aside in the beginning.

So, when should we still use Webforms:

  1. When you like the event-driven model. Having events behind controls is much easier for some developers to understand. If you don’t really understand how the web works, this hides a lot of that from you and can be easy to create web applications quickly.
  2. When you don’t care that much about testing. In these cases you probably won’t use any patterns, which I don’t agree with because I always think testing is important.
  3. When you need to use some of the more advanced controls that take advantage of postbacks and viewstate, such as the grid control and the update panel.
  4. When you want to build out business layers and interfaces before building UIs. Great for design teams to build in the waterfall methodology. You will have to incorporate an MVP pattern for this approach. This is usually done with very big business applications.

In conclusion:
Always use a well defined pattern to help with testing a system. The MVP is usually a good choice, when you are architecting from scratch, but the MVC is still a very good pattern. The difference between the two is just how much work the view is allowed to do. The MVP pattern attempts to take work away from the view. When building webpages in .net you now have two frameworks to choose from – webforms or ASP.Net MVC. When using the ASP.Net MVC you don’t have to worry about creating the framework for the pattern, it is built in for you. However, if you choose a webform, you should create a good MVP or MVC pattern around the work. Deciding on whether to choose a webform or an ASP.Net MVC application is a multi-facet question and has lots of considerations to think about. In the end, a general rule of thumb can be – use the ASP.Net MVC for small to mid size business applications where testing and agile development are important. Also, bear in mind the current control limitations when making this choice. Otherwise, use a webform and implement your own patterns.

if it is helpful, plese dont forget to leave a comment.

1. Use === Instead of ==

JavaScript utilizes two different kinds of equality operators: === | !== and == | != It is considered best practice to always use the former set when comparing.

“If two operands are of the same type and value, then === produces true and !== produces false.” – JavaScript: The Good Parts

However, when working with == and !=, you’ll run into issues when working with different types. In these cases, they’ll try to coerce the values, unsuccessfully.

2. Eval = Bad

For those unfamiliar, the “eval” function gives us access to JavaScript’s compiler. Essentially, we can execute a string’s result by passing it as a parameter of “eval”.

Not only will this decrease your script’s performance substantially, but it also poses a huge security risk because it grants far too much power to the passed in text. Avoid it!

3. Don’t Use Short-Hand

Technically, you can get away with omitting most curly braces and semi-colons. Most browsers will correctly interpret the following:

if(someVariableExists)
   x = false

However, consider this:

if(someVariableExists)
   x = false
   anotherFunctionCall();

One might think that the code above would be equivalent to:

if(someVariableExists) {
   x = false;
   anotherFunctionCall();
}

Unfortunately, he’d be wrong. In reality, it means:

if(someVariableExists) {
   x = false;
}
anotherFunctionCall();

As you’ll notice, the indentation mimics the functionality of the curly brace. Needless to say, this is a terrible practice that should be avoided at all costs. The only time that curly braces should be omitted is with one-liners, and even this is a highly debated topic.

if(2 + 2 === 4) return 'nicely done';

Always Consider the Future

What if, at a later date, you need to add more commands to this if statement. In order to do so, you would need to rewrite this block of code. Bottom line – tread with caution when omitting.

4. Utilize JS Lint

JSLint is a debugger written by Douglas Crockford. Simply paste in your script, and it’ll quickly scan for any noticeable issues and errors in your code.

“JSLint takes a JavaScript source and scans it. If it finds a problem, it returns a message describing the problem and an approximate location within the source. The problem is not necessarily a syntax error, although it often is. JSLint looks at some style conventions as well as structural problems. It does not prove that your program is correct. It just provides another set of eyes to help spot problems.”
– JSLint Documentation

Before signing off on a script, run it through JSLint just to be sure that you haven’t made any mindless mistakes.

5. Place Scripts at the Bottom of Your Page

This tip has already been recommended in the previous article in this series. As it’s highly appropriate though, I’ll paste in the information.

Place JS at bottom

Remember — the primary goal is to make the page load as quickly as possible for the user. When loading a script, the browser can’t continue on until the entire file has been loaded. Thus, the user will have to wait longer before noticing any progress.

If you have JS files whose only purpose is to add functionality — for example, after a button is clicked — go ahead and place those files at the bottom, just before the closing body tag. This is absolutely a best practice.

Better

<p>And now you know my favorite kinds of corn. </p>
<script type="text/javascript" src="path/to/file.js"></script>
<script type="text/javascript" src="path/to/anotherFile.js"></script>
</body>
</html>

6. Declare Variables Outside of the For Statement

When executing lengthy “for” statements, don’t make the engine work any harder than it must. For example:

Bad

for(var i = 0; i < someArray.length; i++) {
   var container = document.getElementById('container');
   container.innerHtml += 'my number: ' + i;
   console.log(i);
}

Notice how we must determine the length of the array for each iteration, and how we traverse the dom to find the “container” element each time — highly inefficient!

Better

var container = document.getElementById('container');
for(var i = 0, len = someArray.length; i < len;  i++) {
   container.innerHtml += 'my number: ' + i;
   console.log(i);
}

Bonus points to the person who leaves a comment showing us how we can further improve the code block above.

7. The Fastest Way to Build a String

Don’t always reach for your handy-dandy “for” statement when you need to loop through an array or object. Be creative and find the quickest solution for the job at hand.

var arr = ['item 1', 'item 2', 'item 3', ...];
var list = '<ul><li>' + arr.join('</li><li>') + '</li></ul>';

I won’t bore you with benchmarks; you’ll just have to believe me (or test for yourself) – this is by far the fastest method!

Using native methods (like join()), regardless of what’s going on behind the abstraction layer, is usually much faster than any non-native alternative.
– James Padolsey, james.padolsey.com

8. Reduce Globals

“By reducing your global footprint to a single name, you significantly reduce the chance of bad interactions with other applications, widgets, or libraries.”
– Douglas Crockford

var name = 'Jeffrey';
var lastName = 'Way';

function doSomething() {...}

console.log(name); // Jeffrey -- or window.name

Better

var DudeNameSpace = {
   name : 'Jeffrey',
   lastName : 'Way',
   doSomething : function() {...}
}
console.log(DudeNameSpace.name); // Jeffrey

Notice how we’ve “reduced our footprint” to just the ridiculously named “DudeNameSpace” object.

9. Comment Your Code

It might seem unnecessary at first, but trust me, you WANT to comment your code as best as possible. What happens when you return to the project months later, only to find that you can’t easily remember what your line of thinking was. Or, what if one of your colleagues needs to revise your code? Always, always comment important sections of your code.

// Cycle through array and echo out each name.
for(var i = 0, len = array.length; i < len; i++) {
   console.log(array[i]);
}

10. Embrace Progressive Enhancement

Always compensate for when JavaScript is disabled. It might be tempting to think, “The majority of my viewers have JavaScript enabled, so I won’t worry about it.” However, this would be a huge mistake.

Have you taken a moment to view your beautiful slider with JavaScript turned off? (Download the Web Developer Toolbar for an easy way to do so.) It might break your site completely. As a rule of thumb, design your site assuming that JavaScript will be disabled. Then, once you’ve done so, begin to progressively enhance your layout!

11. Don’t Pass a String to “SetInterval” or “SetTimeOut”

Consider the following code:

setInterval(
"document.getElementById('container').innerHTML += 'My new number: ' + i", 3000
);

Not only is this code inefficient, but it also functions in the same way as the “eval” function would. Never pass a string to SetInterval and SetTimeOut. Instead, pass a function name.

setInterval(someFunction, 3000);

12. Don’t Use the “With” Statement

At first glance, “With” statements seem like a smart idea. The basic concept is that they can be used to provide a shorthand for accessing deeply nested objects. For example…

with (being.person.man.bodyparts) {
   arms = true;
   legs = true;
}

— instead of —

being.person.man.bodyparts.arms = true;
being.person.man.bodyparts.legs= true;

Unfortunately, after some testing, it was found that they “behave very badly when setting new members.” Instead, you should use var.

var o = being.person.man.bodyparts;
o.arms = true;
o.legs = true;

13. Use {} Instead of New Object()

There are multiple ways to create objects in JavaScript. Perhaps the more traditional method is to use the “new” constructor, like so:

var o = new Object();
o.name = 'Jeffrey';
o.lastName = 'Way';
o.someFunction = function() {
   console.log(this.name);
}

However, this method receives the “bad practice” stamp without actually being so. Instead, I recommend that you use the much more robust object literal method.

Better

var o = {
   name: 'Jeffrey',
   lastName = 'Way',
   someFunction : function() {
      console.log(this.name);
   }
};

Note that if you simply want to create an empty object, {} will do the trick.

var o = {};

“Objects literals enable us to write code that supports lots of features yet still make it a relatively straightforward for the implementers of our code. No need to invoke constructors directly or maintain the correct order of arguments passed to functions, etc.” – dyn-web.com

14. Use [] Instead of New Array()

The same applies for creating a new array.

Okay

var a = new Array();
a[0] = "Joe";
a[1] = 'Plumber';

Better

var a = ['Joe','Plumber'];

“A common error in JavaScript programs is to use an object when an array is required or an array when an object is required. The rule is simple: when the property names are small sequential integers, you should use an array. Otherwise, use an object.” – Douglas Crockford

15. Long List of Variables? Omit the “Var” Keyword and Use Commas Instead

var someItem = 'some string';
var anotherItem = 'another string';
var oneMoreItem = 'one more string';

Better

var someItem = 'some string',
    anotherItem = 'another string',
    oneMoreItem = 'one more string';

…Should be rather self-explanatory. I doubt there’s any real speed improvements here, but it cleans up your code a bit.

17. Always, Always Use Semicolons

Technically, most browsers will allow you to get away with omitting semi-colons.

var someItem = 'some string'
function doSomething() {
  return 'something'
}

Having said that, this is a very bad practice that can potentially lead to much bigger, and harder to find, issues.

Better

var someItem = 'some string';
function doSomething() {
  return 'something';
}

18. “For in” Statements

When looping through items in an object, you might find that you’ll also retrieve method functions as well. In order to work around this, always wrap your code in an if statement which filters the information

for(key in object) {
   if(object.hasOwnProperty(key) {
      ...then do something...
   }
}

As referenced from JavaScript: The Good Parts, by Douglas Crockford.

19. Use Firebug’s “Timer” Feature to Optimize Your Code

Need a quick and easy way to determine how long an operation takes? Use Firebug’s “timer” feature to log the results.

function TimeTracker(){
 console.time("MyTimer");
 for(x=5000; x > 0; x--){}
 console.timeEnd("MyTimer");
}

20. Read, Read, Read…

While I’m a huge fan of web development blogs (like this one!), there really isn’t a substitute for a book when grabbing some lunch, or just before you go to bed. Always keep a web development book on your bedside table. Here are some of my JavaScript favorites.

Read them…multiple times. I still do!

21. Self-Executing Functions

Rather than calling a function, it’s quite simple to make a function run automatically when a page loads, or a parent function is called. Simply wrap your function in parenthesis, and then append an additional set, which essentially calls the function.

(function doSomething() {
   return {
      name: 'jeff',
      lastName: 'way'
   };
})();

22. Raw JavaScript Can Always Be Quicker Than Using a Library

JavaScript libraries, such as jQuery and Mootools, can save you an enormous amount of time when coding — especially with AJAX operations. Having said that, always keep in mind that a library can never be as fast as raw JavaScript (assuming you code correctly).

jQuery’s “each” method is great for looping, but using a native “for” statement will always be an ounce quicker.

23. Crockford’s JSON.Parse

Although JavaScript 2 should have a built-in JSON parser, as of this writing, we still need to implement our own. Douglas Crockford, the creator of JSON, has already created a parser that you can use. It can be downloaded HERE.

Simply by importing the script, you’ll gain access to a new JSON global object, which can then be used to parse your .json file.

 var response = JSON.parse(xhr.responseText);

 var container = document.getElementById('container');
 for(var i = 0, len = response.length; i < len; i++) {
   container.innerHTML += '
	
  • ' + response[i].name + ' : ' + response[i].email + '
  • '; }

    24. Remove “Language”

    Years ago, it wasn’t uncommon to find the “language” attribute within script tags.

    <script type="text/javascript" language="javascript">
    ...
    </script>

    However, this attribute has long since been deprecated; so leave it out.

    if it is helpful, plese dont forget to leave a comment.

    New XSLT-based list view in WSS 4.0

    Windows SharePoint Services 4.0 will ship with a new XSLT-based list view with the following improvements :

    • SharePoint Designer customization support
    • conditional formatting and
    • improved developer experience with XSLT standard-based language support. 😉

    CAML-based custom list views are still working but without the mentioned improvements. The following will not be upgraded to the next version of SharePoint :

    • A list view that uses custom Collaborative Application Markup Language (CAML)
    • A list view that is not associated with a feature
    • A list view that is associated with a custom feature

    By the way: Custom field types with CAML in its RendernPattern will also not be upgraded.

    Webparts are using controls (.ascx)

    The Webparts will use controls so you can use a visual editor when creating your Webparts.

    Miscellaneous

    The other Pre-Upgrade Checker rules are about large lists, the workflow actions file and new authorized types for workflow in web.config

    if it is helpful, plese dont forget to leave a comment.

    We usually use Singleton design pattern where only one object of a class is required. It is very simple and I try to explain it.

    public class MyClass

    {

    static MyClass myclass;

    // make constructor private

    // now you cannot make a direct instance of this class like:

    // MyClass obj=new MyClass() // it wount compile

    private MyClass()

    {

    }

    public static MyClass GetInstance()

    {

    lock (typeof(MyClass))

    {

    if (myclass == null)

    {

    myclass = new MyClass();

    }

    }

    return myclass;

    }

    //Destructor

    ~MyClass()

    {

    myclass = null;

    }

    }

    Concept behind this patteren is very simple, we create a static object of a class which remains in memory until destroyed by the destructor.when we try to make another object of this class our method will check the existing instance, if already exist then retun the existing object otherwise create a new object.

    Now call the static method using this line of codes

    MyClass obj=MyClass.GetInstance();

    if it is helpful, plese dont forget to leave a comment.