Saturday, January 29, 2011

How to config SMTP Server in web.config file

<system.net>
<mailSettings>
<smtp>
<network host="0.0.0.0" port="25" userName="yourusername" password="password"/>
</smtp>
</mailSettings>
</system.net>

Where to set up session timeout in asp.net web.config?

<configuration>
<system.web>
<sessionState timeout="20"></sessionState>
</system.web>
</configuration>
The default value is 20 minutes.

Detail:
http://msdn.microsoft.com/en-us/library/system.web.sessionstate.httpsessionstate.timeout.aspx

Friday, January 28, 2011

How to cancel Ajax call in JQuery?

By abort method in XMLHttpReuest.
Basically, ajax call in JQuery is a XMLHttpReuest.

Var currentcall = null;
currentcall = $.ajax({
type: "POST",
url: "some.php",
data: "name=John&location=Boston",
success: function(msg){
alert( "Data Saved: " + msg );
currentcall=null;
}
});

In other event handler, you can call currentcall.abort();

Reference:
http://www.w3.org/TR/XMLHttpRequest/#the-abort-method
http://api.jquery.com/jQuery.ajax/

Thursday, January 27, 2011

How to make enter key to cause postback in asp.net webform textbox by JQuery

How to make enter key to cause postback in asp.net webform textbox by JQuery

Need call doPostBack in asp.net webforms.
$('#<%=TextBox.ClientID %>').keypress(function (event) {
if (event.which == '13') {
__doPostBack('<%= TextBox.ClientID%>', '');
}
});

How to implement timer event handler in Javascript?

window.setInterval(yourfunction, 10000);
function yourfunction() { alert('test'); }

How to implement TextChanged event handler in JQuery

There is no TextChanged Textbox event handler in Javascript.
Following event handler can handle: Keyup, Copy, Paste and Cut


(function (a) {
    a.event.special.textchange = {
        setup: function () {
            a(this).data("lastValue", this.contentEditable === "true" ? a(this).html() : a(this).val());
            a(this).bind("keyup.textchange", a.event.special.textchange.handler);
            a(this).bind("cut.textchange paste.textchange input.textchange", a.event.special.textchange.delayedHandler)
        },
        teardown: function () {
            a(this).unbind(".textchange")
        },
        handler: function () {
            a.event.special.textchange.triggerIfChanged(a(this))
        },
        delayedHandler: function () {
            var b = a(this);
            setTimeout(function () {
                a.event.special.textchange.triggerIfChanged(b)
            },
            25)
        },
        triggerIfChanged: function (b) {
            var c = b[0].contentEditable === "true" ? b.html() : b.val();
            if (c !== b.data("lastValue")) {
                b.trigger("textchange", b.data("lastValue"));
                b.data("lastValue", c)
            }
        }
    };
    a.event.special.hastext = {
        setup: function () {
            a(this).bind("textchange", a.event.special.hastext.handler)
        },
        teardown: function () {
            a(this).unbind("textchange", a.event.special.hastext.handler)
        },
        handler: function (b, c) {
            c === "" && c !== a(this).val() && a(this).trigger("hastext")
        }
    };
    a.event.special.notext = {
        setup: function () {
            a(this).bind("textchange",
            a.event.special.notext.handler)
        },
        teardown: function () {
            a(this).unbind("textchange", a.event.special.notext.handler)
        },
        handler: function (b, c) {
            a(this).val() === "" && a(this).val() !== c && a(this).trigger("notext")
        }
    }
})(jQuery);
  



Usage:




    $("#textboxid").bind('textchange', function (event, previousText) {

        var textboxContent = $("#textboxid").val();

        if (textboxContent == "" || textboxContent == "default value") {

            $("#buttonid").addClass('disabled').attr('disabled', true);

        } else {

            $("#buttonid").addClass('disabled').attr('disabled', false);

        }

    });





Reference:


http://www.zurb.com/playground/jquery-text-change-custom-event

Wednesday, January 26, 2011

A forum open source project by asp.net MVC3, POP forum

Source code:
http://popforums.codeplex.com/

Article:
http://weblogs.asp.net/jeff/archive/2011/01/24/the-mvc3-special-sauce-in-pop-forums.aspx

How to get and set coordinate for html element by JQuery offset()

How to get and set coordinate for html element by JQuery offset()
Codes example:
Get
var p = $("p:last");
var offset = p.offset();
p.html( "left: " + offset.left + ", top: " + offset.top );</script>


Set:
<script>$("p:last").offset({ top: 10, left: 30 });</script>


Reference:

Tuesday, January 25, 2011

How to break out of iframe by Javascript in masterpage?

How to break out of iframe by Javascript in masterpage?
    <script type="text/javascript">
        if (top != self) top.location.replace(location.href);
    </script>

How to redirect page while user’s browser disabled Javascript?

    <noscript>
        <meta http-equiv="refresh" content="3;url=noscript.htm" />
    </noscript>

How to get SQL Server stored procedure output parameters in C#?

How to get SQL Server stored procedure output parameters in C#?
Two part of codes for this:
First: C#

    public static DataSet Get(out int RowCount)
    {
        SqlCommand selectCommand = new SqlCommand();
        selectCommand.Connection = connection;
        selectCommand.CommandType = CommandType.StoredProcedure;
        selectCommand.CommandText = "SP_OUPUT";
 
        RowCount = 0;
        var p = selectCommand.Parameters.AddWithValue("@RETURNCOUNT", RowCount);
        p.Direction = ParameterDirection.Output;
 
        SqlDataAdapter adapter = new SqlDataAdapter(selectCommand);
        DataSet dataSet = new DataSet("Results");
        adapter.Fill(dataSet);
        RowCount = Convert.ToInt32(selectCommand.Parameters["@TotalSize"].Value);
        return dataSet;
    }

Second part: Store Procedure
CREATE PROCEDURE [SP_OUPUT]
        @RETURNCOUNT        INT OUTPUT

AS
  BEGIN
SELECT * FROM TABLENAME
SET @RETURNCOUNT = @@ROWCOUNT
  END

Monday, January 24, 2011

WebMatric, Microsoft open the door for PHP open source project, Wordpress, Joomla!

WordPress, Joomla!, DotNetNuke and Orchard.
Reference:
http://www.microsoft.com/web/webmatrix/default.aspx

How to use condition comment to hide compatible button in IE8?

How to use condition comment to hide compatible button in IE8?
Put following line into html file before <!DOCTYPE > tag

<!--[if gte IE 7]><meta http-equiv="X-UA-Compatible" content="IE=8"/> <![endif]-->

Condition comment Reference:

Sunday, January 23, 2011

How does jQuery implement hide() and show()

By display: none
Not visibility: hidden


JQuery Source code:

hide: function( speed, easing, callback ) {
if ( speed || speed === 0 ) {
return this.animate( genFx("hide", 3), speed, easing, callback);

} else {
for ( var i = 0, j = this.length; i < j; i++ ) {
var display = jQuery.css( this[i], "display" );

if ( display !== "none" ) {
jQuery.data( this[i], "olddisplay", display );
}
}

// Set the display of the elements in a second loop
// to avoid the constant reflow
for ( i = 0; i < j; i++ ) {
this[i].style.display = "none";
}

return this;
}
}

Saturday, January 22, 2011

Three ways for initialization tasks in Javascript: $(handler), Onload() and pageLoad()

1. pageLoad(), it is called for every partial postback. We should put JQuery event handlers in this function.

2. window.onload = function () {alert("onload");}

Onload() event will be called only after the DOM and associated resources like images got loaded


3. JQuery $(document).ready(handler)
jQuery's document.ready() event will be called once the DOM is loaded, it wont wait for the resources like images to get loaded

All three of the following syntaxes are equivalent:
  • $(document).ready(handler)
  • $().ready(handler) (this is not recommended)
  • $(handler)

Reference:
http://api.jquery.com/ready/




If useful, Consider making a donation to show your support.

Friday, January 21, 2011

How to solve No animation on GIF file if submit a form in html?

Solution: Need to load gif file just before submit by JavaScript/JQuery

<input type="button" class="button" id="process" name="cmdFinish" value="Confirm" />
<div id="processinfo" style="display: none">

<script type= "text/javascript">
$("#process").click(function() {
document.getElementById('processinfo').innerHTML = '<img src= "images/load.gif" /> <br/>Processing...';
$("#processinfo").show();
$("form:first").submit();
});
</script>

How to convert DataTable into anonymous type class list for LINQ

System.Data.DataTable table = dataSet.Tables[0];
var GridviewData = from oneRow in table.AsEnumerable()
  select new
  {
  ID = oneRow.Field<Int32>("ID"),
  Amount = oneRow.Field<decimal>("Amount"),
  Description = oneRow.Field<string>("Description"),
  DateTime = oneRow.Field<System.DateTime?>("DateTime"),
  };

Thursday, January 20, 2011

How to make form input button look like a regular href link?

style="border: 0; cursor: pointer; cursor: hand; background-color: transparent; text-decoration: underline;"

Remote validation, a new feature in MVC 3 for single field server side validation

Common scenario like, you want to check a user name if exist before posting all of information to server.
Before MVC 3, this kind of validation can be implemented by either JQuery ajax calling an action in MVC or a web service in webform.

ASP.NET MVC 3 provides a mechanism that can make a remote server call in order to validate a form field without posting the entire form to the server

Wednesday, January 19, 2011

Tuesday, January 18, 2011

How to call asp.net web service from Jquery?

        $.ajax({

            type: "POST",

            contentType: "application/json; charset=utf-8",

            url: '<%=ResolveClientUrl("~/WebServices/example.asmx/Method")%>',

            data: "{'parameter1':'" + parametervalue1 + "'}",

            dataType: "json",

            async: false,

            success: function (data) {alert(data.d);}

        });
 
Reference:

How to detect Copy Cut and Paste actions on Textbox in JQuery

$("#<%=Textbox1.ClientID %>").bind('cut copy paste', function(e)
{     alert(e.type + ' text!'); });

Monday, January 17, 2011

How to validate post code in webform project by ajax in JQuery calling web service

1.       Web service (Validation.asmx):
    [System.Web.Script.Services.ScriptService]
    public class Validation : System.Web.Services.WebService
    {        public bool GetPostCodeValidation(string statename, string postcode)
        {
            if (postcode == ""return true;
            if (statename == ""return true;

            System.Text.RegularExpressions.Regex r;
            switch (statename)
            {
                case "CA":
                    r = new System.Text.RegularExpressions.Regex(@"^([ABCEGHJKLMNPRSTVXY]\d[ABCEGHJKLMNPRSTVWXYZ])\ {0,1}(\d[ABCEGHJKLMNPRSTVWXYZ]\d)$");
                    return r.IsMatch(postcode.ToUpper());
                case "US":
                    r = new System.Text.RegularExpressions.Regex(@"^(\d{5}-\d{4}|\d{5}|\d{9})$|^([a-zA-Z]\d[a-zA-Z] \d[a-zA-Z]\d)$");
                    return r.IsMatch(postcode);
                default:
                    return true;
            }
        }
    }

2. JQuery ajax call
<script type="text/javascript">

    function ValidatePostCode(source, args) {

        var pc = $("#<%=textboxPostalCode.ClientID %>").val();

        var state = $("#<%=dropdownlistProvince.ClientID %>").val();

        $.ajax({

            type: "POST",

            contentType: "application/json; charset=utf-8",

            url: '<%=ResolveClientUrl("~/Validation.asmx/GetPostCodeValidation")%>',

            data: "{'statename':'" + state + "','postcode':'" + pc + "'}",

            dataType: "json",

            async: false,

            success: function (data) {

                args.IsValid = data.d;

            }

        });

    }

</script>

Please use synchronized call


3. Add custom validator in Html view
<asp:TextBox ID="textboxPostalCode" runat="server"/>           
<asp:CustomValidator ID="customValidatorPostcode" runat="server" ControlToValidate="txtPostalCode" ClientValidationFunction="ValidatePostCode"/>

The concept of JQuery selector is from CSS selector

Borrowing from CSS 1–3, and then adding its own, jQuery offers a powerful set of tools for matching a set of elements in a document.

CSS Selector:
CSS 2 Selector reference

Friday, January 14, 2011

Most important keywords for Object-Oriented

- Inheritance
- Polymorphism
- Data abstraction
- Encapsulation

System.Web.UI.WebControls.Menu css definition problem

If use .Items.Clear() to clear up menu collection, 
will lost css definition in  StaticItemTemplate

IIS Express support SSL in development environment

IIS Express supports SSL. The setup program will install a default, self-signed server certificate in the machine store and configure ports 44300-44399 for use with SSL. You can also set up and configure custom SSL certificates for your websites as an administrator.



Wednesday, January 12, 2011

How to deal with "The underlying provider failed on Open" in Entity Framework

Please use using statement to include your access to Object Context:


            using (var ctx = new Entities())
            {
                ....
            }
Provides a convenient syntax that ensures the correct use of IDisposable objects.

How to set auto-width for dropdownlist in IE by JQuery

<select onmousedown="if($.browser.msie){this.style.position='absolute';this.style.width='auto'}" onblur="this.style.position='';this.style.width=''">

Tuesday, January 11, 2011

How to change master page on the fly in ASP.NET

In web form page, add: 
protected void Page_PreInit(object sender, EventArgs e) 

{ 

    this.Page.MasterPageFile = "~/name.master";

}

How to get current page name in master page?

public string GetCurrentPageName() 
{ 
    string Path = System.Web.HttpContext.Current.Request.Url.AbsolutePath; 
    System.IO.FileInfo fInfo = new System.IO.FileInfo(Path); 
    return fInfo.Name; 
} 

Monday, January 10, 2011

Friday, January 7, 2011

How to trigger the client-side validation manually in javascript

function Validate()
{
Page_ClientValidate('Group1');

}

Thursday, January 6, 2011

innerText and textContent

In firefox, no innerText property, you have to go by textContent.
One line code to check this:
var hasInnerText = (document.getElementsByTagName("body")[0].innerText != undefined) ? true : false;

Two ways to Make Subversion ignore files and folders, suo file etc

two ways:
1. Add to Ignore list

2. Use TortoiseSVN → use Extended Context Menu → Delete (keep local). Press Shift and Right click on that file, goto TortoiseSVN context menu, then click Delete (keep local).

Can we use ASP.NET WebForms and MVC together in one project?

Yes.
1. Easiest way: Create a MVC project, add web form into it.
2. Another way:  Update your web forms project to support MVC on top it. Steps following:
- Add  references to System.Web.Abstractions, System.Web.Mvc and System.Web.Routing
- Update web.config. Compare your web form project to a empty MVC one
- Add routing code into Global.asax.cs
- Create folders for Controllers and Views

References:
http://blogs.imeta.co.uk/MGodfrey/archive/2009/03/31/663.aspx
This one is for MVC 1.0. You need to adjust for 2.0

http://www.sqlmag.com/article/aspnet2/MVC-and-Web-Forms-Two-Great-Tastes-Together-.aspx

Wednesday, January 5, 2011

How to ppulate dropdown list in FireFox and IE in JQuery

var option = new Option(optionData.Text, optionData.Value);
if ($.browser.msie) {
dropdownList.add(option);
}
else {
dropdownList.add(option, null);
}

How to rotate table (turn rows into columns) in MS SQL

Using PIVOT and UNPIVOT
http://msdn.microsoft.com/en-us/library/ms177410.aspx

ASP.NET events sequence: Page load event in master page is called after content page load event

Page load event in master page is called after content page load event

the master page is merged into the content page and treated as a control in the content page

Events in ASP.NET Master and Content Pages
http://msdn.microsoft.com/en-us/library/dct97kc3.aspx

Application pool recycling default setting in IIS 7 causes invalid state error in ASP.NET


Default setting is 1740 minutes, every 29 hours application poop restart.
If happen in rush hour, will cause a lot of connection are cut off.
Should change this one to third option:  Specific time.

IIS manager -> application pool-> Cycling setting 


How to create an ActionButton in ASP.NET/MVC?

In Model of MVC: you create a html helper by static class

public static class Action
{
public static string ActionButton(this HtmlHelper helper, string Url, string Text)
{
return string.Format(@"<input type='button' onclick=""javacript: window.location='{1}';"" value='{0}' />", Text, Url);
}
}

In html source view of ASPX file:
<%=Html.ActionButton(Page.ResolveUrl("~/ControllerName/ActionName"),"buttonText") %>

Tuesday, January 4, 2011

Difference between name and id in html tag

bottom line:
- Form elements must have a name if you want them to be submitted
- Use id only if you need to refer to an element by getElementById
- Many programmers put the same name and ID on form elements

When Netscape created JavaScript, they used "name" to identify
elements. MS built IE to copy Netscape, so also supported "name".

However, the HTML spec decided to use id to identify elements but keep
name for backwards compatibility. Name still applies to form elements
and lots of others (e.g. name is mandatory on PARAM elements). MS seem
to hate ever removing functionality, so they continue to support name
as if it was ID.

Many programmers put the same name and ID on form elements. This isn't
required, but may be helpful if you intend to reference the element
using both the forms.elements collection and getElementById.

Name
"When a form is submitted for processing, some controls have
their name paired with their current value and these pairs
are submitted with the form. Those controls for which
name/value pairs are submitted are called successful
controls."

Make Client IDs easy for Javascript in ASP.NET 4 Web Forms and VS 2010

Cleaner HTML Markup with ASP.NET 4 Web Forms - Client IDs (VS 2010 and .NET 4.0 Series)

Is ASP.net MVC a copy of Ruby on Rails?

- MVC is the Pattern name,  which follow by two frameworks
Model–View–Controller
- ASP.NET MVC 1.0 release date: 13 March 2009
- Ruby on Rails 1.0 release date: December 13, 2005

Other than design pattern,  this two are totally different animals.
As a established developer, you cannot transfer one framework to another very easily.

ScottGu's “Best of 2010” Posts


ASP.NET MVC

We shipped ASP.NET MVC 2 in March, and started previewing ASP.NET MVC 3 this summer.  ASP.NET MVC 3 will RTM in less than 2 weeks from today:

Monday, January 3, 2011

Number only validation in Textbox of ASP.NET by Regular Expressionvalidator

<asp:TextBox ID="TextBox1" runat="server"/>
<asp:RegularExpressionValidator ID="RegularExpressionValidator1" runat="server" ControlToValidate="TextBox1"
ErrorMessage="Number Only" ValidationExpression="^\d+$" />