Sunday, 9 December 2012

Introduction about ASP.Net Application and Pages

Goals:
  • Present main concepts of the ASP.NET applications.
  • Introduce web pages and their events.
Steps:
  1. Create a new project - Visual C# / Web / ASP.NET Web Application.
    There is also possibility to create a 'Web Site' (menu File / New / Web Site), but the 'Web Application' should be preferred. The Web Site has no project file. The lack of a project file can make the application's configuration much harder (sometimes even impossible)
  2. Take a look into the generated project.
    • The AssemblyInfo.cs file, as usually in .NET C# projects, contains definition of the project assembly's properties.
    • The App_Data item is a folder, where all data files used by the project should be kept, e.g. text, xml, or database files. This folder is configured in a special way by default - the user account that is used to run the application (for example, the local ASP.NET account) has permissions to read, write, and create files in this folder.
    • The Default item is a web page (aka 'web form'). There are 3 files generated as parts of this item:
      • Default.aspx contains the design of a web page. All the HTML and ASP.NET tags are placed here (unless some of they are generated dynamically in the source code). There are 2 different views for editing this file: 'Design' and 'Source'. In the Design mode all the design can be visually modified, and in the Source mode you can manually modify all tags. There is also the 'Split' mode which allows to use the Design and Source modes simultaneously.
        The visual designer of ASP.NET pages built in Visual Studio (i.e. the Design mode) is a quite comfortable and powerful visual editor for HTML files, in fact.
      • Default.aspx.cs is so called code-behind file, it contains C# source code for the page. Usually, the code file contains methods responding for the page's or its controls events and some helpful methods.
      • Default.aspx.designer.cs contains C# code generated by the Visual Studio in response for modification of the .aspx file. In example, after adding a control to the .aspx file, a member of the page's class representing this control will be automatically added to this file.
    • The Web.config file is a configuration file of the web application. There are many web-related configuration options allowed to be placed here. This file serves also as a normal configuration file for the .NET project, just like .exe.config files for Windows Forms or console projects.
  3. Add text to the Default page:
  4. Run the project (Ctrl+F5 or menu Debug / Start Without Debugging). Note the following actions:
    • Visual Studio compiles the project.
    • The ASP.NET Development Server is started in the system:
    • The default Internet browser starts and opens the address: http://localhost:49691 (the port number can vary):
    • Take a look into source code of the generated page (use the 'View Source Code' option in the browser):
      <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
      
      <html xmlns="http://www.w3.org/1999/xhtml" >
      <head><title>
      
      </title></head>
      <body>
          <form name="form1" method="post" action="Default.aspx" id="form1">
      <div>
      <input type="hidden" name="__VIEWSTATE" id="__VIEWSTATE" value="/wEPDwULLTE2MTY2ODcyMjlkZO/ZMzP2K7pbdL0x/efEBPI9tp28" />
      </div>
      
          <div>
          
              Welcome on the Default page.</div>
      
          </form>
      </body>
      </html>
      Compare this code with source code of the Default.aspx file in Visual Studio and note some differences - ASP.NET automatically generates the output HTML code based on the source ASP.NET code. For most complicated pages using some ASP.NET controls there will be more differences.
  5. Modify in Visual Studio the text displayed on the page and save the file. Do not compile the project, just refresh the page in the browser. Note that the text has changed. ASP.NET automatically checks for changes in source code files and, when there is such need, recompiles the project.
  6. Add a new Web Form to the project (right click on the project in the Solution Explorer window: Add / New Item / Web Form). Name it Info.aspx:
    • Add the following code to the Page_Load method in the Info.aspx.cs file:
      Response.Write(string.Format("ApplicationPath: {0}<br>", Request.ApplicationPath));
      Response.Write(
      string.Format("CurrentExecutionFilePath: {0}<br>", Request.CurrentExecutionFilePath));
      Response.Write(
      string.Format("FilePath: {0}<br>", Request.FilePath));
      Response.Write(
      string.Format("Path: {0}<br>", Request.Path));
      Response.Write(
      string.Format("PhysicalApplicationPath: {0}<br>", Request.PhysicalApplicationPath));
      Response.Write(
      string.Format("ApplicationPath: {0}<br>", Request.ApplicationPath));
      Response.Write(
      "<br><br>");
      Response.Write(
      string.Format("Physical ~ is {0}<br>", Server.MapPath("~")));
      • The Page_Load method is automatically attached to the Load event of the page. The AutoEventWireup property of the Page declaration starting the Info.aspx file is responsible for this.
      • The Response object used in the C# code is a property of the current page. (All the code in the .aspx.cs file is a part of the page's class, so all its properties are directly available.) The Write method allows to directly generate the output HTML code. (This is very powerful possibility but should not be overused in conjunction with using ASP.NET controls.)
      • The Request is also a property of the current page. It represents the request coming from the user's browser. It makes available some very useful properties, in example these used in the above code.
      • The '~' character in logical paths always represents the main folder of the application. It is used in logical web paths, not in physical disk ones.
      • To convert logical web path to physical disk path, the MapPath method of the HttpServerUtility class can be used. An object of this class is available as the Server property of the current page.
    • Run the application (Ctrl+F5):
    • Make the Default.aspx page the starting one (right click on the page in the Solution Explorer window: Set as Start Page).
  7. Add to the Default.aspx page options that will allow to move to the Info.aspx page (currently, the only option is manual modification of the address displayed in the browser). There are a few ways to do it:
    • The 1st way is to add a simple HTML hyperlink to the Default.aspx file:

      Note, a relative path (i.e. no path - both files are in the same directory) was used. It is always a good idea to avoid hard-coding absolute paths).
    • The 2nd way is to use ASP.NET control that works like an HTML hyperlink. Drop to the Default.aspx design a Hyperlink control dragged from the Standard group from the Toolbox window.
    • The 3rd way is to force the user's browser to ask for another page. This can be done only in response for a request from the browser. To get a request, a button will be used.
      • Drop on the Default.aspx design a Button control (from the Toolbox):
      • Double click the button to generate a handler for its Click event. Add the following code to the handler:
        protected void Button1_Click(object sender, EventArgs e)
        {
            Response.Redirect(
        "Info.aspx");
        }
      • Note that in this way one additional transmission from the server to the client and back is required, so, in most cases, such solution makes sense only when redirection is done to another application or server. Such redirections within a single web application are extremely inefficient.
    • Another way is transferring requests within a single web application. This can be using the Transfer method of the HttpServerUtility class.
      • Add a button like in the previous solution:
      • Add the following code in the Click event handler:
        protected void Button2_Click(object sender, EventArgs e)
        {
            Server.Transfer(
        "Info.aspx");
        }
      • This solution is definitely more efficient than the previous one (no additional round trip of a request/response pair is necessary), but there are some drawbacks
        • The user will see in the browser the address of the Default.aspx page, but the content of the Info.aspx file:
        • The Transfer method throws ThreadAbortException to abort processing of the original request (for the Default.aspx page, in this example).
    • Yet another way is using so-called cross-page posting. Normally, all controls post back to the same page (that's why the C# code for responding for Click event for the above buttons was located on the Default.aspx page). Cross-page posting consists in specifying another page as a target for, in example, clicking a button.
      • Add a button to the Default.aspx page and set its PostBackUrl property to Info.aspx:
  8. Test some of web pages' events:
    • Add a new Web Form to the project.
    • Add the following code to the .aspx.cs file:
      Button dynamicButton;
      protected override void OnInit(EventArgs e)
      {
          Response.Write(
      "=== Init event ===<br>");
          
      base.OnInit(e);

          dynamicButton =
      new Button();
          dynamicButton.Text =
      "Dynamic button";
          dynamicButton.Click +=
      new EventHandler(DynamicButton_Click);
          Form.Controls.Add(dynamicButton);
      }
      void DynamicButton_Click(object sender, EventArgs e)
      {
          Response.Write(
      "=== DynamicButton_Click event ===<br>");
      }
      protected override void OnLoad(EventArgs e)
      {
          Response.Write(
      "=== Load event ===<br>");
          
      base.OnLoad(e);
      }
      protected override void OnPreRender(EventArgs e)
      {
          Response.Write(
      "=== PreRender event ===<br>");
          
      base.OnPreRender(e);

          dynamicButton.OnClientClick =
      "alert('Hello from Dynamic Button')";
      }
    • Run the application and test how it works:
    • In this code instead of the Page_Load method, the OnLoad overridden method was used. In both cases the result is the same - code from these methods is executed during the Load event. The OnLoad method should be preferred, because the Page_Load method is based on the mechanism of 'wiring' automatically methods to events by their names, which is slower than direct overriding methods.
    • Only controls added to the page's Form property (or contained within the <form> tag) will be rendered to the output HTML code. This is the reason of calling the Form.Controls.Add method.
    • The OnClientClick property of a button can contain JavaScript code to be executed in the user's browser.
  9. The source code of the web application can be debugged. It concerns both the C# and JavaScript code. The support for debugging is not limited to the Internet Explorer browser.
    To debug the application just press F5 button in Visual Studio. If it is the first try of debugging, a message appears:

    Note that (as mentioned in the message) enabling debugging should be disabled before deploying the application to the production server.
  10. Apart from the page's and its controls' events, there are also application's events available. There are only a few of application's events, but some of them can be extremely useful.
    • Add to the project the Global Application Class:
    • Add to the Application_Start method in the Global.asax file the following line:
      Application["StartTime"] = DateTime.Now;
      This line allows to store time of the beginning of the application in the dictionary of values shared by all pages of the application.
    • Add to the Page_Load method of the Info.aspx page the following line:
      Response.Write(string.Format("Application[\"StartTime\"]: {0}<br>", Application["StartTime"]));
    • Run the application, refresh the Info.aspx page many times and note that the value of 'StartTime' does not change. Rebuild the application, refresh the Info.aspx in the browser and note a new value. It proves that rebuilding the source code causes restart of the application.
[Source code]

Image without using Generic Handler in ASP.Net

In this article I will explain how to display byte array i.e. Binary Data as Image on the web page in ASP.Net Image Control without using Generic handler and also without saving the file on disk.

HTML Markup

<form id="form1" runat="server">
<asp:FileUpload ID="FileUpload1" runat="server" />
<asp:Button ID="btnUpload" runat="server" Text="Upload"
    onclick="btnUpload_Click" />
<hr />
<asp:Image ID="Image1" Visible = "false" runat="server" Height = "100" Width = "100" />
</form>


Above you will see a FileUpload control to upload the Image File, a Button control to trigger the File upload process and an Image control to display the uploaded image file.
 
Displaying the Byte Array as Image
Below is the code that is being executed when the Upload button is clicked.
C#
 
protected void btnUpload_Click(object sender, EventArgs e)
{
    System.IO.Stream fs = FileUpload1.PostedFile.InputStream;
    System.IO.BinaryReader br = new System.IO.BinaryReader(fs);
    Byte[] bytes = br.ReadBytes((Int32)fs.Length);
    string base64String = Convert.ToBase64String(bytes, 0, bytes.Length);
    Image1.ImageUrl = "data:image/png;base64," + base64String;
    Image1.Visible = true;
}
 

Tuesday, 27 November 2012

How to Imporve or Shaping your technical career

There are close to 100,000 software developers joining the Indian IT industry every year. With so many developers, it is easy to get lost in the crowd. I have engaged myself with the IT industry for over few years now. I have seen the ups and downs of the industry. I have consistently done a decent amount of coding over the last few years. I have put together some of the things I have learnt over my career.

#1: Love coding
If you love coding, you will be interested in a technical career. There are lot of programmers who are in the industry who do not like coding. Their expectation is to become some sort of manager - a product manager, a project manager or a line manager. Everyone is welcome to do coding. But, if you are in for a technical career, you have to love coding.

#2: Application development

Application development is a rare thing. Most applications require maintenance or enhancements. There are lot of products available in the market like business intelligence products: Informatica, Microstrategy or business application tools like SAP, PeopleSoft. There are many developers who work with these products doing various system integration activities. The percentage of people who are involved in hard-core application development is very less. If you like coding, you should find yourself in an organization which does hard-core application development. You will enjoy it much better there.

#3: Choose your platform

There are lot of application development platforms - Microsoft.Net, Java (J2EE), Python, Ruby etc. Choose one and stick to it. Choosing a platform to work on is an emotional decision. It is not a logical decision. All platforms evolve over a period of time. You do not have to work in the best application development platform. You just have to choose one you are most comfortable with and stick to it.

#4: But we do not have projects

I have heard lot of managers saying that they do not have projects in say .Net. I want to narrate an incident that happened to me a few years back. At that time of the incident, I had over 5 years of application development experience. By mistake, I was associated with a project involving MicroStrategy. Soon, I became a BI expert. I remember talking to a manager about moving to a Microsoft specific team. My manager bluntly told me: "You cannot decide which team you want to work with. If the organization wants you to work in a Business intelligence (Data warehousing) team, you have to go to that team". You have to be flexible to the organization. But, not at the cost of your career. I wasted one year of my professional career with that team. But, it is not a complete waste. (humor intended!) I learnt a bit of data modeling - Star Schema design, ETL, BI reporting, and some analytics. It has helped to relate to people who are working in BI. I still have good friends who work in the BI world.

#5: Associate with people who appreciate your technical skills

There are lot of developers who are good in a specific technical discipline rather than posessing a broad range of technical skills. I have seen good programmers who are good in trouble-shooting but poor in design. I have seen some good designers who are weak in trouble-shooting. If you work for an organization where you need to posess a broad range of technical skills, ensure that you associate with people who appreciate your technical skills.

#6: Work on open-source projects

Work on open-source projects. This will help sharpen your technical skills. There are lot of people who will reach out to you. These  people appreciate your technical skills.

#7: Knowledge accumulation

Learning new things is good. But knowing a lot of things does not mean much. Knowledge accumulation is very much the equivalent of building your physique in the gym, or making a lot of fortune in business. Developing good analytical skills, decision making skills, prioritizing and planning skills is more interesting, more valuable than accumulating lot of knowledge. You can be a good technical guy without knowing a lot of things but be able to do a lot of things. Beware of the technical guy who ridicules others for not possessing some knowledge. Such category of developers are very common in India.

#8: Process but not too much of process

Process is necessary. But, if your organization talks only about CMMI, or Greenbelt, you are working for an organization which is an expert in grooming managers (and not technical people).

#9: Beware of colleagues

If you are a good technical guy and  you are in the early stages of your career, then you may not understand your colleague who has developed good organizational skills. Your colleague is on the way to become the biggest manager of all time. So, do not be influenced by him or her. The colleagues with good organizational skills appear to be good backstabbers. (humor, slightly sarcastic, intended) But, they are meaning well, especially for the organization. So, you should learn skills to handle these sort of people. But you should not get carried away by their "cutting-edge" skills to become one of them.

These are tips from my experience. As you can see, I have been an above average developer. So, these are tips for the above average developer. For the excellent developer, the career progression is clear and smooth.

I like to know your comments and what you think about the post.

How to search of excellent programmers

Sachin Tendulkar is the greatest batsman ever. He has almost every batting record to his name. I used to play cricket at college and corporate levels. Sachin is a better batsman than me. Better than me by a factor of, say, 1000 times. In short, Sachin is 10^N times better than me. Sachin achieved this greatness by improving his batting skills. If we were to assess the performance of a batsman (on an annual basis), we can have the following aspects to consider:
  1. Number of runs scored
  2. Batting average
  3. Strike rate
  4. Man of the match awards
  5. Number of 100s
The output is highly visible and very measurable.
Is it possible to have a Sachin Tendulkar among programmers? Is it possible that we have a programmer who is 10^N times better than an amateur programmer. If such programmers exist, how do we find them?
Unfortunately, the performance of programmers cannot be measured that easily. To me, a good programmer is someone who understands the requirements well, provides solutions, designs and architects systems really well, communicate effectively with other team members, and writes maintainable and high quality code. These things are not easy to measure. But, some folks try to measure all of this:
  1. Number of hours logged (Utilization)
  2. Escalations or Feedbacks received (Bugs, Other personal attributes pissing the manager)
  3. Communication skills (Ability to talk politely, or fluently, Ability to write good English emails)
To go back to the analogy of cricket, Sachin is part of a team that competes with other teams. Today, businesses are more like a sports team. To survive, businesses need great products, which in turn, requires great talent. For software companies, great talent means excellent programmers (and managers). We have to measure the impact that programmers create for the organization (to compete). A few attributes that can make excellent programmers are:
  1. Excellent skills in a programming language, and coding algorithms
  2. Excellent skills in enterprise architecture and design patterns
  3. Excellent analytical and problem solving skills (requirements, providing solutions)
But, these attributes are not enough to make great programmers. For the modern world, a few more attributes are required.
  1. Quickly learn new methodologies
  2. Quickly learn new tools
  3. Proactively, suggest product features
  4. Quickly prototype features
A thing to remember is that Sachin makes lots of money. Excellent programmers (Sachin's of programming) should also make lot of money. This is possible only if programmers are part of a team that directly impacts the marketplace. Excellent programmers are excellent, only if, they work for revolutionary companies - Google, Facebook, Microsoft, or any Startups (where the impact of programmer is more).
In cricketing terms, Team India makes an impact in the cricketing world. But, my corporate cricket team does not. It is upto the individual to ensure that he is part of an impact-making team. Apart from cricketing skills, Sachin has the talent to sell his cricketing skills. This is an essential part of excellence. But, BCCI (Board of cricket control, India) also has a part in identifying and grooming talent.
My informal topic of research for several years is: How do great companies set up their performance assessment system to hone talent within the company? Most companies fall into the trap of having a system that works within their culture, or having a system that maximizes benefit to the organization (mostly in the short term). My objective here is to articulate a performance assessment system that hones excellent programmers and rewards them.
Greatness and Excellence comes out of passion to do. If we have a system, where everyone is evaluated on what they are passionate about, it will bring about the best in people. How do we setup a system where measurement is encouraging, beneficial, and evolves talent? Here is my attempt:
  1. Number of product features implemented
  2. Number of product features suggested (and found its way into the product)
  3. Number of prototypes developed
  4. Number of new things learned - products, tools, frameworks
Some people will say that this works for a product company but not a service company. Programmers in service companies can have similar measures:
  1. Number of projects implemented
  2. Number of new things learned - products, tools, frameworks, industry knowledge
  3. Number of features implemented / suggested within the project 
There are some numbers which cannot be captured. The impact to the project or the product cannot be captured in numbers. A verbal feedback is ok (especially for the average performers). But, the verbal or written feedback should be measuring impact in the above measures only.
Example of some ineffective feedback is:
  1. Productivity is low in the project. But, productivity may be good, if the programmer was involved in making unsuccessful prototypes or learning new technologies.
  2. There are too many defects. This is a bad metric because the complexity and dependencies in the project cannot be measured. Too many defects can also happen because of a good testing team. Defect detection and removal is an operational detail.
  3. Team work or Attitude skills are bad. This is a good indication of talent. Usually, people who specialize in honing a specific talent may be oblivious to a few. Mentoring or awareness can induce behavioural changes.
In my opinion, the above feedbacks are not really useful in getting the best out of employees. I like HCL's slogan: Employees first, Customers second. If this were to be put in practice, programmers should be evaulated by measuring their passion to work and not on the immediate benefits to the organization.

Check all checkboxes in GridView using jQuery

Introduction


This is the very basic need when you do bulk operations like email sending, export to excel, delete record etc. from a list. A CheckBox in header on which checked or unchecked all the CheckBoxes in the list should change respectively. Similar thing you can see in Gmail, Hotmail etc. which have more variations to select record. 

In this tutorial I put a CheckBox in header, on its check change, all the checkboxes in the list check change and if you change the check on any of checkboxes in the list the header check also change automatically. 

Using the code

I have created a Class Employee, add some records to it and bind it to grid. 

public class Employee
{
    public int Id { get; set; }
    public string Name { get; set; }
    public string Address { get; set; }
    public string Designation { get; set; }
}

protected void Page_Load(object sender, EventArgs e)
{
    var employees = new List<Employee>()
    {
        new Employee(){ Id = 1, Name = "Ms. Sivani ",     Address = "507 - 20th Ave. E.  Apt. 2A",    Designation = "Sales Representative"},
        new Employee(){ Id = 2, Name = "Dr. Ramesh Kumar",     Address = "908 W. Capital Way",             Designation = "Vice President Sales"},
        new Employee(){ Id = 3, Name = "Ms. Rekha",   Address = "722 Moss Bay Blvd.",             Designation = "Sales Representative"},
        new Employee(){ Id = 4, Name = "Mrs. sangita ", Address = "4110 Old Redmond Rd.",           Designation = "Sales Representative"},
        new Employee(){ Id = 5, Name = "Mr. Hemant ",   Address = "14 Garrett Hill",                Designation = "Sales Manager"},
        new Employee(){ Id = 6, Name = "Mr. Rohit ",    Address = "Coventry House  Miner Rd.",      Designation = "Sales Representative"},
        new Employee(){ Id = 7, Name = "Mr. Rahul ",       Address = "Edgeham Hollow  Winchester Way", Designation = "Sales Representative"},
        new Employee(){ Id = 8, Name = "Ms. Laura Callahan",    Address = "4726 - 11th Ave. N.E.",          Designation = "Inside Sales Coordinator"},
        new Employee(){ Id = 9, Name = "Ms. Anne Dodsworth",    Address = "7 Houndstooth Rd.",              Designation = "Sales Representative"}
    };

    gvEmployees.DataSource = employees;
    gvEmployees.DataBind();
} 
 
This is my Grid Control 
 
<Sort<asp:GridView ID="gvEmployees" runat="server" AutoGenerateColumns="false" CellPadding="4" ForeColor="#333333"
    GridLines="None">
    <AlternatingRowStyle BackColor="White" />
    <Columns>
        <asp:TemplateField>
            <HeaderTemplate>
                <asp:CheckBox runat="server" ID="chkAll" />
            </HeaderTemplate>
            <ItemTemplate>
                <asp:CheckBox runat="server" ID="chkEmployee" />
            </ItemTemplate>
        </asp:TemplateField>
        <asp:TemplateField HeaderText="ID">
            <ItemTemplate>
                <asp:Label runat="server" ID="lblID" Text='<%#Eval("Id") %>'></asp:Label>
            </ItemTemplate>
        </asp:TemplateField>
        <asp:TemplateField HeaderText="Name">
            <ItemTemplate>
                <asp:Label runat="server" ID="lblName" Text='<%#Eval("Name") %>'></asp:Label>
            </ItemTemplate>
        </asp:TemplateField>
        <asp:TemplateField HeaderText="Address">
            <ItemTemplate>
                <asp:Label runat="server" ID="lblAddress" Text='<%#Eval("Address") %>'></asp:Label>
            </ItemTemplate>
        </asp:TemplateField>
        <asp:TemplateField HeaderText="Designation">
            <ItemTemplate>
                <asp:Label runat="server" ID="lblDesignation" Text='<%#Eval("Designation") %>'></asp:Label>
            </ItemTemplate>
        </asp:TemplateField>
    </Columns>
    <EditRowStyle BackColor="#7C6F57" />
    <FooterStyle BackColor="#1C5E55" Font-Bold="True" ForeColor="White" />
    <HeaderStyle BackColor="#1C5E55" Font-Bold="True" ForeColor="White" />
    <PagerStyle BackColor="#666666" ForeColor="White" HorizontalAlign="Center" />
    <RowStyle BackColor="#E3EAEB" />
    <SelectedRowStyle BackColor="#C5BBAF" Font-Bold="True" ForeColor="#333333" />
    <SortedAscendingCellStyle BackColor="#F8FAFA" />
    <SortedAscendingHeaderStyle BackColor="#246B61" />
    <SortedDescendingCellStyle BackColor="#D4DFE1" />
    <SortedDescendingHeaderStyle BackColor="#15524A" />
</asp:GridView> 
 
 
We have two requirements.

1. When top CheckBox checked/unchecked, we have to check/uncheck all the CheckBoxes in the list.

Following function fulfill the requirement.

$("#<%=gvEmployees.ClientID%> input[id*='chkAll']:checkbox").click(function () {
    if ($(this).is(':checked'))
        $("#<%=gvEmployees.ClientID%> input[id*='chkEmployee']:checkbox").attr('checked', true);
    else
        $("#<%=gvEmployees.ClientID%> input[id*='chkEmployee']:checkbox").attr('checked', false);
});
 
2. On each of the list CheckBox checked/unchecked, we have to determine Check/Uncheck top CheckBox.  
 
 function CheckUncheckAllCheckBoxAsNeeded() {
        var totalCheckboxes = $("#<%=gvEmployees.ClientID%> input[id*='chkEmployee']:checkbox").size();
        var checkedCheckboxes = $("#<%=gvEmployees.ClientID%> input[id*='chkEmployee']:checkbox:checked").size();

        if (totalCheckboxes == checkedCheckboxes) {
            $("#<%=gvEmployees.ClientID%> input[id*='chkAll']:checkbox").attr('checked', true);
        }
        else {
            $("#<%=gvEmployees.ClientID%> input[id*='chkAll']:checkbox").attr('checked', false);
        }
    }
 
Following is Complete Javascript. 
 
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript">
    $(document).ready(function () {
        $("#<%=gvEmployees.ClientID%> input[id*='chkEmployee']:checkbox").click(CheckUncheckAllCheckBoxAsNeeded);
        $("#<%=gvEmployees.ClientID%> input[id*='chkAll']:checkbox").click(function () {
            if ($(this).is(':checked'))
                $("#<%=gvEmployees.ClientID%> input[id*='chkEmployee']:checkbox").attr('checked', true);
            else
                $("#<%=gvEmployees.ClientID%> input[id*='chkEmployee']:checkbox").attr('checked', false);
        });
    });

    function CheckUncheckAllCheckBoxAsNeeded() {
        var totalCheckboxes = $("#<%=gvEmployees.ClientID%> input[id*='chkEmployee']:checkbox").size();
        var checkedCheckboxes = $("#<%=gvEmployees.ClientID%> input[id*='chkEmployee']:checkbox:checked").size();

        if (totalCheckboxes == checkedCheckboxes) {
            $("#<%=gvEmployees.ClientID%> input[id*='chkAll']:checkbox").attr('checked', true);
        }
        else {
            $("#<%=gvEmployees.ClientID%> input[id*='chkAll']:checkbox").attr('checked', false);
        }
    }
</script>
 
  
 



 
 
 

How to Enter Camel-Casing Text in TextBox

Camel-case is where the first letter of every word is capitalized. Eg, How Are You? This can be done using the text-transform style as follows:


<asp:TextBox runat="server" style="text-transform: Capitalize;"/>

ASP.NET TextBox Watermark Effect using jQuery

This short article demonstrates how to create a watermark effect on your TextBox and display instructions to users, without taking up screen space.

Note that for demonstration purposes, I have included jQuery code in the same page. Ideally, these resources should be created in separate folders for maintainability.
Let us quickly jump to the solution and see how we can create a watermark effect on your TextBox using client-side code.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
 
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
    <title>TextBox WaterMark</title>
    <script type="text/javascript"
        src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js">
    </script>  
   
    <style type="text/css">
    .water
    {
         font-family: Tahoma, Arial, sans-serif;
         color:gray;
    }
    </style>
   
    <script type="text/javascript">
        $(function() {
 
            $(".water").each(function() {
                $tb = $(this);
                if ($tb.val() != this.title) {
                    $tb.removeClass("water");
                }
            });
 
            $(".water").focus(function() {
                $tb = $(this);
                if ($tb.val() == this.title) {
                    $tb.val("");
                    $tb.removeClass("water");
                }
            });
 
            $(".water").blur(function() {
                $tb = $(this);
                if ($.trim($tb.val()) == "") {
                    $tb.val(this.title);
                    $tb.addClass("water");
                }
            });
        });       
 
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <div class="smallDiv">
     <h2>TextBox Watermark Demonstration</h2>    <br />          
        <asp:TextBox ID="txtFNm" class="water" Text="Type your First Name"
        Tooltip="Type your First Name" runat="server"></asp:TextBox><br />
        <asp:TextBox ID="txtLNm" class="water" Text="Type your Last Name"
        Tooltip="Type your Last Name" runat="server"></asp:TextBox>
        <br /><br />
        <asp:Button ID="btnSubmit" runat="server" Text="Submit" />
        <br /><br />
        Tip: Click on the TextBox to start typing. The watermark
        text disappears.
    </div>
    </form>
</body>
</html>
 
The code shown above adds the “watermark” behavior to controls marked with the ‘class=water’ attribute. When the user loads the page, a watermarked textbox displays a message to the user. As soon as the watermarked textbox receives focus and the user types some text, the watermark goes away. This technique is a great space saver as you can use it to provide instructions to the user, without using extra controls that take up valuable space on your form.
   The ‘Tooltip’ attribute applied to the textbox is crucial to this example. The ‘Tooltip’ gets rendered as ‘title’. Observe the code, as we use this ‘title’ property to compare it to the textbox value and remove the watermark css, when the textbox control gains focus
$(".water").focus(function() {
                $tb = $(this);
                if ($tb.val() == this.title) {
                    $tb.val("");
                    $tb.removeClass("water");
                }
            });
 
Similarly when the user moves focus to a different control without entering a value in the textbox, we add the watermark css again.
$(".water").blur(function() {
                $tb = $(this);
                if ($.trim($tb.val()) == "") {
                    $tb.val(this.title);
                    $tb.addClass("water");
                }
            });
 
The water class declared in Demos.css looks like this:
.water
{
     font-family: Tahoma, Arial, sans-serif;
     font-size:75%;
     color:gray;
}
When the page loads for the first time, the watermark is visible as shown here:
Watermark
When the user enters the First/Last Name and submits the form, the watermark behavior is no more needed to be displayed. This is achieved by comparing the ‘title’ with the ‘value’ of the textbox. If the ‘value’ does not match the ‘title’, this indicates that the user has entered some value in the textboxes and submitted the form. So in this case we remove the watermark appearance.
$(".water").each(function() {
                $tb = $(this);
                if ($tb.val() != this.title) {
                    $tb.removeClass("water");
                }
            });
After the user enters the details and submits the form, the result is similar to the one shown here, without the watermark:
Watermark disappears
Thanks to Arnold Matusz for sharing the tip about the tooltip property. The code has been tested on IE 7, IE 8, Firefox 3, Chrome 2, Safari 4 browsers

Monday, 5 November 2012

Book Rail Tickets with IRCTC Mobile Application

The world adapted fast from paper work to computers, and now are shifting at an incredible fast to mobile solutions. Every sector in government and private services need to keep in up with this chance. While there may have been a time when railway ticket booking offices overflowed with people rushing to book their tickets, the advent of the internet saw the rise of a new outlet of ticketing – The e-tickets and the i-tickets and that is possible with IRCTC Mobile Application. The emergency generation saw the introduction of the Tatkal booking service in terms of mobile app. This advancement leads to the increase in travel booking agencies’ participation in the railways.


But the generation never stops. People get busier and busier, and soon, even computers start seeming bulky. Tablets, smart phones overtake the computer and laptop sales, and soon, all businesses jump on this new avenue to make profit and provide more direct service to its clients. IRCTC booking, naturally, today, can thus be carried out on one’s phone from anywhere in the world.


IRCTC Mobile Pro Logo Book Rail Tickets with IRCTC Mobile Application


The IRCTC  also has its own java application for java based phones as depicted in the erail website. They even have their own android application in two versions – the free version with advertisements and the paid version, called IRCTC Pro.

  • Easily Download IRCTC Mobile Application from here (all OS is supported)
  • Another Announcement, similar kinda app is also available namely ATOM which is released recently. <link>
Note : If you need guide on how to book railway tickets from mobile then have a look over the official website where they have details everything. So you don’t have worry about anything, visit this link for FAQ about IRCTC Mobile, this page will clear your most of the common doubts.
These applications allow for booking of tickets from any station to another on the basis of an online calendar, checking of arrival or departure schedules for any given day as well as any delays in the train’s arrival, availability of tickets for any travel date, PNR status enquiry for a RAC or Wait List passenger, and passenger details all in one light weight application.

The IRCTC server is scheduled to undergo a change to accommodate these applications. Presently if the server gets overloaded, the apps cannot reach the server at all. However, to be able to get one’s ticket on his phone directly definitely reduces paper trail, and also acts as proof of identity.
These applications use nominal data charges as set by the network provider, and thus must comply with their speed requirements.

These apps are updated from time to time, with bugs to previous errors, or improvements to the earlier versions based on user feedback. When the world is moving so fast paper is getting redundant, mobile computing is gaining the upper hand, and wireless technologies are the future, the IRCTC mobile applications are a very important tool and that can really make our life very easy to live. These pro app provided by IRCTC is really very helpful if you a regular traveler and want to check your PNR status and railway following in most time intervals.

So don’t miss to download this app. Please do comment and share your views about this!

Saturday, 3 November 2012

Optimize your database cursors (considering SQL Azure)

Yeah, I know most of the DBAs (if not all) say to avoid using cursors in your SQL Server code, but there are still some things, which you can only achieve via cursors. You can read a lot discussions on whether to use cursors or not, is it good, is it bad.

My post is not about arguing what is good and what is bad. My post is about a tiny little option, which, if your logic allows you can use to optimize how your cursor works.

So we are using cursors, for good or bad. Everything might work just fine if we are using on-premise SQL Server, and if the server is not under heavy load. Our stored procedures, which are using cursors are executing in a matter of seconds. There is nothing unusual. We deploy our application to The Cloud. And of course we utilize SQL Azure as our DB backend. Now strange things begin happening. Our stored procedures crash with timeout exceptions. If we login to the server and use the good “sp_who3” (yes, this works in SQL Azure!) to see the processes running, we notice that some procedures do report a  SOS_SCHEDULER_YIELD. You can read a lot of information on what does that mean. As by definition:
Occurs when a task voluntarily yields the scheduler for other tasks to execute. During this wait the task is waiting for its quantum to be renewed.
Most of the resources you will find explaining what does lot of SOS_SCHEDULER_YIELD mead, will suggest high CPU load, non-optimized queries, etc. But we look at our code and there is nothing unusual. Also, as this is SQL Azure, we can’t see the actual CPU load of the OS. We can’t add more CPU or more RAM. What do we do now ?
Well, review once again our cursor logic! If it is the case that we only read from the cursor’s data. We only read forward, never backward. We never change cursor’s data (update/delete). Then there is a pretty good chance that we can use the FAST_FORWARD keyword when declaring our cursors:
Specifies a FORWARD_ONLY, READ_ONLY cursor with performance optimizations enabled. FAST_FORWARD cannot be specified if SCROLL or FOR_UPDATE is also specified.
It is amazing performance booster and load relief! And we, most probably, will never see again the SOS_SCHEDULER_YIELD process status for our procedures.
Most (if not all) of the cursors I’ve written are never reading backward or updating data, so I pretty amazed to see the performance differences using this keyword. I for sure will use it from now on, whenever possible!.