-->

Saturday, February 15, 2014

Insertion in a unordered LINKED LIST for Data Structure in 'C'

Insertion in a unordered LINKED LIST

Here in this case the NEW node is inserted after the location LOC. LOC is found by comparing the given Information with every node of the Linked List. For example consider the following Linked List. ROOT points to FIRST node with information 10. If a NEW node is to be inserted after a node with Information   20, 20 is given as Information.20 is compared with the information of first node, it is not equal, so it is compared with the second node it is equal hence address of second node is LOC. Now node is inserted by copying address of third node which is given by LINK of LOC, in the LINK field of NEW node and the LINK field of LOC is copied with the new node’s address given by NEW. So after the second node of the original list there comes the just inserted NEW node. When the Linked List is traversed after the second node there comes the new node as the third node. If the Information is printed it will be 10 20 15 5.



Algorithm to Insert node in unordered linked list:

            INSERTNOLL(ROOT,IN)
            [IN is the information of the node after which insertion is done]
            If AVAIL =NULL Then:
               Write: ‘Memory Allocation Error’
                Exit.
            [End of If]
            NEW<--AVAIL
            AVAIL<--AVAIL-->LINK
            NEW-->LINK<--NULL
            NEW-->INFO<--Information
            [Information is the to be data stored in the NEW node]

             LOC<--ROOT
             Repeat While IN< >LOC-->INFO AND LOC< >NULL
               LOC<--LOC-->LINK
             [End of While]
             If LOC = NULL Then:
                Write: ‘Error in Insertion’
                [Error because node with IN is not present]
                Exit.
              Else
                NEW-->LINK<--LOC-->LINK
                LOC-->LINK<--NEW
             [End of If]
             Exit.


Friday, February 14, 2014

How to Create and Apply Templates to Controls Dynamically

We already discuss about create template in .aspx page. Today we will learn, create template dynamically (using class). There are lots of steps to follow
Step-1 : Create a MyTemplate class , which is implement from ITemplate interface

public class MyTemplate : ITemplate
{
}

Here ITemplate interface create ASP.NET template.

Step-2 : Declare ListItemType enum variable in the class

ListItemType templateType;

Step-3 : Initialize variable in class constructor, which you want to take in Repeater control like HeaderTemplate, Item Template, Footer Template etc.

public MyTemplate(ListItemType type)
    {
        templateType = type;
    }

Step-4 : Define InstantiateIn method ( for more detail use link ) with proper template view
Step-5 : Bind Repeater Control through DataBinder class.

Full MyTemplate.cs file code


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

/// <summary>
/// Summary description for MyTemplate
/// </summary>
public class MyTemplate :ITemplate
{
    ListItemType templateType;
    public MyTemplate(ListItemType type)
    {
        templateType = type;
    }

    public void InstantiateIn(Control container)
    {
        PlaceHolder ph = new PlaceHolder();
        Label item1 = new Label();
        Label item2 = new Label();
        item1.ID = "item1";
        item2.ID = "item2";

        switch (templateType)
        {
            case ListItemType.Header:
                ph.Controls.Add(new LiteralControl("<table border=\"1\">" +
                    "<tr><td><b>sno</b></td>" +
                    "<td><b>Name</b></td></tr>"));
                break;
            case ListItemType.Item:
                ph.Controls.Add(new LiteralControl("<tr><td>"));
                ph.Controls.Add(item1);
                ph.Controls.Add(new LiteralControl("</td><td>"));
                ph.Controls.Add(item2);
                ph.Controls.Add(new LiteralControl("</td></tr>"));
                ph.DataBinding += new EventHandler(Item_DataBinding);
                break;
            case ListItemType.AlternatingItem:
                ph.Controls.Add(new LiteralControl("<tr bgcolor=\"lightblue\"><td>"));
                ph.Controls.Add(item1);
                ph.Controls.Add(new LiteralControl("</td><td>"));
                ph.Controls.Add(item2);
                ph.Controls.Add(new LiteralControl("</td></tr>"));
                ph.DataBinding += new EventHandler(Item_DataBinding);
                break;
            case ListItemType.Footer:
                ph.Controls.Add(new LiteralControl("</table>"));
                break;
        }
        container.Controls.Add(ph);
    }
    static void Item_DataBinding(object sender, System.EventArgs e)
    {
        PlaceHolder ph = (PlaceHolder)sender;
        RepeaterItem ri = (RepeaterItem)ph.NamingContainer;
        Int32 item1Value = (Int32)DataBinder.Eval(ri.DataItem, "sno");
        String item2Value = (String)DataBinder.Eval(ri.DataItem, "Name");
        ((Label)ph.FindControl("item1")).Text = item1Value.ToString();
        ((Label)ph.FindControl("item2")).Text = item2Value;
    }


Step-6 : Take a Web Form (.aspx) page, place Repeater control on it.
Step-7 : Bind Repeater control on Page_Load event.

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

public partial class Default3 : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
       SqlConnection conn =new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);

        SqlDataAdapter DA;
        DataSet DS;

        DA = new SqlDataAdapter("SELECT * FROM [userdata]", conn);
        DS = new DataSet();

        Repeater1.HeaderTemplate = new MyTemplate(ListItemType.Header);
        Repeater1.ItemTemplate = new MyTemplate(ListItemType.Item);
        Repeater1.AlternatingItemTemplate =new MyTemplate(ListItemType.AlternatingItem);
        Repeater1.FooterTemplate = new MyTemplate(ListItemType.Footer);
        DA.Fill(DS, "userdata");
        Repeater1.DataSource = DS.Tables["userdata"];
        Repeater1.DataBind();
    }
}

Code Generate the following output

How to Create and Apply Templates to Controls Dynamically

Thursday, February 13, 2014

How to Create Data Model using Database in MVC Application

As I have discussed in earlier article, MVC model folder have all the classes that may be used for application logic in the application. By default an MVC application have some of the models like AccountModels, LogOnModels, RegisterModels etc.

We will create a new model class by using some simple steps.

  • Right click on the Model folder and add a new class named Student.cs
  • Insert some properties in that class like written below.

namespace MvcApplication1.Models
{
    public class Student
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public int Age { get; set; }
        public string City { get; set; }
    }
public class StudentContext: DbContext
{
public DbSet<Student> Students { get; set; }
}
}

This class have all the four properties which are the columns in the student table of the database. Now to work with this class we have to add a controller (after debugging this application) class in the Controllers folder with these simple steps.

  • Right click on the Controller folder and add a new Controller. A window will appear with some of the options to be inputted.
  • Name the controller StudentController and more options like shown in the window.

How to Create Data Model using Database in MVC Application


After clicking on Add button visual web developer will add StudentController.cs file under the Controller folder, and Student folder under the Views folder.

The last steps of this article is to add Database views which are used for UI purpose in the application. There is a plus point in this MVC application i.e. we don’t need to add required views because they are automatically added by the visual web developer.

Lookout under the Views>Student Folder

  • Index.cshtml
  • Create.cshtml
  • Delete.cshtml
  • Details.cshtml
  • Edit.cshtml


Types and Examples of Operators in Java Programming part-1

In Java programming, the operations (specific tasks) are represented by operators and the objects of the operations (s) are referred to as operands.
Java’s rich set of operators comprise of arithmetic, relational, logical and certain other type of operators. Let us discuss these operators in detail.

Arithmetic Operators

To do arithmetic, Java use operators. It provides operators for five basic arithmetic calculations: addition, subtraction, multiplication, division and remainder which are +, -, *, / and % respectively. Each of these operators is a binary operator i.e., it requires two values (operands) to calculate a final answer. A part from these binary operators, Java provides two unary arithmetic operators (that require one operand) also which are unary +, and unary -.

Unary Operators

Operators that act on one operand are referred to us as Unary Operators.

Unary +. The operators unary ‘+’ precedes an operand. The operand (the value on which the operator operates) of the unary + operator must have arithmetic type and the result is the value of the argument.
For example

if a = 5 then +a means 5.
if a = o then +a means 0.
If a = -4 then +a means -4.

Unary-. The operator unary – precedes an operand. The operand of the unary – operator must have arithmetic type and the result is the negation of its operand’s value.
For example

If a = 5 then –a means -5
if a = o then +a means 0. (There is no quantity known as -0)
If a = -4 then +a means -4.

This operators reverse the sing of the operand’s value.

Binary Operators

What is the Scope of Variable in Java Programming?

In Java Programming, an important thing that you must know about variable is their scope. Scope generally refers to the program-region within which a variable is accessible. The board rule is: a variable is accessible with in the set of braces it is declared in e.g.

{
int a ;
:  /* a would be accessible as long as its block (a block is marked with a pair of matching brace) is not closed. Variable a is said to have block scope*/
}

Constants

Often in a program you want to give a name to a constant value. For example you might have fixed tax rate of 0.030 for goods and tax rate of 0.020 for services. These are constants, because their value is not going to change when the program is executed. It is convenient to given these constant a name.

This can be done as follows:

final double TAXRATE = 0.25;
The keyword final makes a variable as constant i.e. whose value cannot be changed during program execution.

Consider the following program that declare and uses two constants.

class calculateTax {
:  {
            final double GOODS_TAX =0.030 ;  
            final double SERVICE_TAX = 0.020 ;
                         …………
         }
     }

The reserved word final tells the compiler that the value will not change in the program. The names of constants follow the same rules as the names for variables. (Programmers sometimes use all capital letters for constants; but that is a matter of personal style, not part of language).      

Once declared constants, their value cannot be modified e.g.; after declaring constant GOODS_TAX, if you issue a statement like:

GOODS_TAX =0.050 ;  //error
It will cause an error, as the value of constants cannot be modified.

Advantage of Constants

They make your program easier to read and check for correctness.
If a constant needs to be changed (for instance a new tax law changes the rates) all you need to do is change the declaration. You don’t have to search through your program for every occurrence of a specific number.

How to use Nested Subqueries in SQL Programming

A subquery can contain one or more subqueries. Subqueries are used when the condition of a query is dependent on the result of another query, which in turn is dependent on the result of another subquery.

Consider an example. You need to view the DepartmentID of an employee whose e-mail address is Sales Agent. To perform this task, you can use the following query:

SELECT DepartmentID FROM HumanResources.EmployeeDepartmentHistory
WHERE BusinessEntityID = /* Level 1 inner query */
(SELECT BusinessEntityID FROM Person.BusinessEntityContact
WHERE ContactTypeID = /* Level 2 inner query */
(SELECT ContactTypeID FROM Person.ContactType WHERE Name= 'Sales Agent')
)

In the preceding example, two queries are nested within another query. The level 2 inner query returns the Contact ID of an employee based on the e-mail address of the employee from the Person table.

The level 1 inner query uses this ContactID to search for the BusinessEntityID of the employee with the given e-mail address. The main query uses the BusinessEntityID returned by level 1 inner query to search for the DepartmentID from the EmployeeDepartmentHistory table.

You can implement subqueries upto 32 levels. However, the number of levels that can be used depends on the memory available on the database server.

How to use Aggregate Functions in SubQuery with Database

While using subqueries, you can also use aggregate functions in the subqueries to generate aggregated values from the inner query. For example, in a manufacturing organization, the management wants to view the sale records of all the items whose sale records are higher than the average sale record of a particular product.

Therefore, the user first needs to obtain the average of a particular product and then find all the records whose sale record exceeds the average value. For this, you can use aggregate functions inside the subquery.

The following example displays the BusinessEntityID of those employees whose vacation hours are greater ta e average vacation hours of employees with title as ‘Marketing Assistant’:

SELECT BusinessEntityID FROM HumanResources.Employee
WHERE VacationHours > (SELECT AVG(VacationHours) FROM HumanResources.Employee
WHERE JobTitle = 'Marketing Assistant')

The output of the subquery that uses the aggregate function is shown in the following figure.

How to use Aggregate Functions in SubQuery with Database

In the preceding example, the inner query returns the average vacation hours of all the employees who are titled as Marketing Assistant. The outer query uses the comparison operator ‘>’ to retrieve the employee ID of all those employees who have vacation hours more than the average vacation hours assigned for a Marketing Assistant.

© Copyright 2013 Computer Programming | All Right Reserved