Dec 4, 2009

Session Timeout Notification


Sometimes you may need to get notification if session of an Asp.net application get expired. For the basics of session management you can find my post here.

In all of the above cases, the session supposed to be timeout. It will handle by the asp.net runtime, which we can set in the web.config <sessionState timeout="1" />. Default timeout is 20 mins. Which means after 20 min session will become abandon and if you are not correctly handle it will leads to system crash. What general recommendation is, always check null of the session item that you’re going to refer. But in most user oriented application, we should notify the user that ,"Hello your current session has expired, what do you want to do?"
 
How to achieve this?
 

Oct 26, 2009

Future IT Practitioner : Ethics

Ethics in a profession will describe professional behavior among professionals. Further it will describes an individual’s behavior towards to his or her profession. Because misbehaving of few professional will disrupt the profession as whole. Hence professional bodies like BCS, IEEE defines “Code of Ethics” for their members.

In both “Code of Ethics” we can see common areas they tried to address.
  1. Public Safety
    We have responsibilities to protect the public in many ways. Special due care should be paid for designing, developing and maintaining critical systems.
    Therac -25  and London ambulance service failure  are two incidents that come into play.
  2. Avoid Discriminations
    This is a wide area to talk about but, basically we should not less favorable because of race, skin colour, religion etc.
  3. Professional Obligations
    Here it addresses, our competency level, integrity with other professionals ,avoiding conflict of interest etc.
  4. Legal Obligations
    This has wide scope that will differ from country to country. But we should know legal legislations for the country that we are going work with. Examples for common legislations of misusing computers, regarding confidential information, discriminations , consumer protection etc.

Code of ethics of
+ BCS http://www.bcs.org/server.php?show=nav.6030
+ IEEE http://www.ieee.org/portal/pages/iportals/aboutus/ethics/code.html

Copyrights © Kelum Ganegoda 2009
Related Posts: Future IT Practitioner

Oct 17, 2009

Future IT Practitioner

It is crystal clear that our current society became information society. Throughout the world organizations and individuals are now starving for information. This happens purely because of following factors,
  • Expansion of IT
    IT is no longer an isolated unit in an organization. It is link into other units with helping out for their work.
  • Evaluation of technologies
    Inevitably Internet, ERPs, SOA, SAAS (Software as a service) etc.
By considering all the facts, IT became truly global profession. All IT practitioners across the world have contributed and contributing to this global profession.

Even though, IT is global profession it has no limitations as a profession like other prominent professions, Medical practicing, Lawyers, Accountants etc. What I’m trying to say is, for an example, no control of entry for IT, like, doctors or engineers. Although this type of control of entry is necessary but it’s too late to implement at the moment. We know, UK and USA had put enormous efforts for this, unfortunately those were not work out.

On the other side, if we put such control of entry, sometime it wouldn’t get as much expansion as the present.

Since you and me contributing to this global profession, as professionals, we have sort of responsibilities. May be, those responsibilities will become practices throughout the professionalism. Mainly we can categorize them into 2.
  1. Ethical practices
  2. Competency
Generally ethical practices are enforced by a professional body, like BCS, IEEE etc, to its members. For this global profession, I think, all practitioners should adhere to general ethical practices. Professional ethics, sometimes, will help to sharpen up our competency level.

Copyrights © Kelum Ganeogda 2009

Oct 3, 2009

Update Progress with AJAX UpdatePanel

In this post I will demonstrate how to create update progress with UpdatePanel, a similar one that we can see in our gmail, like following,


Following key things to be addressed.
  1. It should be on top-center of the page
  2. It should be on top all other HTML controls
  3. When scrolling it should be placed on relative position of the current scroll position.
To achieve this we can use many alternatives but I would use a simple approach.
In addition to the UpdatePanel, I will use </div>, CSS style and javaScript.

Here we go.
  1. Add a div tag within body element.
    <div class="divProg" id="divProg"></div>
    Note that id and class attributes are necessary.

  2. Add following css class to the web page or style sheet file. Keep in mind, without position: absolute; z-index: 10; css properties this won’t work as we expected.
    .divProg
    {
     position: absolute;
     left: 0px;
     top: 0px;
     width: 100px;
     height: 0px;
     z-index: 10;
     border: 1px none #000000;
     visibility: hidden;
     background-color: #FFF1A8;
     font-weight: bold;
     padding: 5px 10px 5px 10px;
    }

  3. Now we want to display div on top-center of the screen as well as move its top position relative to the current scroll position. To address this we will creates following 3 javascript functions.
    To get current Y position of scroll,
    function getScroll_Y() 
    {
            return document.documentElement.scrollTop;  
    }
    To set current top position of div,
    function setDivTop() 
    {
    
            if (document.getElementById("divProg") != null) {
                theDiv= document.getElementById("divProg");
            }
            else {
                return;
            }
            theDiv.style.top = getScroll_Y() + "px";
    }
    Write a function to toggle display for the div.
    function displayDiv(display) 
    {
        if (document.getElementById("divProg") != null) {
            theDiv = document.getElementById("divProg");
        }
        else {
            return;
        }
    
        if (display) {
            var width = document.body.offsetWidth;
            var height = document.body.offsetHeight;
            if (!width) {
                width = window.innerWidth;
                height = window.innerHeight;
    
                if (!width) {
                    width = screen.width;
                    height = screen.height;
                }
            }
            // To center the div, we need to deduct its half of
            // width from half of screen width. So we set div width =100
            // in css, so that deduct by 50
            theDiv.style.left = width / 2 - 50;
            theDiv.style.top = getScroll_Y();
            theDiv.style.height = 25;
            theDiv.innerText = 'Working...';
            theDiv.style.visibility = 'visible';
    
        }
        else {
            theDiv.style.visibility = 'hidden';
        }
    }


  4. Now we want to handle request start and request end events. we will be able to use following code with assist of ajax extension library.

    // Requests Events
    // ============================================
    var prm = Sys.WebForms.PageRequestManager.getInstance();
    
    prm.add_initializeRequest(InitializeRequest);
    prm.add_endRequest(EndRequest);
    
    function InitializeRequest(sender, args) {
        if (prm.get_isInAsyncPostBack()) {
            args.set_cancel(true);
        }
        displayDiv(true);
      
    
    }
    function EndRequest(sender, args) {
        if (args.get_error()) {
            alert(args.get_error().message);
            args.set_errorHandled(true);
    
        }
        displayDiv(false);
    }
    
    //===============================================

  5. Set page's scroll event,
    <body onscroll="setDivTop()">




Download Sample
File Size: 18K

Jul 29, 2009

Be Aware Gmail SMS

You may received an email saying Send & Receive SMS From Your Email !!!

Don't trust that, it's completely fake, but 100% same as GMail logging screen. This will stole your password.

Jun 6, 2009

C# New features

I have move to .net 3.5 and found really cool enhancements in C# language(in VB.Net too).
  • We can create properties like this
    class ProcessData
    {
    public int ID { get; set; }
    public string Name { get; set; }
    public long Memory { get; set; }
    }
    

    Compiler will emits the private variables for properties and nothing diffrent in IL code.

  • Object Initializer
    Lets say we want to populate list of ProcessData class, before C# 3.0 came we have to code like this
    List processList = new List();
    foreach (Process p in Process.GetProcesses())
    {
    ProcessData pd = new ProcessData();
    pd.ID = p.Id;
    pd.Name = p.ProcessName;
    pd.Memory = p.WorkingSet64;
    processList.Add(pd);
    }

    Note its IL code,
    IL_001f: ldloc.2
    IL_0020: ldloc.1
    IL_0021: callvirt instance int32 [System]System.Diagnostics.Process::get_Id()
    IL_0026: callvirt instance void NewFeatures.ProcessData::set_ID(int32)
    IL_002b: nop
    IL_002c: ldloc.2
    IL_002d: ldloc.1
    IL_002e: callvirt instance string [System]System.Diagnostics.Process::get_ProcessName()
    IL_0033: callvirt instance void NewFeatures.ProcessData::set_Name(string)
    IL_0038: nop
    IL_0039: ldloc.2
    IL_003a: ldloc.1
    IL_003b: callvirt instance int64 [System]System.Diagnostics.Process::get_WorkingSet64()
    IL_0040: callvirt instance void NewFeatures.ProcessData::set_Memory(int64)
    IL_0045: nop
    IL_0046: ldloc.0
    IL_0047: ldloc.2
    IL_0048: callvirt instance void class [mscorlib]System.Collections.Generic.List`1::Add(!0)
    IL_004d: nop

    Do you belive if I write same code in 3 lines?
    var processList = new List();
    foreach (var p in Process.GetProcesses())
    processList.Add(new ProcessData { ID = p.Id, Name = p.ProcessName, Memory = p.WorkingSet64 });

    Note new ProcessData { ID = p.Id, Name = p.ProcessName, Memory = p.WorkingSet64 } is called object initializer notation.
    But it does same thing and no any drawbacks, like performance degrading etc. Check this IL code, it is same as above IL code.
      IL_001f:  ldloc.2
    IL_0020:  ldloc.1
    IL_0021:  callvirt   instance int32 [System]System.Diagnostics.Process::get_Id()
    IL_0026:  callvirt   instance void NewFeatures.ProcessData::set_ID(int32)
    IL_002b:  nop
    IL_002c:  ldloc.2
    IL_002d:  ldloc.1
    IL_002e:  callvirt   instance string [System]System.Diagnostics.Process::get_ProcessName()
    IL_0033:  callvirt   instance void NewFeatures.ProcessData::set_Name(string)
    IL_0038:  nop
    IL_0039:  ldloc.2
    IL_003a:  ldloc.1
    IL_003b:  callvirt   instance int64 [System]System.Diagnostics.Process::get_WorkingSet64()
    IL_0040:  callvirt   instance void NewFeatures.ProcessData::set_Memory(int64)
    IL_0045:  nop
    IL_0046:  ldloc.2
    IL_0047:  callvirt   instance void class [mscorlib]System.Collections.Generic.List`1::Add(!0)
    IL_004c:  nop

    We can see several advantages in the latter.
    + We can initialize an object within just one instruction.
    + We don’t need to provide a constructor to be able to initialize simple objects.
    + We don’t need several constructors to initialize different properties of objects.


Reference: LINQ in Action, Manning Publications 2008

Mar 13, 2009

Application File Not Valid in XBAP

When you see this error in XBAP application, which means you changed application manifest file from outside. To resolve this
we can use .net tool, which comes with .net SDK, called mage.exe or mageui.exe. More about mage.exe
Frequently used commands to resolve this is mage.exe -u and mage.exe -cc.
Actually this really happened to me, for one user, problem was remain even use mage.exe until he re-install .net runtime.

Mar 5, 2009

How to create Biztalk schema from FOR XML EXPLICIT

It's very straightforward to create Biztalk schema for SQL adapter if we use FOR XML AUTO. But we'll come across that FOR XML AUTO is not enough to get data from SQL, so that we use FOR XML EXPLICIT. In this case we have to follow some additional things to get biztalk schema generated properly. I''l go step-by-step with an example. This situation really came to me that's why I motivated to do this post.

  1. Assume my SP,BIZTK_GetPPS300Attributes @pono, will generates required XML data set with FOR XML EXPLICIT.

  2. Open Visual Studio and switch to Biztalk Explorer.
    Create a Receive Port.
    Create a Receive Location for that port and set following properties

    Set Address(URI) property as following

    Value of Document Root Element Name will be Root Element of schema.
    Document Target Namespace will be schema's target namespace
    For this example SQL Command will be exe BIZTK_GetPPS300Attributes 12345

  3. Create a send port and set following properties

  4. Enable Receive Location and start Send port by right clicking on them.

  5. Now receive location will execute SQL command that you set and save the XML file in the location where you set in step 3. At this stage we dont want to validate against schema so that we set send/receive pipe line to PassThru.

  6. Go to your biztalk project, select Generated Schemas option from Add Generated Items dialog box, give the XML file just you created.

  7. Cool. Biztalk schema is properly generated.

Feb 23, 2009

Asp.NET Session Management

In Asp.net, there are 4 methods available for session management.

  1. InProc
    This is the default mode used in ASP.net. Session state will be stored on same ASP.net
    process and perform best. If IIS restarts session state will lost.
    Use when, Session data is not critical and Web application hosted in a single server.

  2. StateServer
    This is, Windows NT service called ASPState, used to store session state out of ASP.net process.


    To enable this , Start the service, run command
    net start aspnet_state 

    In the web.config add or change following element

    <configuration>
    <system.web>
    <sessionState mode="StateServer"
    stateConnectionString="tcpip=servername:portno"
    cookieless="false"
    timeout="20"/>
    </system.web>
    </configuration>

    By default stateConnectionString is 127.0.0.1:42424

  3. SqlServer
    Session state will store in SQL server so that higher level of reliability. This is best for clustered/web farm environment although performance isn’t as fast as former 2 modes.
    You have to do,
    On the computer SQL server running, run InstallSqlState.sql
    to create necessary tables and sps to manage session state. This file can be found,by default, %SystemRoot%\Microsoft.NET\Framework\v2.x.xxxx\
    Note: for .net 3.5 you have to find this file from .net 2.0 path.

    In web.config,
    <sessionState
    mode="SQLServer"
    sqlConnectionString="Integrated Security=SSPI;data source=sqlserver;"
    sqlCommandTimeout="10" />
    </system.web>
    </configuration>

    You don’t have to explicitly put Initial Catalog for sqlConnectionString attribute.

  4. Custom
    This mode is very rarely used unless you want to store session state on custom data store. To implement custom mode you can find more information on MSDN.

Feb 11, 2009

Kaspersky Web Site Hacked With SQL Injection

The hacker, known as Unu, hacked Kaspersky web site on Feb. 7, 2009  via a simple SQL injection attack. more ...

As I know that site was built using php & mysql.

In ASP.Net, such SQL injection attack can avoid if we follow standard guidelines. As a developer keep followings in mind.

  1. Always, don’t believe in what user has input.
  2. If executes SQL command from a page, don’t use concatenated SQL commands. Always use respective DbParameter class to build a command string.
    Following example using  SQLParamerter.
    Incorrect
    “SELECT cusid,cusname  FROM customer WHERE cusid= “ + userinput “
    Correct
    “SELECT cusid,cusname  FROM customer WHERE cusid= @userinput “

  3. In the production version of your web application, turn off tracing and avoid <customErrors mode="Off"/> setting in web.config.
  4. Don’t give error messages that intruder can guess information about your database.