-->

Tuesday, February 4, 2014

How to Querying Data by using Subqueries in SQL Programming: Part 1

In SQL programming, while querying data from multiple tables, you might need to use the result of one query as an input for the condition of another query. For example, in the Adventure Works database, you need to view the designation of all the employees who earn more than the average salary. In such cases, you can use subqueries to assign values to the expressions in other queries.

A subquery is an SQL statement that is used within another SQL statement. Subqueries are nested inside the WHERE or HAVING clause of the SELECT, INSERT, UPDATE, and DELETE statements. The query that represents the parent query is called an outer query, and the query that represents the subquery is called an inner query. The database engine executes the inner query first and returns the result to the outer query to calculate the result set.

Depending on the output generated by the subquery and the purpose for which it is to be used in the outer query, you can use different keywords, operators, and functions in subqueries.

Using the IN and EXISTS keywords

A subquery returns values that are used by the outer query. A subquery can return one or more values. Depending on the requirement, you can use these values in different ways in the outer query.

For example, in the Adventure Works database, you need to display the department name for an employee whose BusinessEntityID is 46. To perform this task, you can use the following query:

SELECT Name FROM HumanResources.Department
WHERE DepartmentID =
(SELECT DepartmentID FROM HumanResources.EmployeeDepartmentHistory WHERE BusinessEntityID = 46 AND EndDate IS NULL)

In the preceding query, the inner subquery returns the DepartmentID column of the emoloyee with BusinessEntityID as 46. Using this DepartmentID, the outer query returns the name of the department from the Department table i.e. Production.

In this query, EndDate is NULL Signifying that you need to extract the ID of the department where the emoloyee is currently working.

In the preceding example, the subquery returns a single value. However, at times, you need to return more than one value from the subquery. In addition, you might need to use a subquery only to check the existence of some records and based on that you need to execute the outer query.

You can specify different kinds of conditions on subqueries by using the following keywords:

Comments in c# console application

Comments are non-executale statements. Generally created for making user-friendly application. If we talk about c# comments, there are three types.

first one single line second one is multi-line and last one is XML documentation comments. Look like

Single-line Comments   --- // (created through double slash)
Multi-line Comments  ---- /*   */  
XML Documentation comments --- ///

Note : Don't try to comment every line of code. Use comments only for code, which is difficult to understand.

If you want to create comment in c# application , you can use keyboard shortcut. CTRL+K with C for comment, CTRL+K with U for un-comment.

Lets create a simple application demo for understanding  all types of comments.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            Addtwonumber qd = new Addtwonumber();

            //int number = 10;

            /*if (number == 10)
            {
                Console.WriteLine(number);


            }*/
        }
    }
  /// <summary>
  /// This class is designed for adding two number
  /// </summary>
    public class Addtwonumber
    {

    }
}
Code generate the following output
This example cover all types of comments. According to screen snap, you can better understand XML comments. If you don't use XML comment , before creating the class. Intellisense doesn't dispay the summary of the class. 

ASP.NET Bind Gridview with SqlDataSource in code file

There are various methods, Here we take SqlDataSource in code file. In previous articles, which is written on Gridview. Most of the article cover SqlDataSource for binding purpose, Now , again we use sqldatasource for binding but different style.

Behind the algorithm 

Step-1 : First of all design front-end. Add GridView onto the webform.
Step-2 : Create columns with asp:Bound field, like 

<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns ="false">
        <Columns >
        <asp:BoundField HeaderText ="Serial Number" DataField ="int" />
        <asp:BoundField HeaderText ="Name" DataField ="name" />
        <asp:BoundField HeaderText ="Address" DataField ="address" />

        </Columns>
        </asp:GridView>

Step-3 : Create a object for SqlDataSource control class, also add necessary properties.
Step-4 : Add SqlDataSource object into page.

Now, your code look like 

 SqlDataSource sq = new SqlDataSource();
            sq.ID = "SqlData";
            sq.ConnectionString = ConfigurationManager.ConnectionStrings["DatabaseConnectionString"].ToString();

            sq.SelectCommand = "Select * from [Table1]";
            Page .Controls .Add (sq);

Step-5 : Bind GridView with SqlDataSource object.
Step-6 : Run your application. Code Generate the following output
 
ASP.NET Bind Gridview with SqlDataSource in code file

Now your complete code is

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

<!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>
    
        <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns ="false">
        <Columns >
        <asp:BoundField HeaderText ="Serial Number" DataField ="int" />
        <asp:BoundField HeaderText ="Name" DataField ="name" />
        <asp:BoundField HeaderText ="Address" DataField ="address" />

        </Columns>
        </asp:GridView>
    
    </div>
    </form>
</body>
</html>

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

public partial class Default4 : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {
            SqlDataSource sq = new SqlDataSource();
            sq.ID = "SqlData";
            sq.ConnectionString = ConfigurationManager.ConnectionStrings["DatabaseConnectionString"].ToString();

            sq.SelectCommand = "Select * from [Table1]";
            Page .Controls .Add (sq);

            GridView1.DataSource = sq;
            GridView1.DataBind();

        }
    }
}

Monday, February 3, 2014

How to Perform Text Interaction with GUI in JAVA Programming

Java programming have a lot to learn and we have done some part with our earlier articles like variables, Data types. Now we are going to be designing of a GUI application involving these concepts. But wait, you need to know something more than this in order to design a GUI, application with full understanding. You need to know about to obtain/set the text from/into GUI components. Don’t worry; this section is here to serve this purpose.

For text interaction in GUI, you need to use basically four types of method:

getText()

A getText() method returns the text currently stored in a text based GUI components. The Swing components that support getText() method includes: Text Field, Text Area, Button, Label, Check Box and Radio Button.

Consider the example where you want to concatenate the contents of title, first name and last name fields, you must obtain the text in these fields. This you can do it with the help of getText() method.

To obtain text from title text field, you need to write:
titlezTF.getText()

The getText() returns a value of string type, so we must store the value returned by getText() in String type variable. Thus, complete statement to obtain text from title TF field would be
String str1 = titleTextField.getText();

Now you can manipulate the variable str1 (that now contains the text inside titleTF field) in the way you want.

Parse…()

Sometimes, you use text type components in a GUI but you intend to use it for obtaining numeric values e.g. you may want to read age of a person through a text fields. Since a text field return text i.e., string type of Data you need a method that helps you extract/convert this textual data into a numeric type. For this, parse…() methods are very useful. There are many parse…() methods that help you parse string into different numeric types.

These are
  • Byte.parseByte(String s) convert a sting s into a byte type value
  • Short.parseShort(String s) convert a String into a short type value
  • Integer.parseInt(String s) convert a String into an int type value
  • Long.parseLong(String s) convert a String into a long type value
  • Float.parseFloat(String s) convert a String into Float type value
  • Double.parseDouble(String s) converts a String into Double type value
To obtain a float value, you may use
Float.parseFloat(<text obtain from field>)
To obtain a double value, you my use
Double.parseDouble(<text obtained from field>)
To obtain a long value, you may use
Long.parseLong(<textobtained from field>)
And so on for other data types.

Introduction to Variables and its stages in JAVA Programming

In Java, Variables represent named storage locations, whose values can be manipulated during program run. For instance, to store name of a student and marks of a student during a program run, we require storage locations that should be named too so that these can be distinguished easily. Variable called as symbolic variables (because these are named), serve the purpose.

Declaration of a variable

The declaration of a variable generally takes the following form
type variable-name;

Where type is any DataType in Java and variable-name is the variable to be used further, it is an identifier thus all rules of identifier naming apply to the name of variable. Following declaration creates a variable age of int type:
int age;

Following are some more examples of C variables declarations
double pival;
float res;

The above declaration creates a variable ‘pival’ of type double and a variable ‘res’ of type float. A simply definition consist of a type specifier followed by a variable-name. When more than one identifier of a type is being defined, a comma-separated list of identifiers may follow the type specifier. For example,
double salary, wage ;
int month, day, year ;
long distance, area ;

Initialization of Variables  

All the example definitions of previous paragraph are simple definitions. A simple definition does not provide a first value or initial value to the variable i.e. variable is uninitialized and the variable’s value said to be undefined. A first value (initial value) may be specified in the definition of a variable. A variable with declaration first value is said to be an initialised variable. Java supports two form of variable definition:

int val = 1001;

Here val is initialized with a first value of 1001. Following are some more examples of initialized variables:
double price = 214.70, discount = 0.12;
float fint =0.27 F;
long val = 25;
string name = “Rohan”;

Dynamic Initialization

The expression that initializes a variables (that assign it a value for initial use) can be an expression with:
a literal 
Byte a = 3
a reference to another variables e.g.
short a = 0;
short b = a ;
a call to a method, in which case the return value determines the initialization. This type of initialization is called dynamic initialization. In the below code a and b is initialized but not yet c. When program runs then c will have the value returned by the function invoked here i.e. math.sqrt().

double a =3.0, b =4.0 ;
double c = math.sqrt (a*a + b*b);

Initial Values of Variables

Every variable in a program must have a value before its value is used. Each class variable (also called Field variable), instance variable, or array components is initialized with a default value when it is created:

Introduction to Variables and its stages in JAVA Programming


Add Hyperlink field into GridView control in ASP.NET

Step-1 : First bind your GridView using SqlDataSource control
Step-2 : Select 'Edit Column' link using show smart tag.


Edit Columns of gridview in asp.net

Step-3 : Now, Appear new field window, which is contain two pane (left or right).
Step-4 : Remove All selected field in left pane.
Step-5 : Add new HyperLink field From Left pane.

Add Hyperlink field into gridview

Step-6: After Added Hyperlink field , you can set DataTextField and DataNavigationUrl field property  from right pane.

Note : Assign Table column name to DataTextField and DataNavigationUrlField.

Step-7 : Click ok
Step-8: Run You application

Code Generate the following output

Add Hyperlink field into GridView control in ASP.NET

Generated Code are:

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

<!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>
    
    </div>
    <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" 
        DataKeyNames="int" DataSourceID="SqlDataSource1" GridLines="None" Width="43px">
        <Columns>
            <asp:HyperLinkField DataNavigateUrlFields="address" DataTextField="name" 
                Text="Fav. Links" />
        </Columns>
    </asp:GridView>
    <asp:SqlDataSource ID="SqlDataSource1" runat="server" 
        ConnectionString="<%$ ConnectionStrings:DatabaseConnectionString %>" 
        SelectCommand="SELECT * FROM [Table1]"></asp:SqlDataSource>
    </form>
</body>
</html>

Advantage of dynamic over static memory allocation

When you have gone through the above static memory allocation concept, it is clear that the static memory allocation major disadvantages. To overcome those disadvantages dynamic memory allocation is used. That is the reason why dynamic memory allocation has many advantages over static memory allocation .

When main memory is allocated statically it cannot be altered during the execution of program. When main memory is allocated dynamically it can be altered during the execution of program as per the user wish. The length of dynamically allocated memory either can be decreased or increased. This is the major advantage of dynamic memory allocation over static memory allocation.

Suppose user wishes to enter elements of an array or a list one by one just after allocating memory and he may stop at any point then definitely it is not possible by means of static memory allocation. So the dynamic memory allocation certainly has an advantage in this case over static memory allocation. Such dynamically created list is called as linked list.

In case of dynamically created lists insertions and deletions can be done very easily just by the manipulation of addresses whereas in case of statically allocated memory insertions and deletions lead to more number of movements and wastage of memory.

In case of statically allocated memory there is every chance of “overflow”  during insertions in the lists, whereas in case of dynamically allocated memory it does not come into picture unless otherwise unavailability of main memory.

For some liner data structures like STACK and QUEUE, dynamic memory allocation proves very much appropriate because the length of such data structure is not fixed. They may increase or decrease dynamically that is during the execution of program. Similarly non-linear data structures need recursive definitions of   “struct” data type, so the need of dynamic memory allocation.
Once you go through the implementation of dynamic data structure the advantages of the same will be clear.  

© Copyright 2013 Computer Programming | All Right Reserved