Senin, 30 Desember 2013

Mathematical Functions to Work with Numerical Values in Sql Server: SQL Programming

In SQL Programming, mathematical functions are used to operate with numeric values. Programmer can easily perform all type of scientific functions as well as simple arithmetic operations using these mathematical functions.

Programmer can use mathematical functions to manipulate the numeric values in a result set. You can perform various numeric and arithmetic operations on the numeric values. For example, you can calculate the absolute value of a number or you can calculate the square or square root of a value.

The following table lists the mathematical functions provided by SQL Server 2005.

  • Abs, Returns an absolute value
  • Acos, asin and atan, returns the angle in radians whose cosine, sine, or tangent is a floating-point value
  • Cos, sin, cot and tan, returns the cosine, sine, cotangent, or tangent of the angle in radians
  • Degrees, returns the smallest integer greater than or equal to the specified value
  • Exp, returns the exponential value of the specified value
  • Floor, returns the largest integer less than or equal to the specified volume
  • Log, returns the natural logarithm of the specified value
  • Log10, returns the base-10 logarithm of the specified value
  • Pi, returns the constant value of 3.141592653589793
  • Power, returns the value of numeric_expression to the value of y
  • Radians, converts from degrees to radians
  • Rand, returns a random float number between 0 and 1
  • Round, returns a numeric expression rounded off to the length specified as an integer expression
  • Sign, returns positive, negative, or zero
  • Sqrt, returns the square root of the specified value
For example, to calculate the round off value of any number, you can use the round mathematical function. The round mathematical function calculates and returns the numeric value based on the input values provided as an argument.

The syntax of the round function is:
round (numeric_expression, length)

where

  • numeric_expression is the numeric expression to be rounded off.
  • Length is the precision to which the expression is to be rounded off.
The following SQL query retrieves the EmployeeID and Rate for a specified employee id from the EmployeePayHistory table:

SELECT BusinessEntityID, 'Hourly Pay Rate' = round (Rate, 2)
FROM HumanResources.EmployeePayHistory WHERE BusinessEntityID =3

In the result set, the value of the Rate column is rounded off to two decimal places.

Mathematical Functions to Work with Numerical Values in Sql Server: SQL Programming

While using the round function, if the length is positive, then the expression is rounded to the right of the decimal point. If the length is negative then the expression is rounded to the left of the decimal point. SQL Server provides the following usage of the round function.

  • Round (1234.567, 2) outputs 1234.570
  • Round (1234.567, 1) outputs 1234.600
  • Round (1234.567, 0) outputs 1235.000
  • Round (1234.567, -1) outputs 1230.000
  • Round (1234.567, -2) outputs 1200.000
  • Round (1234.567, -3) outputs 1000.000

Use Date Functions to Operate with Date Values in Sql Server: SQL Programming

In SQL Programming, programmer can use the date functions of the SQL Server to manipulate date-time values. You can either perform arithmetic operations on date values or parse the date values. Date parsing includes extracting components, such as the day, the month, and the year from a date value.

Programmer can also retrieve the system date and use the value in the date manipulation operations. To retrieve the current system date, you can use the getdate function. The following statement displays the current date:

SELECT getdate ( )

The following SQL query uses the datediff function to calculate the difference between the current date and the date of birth of employees in AdventureWorks, Inc. The date of birth of employees is stored in the BirthDate column of the Employee table.

SELECT datediff (yy, BirthDate, getdate()) AS 'Age'
FROM HumanResources.Employee

Outputs:

Use Date Functions to Operate with Date Values in Sql Server: SQL Programming

The following table lists the date functions provided by SQL Server.

  • dateadd, adds the number of date parts to the date
  • datediff, calculates the number of date parts between two dates
  • datename, returns date part from the listed date, as a character value (for example, October)
  • datepart, returns date part from the listed date as an integer
  • getdate(), returns the current date and time, day, (date), returns an integer, which represents the day getutcdate, returns the current date of the system in Universal Time Coordinate (UTC) time. UTC time is also known as the Greenwich Mean Time (GMT)
  • month, returns an integer, which represents the month
  • year, returns an integer which represents the year

SQL Server provides the following abbreviation and values of the datepart function

  • Year, Abbreviation -- (yy,yyyy),  may have values (1753-9999)
  • Qartr, Abbreviation -- (qq, q), may have values (1-4)
  • Month, Abbreviation -- (mm, m), may have values (1-12)
  • Day of year, Abbreviation -- (dy, y), may have values (1-366)

Minggu, 29 Desember 2013

Computer Programming: Add item with value in code file, ASP.NET Example

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="itemwithvalue.aspx.cs" Inherits="itemwithvalue" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
   
        <asp:RadioButtonList ID="RadioButtonList1" runat="server" Height="65px" Width="235px">
        </asp:RadioButtonList>
   
    </div>
    </form>
</body>
</html>

Code File
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class itemwithvalue : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {
            RadioButtonList1.Items.Add(new ListItem("ASP.NET", "FIRST NUMBER"));
            RadioButtonList1.Items.Add(new ListItem("WINFORMS", "SECOND NUMBER"));
            RadioButtonList1.Items.Add(new ListItem("WPF", "THIRD NUMBER"));
            RadioButtonList1.Items.Add(new ListItem("WCF", "FORTH NUMBER"));
           
        }
    }
}

Output
Computer Programming: Add item with value in code file, ASP.NET Example
 

Computer Programming : TextBox WatermarkExtender control in Ajax with example

Computer Programming : TextBox WatermarkExtender is used to provide a tip to the user that specifies the type of parameter entered within the text box. This extender attaches to a TextBox control and displays a text within the text box when the web page render for the first time. When the user clicks the text box to insert values, the default text gets hidden.

Public Properties of TextBox Watermark Extender are

TargetControlID : Sets the .ID of the TextBox control to which you want to attach the extender
WatermarkText  : Sets the text to display when the value in the text box is empty.
watermarkCssClass : Sets the CSS class for the text box when it is empty.
 

Lets take a simple example

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="watermark-example.aspx.cs" Inherits="watermark_example" %>
<%@ Register assembly="AjaxControlToolkit" namespace="AjaxControlToolkit" tagprefix="asp" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
        <asp:ScriptManager ID="ScriptManager1" runat="server"></asp:ScriptManager>
    <div>
   
        <asp:TextBox ID="TextBox1" runat="server" Height="18px" Width="205px"></asp:TextBox>
        <asp:TextBoxWatermarkExtender ID="TextBox1_TextBoxWatermarkExtender" runat="server" Enabled="True" TargetControlID="TextBox1" WatermarkText="Use ; as a separator">
        </asp:TextBoxWatermarkExtender>
        <asp:Button ID="Button1" runat="server" Text="Search" BorderColor="Black" BorderStyle="Solid" BorderWidth="2px" Width="71px" />
   
    </div>
    </form>
</body>
</html>
Output
Computer Programming : Watermark Textbox example in asp.net

Sabtu, 28 Desember 2013

Computer Programming : How to create new user role in drupal like Author

User Role

If you want to handle your website from different users then you should go for user role concept. Role is a function, which is declared for users. According to Drupal CMS
Roles allow you to fine tune the security and administration of Drupal. A role defines a group of users that have certain privileges as defined on the permissions page. Examples of roles include: anonymous user, authenticated user, moderator, administrator and so on. In this area you will define the names and order of the roles on your site. It is recommended to order your roles from least permissive (anonymous user) to most permissive (administrator). To delete a role choose "edit role".
By default, Drupal comes with two user roles:
•Anonymous user: this role is used for users that don't have a user account or that are not authenticated.
•Authenticated user: this role is automatically granted to all logged in users.

Lets take a simple example to understand how to add it in Drupal

Step-1 : Logged into your admin account.
Step-2 : Select 'People' tab from admin toolbar.
 
Administrator tool bar in drupal
 
 
Step-3 : Select Permissions tab (top right side) in appearing window.
Permission tab in drupal
 
 
Step-4 : Select role in appear new window (top right side bar).
Select role in appear new window (top right side bar).
 
 
Step-5 : Write role name in given textbox also click Add role button.
 
Add role in Drupal
 
Step-6 :  Click Save Order button.

Jumat, 27 Desember 2013

Computer Programming : How to create new user in drupal

In Computer Programming, you work on different types of module such as functions, inbuilt libraries etc.. Same as in Drupal CMS you have to work on different modules like core module(captcha, aggregator module, token module) and community module. Here we learn about user module and their functionality like how to create new user, user permission etc.

User

User also known as person, who work in website. Basically two types of user exists in any system, first is anonymous user and second one is authenticated user. Those person are authenticated for website which is registered in the site. Who doesn't registered in the site, known as anonymous user. 
 

Different steps of creating new user in Drupal CMS

Step-1 : Logged into your administrator account.
Computer Programming : How to create new user in drupal
 
Step-2 : Select Configuration tab, which is snap given above.


Administrator toolbar contains some administrative links like Content, Structure, Appearance etc. Specific link designed for specific tasks.
Step-3 : Select Administration link in appearing window, which is given below.

Computer Programming : How to create new user in drupal

Step-4 : Select People in given below snap, which is provides user account information, role information etc.
Computer Programming : How to create new user in drupal

Step-5 : For adding new user in CMS, click 'Add user' link.
Computer Programming : How to create new user in drupal













 

Step-6 : Filled Required Field and click to save button.

 
Computer Programming : How to create new user in drupal

Kamis, 26 Desember 2013

How to Work with Basic Controls in NetBeans: Java Programming

After talking about many elementary concepts and features of GUI in Java, we have reached a point where we can design our first application. But prior to that we shall learn to work with some most common controls. And after that we shall design our very first GUI application.

There are many graphical controls that are used in java GUI programming. Here’re the list of common GUI controls used:

  • TextField is a basic field that allows the user to type some textual information. It allows at most one line of input. To input some more lines, programmer have to use TextArea discussed below.
  • Label is another basic control that lets you display uneditable text. It is the basic unit that is used almost in every jFrame in Java GUI Application. Label is used to indicating about to do something like in entry form it indicates about where to enter name, address etc.
  • Button displays common GUI button and performs an action when the users clicks on it or presses Enter key after choosing it. Used when programmer wants to do something on the Frame window.
  • TextArea is a component that is used to input multiple lines of text. It optionally allows the user to edit the text. Programmer can also disable the editing option for the user.

After working a lot in NetBeans IDE, programmer have to save the overall work for further use. Programmer can save the work by clicking File → Save or File → Save As commands. Toolbar have also an icon to do the same task i.e. Save.

In further articles we will do some creativity to learn more about these controls as well as working of these controls in NetBeans IDE.

Use String Functions to Manipulate String Values in Sql Server: SQL Programming

In Sql Programming, programmer can use the string functions to manipulate the string values in the result set. There are list of string functions used in sql server and explained in this article. For example, to display only the first eight characters of the values in a column, you can use the left ( ) string function.

String functions are used with the char and varchar data types. The SQL Server provides string functions that can be used as a part of the character expression. These functions are used for various operations on string.

Syntax:
    SELECT function_name (parameters)

Where
  • Function_name is the name of the function
  • parameters are the required parameters for the string function.
The following table lists the string functions provided by SQL Server
  • Ascii, returns the ASCII code of the leftmost character, e.g. SELECT ascii (‘ABC’) will return ascii code of 'A'.
  • Char, return the character equivalent of the ASCII code value, e.g. SELECT char (65)   
  • Charindex, returns the starting position of the specified pattern in the expression e.g. SELECT charindex (‘E’, ‘HELLO’)
  • Difference, compares two strings and evaluates the similarity between them, returning a value from 0 through 4. The value 4 is the best match e.g. SELECT difference (‘HELLO’, ‘hell’)
  • Left, returns apart of the character string equal in size to the integer_expression    characters from the left e.g. SELECT left(‘RICHARD’, 4) will return RICH
  • Len, returns the number of characters in the character_expression e.g. SELECT len(‘RICHARD’)
  • Lower, returns after converting character_expression to lower case e.g. SELECT lower (‘RICHARD’)
  • Ltrim, removes leading blanks from the character expression e.g. SELECT ltrim (‘RICHARD’)
  • Patindex, returns staring position of the first occurrence of the pattern in the specified expression, or zeros if the pattern is not found e.g. SELECT patindex (‘%BOX%’, ‘ACTIONBOX’)
  • Reverse, returns reverse of the character_expression e.g. SELECT reverse (‘ACTION’)
  • Right, returns a part of the character string, after extracting from the right the number of characters specified in the integer_expression e.g. SELECT right (‘RICHARD’, 4) will return HARD
  • Rtrim, returns after removing any trailing blanks from the character expression e.g. SELECT rtrim (‘RICHARD   ’)
  • Space, spaces are inserted between the first and second word e.g. SELECT ‘RICHARD’+space (2)+’HILL’, will add two spaces between 1st and 2nd word.
  • Str, converts numeric data to character data where the length is the total length, including the decimal point, the sign, the digits, and the spaces and the decimal is the number of places to the right of the decimal point e.g. SELECT str (123.45, 6, 2)
  • Stuff, deletes the number of characters as specified in the character_expression1 from the start and then inserts char_expression2 into character_expression1 at the start position e.g. SELECT stuff (‘Weather’, 2,2, ‘I’) will returns ‘wither’.
  • Substring, returns the part of the source character string from the start position of the expression e.g. SELECT substring (‘weather’, 2,2) will return ‘ea’.
  • Upper, converts lower case characters to upper case e.g. SELECT upper (‘Richard’)

The following SQL query uses the upper string function to display data in uppercase. The Name, DepartmentID, and GroupName columns are retrieved from the Department table and the data of the Name column is displayed in uppercase with a user-defined heading, Department Name:
 
SELECT 'Department Name' = upper (Name), DepartmentID, GroupName
FROM HumanResources.Department

 
Outputs:

Use String Functions to Manipulate String Values in Sql Server: SQL Programming

How to Customize the Result Set using Functions in SQL Server: SQL Programming

SQL server provides some in-built functions to hide the steps and the complexity from other code. Generally in sql programming, functions accepts parameters, perform some actions and return a result.

While querying data from SQL Server, programmer can use various in-built functions to customize the result set. Some of the changes includes changing the format of the string or date values or performing calculations on the numeric values in the result set. For example, if you need to display all the text values in uppercase, you can use the upper () string function. Similarly, if you need to calculate the square of the integer values, you can use the power ( ) mathematical function.

Depending on the utility, the in-built functions provided by SQL Server are categorized as listed below:
All these functions are for specific use in sql programming like string functions are used to manipulate the string in result set, to manipulate date values date functions are used, as so on. Arithmetic operations can also be performed with these functions like add, subtract operations on any of the above listed type of functions.

Functions can be easily used anywhere in the sql programming to build the software composable. Programmer can use these functions in constraints, computed columns, where clauses even in other functions. Overall the result, functions are powerful part in sql server.

Further article will describe about the use and example of above listed functions.

Selasa, 24 Desember 2013

How to Delete Multiple Records from DataGridView in Winforms: C#

To remove multiple records from the DataGridView, programmer need to write some line of code, code may be written in a button's click event that is outside of the DataGridView. The article shows about how to select multiple records of DataGridView and the c# code to remove them with a single mouse click.

When a programmer have to remove a single record entry from the DataGridView, then a command button can be added as discussed. Removing a single record can be performed by the index of the record. Through the index programmer can easily get all the unique values about the record which helps to perform the action.

To remove multiple records, follow the steps written below:
  • Drag-n-Drop DataGridView on the form and set its MultiSelect property to True.
  • Create a list of records (Student Class) and bind this DataGridView with that list.
  • Create a button outside of this DataGridView and generate its click event.
  • Write following C# code in the click event of button to remove multiple records:
private void removeButton_Click(object sender, EventArgs e)
{
DataContext dc = new DataContext();
foreach (var item in dataGridView1.Rows)
{
DataGridViewRow dr = item as DataGridViewRow;
if (dr.Selected)
{
string name = dr.Cells["Name"].Value.ToString();
var student = dc.Student.FirstOrDefault(a => a.Name.Equals(name));
if (student != null)
{
dc.Student.Remove(student);
}
}              
}
dataGridView1.DataSource = null;
dataGridView1.DataSource = dc.Student;
}
  • Run the form and select some of the records as in the image:
How to Delete Multiple Records from DataGridView in Winforms: C#

  • Click on the remove button and all these selected records will be deleted. A single record remain safe shown in the image:
How to Delete Multiple Records from DataGridView in Winforms: C#


So all these simple steps are used to delete multiple as well as single record from the DataGridView. Programmer can also use a confirmation message for the surety of the deletion by the user. To do that, just place all the above code in between the below c# code:

if (MessageBox.Show("Are you sure you want to remove all these records?", "Confirm", MessageBoxButtons.YesNo, MessageBoxIcon.Question).ToString() == "Yes")
{
//above code
}

When the programmer will click on the button then a confirmation message will be shown. After clicking on the "Yes" button, all the selected records will be deleted otherwise none of them.

Bubble Sort Algorithm in Computer Programming: C

More often in computer programming, programmers works with large amount of data and it may be necessary to arrange them in ascending or descending order. This process of arranging the given elements in a order is called sorting, the order may be ascending or descending.

For example, consider the unsorted elements:
10, 60, 50, 20, 30, 70, 40
After arranging them in ascending order, the elements are rearranged as shown below:
10, 20, 30, 40, 50, 60, 70
After arranging them in descending order, the elements are rearranged as shown below:
70, 60, 50, 40, 30, 20, 10

The two important and simple sorting techniques are described below with example:

Bubble sort

This is the simplest and easiest sorting technique. In this technique, the two successive items or elements arr[i] and arr[i+1] are exchanged whenever the condition arr[i]>arr[i+1] will be true. For example, consider the elements shown below:

Bubble Sort Algorithm in Computer Programming: C

In the first pass 50 is compared with 40 and they are exchanged since 50 is greater than 40. Next 50 is compared with 30 and they are exchanged since 50 is greater than 30. If we proceed in the same manner, at the end of the first pass the largest item occupies the last position. On each successive pass, the items with the next largest value will be moves to the bottom and thus elements are arranged in ascending order.

Note: Observe that after each pass, the larger values sink to the bottom or next position of the array and hence it is also called sinking sort. The following figure shows the output of each pass:

Bubble Sort Algorithm in Computer Programming: C

Note: Observe that at the end of each pass, smaller values gradually "bubble" up to the top (like air bubble moving to surface of water). So, this sorting technique is called bubble sort.

The comparisons that are performed in each pass are as follows:

In general, we can say i = 0 to n-(j+1) or i=0 to n-j-1. Here, j=1 to 4 represent pass numbers. In general j=1 to n-1. So, the partial code can be written as follows:
for(j=1; j<n; j++)
{
  for(i=0; i<n-j; i++)
   {
     if(arr[i]>arr[i+1])
     {
       exchange (arr[i], arr[i+1])
      }
   }
}

Algorithm

Step 1:    [Input number of items]
Read: n
Step 2:    [Read n items]
    for I = 0 to n-1
        Read: arr[i]
    [End of for]
Step 3:    for j = 1 to n-1 do
          for i = 0 to n-j do
        if(arr[i] >= arr[i+1])
             temp = arr[i]
             arr[i] = arr[i+1]
             arr[i+1] = temp
        [End of if]
          [End of for]
    [End of for]
Step 4:    for i = 0 to n-1
          Write: arr[i]
    [End of for]
Step 5:    Exit

C Program.

main()
{
 int n,i,j,temp,arr[10];
 clrscr();
printf("Enter the number of items:");
scanf("%d",&n);
printf("Enter the items:");
for(i=0;i<n;i++)
scanf("%d",&arr[i]);
for(j=0;j<n;j++)
{
 for(i=0;i<n-j;i++)
{
 if(arr[i]>=arr[i+1])
{
temp=arr[i];
arr[i]=arr[i+1];
arr[i+1]=temp;
}
}
}
printf("The sorted items are:\n");
for(i=0;i<n;i++)
printf("%d\n",arr[i]);
getch();
}

Bubble Sort Algorithm in Computer Programming: C

Advantages

  • Very simple and easy to program
  • Straight forward and approach

Disadvantages

  • It runs slowly and hence it is not efficient. More efficient sorting techniques are present.
  • Even if the elements are sorted, n-1 passes are required to sort.


Selection Sort in C

What is Variable Length String Format in Computer Programming: C Language

As the name implies, variable–length strings don’t have a pre-defined length. In this string, neither the precise length nor maximum length is known at the time of creating it. The array storage structure for a string can expand or shrink to accommodate any number of characters. But, there should be a mechanism to indicate the end of the string. The two common techniques to implement variable length strings are described in the article.

Length Controlled String

A length controlled string is a string whose length is stored as part of the string itself. This technique uses a count that specifies string length. The count is normally stored as the first byte followed by the string. This count is used by the string manipulation functions to determine the actual length of the string data.
For example, the strings "DOT" and "PROGRAM" are stored using length controlled format are:

What is Varaible Length String Format in Computer Programming: C Language

Note: The first byte contains string length. Since its length is 1 byte (* bits) w can have a string length whose range is from 0 to 255. So, the string length should not exceed 255 characters.

The disadvantages can be overcome using delimited string. As we use various delimiters such as semicolons, colon, comma, period (.), in a sentence in English, the string can also be ended with delimiters.

Delimited String

In a variable length string, the string ends with a delimiter NULL (denoted by '0') character. This string which ends with a delimiter denoting the end of the string is called delimited string.

For example, the string "DOT" and "PROGRAM" are stored using a delimiter as shown here.

What is Varaible Length String Format in Computer Programming: C Language



String Literals and Constants in Computer Programming: C Language

There is no separate data type for strings in C language. In C language, a string is an array of characters and terminated by NULL character which is denoted by the escape sequence '0'. A NULL terminated string is the only type string defined using C language.

A string is stored as a sequence of characters in an array terminated by \0. For example, consider the string "DOTPROGRAMMING". This string is stored in the form of an array as shown below:

String Literals and Constants in Computer Programming: C Language
Note that the characters are stored from location zero. Each location holds one character string from 0 to 14. The string always ends with NULL. Character denoted by '\0'. Here, the string "DOTPROGRAMING" is called a string literal.

String Literal or Constant

A string literal or constant is a sequence of characters enclosed within double quotes. For example, "DOT PROGRAMMING", "DOT", "PROGRAMMING" are all string literals. When a string literal is defined, the C compiler does the following activities:

  • The compiler creates an array of characters.
  • Initializes each location of array with the characters specified within double quotes in sequence.
  • Null-terminates the string that is appends ‘\0’ at the end of the string. This is done by the compiler automatically.
  • Stores the starting address of the string constant that can be used later. For example, the literals "DOT", and "PROGRAM" can be stored in the memory as shown below:

String Literals and Constants in Computer Programming: C Language

Referencing String Literal or Constant

An array of integers is stored in contiguous memory locations, it is clear from the above figures that a string literal is also stored in memory contiguously one after the other. So, each character of the literal or constant can be accessed using index (array or pointer concept can be used). For example, consider the following program:

main()
{
clrscr();
printf("5c","DOT"[0]);
printf("5c","DOT"[1]);
printf("5c","DOT"[2]);
getch();
 }

The entire string can be referred and display as shown below:

main()
{
clrscr();
printf("DOT");
getch();
 }

Each of the above program will outputs "DOT" string on the monitor or any output device connected with the PC.

Senin, 23 Desember 2013

Computer Programming : How to get height and width of an image in ASP.NET

If you want to get uploaded image height and width then you should go for Bitmap class. Suppose I have an image, and I want to get height and width parameter of it. Lets take an simple example

How to get height and width of an image in ASP.NET

You have an image with height and width parameter. You can see in above snap, which is contains 578pixel in wide and 141pixel in height. Now, you want get that these pixel at runtime in ASP.NET.
A Bitmap class is used for getting Height and Width of image.
Encapsulates a GDI+ bitmap, which consists of the pixel data for a graphics image and its attributes. A Bitmap is an object used to work with images defined by pixel data. according to msdn library.

    Simple example

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

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>

<asp:FileUpload ID="FileUpload1" runat="server" />
<br />
<asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="Button" />
<br />
<br />
<asp:Label ID="Label1" runat="server"></asp:Label><br />
<asp:Label ID="Label2" runat="server"></asp:Label><br />


</div>
</form>
</body>
</html>

using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class Default2 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{

}
protected void Button1_Click(object sender, EventArgs e)
{

using (Bitmap bi = new Bitmap(Server.MapPath("~/img/"+FileUpload1 .FileName), true))
{
Label1.Text = Convert.ToString(bi.Height);
Label2.Text = Convert.ToString(bi.Width);
}



}
}
 

Output of the code

How to get height and width of an image in ASP.NET
 

Sabtu, 21 Desember 2013

How to Create a Project in NetBeans GUI Builder: Java Programming

A NetBeans IDE project is a group of Java source files plus its associated Meta data, including project-specific files. A Java application may consist of one or more projects. All Java development in the IDE takes place with in projects, we first need to create a new project within which to store sources and other project files.

To create a new GUI application project:

  • Click File → New Project command. Alternately. You can click the New Project icon in the IDE toolbar or press Ctrl + Shift + N.
  • In the Categories pane, select the Java node and in the projects pane, choose the Java Desktop Application and then Click Next.

How to Create a Project in NetBeans GUI Builder: Java Programming

  • Enter desired name in the Project Name field and specify the project location.
  • Leave the Use Dedicated Folder for storing Libraries checkbox unselected. (If you are using IDE 6.0, this option ids not available.)
  • Ensure that the Set as Main Project checkbox is selected.

How to Create a Project in NetBeans GUI Builder: Java Programming


  • Finally click Finish button.
    Now the NetBeans IDE will create the project folder on your system in the designated location. This folder contains all of the project’s associated files.
  • Next, you need to first add a frame window to your project where you can add desired components and functionally.
    For this, on the top left pane, under Projects Tab, right click on your project’s name and select New. From the submenu, select JFrame Form. A new Frame dialog box will open as shown:

How to Create a Project in NetBeans GUI Builder: Java Programming

  • In this dialog box, specify the name of the frame being added in the box next to Class Name and click Finish.

This is newly added frame is the top level container of your application. Now in the Design View of this frame, you can add desired components from the Swing Controls under Palette and work further.

Jumat, 20 Desember 2013

Connect SqlDataSource Control with Database, Insert, Update and Delete

How to connect SqlDataSource Control with database, also add extra features like insert, update and delete. Here we will take some steps, these are

Step-1 : Create a SQL Table with some fields like
sno int (primaryKey, Isidentity=true)
name nvarchar(50)
address nvarchar(250)


Step-2 : Add SqlDataSource Control to Design window from toolbox
Step-3 : Select 'Configure Data Source' link using show Smart tag.

'Configure Data Source'



Step-4 : Select Database or ConnectionString from Dropdown menu.
ConnectionString

Step-5 : Select Table-name from Dropdown menu also select Advanced tab.
Table-name from Dropdown menuAdvanced tab

Step-6 : Select Insert, Update and delete checkbox option.
Step-7 : Click to Test Query and  Finish button

Now generate source code in page file

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
<!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></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    Database items
        <br />
        <asp:SqlDataSource ID="SqlDataSource1" runat="server"
            ConnectionString="<%$ ConnectionStrings:xyz %>"
            DeleteCommand="DELETE FROM [emp] WHERE [sno] = @sno"
            InsertCommand="INSERT INTO [emp] ([name], [address]) VALUES (@name, @address)"
            SelectCommand="SELECT * FROM [emp]"
            UpdateCommand="UPDATE [emp] SET [name] = @name, [address] = @address WHERE [sno] = @sno">
            <DeleteParameters>
                <asp:Parameter Name="sno" Type="Int32" />
            </DeleteParameters>
            <InsertParameters>
                <asp:Parameter Name="name" Type="String" />
                <asp:Parameter Name="address" Type="String" />
            </InsertParameters>
            <UpdateParameters>
                <asp:Parameter Name="name" Type="String" />
                <asp:Parameter Name="address" Type="String" />
                <asp:Parameter Name="sno" Type="Int32" />
            </UpdateParameters>
        </asp:SqlDataSource>

    </div>
    </form>
</body>
</html>

 

Steps to Retrieve Records with SQL Server Management Studio: SQL Programming

As I have discussed in my first SQL article that the database scenario is AdventureWorks, on which we will work on. The AdventureWorks database is stored on the LocalDb (Currently used) database server. The problem we are sorting out is, the details of the sales persons are stored in the SalesPerson table. The management wants to view the details of the top three sales persons who have earned a bonus between $4,000 and $6,000.

To retrieve the specified records, programmer need to create a query first and then execute the query to generate the report. To display the top three sales person records from the SalesPerson table, programmer need to use the TOP keyword. In addition, to specify the range of bonus earned, you need to use the BETWEEN range operator.

To create the query by using the SQL Server Management Studio, just follow simple steps written below:
  • Select Start>Programs>SQL Server Management Studio to display the Microsoft SQL Server Management Studio Window. Connect to Server dialog box is displayed by-default, if not you can simple open it from File>Connect Object Explorer.
  • Select the server name from the Server name drop-down list.

    Steps to Retrieve Records with SQL Server Management Studio: SQL Programming
    Note: Name of the server is computer specific. In this example, the name of the server is (LocalDb)\v11.0. You can use the default server as the database server.
  • Fill the details as given in the image and click on Connect button. It will connect to the server and management studio will be displayed as shown in the image.

    Steps to Retrieve Records with SQL Server Management Studio: SQL Programming
  • Expand the Databases node and it will show all the databases on this server. Now right click on AdventureWorks2012 database and select New Query.
  • Name of the Query Editor window is specific to machine.
  • Type the following query in the Query Editor window:
SELECT TOP 3 *
FROM [AdventureWorks2012].[Sales].[SalesPerson]
Where Bonus BETWEEN 4000 AND 6000

  • Click on Execute (in SQL editor toolbar) or press F5 and check the result as shown in the following image:

Steps to Retrieve Records with SQL Server Management Studio: SQL Programming


About and Uses of String Data Types in Computer Programming: C

String is a data type and is often used as an array of bytes that stores a sequence of elements i.e. characters, in computer programming. C language supports string in every calculation of programming, the article describes the use with examples.

No program generally exists without the manipulation of the strings. In all our previous articles, we have used several times the statements:
pritnf("Enter the number of n");

Here, the sequence of characters enclosed within a pair of double quotes is a string. Strings are generally used to store and manipulate data in text form like words or sentences.

Definition: An array (or sequence) of characters is called as string. A string is most conveniently represented using continuous storage locations in memory. The storage representations of strings are classified as shown below:

Fixed length Format:

A fixed length string is a string whose storage requirement is "known when the string is created". In this string, irrespective number of characters the string has, the length of the string is always fixed. Once the string is defined, the length of a string cannot be changed. It is ‘fixed’ for the duration of program execution. In this format, the non-data characters such as space are added at the end of the data.

For example, the string "DOT" and "PROGRAM" are stored in fixed format where size is fixed for 10 bytes as shown below:


Note: The string "DOT" is 10 bytes string ending with 7 blanks characters.
Note: The string "PROGRAM" is 10 bytes string ending with 3 blanks characters.
Note: The blank characters cannot be used as data since it acts as end of the string.

Disadvantages
  • If the length reserved for string is too small, it is not possible to store the large string.
  • If the length reserved for string is too large, too much memory is wasted.
  • Once the string is defined, the length of a string cannot be changed. It id ‘fixed’ for the duration of program execution.
  • There is the problem of distinguishing data character from non-data characters. Normally non-data character such as spaces are added at the end of the data.
The above disadvantages can be overcome using variable length format, will be discussed in later article.

String literals and constants

Selection Sorting Algorithm in Computer Programming: C

Selection sort, also called in-place comparison sort, is a sorting algorithm in computer programming. It is well-known algorithm for its simplicity and also performance advantages. The article shows the process with C language code and an example.

As the name indicates, first we select the smallest item in the list and exchange it with the first item. Then we select the second smallest in the list and exchange it with the second element and so on. Finally, all the items will be arranged in ascending order. Since, the next least item is selected and exchanged accordingly so that elements are finally sorted, this technique is called selection sort.

For example, consider the elements 50, 40, 30, 20, 10 and sort using selection sort.

Selection Sorting Algorithm in Computer Programming: C

Design: The position of smallest element from i'th position onwards can be obtained using the following code:

pos = i;
for(j=i+1; j<n; j++)
{
   If(arr[j] < arr[pos])
   pos = j;
}

After finding the position of the smallest number, it should be exchanged with i'th position. The equivalent statements are shown below:

temp = arr[pos];
arr[pos] = arr[i];
arr[i] = temp;

The above procedure has to be performed for each value of i in the range 0 < i < n-1. The equivalent algorithm to sort N elements using selection sort is shown below:

Step1:    [Input the number of items]
    Read: n
Step2:    [Read n elements]
    for i = 0 to n-1
        Read: arr[i]
    [End of for]
Step3:    for i = 0 to n - 2  do
        pos = i;
        for j = I + 1 to n – 1 do
            if(arr[j] < arr[pos]) then
                pos = j
            [End of if]
        [End of for]
        temp = arr[pos]
        arr[pos] = arr[i]
        arr[i] = temp
    [End of for]
Step4:    [Display Sorted items]
    for i = 0 to n -1
        Write: arr[i]
    [End of for]
Step5:    Exit

C program to implement the selection sort.

main()
{
 int n, arr[10], pos, i, j, temp;
clrscr();
 printf("Enter the number of items:\n");
 scanf("%d",&n);
 printf("Input the n items here:\n");
 for(i = 0; i< n; i++)
{
 scanf("%d",&arr[i]);
 }
for(i = 0; i <n; i++)
    {
        pos = i;
        for(j = i+1; j< n; j++)
            {
                if(arr[j] < arr[pos])
                    pos = j;
            }
            temp = arr[pos];
            arr[pos] = arr[i];
            arr[i] = temp;
    }
printf("The sorted elements are as:\n");
for( i = 0; i < n; i++)
    {
        printf("%d\n",arr[i]);
    }
getch();
}
The program will outputs as:

Selection Sorting Algorithm in Computer Programming: C, output

Advantages

  • Very simple and easy to implement.
  • Straight forward approach.

Disadvantages

  • It is not efficient. More efficient sorting techniques are present.
  • Even if the elements are sorted, n-1 passes are required.

Binary Search in C
Linear Search in C

Rabu, 18 Desember 2013

How to Add Functionality to NetBeans GUI: Java Programming

Programmer can know, to add graphical components in a frame and how to set their properties. But doing much is not sufficient in java programming, because the graphical controls that you add to frame can’t do anything on their own.

In other words, they have the look but not any feel. To add feel i.e. functionality or behaviour to them, you must also know about something called events and listeners. The three major players that add functionality to GUI are:

  • The Event: An event is an objects that gets generated when user does something such as mouse click, dragging, pressing a key on the keyboard etc.
  • Source of the Event: The component where the event has occurred, is the source of the event. For example, if a user clicks (the Event) on a Submit button then the source of this event is Submit button.
  • Event Listener: An event listener is attached to a component and contains the methods/functions that will be executed in response to an event. For example, if a user click on a button, then the buttons event listener will executed some code in response to this event.
    Listener Interface. An event Listener stores all the methods that it will implement in response to events, inside the listener interface. So, you can say that a listener interface stores all event-response-methods or event-handler methods of an event listener.

Commonly used Events and Listeners.


  • ActionEvents: of type ActionListener used to gets activated when the user performs an action with a button or other components. Usually, a user invokes the button by clicking over it. However, the user can also invoke a button action tabbing to the button and pressing the Enter key.
  • ItemEvent of type ItemListener used to gets activated when the selected item in a list control, such as a combo box or list box, is changed.
  • AdjustmentEvent of type AdgustListener used to gets activated when the user drags or moves knob of a scroll bar.
  • ChangeEvent of type ChangeListener used to gets active when the properties of a slider change.
  • KeyEvents of type KeyListener used to gets activate when the user press a key on the keyboard. You can use this event to watch for specific keystrokes entered by the user.
  • ListSelection of type ListSelectionListener used to get activated when an item is selected/deselected from list (JList).
  • MouseEvent of type MouseEventListener used to gets activated when the user does something with the mouse, such as clicks one of the buttons, drags the mouse, or simply moves over another objects.
  • FocusEvent of type FocusEventListener used to gets activated when a components receives or lose focus. Focus is ability to receive input, e.g., you can select from a list box only when it has focus, you can type in a text field only if it has focus.  


Each of the listeners listed above have multiple methods stored in their listener interfaces to respond to different type of events. You are armed with some basic knowledge of GUI functioning in Java so in further articles i will let you know about to create a GUI application using NetBeans.