Friday, December 31, 2010

Definition of "Unobtrusive JavaScript"

Separation Javascript from a Web page's structure/content and presentation

ASP.NET reading list in 2010

ASP.NET, ASP.NET MVC and jQuery
TextBox AutoComplete with ASP.NET and jQuery UI - This article demonstrates how to use the jQuery UI AutoComplete widget to consume an ASP.NET Web Service that is JSON Serialized.
Building A Custom ActionResult in MVC 2 To Download Excel Files - The following article demonstrates how to create a custom ActionResult to allow users to download Microsoft Excel files using ASP.NET MVC 2.
Handle JSON Exceptions Gracefully in ASP.NET MVC 2 - The following article demonstrates how to handle exceptions gracefully when calling Ajax methods using ASP.NET MVC 2.
What's New in ASP.NET 4.0 – Better ViewState Control - In ASP.NET 2.0/3.5, you could disable ViewState for individual controls. However what you could not do is disable ViewState at a Page level and then enable it individually for controls on that page that require it. ASP.NET 4.0 changes that and gives more control to developers.
Keeping Your ASP.NET Session Alive Using jQuery - The following article demonstrates how to keep your session alive when you're using ASP.NET MVC and jQuery.
ASP.NET MVC 3 Preview 1 - Razor View Engine - The following article demonstrates how to use the new Razor view engine in ASP.NET MVC 3 Preview 1 release.
What's New in ASP.NET 4.0 – SEO Enhancements with MetaKeywords and MetaDescription properties - In this article, we will take an overview of the two new properties added to the Page class in ASP.NET 4.0 – MetaKeywords and MetaDescription.
Populate an ASP.NET ListBox from JSON results using jQuery - This article demonstrates how to populate an ASP.NET ListBox using data coming from a JSON Serialized ASP.NET Web Service.
Localize the jQuery DatePicker Control in an ASP.NET Page - The jQuery UI DatePicker widget is highly configurable and full of features, and I use it in my applications whenever I can. In this article, we will see how to localize the DatePicker based on the value selected from an ASP.NET DropDownList.
ASP.NET MVC 3 Preview 1 – Global and Conditional Filters - The following article demonstrates how to use global filters in ASP.NET MVC 3 Preview 1 and also how to use them conditionally.
Efficient Paging with WebGrid Web Helper - ASP.NET MVC 3 RC - The following article demonstrates one way of performing efficient paging using the WebGrid WebHelper in ASP.NET MVC 3 RC.
Three Ways to Populate a Select Element with ASP.NET MVC and jQuery - The following article demonstrates three ways to populate a select element using ASP.NET MVC and jQuery.
Using Dynamic Views In ASP.NET MVC 2 - A really cool addition to ASP.NET MVC 2 is the ability to use the dynamic type as the object passed into the view. This is also known as a dynamic view. If you create a new view and don't create a strongly typed view, out of the box, the MVC framework will make the view inherit from the ViewPage class, but the generic type will be dynamic

Thursday, December 30, 2010

Wednesday, December 29, 2010

How to implement busy cursor in web forms by JQuery?

No validation:

            <asp:Button UseSubmitBehavior="false" OnClientClick="$('body').css('cursor', 'wait'); $('.Buttons').attr('disabled', 'true');"
                ID="ButtonBack" runat="server" Text="aa" ValidationGroup="novalidation"
                OnClick="ButtonBack_Click" />


With validation 

            <asp:Button UseSubmitBehavior="false" OnClientClick='if (Page_ClientValidate("vg")) { $("body").css("cursor", "wait"); $(".Buttons").attr("disabled", "true");}; '
                ID="ButtonReview" runat="server" Text="Next" OnClick="ButtonReview_Click"
                ValidationGroup="vg" />


And also add following code into master page or web forms page to reset cursor to normal, if validation failed
    <script type="text/javascript">
        function pageLoad() {
   $('body').css('cursor', 'auto');
        } 
    </script>



Saturday, December 25, 2010

How to solve “New transaction is not allowed because there are other threads running in the session” in Entity Framework

Make sure only call SaveChanges method once in the end, not inside loop.
Or covert collection to IList

Friday, December 24, 2010

How to use Ajaxupload in MVC

Client side:
1. Get the latest lib from http://valums.com/ajax-upload
2. Copy into your project
3. Add refrence in your aspx file:
<script src='<%=Page.ResolveClientUrl("~/Scripts/ajaxupload.3.6.js")%>' type="text/javascript"></script>
4. Add Javascript code to call ajaxupload
<script type="text/javascript">
$(document).ready(function() {
var button = $('#upload')[0], interval;
new AjaxUpload(button, {
action: '<%= Url.Relative("~/ControllerName/Save") %>',
name: 'myfile',
onSubmit: function(file, ext) {
if (!(ext && /^(doc|pdf|txt|xls)$/.test(ext))) {
alert('Error: invalid file extension');
return false;
}
button.value = 'Uploading';
this.disable();
interval = window.setInterval(function() {
var text = button.value;
if (text.length < 13) {
button.value = button.value + '.';
} else {
button.value = 'Uploading';
}
}, 200);
},
onComplete: function(file, response) {
button.value = 'Upload';

window.clearInterval(interval);
this.enable();
if (response == 'error')
alert('Error: File size is over limit (10mb). '+file);
else
//Dispaly uploaded file
},
responseType:'json'
});
});
</script>

Server side is very simple. Just create a Json action:
public JsonResult Save()
{
try
{
var files = this.HttpContext.Request.Files;
string filename = System.IO.Path.GetFileName(files[0].FileName);
files[0].SaveAs(filename);
return Json(null);
}
catch
{
return Json("error");
}
}

Thursday, December 23, 2010

Wednesday, December 22, 2010

How to make ribbon style menu in ASP.NET webform project?

- Download and test demo from:
http://jqueryribbon.codeplex.com/
- Steps:
1. Add JQuery and ribob JavaScript references into master page

2. Add ribbon menu html tab into master page



If use JQuery 1.4.2, you will get following error (http://jqueryribbon.codeplex.com/workitem/26828):
$(".ribbon-list div ul:visible").parent().offset() is null
Please use following script to replace jquery.ribbon.js.


///<reference path="jquery-1.3.2-vsdoc2.js" />
/*
Copyright (c) 2009 Mikael Söderström.
Contact: vimpyboy@msn.com
 
Feel free to use this script as long as you don't remove this comment.
*/
 
(function ($) {
    var isLoaded;
    var isClosed;
 
    $.fn.Ribbon = function (ribbonSettings) {
        var settings = $.extend({ theme: 'windows7' }, ribbonSettings || {});
 
        $('.ribbon a').each(function () {
            if ($(this).attr('accesskey')) {
                $(this).append('<div rel="accesskeyhelper" style="display: none; position: absolute; background-image: url(images/accessbg.png); background-repeat: none; width: 16px; padding: 0px; text-align: center; height: 17px; line-height: 17px; top: ' + $(this).offset().top + 'px; left: ' + ($(this).offset().left + $(this).width() - 15) + 'px;">' + $(this).attr('accesskey') + '</div>');
            }
        });
        $('head').append('<link href="/ribbon/themes/' + settings.theme + '/ribbon.css" rel="stylesheet" type="text/css" />');
 
        if (!isLoaded) {
            SetupMenu(settings);
        }
 
        $(document).keydown(function (e) { ShowAccessKeys(e); });
        $(document).keyup(function (e) { HideAccessKeys(e); });
 
        function SetupMenu(settings) {
            $('.menu li a:first').addClass('active');
            $('.menu li ul').hide();
            $('.menu li a:first').parent().children('ul:first').show();
            $('.menu li a:first').parent().children('ul:first').addClass('submenu');
            $('.menu li > a').click(function () { ShowSubMenu(this); });
            $('.orb').click(function () { ShowMenu(); });
            $('.orb ul').hide();
            $('.orb ul ul').hide();
            $('.orb li ul li ul').show();
            $('.orb li li ul').each(function () { $(this).prepend('<div style="background-color: #EBF2F7; height: 25px; line-height: 25px; width: 292px; padding-left: 9px; border-bottom: 1px solid #CFDBEB;">' + $(this).parent().children('a:first').text() + '</div>'); });
            $('.orb li li a').each(function () { if ($(this).parent().children('ul').length > 0) { $(this).addClass('arrow') } });
 
            //$('.ribbon-list div').each(function() { $(this).parent().width($(this).parent().width()); });
 
            $('.ribbon-list div').parents().click(function (e) {
                var inX = true;
                if ($('.ribbon-list div ul').has(':visible').length > 0) {
                    var p = $('.ribbon-list div ul').has(':visible').parent();
                    var outsideX = e.pageX < p.offset().left || e.pageX > p.offset().left + p.width();
                    var outsideY = e.pageY < p.offset().top || e.pageY > p.offset().top + p.height();
 
                    if (outsideX || outsideY)
                        inX = true;
                    else
                        inX = false;
 
                }
                if (inX) {
                    $('.ribbon-list div ul:visible').each(function () {
                        $(this).fadeOut('fast');
                    });
                    $('.ribbon-list div').css('background-image''');
                }
            });
 
            $('.ribbon-list div').parents().click(function (e) {
                var $ulParent = $('.ribbon-list div ul:visible').parent();
                if ($ulParent.length) {
                    var outsideX = e.pageX < $ulParent.offset().left || e.pageX > $ulParent.offset().left + $ulParent.width(),
outsideY = e.pageY < $ulParent.offset().top || e.pageY > $ulParent.offset().top + $ulParent.height();
 
                    if (outsideX || outsideY) {
                        $('.ribbon-list div ul:visible').each(function () {
                            $(this).fadeOut('fast');
                        });
                        $('.ribbon-list div').css('background-image''');
                    }
                }
            });
 
            $('.orb li li a').mouseover(function () { ShowOrbChildren(this); });
 
            $('.menu li > a').dblclick(function () {
                $('ul .submenu').animate({ height: "hide" });
                $('body').animate({ paddingTop: $(this).parent().parent().parent().parent().height() });
                isClosed = true;
            });
        }
 
        $('.ribbon').parents().click(function (e) {
            var outsideX = e.pageX < $('.orb ul:first').offset().left || e.pageX > $('.orb ul:first').offset().left + $('.orb ul:first').width();
            var outsideY = e.pageY < $('.orb ul:first img:first').offset().top || e.pageY > $('.orb ul:first').offset().top + $('.orb ul:first').height();
 
            if (outsideX || outsideY)
                $('.orb ul').fadeOut('fast');
        });
 
        if (isLoaded) {
            $('.orb li:first ul:first img:first').remove();
            $('.orb li:first ul:first img:last').remove();
            $('.ribbon-list div img[src*="/images/arrow_down.png"]').remove();
        }
 
        $('.orb li:first ul:first').prepend('<img src="ribbon/themes/' + settings.theme + '/images/menu_top.png" style="margin-left: -10px; margin-top: -22px;" />');
        $('.orb li:first ul:first').append('<img src="ribbon/themes/' + settings.theme + '/images/menu_bottom.png" style="margin-left: -10px; margin-bottom: -22px;" />');
 
        $('.ribbon-list div').each(function () { if ($(this).children('ul').length > 0) { $(this).append('<img src="ribbon/themes/' + settings.theme + '/images/arrow_down.png" style="float: right; margin-top: 5px;" />') } });
 
        //Hack for IE 7.
        if (navigator.appVersion.indexOf('MSIE 6.0') > -1 || navigator.appVersion.indexOf('MSIE 7.0') > -1) {
            $('ul.menu li li div').css('width''90px');
            $('ul.menu').css('width''500px');
            $('ul.menu').css('float''left');
            $('ul.menu .submenu li div.ribbon-list').css('width''100px');
            $('ul.menu .submenu li div.ribbon-list div').css('width''100px');
        }
 
        $('a[href=' + window.location.hash + ']').click();
 
        isLoaded = true;
 
        function ResetSubMenu() {
            $('.menu li a').removeClass('active');
            $('.menu ul').removeClass('submenu');
            $('.menu li ul').hide();
        }
 
        function ShowSubMenu(e) {
            var isActive = $(e).next().css('display') == 'block';
            ResetSubMenu();
 
            $(e).addClass('active');
            $(e).parent().children('ul:first').addClass('submenu');
 
            $(e).parent().children('ul:first').show();
            $('body').css('padding-top''120px');
 
            isClosed = false;
        }
 
        function ShowOrbChildren(e) {
            if (($(e).parent().children('ul').css('display') == 'none' || $(e).parent().children('ul').length == 0) && $(e).parent().parent().parent().parent().hasClass('orb')) {
                $('.orb li li ul').fadeOut('fast');
                $(e).parent().children('ul').fadeIn('fast');
            }
        }
 
        function ShowMenu() {
            $('.orb ul').animate({ opacity: 'toggle' }, 'fast');
        }
 
        function ShowAccessKeys(e) {
            if (e.altKey) {
                $('div[rel="accesskeyhelper"]').each(function () { $(this).css('top', $(this).parent().offset().top).css('left', $(this).parent().offset().left - 20 + $(this).parent().width()); $(this).show(); });
            }
        }
 
        function HideAccessKeys(e) {
            $('div[rel="accesskeyhelper"]').hide();
        }
    }
})(jQuery);


If still do not show up, please double check following line, make sure themes files location is correct
        $('head').append('<link href="/ribbon/themes/' + settings.theme + '/ribbon.css" rel="stylesheet" type="text/css" />');

Monday, December 20, 2010

How to improve ASP.Net Performance 3: html view

- Keep StyleSheets in the Header and Scripts to the end of Document
- Keep JavaScript and CSS External
- Turn Off ViewState if possible
  <%@ Page EnableViewState = "false" %>
- Disable Session State if possible
  <%@ Page EnableSessionState= "false" %>

How to redirect to another Controller/Action in Javascript (ASP.NET/MVC)

1. By html button
<input type="button" name="cmd" onclick="javacript: window.location='<%= Page.ResolveUrl("~/EventName/ActionName/"+ViewData["Id"].ToString()) %>';" value="Go" />
2. Set two forms, and use Redirection in Controller

Sunday, December 19, 2010

How to upload file in MVC ASP.NET

In view (.aspx):

<form action="/Home/SaveDocuments" method="post" enctype="multipart/form-data">
    <label for="file1">Upload Documents</label>
    <input type="file" id="file1" name="file1" class="multi"/>
    <input type="submit" value="Upload" />
</form>

In Controller:

        public string EventFileDirectory = @"C:\Downloads";
        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult SaveDocuments()
        {
            foreach (string inputTagName in Request.Files)
            {
                System.Web.HttpPostedFileBase file = Request.Files[inputTagName];
                if (file.ContentLength > 0)
                {
                    string filePath = System.IO.Path.Combine(EventFileDirectory, System.IO.Path.GetFileName(file.FileName));
                    file.SaveAs(filePath);
                }
            }
            return RedirectToAction("Index", "Home");
        }

Saturday, December 18, 2010

In Entity Framework, no method for deleting collection.

Have to delete object one by one. :(
Reference:
http://social.msdn.microsoft.com/forums/en-US/adodotnetentityframework/thread/2fa38cb9-8815-4767-ab17-04b424f3af57/

Friday, December 17, 2010

How to improve ASP.Net Performance 1: Check list for web.config file

1. Ensure Pages Are Batch Compiled
<compilation batch="true" />

2. Disable debug
<compilation debug="false" />

3. Disable Tracing
< trace enabled =”false” pageOutput="false"/>

4. If use IIS 7, please add following section into web config file to Cache static files
    <staticContent>
      <clientCache httpExpires="Sun, 29 Mar 2012 00:00:00 GMT" cacheControlMode="UseExpires" />
    </staticContent>

How to improve ASP.Net Performance 2- Coding guideline

- Check Page.IsPostBack to avoid unneccercery databinding
- Try use Repeater Control first. Viewstate in DataList, DataGrid, and DataView controls is huge sometime, although event handler is very covernient
- Prefer Transfer over Response.Redirect
- Check HttpResponse.IsClientConnected before performing a large operation

Wednesday, December 15, 2010

How to fix Invalid viewstate and Validation of viewstate MAC failed in asp.net?

There are couple of errors in asp.net related to viewstate
1. System.Web.HttpException: The client disconnected. —> System.Web.UI.ViewStateException: Invalid viewstate.
2. System.Web.HttpException: Validation of viewstate MAC failed. If this application is hosted by a Web Farm or cluster, ensure that <machineKey> configuration specifies the same validationKey and validation algorithm. AutoGenerate cannot be used in a cluster. —> System.Web.UI.ViewStateException: Invalid viewstate.

How to fix?
1. Check HttpResponse.IsClientConnected in page load event, if not, logoff user.
2. Check Application Pool Recycling IIS setting to avoid recycling is less likely to occur at peak periods
3. put machineKey section into your web.config (http://www.aspnetresources.com/tools/keycreator.aspx)
Such as:
<machineKey
validationKey="80FE3D40B4CDD7FBC1DC32FA0DC87C83586B651214A19F4BC140970DEAE7F99A6B24D2323DB2088E472194BF14CB996062B41F9C2D3A4D821091AA53282F55D5"
decryptionKey="DA085C28238653E0C85994B40AB4208236E0E814BF698F9C202A80901C00F613"
validation="SHA1"
decryption="AES"
/>

References:
1. Intermittent Invalid Viewstate Error in ASP.NET Web pages
http://support.microsoft.com/default.aspx?scid=kb;en-us;555353&sd=rss&spid=6351
2.ASP.NET state management: viewstate
http://www.aspnetresources.com/articles/ViewState.aspx#

Top 50 Programming Quotes of All Time

http://www.junauza.com/2010/12/top-50-programming-quotes-of-all-time.html

Azure

An introduction for hosting a MVC project into Cloud:
http://blogs.msdn.com/b/brandonwerner/archive/2009/11/28/how-to-host-your-site-and-content-on-azure-quickly-and-easily.aspx

Tuesday, December 14, 2010

ASP.NET Performance

Monitoring as.net performance in Windows 7 using perfmon.exe

http://wiki.asp.net/page.aspx/31/performance/

Checklist: ASP.NET Performance
http://msdn.microsoft.com/en-us/library/ff647706.aspx

50 Tips to Boost ASP.NET Performance - Part I
http://www.aspnet101.com/2010/03/50-tips-to-boost-asp-net-performance-part-i/

Friday, December 10, 2010

Make ASP.NET project compile/load time faster

Add following settings into compilation section in web.config file:

batch="false" optimizeCompilations="true" tempDirectory="g:\"
tempDirectory is for the RAM drive


 <compilation debug="true" batch="false" optimizeCompilations="true" tempDirectory="g:\">


Install RAM drive

Slash your ASP.NET compile/load time without any hard work

Wednesday, December 8, 2010

WPF/Silverlight and HTML 5

WPF is dead, html 5 is the future

Diagram
http://www.cincomsmalltalk.com/userblogs/runarj/blogView?showComments=true&entry=3366522423

Monday, December 6, 2010