learned/learning/to learn RSS 2.0
# Monday, November 16, 2009

 I was trying to add AJAX Control Toolkit to my Toolbox, for some reason Visual Studio was crashing. I found a solution for it, see this works out for you – start Visual Studio in safe mode (go to Visual Studio’s command prompt and execute ‘devenv /safemode’) and then try to add items to your toolbox, I was able to do it! There might be a better solution for this, please let me know if there is one.

Monday, November 16, 2009 3:04:38 PM (GMT Standard Time, UTC+00:00)  #    Comments [0] -
.NET | Solutions
# Saturday, November 14, 2009

Initially, I developed this deals alert service for my personal use and later on thought it might be useful for others too, so I extended it accordingly and added it here. This service basically grabs RSS feeds from deals sites (listed on the deals alert page of my site) and checks for the keyword(s) that are added, and if it finds a match, sends email at the time mentioned on the page. This service performs properly only if the keyword(s) are specific, because it is  just using some ‘exact’ and ‘like’ string searches. I might be improvising this by using dictionary or thesaurus in the future.  You can enter multiple keywords (separated by spaces) related to a single product, and only if all the words are present on the deal title, alert email will be sent. As I’m just using simple search here, the deal may not be related to the product you are looking. For eg., say suppose you add an alert for ‘card reader’ and if there is any deal for a laptop with ‘card reader’, my service is going to grab this deal too, because this service is not as intelligent as you are :). So, in this case it is better to add price limit too.

 

I have added this service without any commercial intention, so do not worry about your emailids, I won’t trade them to advertisers, and moreover you can unsubscribe from this service or modify the added keywords at any time by clicking ‘Unsubscribe’ link on the email that will be sent to you after adding an alert.

 

After writing this service I understood how difficult it is come up with search algorithms, hats off to Google and other search engines. Implementing ‘exact’ keyword search was easy whereas ‘like’ search was very difficult.  For eg., I added ‘backpack’ as keyword, the service was bringing all the deals having ‘pack’ on the title, like ‘cd pack’, ‘dvd pack’ etc. I told about this service to couple of my friends, and one of my friends added ‘mens watches’ as keyword, and found out that most of the deals had “men’s” on the title. I recoded to accommodate this scenario, but still it is going to bring deals related to women's watch even if you add men's watch. One last example, keyword ‘all in one printer’, there was a deal with title ‘Calls to any phone in India’, if you see here ‘all’ is in ‘calls’, ‘in’ is in ‘India’ and ‘one’ is in ‘phone’. I can keep listing out examples on this service's ability/disability. As a developer, I have done my testing part (developer's test cases are always subset of testers' test cases) to an extent, it is yours now...you are my testers!

 

If you have any idea or thoughts to improvise this service, please send your comments. Here is the link.

Saturday, November 14, 2009 3:01:34 PM (GMT Standard Time, UTC+00:00)  #    Comments [1] -
Miscellaneous
# Thursday, November 12, 2009

This program prevents your system from getting locked even if it is left idle for time greater than your screen saver time. It basically presses ‘down’ arrow key every minute.

 

Create a Windows Forms Application and add a timer to the form.

 

public Form1()

{

    InitializeComponent();

    StartAction();

}

 

private void StartAction()

{

    // the timer is started and the form is minimized

    // set the timer interval as per your needs. I have set it to be 60000 milliseconds = 1 min

    timer_keypress.Enabled = true;

    this.WindowState = FormWindowState.Minimized;

    this.ShowInTaskbar = false;

}

 

 

To add the application to your system tray when minimized, add a notify icon from your toolbox to the forms and set properties appropriately. I chose an icon and changed the text property. By default this form will be in minimized state, as I have added code to do so in my StartAction function.

 

Add context menu from your toolbox to show menu when the system tray icon is right clicked. Right click contextMenuStrip and choose Edit items to add your menu items. Double click on the menu item to add a handler. I’ve added ‘Exit’ menu. Set your notify icon’s contextmenustrip property.

 

private void exitToolStripMenuItem_Click(object sender, EventArgs e)

{

    StopAction();

}

 

private void StopAction()

{

    // the timer is stopped and the form is closed  

    timer_keypress.Enabled = false;

    this.Close();

}

 

// this event will be triggered every minute

private void timer_keypress_Tick(object sender, EventArgs e)

{

    SendKeys.SendWait("{DOWN}");

}

 

There are many ways to do this, I found this one to be easy.


Here is the fileKeyPress.exe (889 KB)
Thursday, November 12, 2009 10:52:51 PM (GMT Standard Time, UTC+00:00)  #    Comments [0] -
.NET
# Friday, November 06, 2009

With <authentication mode="Windows"/> in your application and Anonymous access enabled in IIS, you will see the following results:

 

System.Environment.UserName: Computer Name

Page.User.Identity.Name: Blank

System.Security.Principal.WindowsIdentity.GetCurrent().Name: Computer Name

 

With <authentication mode="Windows"/> in your application, and ‘Anonymous access’ disabled and only ‘Integrated Windows Authentication’ in IIS, you will see the following results:

 

System.Environment.UserName: ASPNET (user account used to run ASP.NET service)

Page.User.Identity.Name: Domain\ Windows Account Name

System.Security.Principal.WindowsIdentity.GetCurrent().Name: Computer Name\ASPNET

 

With <authentication mode="Windows"/> and <identity impersonate ="true"/> in your application, and ‘Anonymous access’ disabled and only ‘Integrated Windows Authentication’ in IIS, you will see the following results:

 

System.Environment.UserName: Windows Account Name

Page.User.Identity.Name: Domain\ Windows Account Name

System.Security.Principal.WindowsIdentity.GetCurrent().Name: Domain\ Windows Account Name


With <authentication mode="Forms"/>:

Request.ServerVariables["LOGON_USER"]: Domain\ Windows Account Name


Friday, November 06, 2009 3:04:37 PM (GMT Standard Time, UTC+00:00)  #    Comments [0] -
.NET
# Thursday, November 05, 2009
Thursday, November 05, 2009 4:57:42 AM (GMT Standard Time, UTC+00:00)  #    Comments [0] -
Softwares
# Friday, October 23, 2009

Solutions for postback problem:
1. Add "<base target = “_self” />" inside <head> tag of the popup.
2. You can use window.open instead of window.showModalDialog.

Solutions for session transfer problem:

1. You can use window.open instead of window.showModalDialog.

2. You can use AJAX modal popup.

 

This seems to be a IE bug (working fine in firefox and chrome), I have this problem if I open the .NET application after opening an instance of IE (say google.com) whereas if I open the former before the latter, things are fine.


Please let me know if anybody has any good solution for this.

Friday, October 23, 2009 12:07:04 PM (GMT Daylight Time, UTC+01:00)  #    Comments [0] -
.NET | Solutions
# Wednesday, September 30, 2009

This article describes how to notify users about session expiration and allow them to renew the session.

Controls that need to be added:
1. A Panel with an OK button.

2. A label with session expiration notification message.

3. An AJAX ModalPopupExtender.

4. A dummy button and set ModalPopupExtender’s TargetControlId as this button.

 

This is how it looks:

 

<cc1:ModalPopupExtender ID="modext_promptmessage" runat="server" BehaviorID="popup_promptmessage"

    PopupControlID="pnl_popup" TargetControlID="btn_dummy">

</cc1:ModalPopupExtender>

<asp:Panel ID="pnl_popup" runat="server" Style="display: none">

    <table cellpadding="0" cellspacing="0" border="0">

        <tr valign="top">

            <th>

                Prompt Message

            </th>

        </tr>

        <tr>

            <td>               

                        <label>Your session is going to expire in 2 minutes. Please click OK to renew it."></label>

<asp:Button ID="btn_ok" runat="server" OnClientClick="ResetSession()" Text="OK" />

            </td>

        </tr>

    </table>

</asp:Panel>

 

My code behind class looks like this:

 

   Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load

     

      ' checks whether session expired

      If Current.Session.Keys.Count = 0 Then

                        Response.Redirect("sessionexpired.aspx", True)

            Exit Sub

      End If

 

' Javascript function PromptSessionExpiration() will be called 2 minutes before session expiration (120000 milliseconds)

      Dim strExpireSessionScript As String = String.Format("setTimeout('PromptSessionExpiration()', {0}); ", (Me.Session.Timeout * 60000) - 120000)

      Me.Page.ClientScript.RegisterClientScriptBlock(Me.GetType(), "expirescript", strExpireSessionScript, True)

 

   End Sub

 

   ''' This click event will renew the session, need not add any code inside it

   Protected Sub btn_ok_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btn_ok.Click 

   End Sub

 

 

My javascript:

 

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

 

    function PromptSessionExpiration() {

              // the function below will be triggered at the 125th second

        setTimeout('CheckSessionStatus()', 125000);

        // show popup

        $find('popup_promptmessage').show();

    }

 

    // handles closing popup

    function ResetSession() {

        $find('popup_promptmessage').hide();

    }

 

    // this function will be called if user doesn’t respond to the prompt message

    // which will redirect to sessionexpired page

    function CheckSessionStatus() {

            window.location = “sessionexpired.aspx”;

    }   

  

 </script>

 

Thanks.

Wednesday, September 30, 2009 7:55:52 PM (GMT Daylight Time, UTC+01:00)  #    Comments [0] -
.NET
# Monday, September 28, 2009

I came across this article on The Hindu magazine, this article clearly tells why Lehman Brothers collapsed? ...and the reason for the eventual economic crisis, a video is also added under resources/videos tab 'The Crisis of Credit Visualized'.

The bursting of the speculative bubble in the U.S. housing market has destroyed billions of dollars in investor wealth across the world, crippled the banking system, expunged close to a million jobs…and India has not been spared either. With banks failing by the day, definitely, these are uncertain times for the financial services industry. While many people who have lost their jobs are faced with permanent shrinkage of their lifestyle, others in the industry are going through the trauma of not knowing if and when their turn would come. Who is to blame?

Flashback to year 2003:

Rohit (name changed to protect identity), a good friend of mine and someone who was officially considered to be a genius with an IQ of 150+, graduated from one of the leading IIMs. Rohit managed to make it into the New York Headquarters of the most sought after firm that had arrived on campus for the first time — Lehman Brothers — a top U.S. Investment Bank (then). On joining, he was assigned to Lehman’s mortgage securities desk that dealt with Collateralised Debt obligations (or CDOs).

Following is an extracted transcript of a chat session I had with Rohit back in 2004:

Me: So man, you must feel like you are on top of the world.

Rohit: Yes dude, the job here is amazing, I get to interact with people around the world, investment managers who want to invest millions of dollars

Me: Great…so tell me something interesting. What’s your job all about?

Rohit: You know there is a great demand for American home loans, which we buy from the U.S. banks. We then convert these into what is called as CDOs (Collateralised Debt Obligations). In plain English, this refers to buying home loans that banks had already issued to customers, cutting them into smaller pieces, packaging the pieces based on return (interest rate), value, tenure (duration of the loans) and selling them to investors across the world after giving it a fancy name, such as “High Grade Structured Credit Enhanced Leverage Fund”.

Me: Wow! I would’ve never guessed that boring home loans could transform into something that sounds so cool!

Rohit: Hahaha…actually we create multiple funds categorised based on the nature of the CDO packages they contain and investors can buy shares in any of these funds (almost like mutual funds…but called Structured Investment Vehicles or SIVs)

Me: Dude, you make your job sound like a meat shop…chopping and packaging. So, in effect when an investor purchases the CDOs (or the fund containing the CDOs), he is expected to receive a share of the monthly EMI paid by the actual guys who have taken the underlying home loans?

Rohit: Exactly, the banks from whom we purchased these home loans send us a monthly cheque, which we in turn distribute to the investors in our funds

Me: Why do the banks sell these home loans to you guys?

Rohit: Because we allow them to keep a significant portion of the interest rate charged on the home loans and we pay them upfront cash, which they can use to issue more home loans. Otherwise home loans go on for 20-30 years and it would take a long time for the bank to recover its money.

Me: And, why does Lehman buy these loans?

Rohit: Because we get a fat commission when we convert the loans into CDOs and sell it to investors.

Me: Who are these investors?

Rohit: They include everyone from pension funds in Japan to Life Insurance companies in Finland.

Me: But tell me, why are these funds so interested in purchasing American home loans?

Rohit: Well, these guys are typically interested in U.S. Govt. bonds (considered to be the safest in the world). But unfortunately, Mr. Alan Greenspan (head of Federal Reserve Bank, similar to RBI in India) has reduced the interest rate to nearly 1 per cent to perk up the economy after the dotcom crash 9/11attacks. This has left many funds looking for alternative investments that can give them higher returns. Home loans are ideal because they offer 4-6 per cent interest rate.

Me: Wait, aren’t home loans more risky than U.S Bonds?

Rohit: We have made home loans less risky now. In fact they have become as safe as U.S Govt. bonds.

Me: What are you saying, man? What if the people who have taken these underlying home loans default? Then the investors would stop getting the EMIs, and their returns would take a hit. Wouldn’t it?

Rohit: Boss, may be some will default, but not definitely more than 2-3 per cent. Moreover, we have convinced AIG (a leading insurance company) to insure our CDOs. This means that even if there were big defaults,the insurance company would compensate the investors.

Me: that’s amazing. What are these insurances called?

Rohit: Credit Default Swaps.

Me: Definitely you guys are the most creative when it comes to naming.

Rohit: Thanks.

Me: And why has this AIG guy insured millions of home loans?

Rohit: See man, the logic is simple. Home prices in the U.S always go up. In fact over the last three years alone they have doubled. So even if someone defaults paying the EMI, the home can be seized and sold for a much higher price. So there is no risk. Insurance companies are actually competing to insure this, because they can earn risk-free premiums.

Me: No wonder investment managers from all over the world want to put money in your CDOs.

*A global financial cobweb started getting built around the American dream of purchasing a home and it rested on the assumption that “home prices will keep rising”. As demand for the CDOs started growing across the global investment community, the investment bankers (like Lehman) who were meant to sell these instruments also started investing a significant portion of their own capital in these. I guess after selling the story to the whole world, they themselves got sold on the seemingly foolproof concept. Gradually the markets for CDOs and Credit Default Swaps started expanding with traders and investors buying and selling these as if they were shares of a company, happily forgetting the underlying people behind these products who took the home loans in the first place and on whose capacity to repay the loans, the safety of these products depended.

As Wall Street firms like Lehman were churning more and more home loans into CDOs and selling them or investing their own money, there was a pressure on the banks to issue more loans so that they can be sold to the Wall Street firms in return for a commission. Slowly banks started lowering the credit quality (qualification criteria) for availing a home loan and aggressively used agents to source new loans. This slippery slope went to such an extent that in 2005, almost anyone in the U.S could buy a home worth $100,000 (45 lakhs INR) or more without income proof, without other assets, without credit history, sometimes even without a proper job. These loans were called NINA — “no income no assets”.

The U.S. housing market went into a classic speculative bubble. Home loans were easy to get, so more and more people were buying houses. The increased demand for houses caused the price to increase. The rising prices created even more demand, as people started to look at homes as investments — investments that never went down in value.

When I touched base with my friend Rohit in late 2005, he was on cloud nine. During the previous one year, he managed to buy a home in Long Island (a posh area near New York City) worth almost a million dollars, and got himself a Mercedes. All this was interesting to hear, but what shocked me was that although he was earning close to $20,000 a month (that is what CEOs in India make) he was not able to save anything because his lifestyle expenses where growing faster than his salary.

Unheeded signals

In late 2006, Mortgage lenders noticed something that they’d almost never seen before. People would choose a house, sign all the mortgage papers, and then default on their very first payment. Although no one could really hear it, that was probably the moment when one of the biggest speculative bubbles in American history popped. Another factor that lead to the burst of the housing bubble was the rise in interest rates from 2004-2006. Many people had taken variable rate home loans that started getting reset to higher rates, which in turn meant higher EMIs that borrowers had not planned for.

The problem was that once property values starting going down, it set off a reverse chain reaction, the opposite of what had been happening in the bubble. As more people defaulted, more houses came on the market. With no buyers, prices went even further down.

In early 2007, as prices began their plunge, alarm bells started going off across mortgage-backed securities desks all over Wall Street. The people on Wall Street, like Rohit, started getting calls from investors about not getting their interest payments that were due. Wall Street firms stopped buying home loans from the local banks. This had a devastating effect on particularly the small banks and finance companies, which had borrowed money from larger banks to issue more home loans thinking they could sell these loans to Wall Street firms like Lehman and make money.

Everyone got into a mad scramble to seize and sell the homes in order to get back at least some of the money. But there were just not enough buyers. The guys who had insured these loans thinking they had near zero risk (e.g. AIG) could not fulfil the unexpectedly huge number of claims. The best part was that since these insurance policies (credit default swaps) could themselves be traded, multiple people had bought and sold them, and it became so tough to even trace who was supposed to compensate for the loss.

The global financial cobweb built around mortgages is on the brink of collapse. Firms, large and small, some young some as old as a 100 years have crumbled as a result of suing each other over the dwindling asset values. Lehman’s India operations, that employed over a thousand staff, is up for sale and many of the employees have been asked to leave. The Indian stock market has crashed almost 50 per cent from its high (and so have markets around the world) as the Wall Street giants sold their investments in the country in an effort to salvage whatever is good in order to make up for the mortgage related loss. Hedge funds, pension funds, insurance companies all over the world have lost billions in investor’s money. Many Indian B-School graduates with PPOs (pre-placement offers) in the financial sector (India and abroad) have either received an annulment or indefinite postponement of joining dates. IT firms that built and maintained software for the U.S. mortgage industry or the related Investment Banks, have shut down their business units, laid-off people or transferred them to other verticals.

Fragile system

For all the hoopla over the sharp and sophisticated people on Wall Street, the current financial crisis has exposed the fragility of the system. Wall Street is blaming the entire episode on people who could not repay their home loans. But the reality seems to point towards the stupidity of people who lent all this money, financial institutions that built fancy derivative packages and in effect facilitated billions in trading and investments in these fragile low quality loans.

The U.S. Govt is planning to grant 700 billion dollars to the Wall Street firms to compensate the financial speculators for the money that they have lost. Isn’t this like rewarding greed and stupidity? The head of a leading Investment Bank has stated, “This is necessary to sustain financial ingenuity. We don’t want to spend this money on ourselves. We just want this money to go into the market so that we can carry on trading complex securities, borrowing and lending money.” (Yeah…right, so that one can act as if nothing had happened without analysing too much into it). The real question is: Who is going to compensate the common investors across the world who have lost their wealth in the resultant market meltdown? (either directly or through pension funds).

After being unreachable for a month now, finally I heard back from my pal, Rohit, saying he is back in India to take a break from the roller coaster ride that he had lived through. After Lehman’s collapse he has lost his job and probably the house that he had bought by taking a hefty loan. I really don’t know whether to feel happy for him, for getting an opportunity to learn a lesson or two from the experience or to feel sad for him for losing his job. May be I’ll get a better sense of things once I meet him next week.

Monday, September 28, 2009 4:01:40 AM (GMT Daylight Time, UTC+01:00)  #    Comments [0] -
Business
# Tuesday, September 15, 2009

This article shows you how to use ASP.NET AJAX PageMethods to perform Create, Read, Update and Delete (CRUD) operations with an HTML table. Here HTML table acts as a light-weight DataGrid.

 

Inorder to make PageMethods work, following things need to be done:

  1. ScriptManager should be added to your ASPX page.
  2. EnablePageMethods property of the ScriptManager should be set to true.
  3. System.Web.Services namespace should be added as reference on your codebehind class.
  4. Page Methods on your code-behind should be decorated with [WebMethod] attribute.

 

First let us start with Read.


As mentioned above, add a ScriptManager and set its 'EnablePageMethods' property to true. Add an HTML button and an onclick handler to it, and then add an HTML table with thead, tbody and tfoot. Since the HTML table will be referenced from javascript, add id to the table and its body. Here, only HTML tags/controls are used because, server side controls cannot be referenced in PageMethods.


Your ASPX page should look something like this.

 

<body>

    <form id="form1" runat="server">   

        <asp:ScriptManager ID="ScriptManager1" runat="server" EnablePageMethods ="true" ></asp:ScriptManager>

        <%--This click event handles loading data from the database--%>

        <input id="btn_load" type="button" value="Load" onclick = "LoadData()" />

        <br /><br />

    <div>

        <table style=" height: 100%; border: solid 1px #000" cellpadding="0" cellspacing="1" id="tbl_grid" border = "1">

            <thead style = "background-color: #666; color: #fff">

                <tr>

                    <td style="width: 100px;">

                        Column1

                    </td>

                    <td style="width: 500px;">

                        Column2

                    </td>

                    <td style="width: 150px;">

                        Edit

                    </td>

                </tr>

            </thead>

            <tbody id="tbody_grid">

            </tbody>

            <tfoot>

                <tr>

                    <td style="width: 100px;">

                        <input id="txt_addcol1" style ="width: 30px" type="text" />

                    </td>

                    <td style="width: 500px;">

                        <input id="txt_addcol2" type="text"  style ="width: 300px" />

                    </td>

                    <td style="width: 150px;">                   

                        <%--This click event handles adding data to the database--%>

                        <input id="btn_add" type="button" onclick = "Add()" value="Add" />

                    </td>

                </tr>

            </tfoot>

        </table>

    </div>

    </form>

</body>

 

Now add your JavaScript function to load data from the database using PageMethods. PageMethod call should always have a success handler (this will be executed if the page method is executed successfully) and an exception handler (this will be executed if an exception is thrown). Say suppose we added 'GetData()' as the page method on the code behind, our javascript will be PageMethods.GetData(SuccessHandler, ExceptionHandler). Just for understanding, I have named the success and exception handler appropriately, you can name them as you wish. In case, the page methods takes parameters, you can add like PageMethods.GetData(param1, param2, SuccessHandler, ExceptionHandler).

Page methods should be decorated with [WebMethod] attribute and should be declared as static. Its signature shoul look something like this:

[WebMethod]

public static string GetData()


Page method to return data to javascript.


public partial class AJAXGrid : System.Web.UI.Page

{

    protected void Page_Load(object sender, EventArgs e)

    {

 

    }


    [WebMethod]

    public static IEnumerable<MyEntity> GetData()

    {

        try

        {                  

Data fetch part should go here

            // used List, as collections are serializable. See below for MyEntity class

            List<MyEntity> MyEntities = new List<MyEntity>();

 

            MyEntities.Add("1", "abc");

MyEntities.Add("2", "xyz");

MyEntities.Add("3", "pqr");

MyEntities.Add("4", "mno");


return MyEntities; 

}

        catch(Exception ex)

        {

            throw ex;

        }

 

    }
}


MyEntity class

 

public class MyEntity

{

    private string _Column1;

 

    public string Column1

    {

      get { return _Column1; }

      set { _Column1 = value; }

    }

   

    private string _Column2;

 

    public string Column2

    {

      get { return _Column2; }

      set { _Column2 = value; }

    }

 

    public MyEntity(string sCol1, string sCol2)

    {

        _Column1 = sCol1;

        _Column2 = sCol2;

    }

}

 

Javascript function that calls page method and populates the HTML table
 

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

 

//Loading Data

 

    // Handles btn_load click event

    function LoadData() {

 

        // If data was fetched successfully, SuccessHandler will be called; else, ExceptionHandler

        PageMethods.GetData(SuccessHandler, ExceptionHandler);

 

  // Incase parameters need to be passed to PageMethods, you can do like this PageMethods.GetData(param1, param2, SuccessHandler, ExceptionHandler)

 

 

    }

 

    // After fetching the data successfully

    function SuccessHandler(result) {

 

        var tbody = $get("tbody_grid");

        // clear the table

        for (var j = tbody.rows.length; j > 0; j--) {

            tbody.deleteRow(j - 1);

        }

        // populate the table

        for (var i = 0; i < result.length; i++) {

            //two columns fetched from database are sent as parameters

            AddRow(result[i].Column1, result[i].Column2);        

        }

        return true;

    }

 

    // Edit and Delete buttons are added to the rows

    function AddRow(col1, col2) {

        var tbody = $get("tbody_grid");

        var row = document.createElement("tr")

        var td1 = document.createElement("td")

        td1.innerText = col1;

        var td2 = document.createElement("td");

        td2.innerText = col2;

        var td3 = document.createElement("td");

        // add buttons

        var btnEdit = document.createElement('input');

        btnEdit.setAttribute('type', 'button');

        btnEdit.setAttribute('name', 'Edit');

        btnEdit.setAttribute('value', 'Edit');

        // first parentNode represents <td> and the second represents <tr>

        btnEdit.onclick = function() { Edit(this.parentNode.parentNode); };

        var btnDelete = document.createElement('input');

        btnDelete.setAttribute('type', 'button');

        btnDelete.setAttribute('name', 'Delete');

        btnDelete.setAttribute('value', 'Delete');

        btnDelete.onclick = function() { DeleteRow(this.parentNode.parentNode); };

        td3.appendChild(btnEdit);

        td3.appendChild(btnDelete);

        row.appendChild(td1);

        row.appendChild(td2);

        row.appendChild(td3);

        tbody.appendChild(row);       

    }

 

    // Handles exception

    function ExceptionHandler(result) {

    }


After populating the HTML table 



Javascript functions to handle Edit, Update, Delete and Insert:


Editing Data

 

    //  this function handles edit button click

    function Edit(row) {

 

        var col1 = row.childNodes[0].innerText;

        var col2 = row.childNodes[1].innerText;

       

        // populates values in textboxes and displays Update and Cancel buttons

        var editableRow = document.createElement("tr")

        var td1 = document.createElement("td")

        var txtBox1 = document.createElement('input');

        txtBox1.setAttribute('type', 'text');

        txtBox1.setAttribute('name', 'col1');

        txtBox1.setAttribute('value', col1);

        txtBox1.setAttribute('width', 30);

        td1.appendChild(txtBox1);

        var td2 = document.createElement("td");

        var txtBox2 = document.createElement('input');

        txtBox2.setAttribute('width', 300);

        txtBox2.setAttribute('type', 'text');

        txtBox2.setAttribute('name', 'col1');

        txtBox2.setAttribute('value', col2);

        td2.appendChild(txtBox2);

        var td3 = document.createElement("td");

        var btnUpdate = document.createElement('input');

        btnUpdate.setAttribute('type', 'button');

        btnUpdate.setAttribute('name', 'Update');

        btnUpdate.setAttribute('value', 'Update');

        btnUpdate.onclick = function() { Update(this.parentNode.parentNode); };

        var btnCancel = document.createElement('input');

        btnCancel.setAttribute('type', 'button');

        btnCancel.setAttribute('name', 'Cancel');

        btnCancel.setAttribute('value', 'Cancel');

        btnCancel.onclick = function() { Cancel(this.parentNode.parentNode); };

        td3.appendChild(btnUpdate);

        td3.appendChild(btnCancel);

        editableRow.appendChild(td1);

        editableRow.appendChild(td2);

        editableRow.appendChild(td3);

        row.parentNode.replaceChild(editableRow, row);

    }


After edit button click



 

Updating Data

 

    //  this function handles update button click

    function Update(row) {

 

        // fetches values entered in the textboxes

        // first childNode represent <td> inside <tr> and second childNode represents textbox

        var col1 = row.childNodes[0].childNodes[0].value;

        var col2 = row.childNodes[1].childNodes[0].value;

 

        // values sent to server

        PageMethods.UpdateData(col1, col2, UpdateSuccess(row), ExceptionHandler);      

    }

 

    // After updating the values successfully

    function UpdateSuccess(row) {

 

        var col1 = row.childNodes[0].childNodes[0].value;

        var col2 = row.childNodes[1].childNodes[0].value;

 

        var editableRow = document.createElement("tr")

        var td1 = document.createElement("td")

        td1.innerText = col1;

        var td2 = document.createElement("td");

        td2.innerText = col2;

        var td3 = document.createElement("td");

        var btnEdit = document.createElement('input');

        btnEdit.setAttribute('type', 'button');

        btnEdit.setAttribute('name', 'Edit');

        btnEdit.setAttribute('value', 'Edit');

        btnEdit.onclick = function() { Edit(this.parentNode.parentNode); };

        var btnDelete = document.createElement('input');

        btnDelete.setAttribute('type', 'button');

        btnDelete.setAttribute('name', 'Delete');

        btnDelete.setAttribute('value', 'Delete');

        btnDelete.onclick = function() { DeleteRow(this.parentNode.parentNode); };

        td3.appendChild(btnEdit);

        td3.appendChild(btnDelete);

        editableRow.appendChild(td1);

        editableRow.appendChild(td2);

        editableRow.appendChild(td3);

        row.parentNode.replaceChild(editableRow, row);

 

    }

 

    // this function handles cancel button click

    function Cancel(row) {

 

        // values are again populated in labels instead of textboxes

        var col1 = row.childNodes[0].childNodes[0].value;

        var col2 = row.childNodes[1].childNodes[0].value;

 

        var editableRow = document.createElement("tr")

        var td1 = document.createElement("td")

        td1.innerText = col1;

        var td2 = document.createElement("td");

        td2.innerText = col2;

        var td3 = document.createElement("td");

        var btnEdit = document.createElement('input');

        btnEdit.setAttribute('type', 'button');

        btnEdit.setAttribute('name', 'Edit');

        btnEdit.setAttribute('value', 'Edit');

        btnEdit.onclick = function() { Edit(this.parentNode.parentNode); };

        var btnDelete = document.createElement('input');

        btnDelete.setAttribute('type', 'button');

        btnDelete.setAttribute('name', 'Delete');

        btnDelete.setAttribute('value', 'Delete');

        btnDelete.onclick = function() { DeleteRow(this.parentNode.parentNode); };

        td3.appendChild(btnEdit);

        td3.appendChild(btnDelete);

        editableRow.appendChild(td1);

        editableRow.appendChild(td2);

        editableRow.appendChild(td3);

        row.parentNode.replaceChild(editableRow, row);

    }

 

    //  this function handles 'add' button click

    function Add() {

 

        var col1 = $get("txt_addcol1").value;

        var col2 = $get("txt_addcol2").value;

 

        // data sent to the database

        PageMethods.InsertData(col1, col2, AddSuccess(col1, col2), ExceptionHandler);        

 

    }

 

    // After adding the data successfully

    function AddSuccess(col1, col2) {

 

        // add the values to the table

        AddRow(col1, col2);

       

        // clear the textboxes in the footer

        $get("txt_addcol1").value = "";

        $get("txt_addcol2").value = "";

       

    }

 

Deleting Data

 

    // this function handles delete button click

    function DeleteRow(row) {

 

        var col1 = row.childNodes[0].innerText;

        // delete from the database

        PageMethods.DeleteData(col1, DeleteSuccess(row), ExceptionHandler);

    }

 

    function DeleteSuccess(row) {

        // delete the row from the table

        var tbody = $get("tbody_grid");

        tbody.removeChild(row);

    }

   

 

</script>

 

Page methods to handle Edit, Update, Delete and Insert:

           

 

    [WebMethod]

    public static void UpdateData(string sCol1, string sCol2)

    {

  try

        {                  

        Data update part should go here     

        }

        catch(Exception ex)

        {

            throw ex;

        }

 

    }

 

    [WebMethod]

    public static void InsertData(string sCol1, string sCol2)

    {

        try

        {

                          Data insert part should go here        

        }

        catch(Exception ex)

        {

            throw ex;

        }

    }

 

    [WebMethod]

    public static void DeleteData(string sCol1)

    {

        try

        {

                           Data delete part should go here         

        }

        catch (Exception ex)

        {

            throw ex;

        }

    }

}


We can add paging and sorting too.


This code has been tested in IE7+, Firefox, Chrome and Safari.

 

Some of the limitations in using ASP.NET AJAX PageMethods:

1.       We can't access asp.net server controls (like TextBox control) in the WebMethod directly as we normally access in the server side methods.

2.       We can't access any variable declared in the code behind.

Advantage: PageMethods is a simple lightweight way to submit/fetch data to the server using ASP.NET AJAX. This doesn't submit whole page data to the server and also as opposed to the ASP.NET AJAX call back this doesn't even fire the Page_Load and other Page events of the code behind page.




Tuesday, September 15, 2009 8:24:25 PM (GMT Daylight Time, UTC+01:00)  #    Comments [3] -
.NET
# Saturday, August 01, 2009

As I started getting too many spams because of bots, I implemented Completely Automated Public Turing test to tell Computers and Humans Apart (CAPTCHA) in all the interactive pages of my site.

 

Took the control from here http://www.codeproject.com/KB/custom-controls/CaptchaControl.aspx, and customized according to my needs. The code was easy to understand and customize.

Saturday, August 01, 2009 6:45:44 PM (GMT Daylight Time, UTC+01:00)  #    Comments [0] -
.NET
Navigation
Archive
<November 2009>
SunMonTueWedThuFriSat
25262728293031
1234567
891011121314
15161718192021
22232425262728
293012345
About the author/Disclaimer

Disclaimer
The opinions expressed herein are my own personal opinions and do not represent my employer's view in any way.

© Copyright 2013
Gokulnath
Sign In
Statistics
Total Posts: 42
This Year: 0
This Month: 0
This Week: 0
Comments: 47
Themes
Pick a theme:
All Content © 2013, Gokulnath
DasBlog theme 'Business' created by Christoph De Baene (delarou)