johnllao

June 30, 2008

Events and delegated using Reflection

Filed under: Uncategorized — johnllao @ 9:52 am

This code allows us to get the reference of a method using Reflection and assign it to an event.

 

Delegate d;
// This code gets the reference of the OnSubmit method from the control 
// object. The OnSubmit method must be implementing the Click
// Handler
d = Delegate.CreateDelegate(btnSubmit.GetType()
    .GetEvent("Click").EventHandlerType, control, "OnSubmit");
// This code assigns the Click handler to the Click event of the button
btnSubmit.Click += (EventHandler) d;

June 29, 2008

Tools

Filed under: Uncategorized — johnllao @ 4:17 pm

Usefult tools and libraries for development

Tigris.Org – Home of the famous open source subversion.

Fiddler – Web debugging tools.

IIS Tools – Tools for debugging / monitoring IIS.

SysInternals – Tools for monitoring process

FileHelpers – Strong type your flat file (fixed or delimited) simply describing a class that maps to each record and later read/write your file as an strong typed .NET array

June 24, 2008

Improving .NET Application Performance.

Filed under: Uncategorized — johnllao @ 10:43 pm

Very nice MSDN article on guide to improving .NET Application Performance.

http://msdn.microsoft.com/en-us/library/ms998530.aspx

happy reading

FindControl in UltraWebGrid

Filed under: ASP.NET, Infragistics — johnllao @ 11:11 am

Most of us find it difficult to implement a similar FindControl functionality from GridView in UltraWebGrid using the TemplatedColum. Here is a way to do it.

 

/// <summary>
/// Initalize grid row
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
protected void _Grid_InitializeRow(object sender, Infragistics.WebUI.UltraWebGrid.RowEventArgs e)
{
    UltraWebGrid grid = sender as UltraWebGrid;
    if(grid == null)
        return;

    TemplatedColumn col = (TemplatedColumn) grid.Columns[0];
    CellItem item = (CellItem) col.CellItems[e.Row.Index];
    RadioButton optSelect = item.FindControl("optSelect") as RadioButton;
    if (optSelect != null)
    {
        optSelect.Attributes["onclick"] =
            string.Format("alert('Row# : {0}')", e.Row.Index);
    }
}

Grid RadioButton

Filed under: Uncategorized — johnllao @ 10:34 am

Most of us will find that placing a RadioButton in a grid will not work as it used to be, all the options may be selected and you cannot implement grouping.

I have found a very nice article in the code project where the author developed / extended the radio button control to function like this. I cannot find the article again however I will just paste the code here just for reference.

 

/// <summary>
/// GroupRadioButton control is a standard radio-button with the extended 
/// abilities to be used in groups.
/// </summary>
/// <remarks>
/// Standard <see cref="System.Web.UI.WebControls.RadioButton"/> controls 
/// cannot be grouped when are placed at the different rows of the DataGrid, 
/// DataList, Repeater, etc. controls. 
/// 
/// The "name" attribute of the radio button HTML control that is rendered 
/// at the web form after RadioButton control has been executed is depend 
/// on the UniqueID of the RadioButton. So for the different rows of the 
/// DataGrid/DataList/Repeater these attributes are different and radio 
/// buttons do not belong to the same group.
/// </remarks>    
[ToolboxData("<{0}:MyGroupRadioButton runat=server></{0}:MyGroupRadioButton >")]
public class MyGroupRadioButton : RadioButton, IPostBackDataHandler
{
    /// <summary>
    /// 
    /// </summary>
    public MyGroupRadioButton () : base()
    {
    }

    #region Properties

    private string Value
    {
        get
        {
            string val = Attributes["value"];
            if (val == null)
                val = UniqueID;
            else
                val = UniqueID + "_" + val;
            return val;
        }
    }

    #endregion

    #region Rendering

    protected override void Render(HtmlTextWriter output)
    {
        RenderInputTag(output);
    }

    private void RenderInputTag(HtmlTextWriter htw)
    {
        htw.AddAttribute(HtmlTextWriterAttribute.Id, ClientID);
        htw.AddAttribute(HtmlTextWriterAttribute.Type, "radio");
        htw.AddAttribute(HtmlTextWriterAttribute.Name, GroupName);
        htw.AddAttribute(HtmlTextWriterAttribute.Value, Value);
        if (Checked)
            htw.AddAttribute(HtmlTextWriterAttribute.Checked, "checked");
        if (!Enabled)
            htw.AddAttribute(HtmlTextWriterAttribute.Disabled, "disabled");

        string onClick = Attributes["onclick"];
        if (AutoPostBack)
        {
            if (onClick != null)
                onClick = String.Empty;
            //onClick += Page.GetPostBackClientEvent(this, String.Empty);
            onClick +=
            this.Page.ClientScript.GetPostBackEventReference(
                this, string.Empty
            );
            htw.AddAttribute(HtmlTextWriterAttribute.Onclick, onClick);
            htw.AddAttribute("language", "javascript");
        }
        else
        {
            if (onClick != null)
                htw.AddAttribute(HtmlTextWriterAttribute.Onclick, onClick);
        }

        if (AccessKey.Length > 0)
            htw.AddAttribute(HtmlTextWriterAttribute.Accesskey, AccessKey);
        if (TabIndex != 0)
            htw.AddAttribute(HtmlTextWriterAttribute.Tabindex,
                TabIndex.ToString(NumberFormatInfo.InvariantInfo));
        htw.RenderBeginTag(HtmlTextWriterTag.Input);
        htw.RenderEndTag();
    }

    #endregion

    #region IPostBackDataHandler Members

    void IPostBackDataHandler.RaisePostDataChangedEvent()
    {
        OnCheckedChanged(EventArgs.Empty);
    }

    bool IPostBackDataHandler.LoadPostData(string postDataKey,
        System.Collections.Specialized.NameValueCollection postCollection)
    {
        bool result = false;
        string value = postCollection[GroupName];
        if ((value != null) && (value == Value))
        {
            if (!Checked)
            {
                Checked = true;
                result = true;
            }
        }
        else
        {
            if (Checked)
                Checked = false;
        }
        return result;
    }

    #endregion
}

ASP.NET Paging using the PagedDataSource

Filed under: Uncategorized — johnllao @ 10:05 am

Mostly happens in an ASP.NET developers life is to develop paging in the Grid. It has been a popular way to implement paging in the database server itself. But how if you cannot change the database object, so you have no choice but to implement paging in your web page alone.

Currently the ASP.NET GridView is already equiped with this functionality however this feature if for the Grid control alone. We have a PagedDataSource which you can implement this easily. Please see code below.

private PagedDataSource _PagedDataSource;
/// <summary>
/// Gets the datasource bound to the grid
/// </summary>
/// <returns></returns>
protected PagedDataSource GetGridDataSource(int page)
{
    if (_PagedDataSource == null)
    {
        _PagedDataSource = new PagedDataSource();
        _PagedDataSource.AllowPaging = true;
        _PagedDataSource.PageSize = 20;
        _PagedDataSource.DataSource = GetCustomerOrders();
    }

    _PagedDataSource.CurrentPageIndex = page;
    return _PagedDataSource;
}

/// <summary>
/// Page Load
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
protected void Page_Load(object sender, EventArgs e)
{
    grdOrders.DataSource = GetGridDataSource(1);
    grdOrders.DataBind();
}

June 19, 2008

Useful Command Tools

Filed under: Uncategorized — johnllao @ 9:52 am

Useful Command Tools

1. NetStat – Displays protocol statistics and current TCP/IP network connections.

NETSTAT [-a] [-b] [-e] [-n] [-o] [-p proto] [-r] [-s] [-v] [interval]

  -a            Displays all connections and listening ports.
  -b            Displays the executable involved in creating each connection or
                listening port. In some cases well-known executables host
                multiple independent components, and in these cases the
                sequence of components involved in creating the connection
                or listening port is displayed. In this case the executable
                name is in [] at the bottom, on top is the component it called,
                and so forth until TCP/IP was reached. Note that this option
                can be time-consuming and will fail unless you have sufficient
                permissions.
  -e            Displays Ethernet statistics. This may be combined with the -s
                option.
  -n            Displays addresses and port numbers in numerical form.
  -o            Displays the owning process ID associated with each connection.
  -p proto      Shows connections for the protocol specified by proto; proto
                may be any of: TCP, UDP, TCPv6, or UDPv6.  If used with the -s
                option to display per-protocol statistics, proto may be any of:
                IP, IPv6, ICMP, ICMPv6, TCP, TCPv6, UDP, or UDPv6.
  -r            Displays the routing table.
  -s            Displays per-protocol statistics.  By default, statistics are
                shown for IP, IPv6, ICMP, ICMPv6, TCP, TCPv6, UDP, and UDPv6;
                the -p option may be used to specify a subset of the default.
  -v            When used in conjunction with -b, will display sequence of
                components involved in creating the connection or listening
                port for all executables.
  interval      Redisplays selected statistics, pausing interval seconds
                between each display.  Press CTRL+C to stop redisplaying
                statistics.  If omitted, netstat will print the current
                configuration information once.

 2. NBTStat – Displays protocol statistics and current TCP/IP connections using NBT (NetBIOS over TCP/IP).

 

NBTSTAT [ [-a RemoteName] [-A IP address] [-c] [-n]
        [-r] [-R] [-RR] [-s] [-S] [interval] ]

  -a   (adapter status) Lists the remote machine's name table given its name
  -A   (Adapter status) Lists the remote machine's name table given its
                        IP address.
  -c   (cache)          Lists NBT's cache of remote [machine] names and their IP addresses
  -n   (names)          Lists local NetBIOS names.
  -r   (resolved)       Lists names resolved by broadcast and via WINS
  -R   (Reload)         Purges and reloads the remote cache name table
  -S   (Sessions)       Lists sessions table with the destination IP addresses
  -s   (sessions)       Lists sessions table converting destination IP
                        addresses to computer NETBIOS names.
  -RR  (ReleaseRefresh) Sends Name Release packets to WINS and then, starts Refresh

  RemoteName   Remote host machine name.
  IP address   Dotted decimal representation of the IP address.
  interval     Redisplays selected statistics, pausing interval seconds
               between each display. Press Ctrl+C to stop redisplaying
               statistics.

3. TaskList – This command line tool displays a list of application(s) and associated task(s)/process(es) currently running on either a local or remote system.

TASKLIST [/S system [/U username [/P [password]]]]
         [/M [module] | /SVC | /V] [/FI filter] [/FO format] [/NH]

Parameter List:
   /S     system           Specifies the remote system to connect to.

   /U     [domain\]user    Specifies the user context under which
                           the command should execute.

   /P     [password]       Specifies the password for the given
                           user context. Prompts for input if omitted.

   /M     [module]         Lists all tasks that have DLL modules loaded
                           in them that match the given pattern name.
                           If the module name is not specified,
                           displays all modules loaded by each task.

   /SVC                    Displays services in each process.

   /V                      Specifies that the verbose information
                           is to be displayed.

   /FI    filter           Displays a set of tasks that match a
                           given criteria specified by the filter.

   /FO    format           Specifies the output format.
                           Valid values: "TABLE", "LIST", "CSV".

   /NH                     Specifies that the "Column Header" should
                           not be displayed in the output.
                           Valid only for "TABLE" and "CSV" formats.

   /?                      Displays this help/usage.

Filters:
    Filter Name     Valid Operators           Valid Value(s)
    -----------     ---------------           --------------
    STATUS          eq, ne                    RUNNING | NOT RESPONDING
    IMAGENAME       eq, ne                    Image name
    PID             eq, ne, gt, lt, ge, le    PID value
    SESSION         eq, ne, gt, lt, ge, le    Session number
    SESSIONNAME     eq, ne                    Session name
    CPUTIME         eq, ne, gt, lt, ge, le    CPU time in the format
                                              of hh:mm:ss.
                                              hh - hours,
                                              mm - minutes, ss - seconds
    MEMUSAGE        eq, ne, gt, lt, ge, le    Memory usage in KB
    USERNAME        eq, ne                    User name in [domain\]user
                                              format
    SERVICES        eq, ne                    Service name
    WINDOWTITLE     eq, ne                    Window title
    MODULES         eq, ne                    DLL name

Examples:
    TASKLIST
    TASKLIST /M
    TASKLIST /V
    TASKLIST /SVC
    TASKLIST /M wbem*
    TASKLIST /S system /FO LIST
    TASKLIST /S system /U domain\username /FO CSV /NH
    TASKLIST /S system /U username /P password /FO TABLE /NH
    TASKLIST /FI "USERNAME ne NT AUTHORITY\SYSTEM" /FI "STATUS eq running"

4. TaskKill – This command line tool can be used to end one or more processes. Processes can be killed by the process id or image name.

TASKKILL [/S system [/U username [/P [password]]]]
         { [/FI filter] [/PID processid | /IM imagename] } [/F] [/T]

Description:
    This command line tool can be used to end one or more processes.
    Processes can be killed by the process id or image name.

Parameter List:
    /S    system           Specifies the remote system to connect to.

    /U    [domain\]user    Specifies the user context under which
                           the command should execute.

    /P    [password]       Specifies the password for the given
                           user context. Prompts for input if omitted.

    /F                     Specifies to forcefully terminate
                           process(es).

    /FI   filter           Displays a set of tasks that match a
                           given criteria specified by the filter.

    /PID  process id       Specifies the PID of the process that
                           has to be terminated.

    /IM   image name       Specifies the image name of the process
                           that has to be terminated. Wildcard '*'
                           can be used to specify all image names.

    /T                     Tree kill: terminates the specified process
                           and any child processes which were started by it.

    /?                     Displays this help/usage.

Filters:
    Filter Name   Valid Operators           Valid Value(s)
    -----------   ---------------           --------------
    STATUS        eq, ne                    RUNNING | NOT RESPONDING
    IMAGENAME     eq, ne                    Image name
    PID           eq, ne, gt, lt, ge, le    PID value
    SESSION       eq, ne, gt, lt, ge, le    Session number.
    CPUTIME       eq, ne, gt, lt, ge, le    CPU time in the format
                                            of hh:mm:ss.
                                            hh - hours,
                                            mm - minutes, ss - seconds
    MEMUSAGE      eq, ne, gt, lt, ge, le    Memory usage in KB
    USERNAME      eq, ne                    User name in [domain\]user
                                            format
    MODULES       eq, ne                    DLL name
    SERVICES      eq, ne                    Service name
    WINDOWTITLE   eq, ne                    Window title

NOTE: Wildcard '*' for the /IM switch is accepted only with filters.

NOTE: Termination of remote processes will always be done forcefully
      irrespective of whether /F option is specified or not.

Examples:
    TASKKILL /S system /F /IM notepad.exe /T
    TASKKILL /PID 1230 /PID 1241 /PID 1253 /T
    TASKKILL /F /IM notepad.exe /IM mspaint.exe
    TASKKILL /F /FI "PID ge 1000" /FI "WINDOWTITLE ne untitle*"
    TASKKILL /F /FI "USERNAME eq NT AUTHORITY\SYSTEM" /IM notepad.exe
    TASKKILL /S system /U domain\username /FI "USERNAME ne NT*" /IM *
    TASKKILL /S system /U username /P password /FI "IMAGENAME eq note*"

June 11, 2008

MSDN Magazine web links

Filed under: Uncategorized — johnllao @ 12:37 am

I just listed below some interesting links I’ve found from the MSDN Magazine site. I decided to post it my blog so I wont forget about this links and I can visit them everytime I want. It’s already 12.30am here in Singapore so I don’t have to read them now, I hope I will have time tomorrow.

Updatepanel Tips and Tricks

http://msdn.microsoft.com/en-us/magazine/cc163413.aspx

Canceling Server Task with ASP.NET AJAX

http://msdn.microsoft.com/en-us/magazine/cc163380.aspx

AJAX Application Architecture

http://msdn.microsoft.com/en-us/magazine/cc163363.aspx

http://msdn.microsoft.com/en-us/magazine/cc163347.aspx

Scriptmanagers

http://msdn.microsoft.com/en-us/magazine/cc163354.aspx

Inside MS AJAX Library

http://msdn.microsoft.com/en-us/magazine/cc163300.aspx

Scaling Strategies in ASP.NET

http://msdn.microsoft.com/en-us/magazine/cc500561.aspx

AJAX Design Patterns

http://blogs.msdn.com/msdnmagazine/archive/2008/06/06/8578509.aspx

June 7, 2008

Calling a Web Page or a Web Service Method using ASP.NET AJAX

Filed under: ASP.NET — Tags: , , — johnllao @ 2:27 pm

Most of the time when developing a web application we will encounter scenarios wherein we need to call a page function or a web service function from client script (e.g. javascript). Thought ASP.NET AJAX has created a PageMethods to do this task, however studying the html that it generates we will find that it creates complex markup to our page which may add to the size of html being rendered and transmitted into the network. Here is an alternative example to do this.

Javascript:

<form id="_default" runat="server">
<asp:ScriptManager ID="_ScriptManager" runat="server"></asp:ScriptManager>
<script type="text/javascript">
//<!--
function ShowServerDateWS()
{
Sys.Net.WebServiceProxy.invoke('CommonUtil.asmx',
    'GetServerDate', true, {},function (result, args) {
    alert(result);
    },function (error) {
    alert('sorry error happens...');
    },
    '',0
);
}

function ShowServerDateWP()
{
Sys.Net.WebServiceProxy.invoke('CommonFunctions.aspx',
    'GetServerDate', true, {},function (result, args) {
    alert(result);
    },function (error) {
    alert('sorry error happens...');
    },
    '',0
);
}
//-->
</script>
<input type="button" id="btnShowServerDateWs" value="Show Server Date from Web Service" onclick="javascript:ShowServerDateWS()" /><br />
<input type="button" id="btnShowServerDateWp" value="Show Server Date from Web Page" onclick="javascript:ShowServerDateWP()" /><br />
</form>

Web Page:

[System.Web.Services.WebService()]
public partial class CommonFunctions : System.Web.UI.Page
{
    [System.Web.Services.WebMethod()]
    [System.Web.Script.Services.ScriptMethod(UseHttpGet = true)]
    public static string GetServerDate()
    {
        return DateTime.Now.ToString("dd-MMM-yyyy");
    }
}

Web Service:

[System.Web.Services.WebService()]
[System.Web.Script.Services.ScriptService]
public class CommonUtil : System.Web.Services.WebService
{
    [System.Web.Services.WebMethod()]
    [System.Web.Script.Services.ScriptMethod(UseHttpGet = true)]
    public string GetServerDate()
    {
        return DateTime.Now.ToString("dd-MMM-yyyy");
    }
}

Cheers!

June 6, 2008

Displaying a progress indicator during DemandLoad of the UltraWebTree

Filed under: ASP.NET — Tags: , , — johnllao @ 11:42 am

Declare InitializeTree and DemandLoad event handlers in the ClientSideEvents of the UltraWebTree.

<ClientSideEvents InitializeTree="func_initializeTree" DemandLoad="func_demandLoad" />

The DemandLoad event handler will respond when the user click on a node and process an ajax postback to retrieve thechild nodes. In this handler you can display any progress indicator message.

The InitializeTree event handler will act like the callback, this is assumed because the UltraWebTree does not have any AfterDemandLoad event. In this handler you can hide the progress indicator message.

 

var _currentNodeId = '';
var _currentNodeText = '';

function func_initializeTree(treeId)
{
    var tree;
    tree = igtree_getTreeById(treeId);
    if(_currentNodeId.length > 0 && _currentNodeText.length > 0)
    {
        var node = igtree_getNodeById(_currentNodeId);
        node.setText(_currentNodeText);
    }
    _currentNodeId = '';
    _currentNodeText = '';
}

function func_demandLoad(treeId, nodeId)
{
    var tree = igtree_getTreeById(treeId);
    var node = igtree_getNodeById(nodeId);
    _currentNodeId = nodeId;
    _currentNodeText = node.getText();
    node.setText(_currentNodeText + ' [Loading...]');
}
Older Posts »

Create a free website or blog at WordPress.com.