How to get set read TextBox value using JQuery: Simple a + b program Thursday, Oct 28 2010 

As we knew that using javascript to read or get or set textbox value is easy but due to JQuery notation novice developers always make mistakes to read textbox value. Here in this article i will show you how one can get set read textbox value or textbox text using JQuery.

To run the example first add a page in your project. Then add three textboxes and one command button to do sum like below:

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="jQuery1.aspx.cs" Inherits="jQuery1" %>

<!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 runat="server">
    <title>How to read TextBox value using JQuery</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:TextBox runat="server" ID="txtFirst"></asp:TextBox>
        <asp:TextBox runat="server" ID="txtSecond"></asp:TextBox>
        <asp:Button runat="server" ID="btn" Text="+" />
        <asp:TextBox runat="server" ID="txtSum"></asp:TextBox>
    </div>
    </form>
</body>
</html>

Now add the below JQuery script which will read two number from txtFirst & txtSecond and set the result into third TextBox:

<script language="javascript">
            $(document).ready(function() {          
                $('#btn').click(function() {

                    // Read First number & 2nd Number from TextBox
                    var $nFirstNum = parseInt($('#txtFirst').val())
                    var $nSecondNum = parseInt($('#txtSecond').val())
                    var $nResult = $nFirstNum+$nSecondNum

                    // Set the result into txtSum TextBox
                    $('#txtSum').val($nResult)
                    return false;
                });
            });
    </script>

Now run the page. Hope you will get below interface:

JQuery SUM

Hope now you can read or write value to a TextBox using JQuery easily.

Source: http://shawpnendu.blogspot.com/2010/05/how-to-get-set-read-textbox-value-using.html

How to know IP address of a client Machine using JQuery Thursday, Oct 28 2010 

It’s very easy to get IP of any machine.

First I was trying to do it using javascript. But I think it was not possible to do so.

Then my friend suggest me to try with jquery. This is my first experience to work with jquery.

I searched on google and I got code for it. It’s just 2 lines code.

$(document).ready(function(){

alert();

$(‘button’).click(function()
{
alert(‘saa’);
$.getJSON(“http://jsonip.appspot.com?callback=?&#8221;,function(ipadd){
alert( “Your IPAddress is : ” + ipadd.ip);
});
});
});

Easy ???

Don’t forget to add reference of JQuery file.

How to create a simple class in Javascript with Hello world Example Monday, Oct 25 2010 

Hello, world!

JavaScript OOP Tutorial: Classes

This is a JavaScript DOM exercise from Chapter 3 of Microsoft AJAX Library Essentials: JavaScript in ASP.NET AJAX 1.0 Explained.

Not only that JavaScript functions can contain other functions, but they can also be instantiated. This makes JavaScript functions a good candidate for implementing the concept of class from traditional object-oriented programming. This is very helpful feature indeed, because JavaScript doesn’t support the notion of class in the classic sense of the word. Functions can be instantiated using the new operator, such as in this example:

var myHelloWorld = new ShowHelloWorld();

This line of code effectively creates an object named myHelloWorld, which represents an instance of the ShowHelloWorld() function. When the object is instantiated, the function code is executed, so creating the object has the same effect as calling ShowHelloWorld() like in the previous examples.

Here are a few facts that will help you port your C# OOP knowledge into the JavaScript world:

  • When a function is used as a class, its body code is considered to be the constructor. In classic OOP, the constructor is a special method that doesn’t return anything, and that is called automatically when the object is created. The same effect happens in JavaScript when creating an instance of the function: its code executes. A C# constructor is equivalent with the code in the JavaScript function – without including any inner functions (whose code doesn’t execute automatically).
  • In C# constructors can receive parameters, and also in JavaScript. If the code in a function represents the “class constructor”, the parameters received by that function play the role of constructor parameters.
  • Class fields in JavaScript are created and referenced with the this keyword. In a JavaScript function, this.myValue is a public member of the function (class), while myValue is a local variable that can’t be accessed through function instances. Also, the local variable is destroyed after the function executes, while class fields persist their value for the entire object life time.
  • Class methods that need to be accessible from outside the class need to be referred using this as well. Otherwise the inner function will be regarded as a local function variable, rather than a “class” member.

We’ll demonstrate these concepts by transforming the ShowHelloWorld() function that you saw earlier into a “real” class. We will:

  • Change the name of the function from ShowHelloWorld() to HelloWorld().
  • Add a parameter named hour to the function’s “constructor” so that we tell the class the hour for which we need a greeting message, when instantiating it. If this parameter is passed when creating objects of the class, we store it for future use as a class field. If this parameter is not specified, the current hour of the day should be stored instead.
  • The method DisplayGreeting() of the class should not support the hour parameter any longer. Instead, it should display the greeting message depending on the hour field that was initialized by the constructor.

TIP. Why are we changing the name of the function? Remember, OOP is a style of coding, not a list of technical requirements that a language must support. JavaScript is considered as an OOP-capable language because it supports an object-based programming style. In the OOP paradigm, a class should represent an entity, and not an action. Since we intend now to use ShowHelloWorld() as a class, we are changing its name to one that reflects this purpose.

Once your new class is created, you use it just like you’d use a C# class. For example, this is how you’d create a new class instance, and call its DisplayGreeting() method:

// create class instance
var myHello = new HelloWorld();

// call method
myHello.DisplayGreeting();

A possible implementation of the HelloWorld class is the following.

// "Hello, World" class
function HelloWorld(hour)
{
  // class "constructor" initializes this.hour field
  if (hour)
  {
    // if the hour parameter has a value, store it as a class field
    this.hour = hour;
  }
  else
  {
    // if the hour parameter doesn't exist, save the current hour
    var date = new Date();
    this.hour = date.getHours();
  }

  // display greeting
  this.DisplayGreeting = function()
  {
    if (this.hour >= 22 || this.hour <= 5) 
      document.write("Goodnight, world!");
    else
      document.write("Hello, world!");
  }  
}

The HelloWorld class is formed of the constructor code that initializes the hour field (this.hour), and of the DisplayGreeting method – this.DisplayGreeting(). Fans of the ternary operator can rewrite the constructor using this shorter form, which also makes use of the object detection feature that was discussed in Chapter 2:

  // define and initialize this.hour
  hour = (hour) ? hour : (new Date()).getHours();

TIP: The ternary operator is supported both by C# and JavaScript. It has the form (condition ? valueA : valueB). In case the condition is true, the expression returns valueA, otherwise it returnsvalueB. In the shown example, object detection is used to test if a value was supplied for the hour parameter. If it was not, the current hour is used instead.

Implement the exercise step by step and find detailed explanations in our book, Microsoft AJAX Library Essentials: JavaScript in ASP.NET AJAX 1.0 Explained.

Reference: http://www.cristiandarie.ro/asp-ajax/JavaScriptClass.html

How to detect browsers using javascript Monday, Oct 25 2010 

There is a very simple approach to detecting the browser name using java script:

function detect_browser()
{
var browser_name = navigator.userAgent;
// We have to check for Opera first because
// at the beginning of the userAgent variable
// Opera claims it is MSIE.

if (browser_name.indexOf(“Opera”)!= -1)
browser_name = “Opera”;
else if (browser_name.indexOf(“Firefox”)!= -1)
browser_name = “Firefox”;
else if (browser_name.indexOf(“MSIE”)!= -1)
browser_name = “MSIE”;
else if (browser_name.indexOf(“Netscape”)!= -1)
browser_name = “Netscape”;
else if (browser_name.indexOf(“Safari”)!= -1)
browser_name = “Safari”;

alert(browser_name);

} // end function detect_browser()

How to get HTML table data without knowing the table id/name using javascript Friday, Oct 22 2010 

In this article I will show you how to fetch data from a table without knowing the table id or table name from a page.

It’s rather easy but when I face this problem it takes too long to resolve it.

So let’s start from HTML content. Suppose we have two table in our page we wants to traverse a particular table which doesn’t have id. The HTML content looks like:

<body onLoad=”GetTdContent();”>
<div id=”div1″>
<table border=”1″>
<tr>
<td>Name</td>
<td>Designation</td>
<td>Company Name</td>
</tr>
<tr>
<td>ABCD</td>
<td>Software Engineer</td>
<td>Microsoft</td>
</tr>
<tr>
<td>WXYZ</td>
<td>Manager</td>
<td>Oracle</td>
</tr>
<tr>
<td>PQRS</td>
<td>Salesman</td>
<td>Google</td>
</tr>
</table>
</div>
<table border=”1″>
<tr>
<td>Name</td>
<td>Designation</td>
<td>Company Name</td>
</tr>
<tr>
<td>ABC</td>
<td>Software Engineer</td>
<td>Infosys</td>
</tr>
<tr>
<td>XYZ</td>
<td>HR Manager</td>
<td>TCS</td>
</tr>
<tr>
<td>PQR</td>
<td>Salesman</td>
<td>HCL</td>
</tr>
</table>
</body>

Here we have two tables and we are calling a method(GetTdContent) on body load event. I think nothing is special here.

Now let’s go thru javascript code of this:

<script language=”javascript”>
function GetTdContent()
{
var theDivElement = document.getElementById(“div1”);
var Tables = theDivElement.getElementsByTagName(“table”);
alert(Tables.length);
var foundFlag = false;
if (theDivElement != null)
{
if(Tables.length > 0)
{
var TRs = Tables[0].getElementsByTagName(“tr”);
for (var j = 0; j < TRs.length; j++)
{
if(j == 0)
{
var TDs = TRs[j].getElementsByTagName(“td”);
var headVariable = “”;
for (var i = 0; i < TDs.length; i++)
{
headVariable += TDs[i].innerHTML + ”  “;
}
alert(headVariable + ” “);
}
else
{
var elementVariable = “”;
var TDs = TRs[j].getElementsByTagName(“td”);
for (var i = 0; i < TDs.length; i++)
{
elementVariable += TRs[j].getElementsByTagName(“td”)[i].innerHTML + ”  “;
}
alert(elementVariable);
}
}
}
}
}
</script>
That’s it.

 

How to read an Excel file in C# Thursday, Oct 21 2010 

From the following section you can see How to find the last row data in Excel worksheet or How to find the Used area in an Excel worksheet from C#.

The following C# source code using Microsoft Excel 12.0 Object Library for reading an Excel file. In the previous section we saw how to import Microsoft Excel 12.0 Object Library in the CSharp project .

Create Excel file from CSharp

For reading entire content of an Excel file in C#, we have to know how many cells used in the Excel file. In order to find the used range we use “UsedRange” property of xlWorkSheet . It will return the last cell of used area.

Excel.Range range ;

range = xlWorkSheet.UsedRange;

using System;
using System.Windows.Forms;
using Excel = Microsoft.Office.Interop.Excel; 

namespace WindowsApplication1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            Excel.Application xlApp ;
            Excel.Workbook xlWorkBook ;
            Excel.Worksheet xlWorkSheet ;
            Excel.Range range ;

            string str;
            int rCnt = 0;
            int cCnt = 0;

            xlApp = new Excel.ApplicationClass();
            xlWorkBook = xlApp.Workbooks.Open("csharp.net-informations.xls", 0, true, 5, "", "", true, Microsoft.Office.Interop.Excel.XlPlatform.xlWindows, "\t", false, false, 0, true, 1, 0);
            xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);

            range = xlWorkSheet.UsedRange;

            for (rCnt = 1; rCnt <= range.Rows.Count; rCnt++)
            {
                for (cCnt = 1; cCnt <= range.Columns.Count; cCnt++)
                {
                    str = (string)(range.Cells[rCnt, cCnt] as Excel.Range).Value2 ;
                    MessageBox.Show(str);
                }
            }

            xlWorkBook.Close(true, null, null);
            xlApp.Quit();

            releaseObject(xlWorkSheet);
            releaseObject(xlWorkBook);
            releaseObject(xlApp);
        }

        private void releaseObject(object obj)
        {
            try
            {
                System.Runtime.InteropServices.Marshal.ReleaseComObject(obj);
                obj = null;
            }
            catch (Exception ex)
            {
                obj = null;
                MessageBox.Show("Unable to release the Object " + ex.ToString());
            }
            finally
            {
                GC.Collect();
            }
        } 

    }
}
When you execute this C# source code the program read all used cells from Excel file.

reference: http://csharp.net-informations.com/excel/csharp-read-excel.htm


 

How to create Excel file in C# Thursday, Oct 21 2010 

The following section explains how to create an Excel file programmatically using C#.

Before you create an Excel file in C# , you have to add the Microsoft Excel 12.0 Object Library to you project.

Create a new project and add a Command Button to the Form.

Form the following pictures you can find how to add Excel reference library in your project.

Select reference dialogue from Project menu

scsharp-excel-reference

Select Microsoft Excel 12.0 Object Library and click OK button

csharp-excel-library

Copy and paste the following source code in your C# project file.

 

using System;
using System.Windows.Forms;
using Excel = Microsoft.Office.Interop.Excel; 

namespace WindowsApplication1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            Excel.Application xlApp ;
            Excel.Workbook xlWorkBook ;
            Excel.Worksheet xlWorkSheet ;
            object misValue = System.Reflection.Missing.Value;

            xlApp = new Excel.ApplicationClass();
            xlWorkBook = xlApp.Workbooks.Add(misValue);

            xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);
            xlWorkSheet.Cells[1, 1] = "http://csharp.net-informations.com";

            xlWorkBook.SaveAs("csharp-Excel.xls", Excel.XlFileFormat.xlWorkbookNormal, misValue, misValue, misValue, misValue, Excel.XlSaveAsAccessMode.xlExclusive, misValue, misValue, misValue, misValue, misValue);
            xlWorkBook.Close(true, misValue, misValue);
            xlApp.Quit();

            releaseObject(xlWorkSheet);
            releaseObject(xlWorkBook);
            releaseObject(xlApp);

            MessageBox.Show("Excel file created , you can find the file c:\\csharp-Excel.xls");
        }

        private void releaseObject(object obj)
        {
            try
            {
                System.Runtime.InteropServices.Marshal.ReleaseComObject(obj);
                obj = null;
            }
            catch (Exception ex)
            {
                obj = null;
                MessageBox.Show("Exception Occured while releasing object " + ex.ToString());
            }
            finally
            {
                GC.Collect();
            }
        }
    }
}
Note : You have to add Microsoft.Office.Interop.Excel to your source code. 
using Excel = Microsoft.Office.Interop.Excel; 

When you execute this program , it will create an excel file in you c:

Reference: http://csharp.net-informations.com/excel/csharp-create-excel.htm

 

 

How to find IP Adress Thursday, Oct 21 2010 

Network programming in console/windows is possible with sockets . C# simplifies network programming through its namespaces like System.Net and System.Net.Sockets .

The System.Net classes provide functionalities that is similar to Microsoft WinInet API. The System.net namespace provides the information about IP Address . The following C# program shows how to find the IP Address of a host.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
namespace GetIPAddressDemo2
{
class Program
{
static void Main(string[] args)
{
Console.Write(“Enter Host name(e.g. http://www.google.com): “);
string host = Console.ReadLine();
try
{
IPHostEntry hostname = Dns.GetHostEntry(host);
IPAddress[] ip = hostname.AddressList;
Console.WriteLine(“\nIP Address is ” + ip[0].ToString());
Console.ReadKey();
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
}
}
}

Reference: http://csharp.net-informations.com/communications/csharp-ip-address.htm

ACID Properties of Database Tuesday, Oct 19 2010 

In a perfect transaction world, a transaction must contain a series of properties known as ACID. These properties are:
Atomicity
A transaction is an atomic unit of work or collection of separate operations. So, a transaction succeeds and is committed to the database only when all the separate operations succeed. On the other hand, if any single operations fail during the transaction, everything will be considered as failed and must be rolled back if it is already taken place. Thus, Atomicity helps to avoid data inconsistencies in database by eliminating the chance of processing a part of operations only.
Consistency
A transaction must leave the database into a consistent state whether or not it is completed successfully. The data modified by the transaction must comply with all the constraints in order to maintain integrity.
Isolation
Every transaction has a well defined boundary. One transaction will never affect another transaction running at the same time. Data modifications made by one transaction must be isolated from the data modification made by all other transactions. A transaction sees data in the state as it was before the second transaction modification takes place or in the state as the second transaction completed, but under any circumstance a transaction can not be in any intermediate state.
Durability
If a transaction succeeds, the updates are stored in permanent media even if the database crashes immediately after the application performs a commit operation. Transaction logs are maintained so that the database can be restored to its original position before failure takes place.

Reference: http://www.dotnetfunda.com/codes/code21-acid-properties-of-database-.aspx

An Introduction to Database Normalization Tuesday, Oct 19 2010 

n this article, we’ll introduce the concept of normalization and take a brief look at the most common normal forms. Future articles will provide in-depth explorations of the normalization process.

What is Normalization?

Normalization is the process of efficiently organizing data in a database. There are two goals of the normalization process: eliminating redundant data (for example, storing the same data in more than one table) and ensuring data dependencies make sense (only storing related data in a table). Both of these are worthy goals as they reduce the amount of space a database consumes and ensure that data is logically stored.

The Normal Forms

The database community has developed a series of guidelines for ensuring that databases are normalized. These are referred to as normal forms and are numbered from one (the lowest form of normalization, referred to as first normal form or 1NF) through five (fifth normal form or 5NF). In practical applications, you’ll often see 1NF2NF, and 3NF along with the occasional 4NF. Fifth normal form is very rarely seen and won’t be discussed in this article.

Before we begin our discussion of the normal forms, it’s important to point out that they are guidelines and guidelines only. Occasionally, it becomes necessary to stray from them to meet practical business requirements. However, when variations take place, it’s extremely important to evaluate any possible ramifications they could have on your system and account for possible inconsistencies. That said, let’s explore the normal forms.

First Normal Form (1NF)

First normal form (1NF) sets the very basic rules for an organized database:

  • Eliminate duplicative columns from the same table.
  • Create separate tables for each group of related data and identify each row with a unique column or set of columns (the primary key).

Second Normal Form (2NF)

Second normal form (2NF) further addresses the concept of removing duplicative data:

  • Meet all the requirements of the first normal form.
  • Remove subsets of data that apply to multiple rows of a table and place them in separate tables.
  • Create relationships between these new tables and their predecessors through the use of foreign keys.

Third Normal Form (3NF)

Third normal form (3NF) goes one large step further:

  • Meet all the requirements of the second normal form.
  • Remove columns that are not dependent upon the primary key.

Fourth Normal Form (4NF)

Finally, fourth normal form (4NF) has one additional requirement:

  • Meet all the requirements of the third normal form.
  • A relation is in 4NF if it has no multi-valued dependencies.

Remember, these normalization guidelines are cumulative. For a database to be in 2NF, it must first fulfill all the criteria of a 1NF database.

Reference: http://databases.about.com/od/specificproducts/a/normalization.htm

Next Page »