-->

Saturday, May 31, 2014

How to validate fileupload control in asp.net also choose selected format

In my previous article we already discussed about file upload control. Suppose your picture is required in the form of registration then you must to validate the file upload control. Also you want to take only jpeg, gif and selected format then should use RegularExpressionValidator with regular expression. Now lets take a simple example.

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

<!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>dotptogramming</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    <asp:FileUpload ID="fileUpload1" runat="server" Width="280px" />
                                
<asp:RequiredFieldValidator ID="R1" runat="server" 
            ErrorMessage="Select File From File Upload" Text="*"  ValidationGroup="v2" 
            ControlToValidate="fileUpload1" ForeColor="Red"></asp:RequiredFieldValidator>

<asp:RegularExpressionValidator ID="RE1" runat="server" 
            ErrorMessage="Upload .jpg, .jpeg, .gif files only." Text="*"  
            ValidationGroup="v2" ControlToValidate="fileUpload1" 
            ValidationExpression="^.+\.((jpg)|(jpeg)|(gif))$" ForeColor="Red"></asp:RegularExpressionValidator>

    </div>
    <p>

        <asp:Button ID="Button1" runat="server" Text="Button" ValidationGroup="v2"/>
    </p>
    <asp:ValidationSummary ID="ValidationSummary1" runat="server" 
        ValidationGroup="v2" ForeColor="Red" />
    </form>
</body>
</html>

Code Generate the following output

How to validate fileupload control in asp.net also choose selected format

How to validate fileupload control in asp.net also choose selected format

How to pass session value in page title in asp.net

Suppose you have to enter into your account. Now, a session variable created after login and you want to pass this value in page title. If you have a master page then simple use this code in code behind page. Also you can use this code in web form. Lets take a simple example

Use only Business Logic code


public partial class Default5 : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        Session["username"] = "- ASP.NET CODE";
        Page.Title += Session["username"].ToString();
    }
} 

Code Generate the following Output

How to pass session value in page title in asp.net

Dynamically add rows and columns in data table, also bind Gridview with data table

First create instance of DataTable class, which is inside in System.Data namespace. After that you make columns and rows inside the DataTable. First create columns with their data type also insert rows data in it.

Source Code

<div>
        <asp:GridView ID="GridView1" runat="server">
        <HeaderStyle BackColor ="Green" ForeColor ="Orange" />
        <RowStyle BackColor ="Black" ForeColor ="White" />

        </asp:GridView><br />

        <asp:Button ID="B1" runat="server" Text="Bind GridView" onclick="B1_Click" />
    
    </div>

Business Logic Code

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

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


    protected void B1_Click(object sender, EventArgs e)
    {
  
DataTable datatable = new DataTable();
datatable.Columns.Add("serial Number", typeof(Int32));
datatable.Columns.Add("Name", typeof(string));
datatable.Columns.Add("Address", typeof(string));
datatable.Rows.Add(1, "Jacob", "USA");
datatable.Rows.Add(2, "Lefore", "USA");
datatable.Rows.Add(3, "Bill", "UK");
datatable.Rows.Add(4, "Smith", "UK");
GridView1 .DataSource =datatable;
            GridView1.DataBind ();

    }
}

Code Generate the following Output

Dynamically add rows and columns in data table, also bind Gridview with data table

Friday, May 30, 2014

How to call event in page load method and example of EventHandler class

If you want to add event at run time like click event in page load method. For this types of problem you can use EventHandler class. Create a object of this class also pass new method as a parameter.

Source Code

<div>
    
        <asp:Button ID="B1" runat="server" CommandName="Add" Text="Button" />
    
    </div>

    Business Code


    public partial class Default4 : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        B1.Click += new System.EventHandler(this.calculate);
    }
    protected void calculate(object sender, System.EventArgs e)
    {
        switch (((Button)sender).CommandName)
        {
            case "Add": Response.Write("hello");
                break;
        }
    }

}
Code Generate the following output
How to call event in page load method and example of EventHandler class

How to Use Filtered TextBox Extender of AJAX in ASP.NET

FilteredTextBoxExtender enables you to apply filtering to a text box control that prevents certain characters from being inserted in the text box. For example, you can limit a text box to either enter only characters, or digit, or dates. This extender is different from ASP.NET validation controls as it prevents the users from entering invalid characters.

Lets take an simple example

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

<%@ Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="asp" %>

<!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">
    <asp:ScriptManager ID="ScriptManager1" runat="server">
    </asp:ScriptManager>
    <div>
    Enter Number only:
        <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
        <asp:Button ID="Button1" runat="server" Text="Button" />
        <asp:FilteredTextBoxExtender ID="FilteredTextBoxExtender1" runat="server" TargetControlID ="TextBox1" FilterType="Numbers">
        </asp:FilteredTextBoxExtender>
    </div>
    </form>
</body>
</html>

Code Generate the following Output

How to Use Filtered TextBox Extender of AJAX in ASP.NET

For Lower case Letter Only Set 
FilterType="LowercaseLetters"
For Upper Case Letter only
FilterType="UppercaseLetters"
For Upper and Number
FilterType="UppercaseLetters,Numbers"

Thursday, May 29, 2014

Nested Gridview Example in ASP.NET

A gridview with some items and another gridview structure

<form id="form1" runat="server">
    <div>
        <asp:GridView ID="GridView1" runat="server">
        <Columns>
        <asp:TemplateField>
        
        <ItemTemplate>
            <asp:TextBox ID="TextBox1" runat="server" Text ='<%# Eval("database field") %>' />
        
        </ItemTemplate>
         <ItemTemplate>
             <asp:GridView ID="GridView2" runat="server">
             <Columns>
             <asp:TemplateField>
                 
        <ItemTemplate>
            <asp:DropDownList ID="DropDownList1" runat="server">
            </asp:DropDownList>
        
        </ItemTemplate>
             
             </asp:TemplateField>
             
             </Columns>
             </asp:GridView>
        
        </ItemTemplate>
        
        
        </asp:TemplateField>
        
        </Columns>
        </asp:GridView>
    </div>
    </form>

Multiple Events call same event Handler in ASP.NET

In ASP.NET,  you can connect multiple Events with same event handler. If you thing about it, this types of code reduce space complexity as well as time complexity. If you use events with separate events handler then take more time. Like

<div>
    Both Event and methods name are same, both call to same handler.<br />
&nbsp;<asp:Button ID="Button1" runat="server" Text="First Button" 
            onclick="Button1_Click" /><br />
         <asp:Button ID="Button2" runat="server" Text="Second Button" onclick="Button1_Click" /><br />
        <asp:Label ID="Label1" runat="server" Text=""></asp:Label>
    </div>
In my previous article, we have already discussed about it, which is how to determine which web server control is raised.

Business Logic Code

 protected void Button1_Click(object sender, EventArgs e)
    {
        Button button = (Button)sender;
        Label1.Text = button.Text;
    }

Code generate the following output

Multiple Events call same event Handler in ASP.NET

Multiple Events call same event Handler in ASP.NET

Tuesday, May 27, 2014

How to Render HTML Controls in View: Asp.Net MVC

Asp.Net MVC provides a way to write simple programming syntaxes and HTML Helpers convert them in to HTML at runtime to be simply open the pages at client end. These provides generates html and return result as a string.

Like other web form controls in Asp.Net, HTML helpers are used to modify HTML, but HTML Helpers does not have an event model/ view state as web form controls have. Programmer can use these helpers by using built in HTML property of the view that are in System.Web.Mvc.Html namespace. We can create our own Html helpers or use built-in provided in the specified namespace.

HTML helpers have methods for creating forms, rendering partial views, performing input validation etc. Here are some mostly used html helpers:

HTML Links

These type of links are used to render an html link on the page, but in MVC they create a link to redirect on a particular action of the controller.
        @Html.ActionLink(“Text to Display”, “Action-name”)

The first parameter is used to specify the text to be displayed for user and second parameter is used to specify the action-name to which user will redirect after click.

HTML BeginForm

To place a form element on MVC, following syntax is used that will create an HTML form with some parameter values listed below.

@using (Html.BeginForm())
{
//Other Html Helpers to complete the form
}

Parameters used 
  • ActionName: specify the name of action on which user will redirect
  • ControllerName: name of controller in which action has written
  • Route values: the values send as a parameter to action
  • FormMethod: Type of form whether HttpPost or HttpGet
  • Html attributes: used at run time like making readonly, applying css classes and more.

    ------------------------
Here are some standard html helpers used mostly when programming:

Understanding Attributes in Asp.Net MVC

Earlier article was about to handle browser request from the user and then invokes related controller and actions written for that particular URL. What is to be done after these requests can also be specified by the programmer in Asp.Net MVC, as this article will discuss.

Asp.Net MVC provides a way to use some extra features for actions and controller, these features are called Attributes and Filters. We have discusses about Required attribute in creating MVC View Model using required field validations.

The first and most attribute, MVC use by default is [Authorize] which specifies which action is to be executed by authenticated users only or it may be used for whole controller. The syntax for this authorize attribute is:

[Authorize]
Public ActionResult Profile()
{
return View();
}

Now whenever an un-authorized user will try to get access of this profile action, it will redirect the request to login page or the page specified.

Attributes can also take parameters specified in their declaration, they may be positional or named. Positional parameter corresponds to attribute’s public constructor like the one specified below. It will change the name of this action profile to Details, as specified as the parameter.

[ActionName(“Details”)]
Public ActionResult Profile()
{ return View(); }

Named parameter correspond to public property or field of the respective attribute. For example authorize attribute have some named parameters like order, roles and users as written in following code:

[Authorize(Roles="Role1, Role2", Users="User1, User2")]
Public ActionResult Profile()
{ return View(); }

By specifying these named parameters, this profile action will only be accessed by the users having role "Role1" and "Role2". If we talk about the users, this action will only be accessed by only the person having username "User1" and "User2".
Attribute is a class which inherits from the abstract class System.Attribure. 
So we have to inherit from the same System.Attribute class to create our own attribute. Each attribute class (created by us) will must ends with the word "Attribute". E.g.
  • AuthorizeAttribute
  • RequiredAttribute
  • ActionNameAttribute
  • CustomizedAttribute
  • ValueCheckAttribute

Search Value using Non-Clustered index: SQL Server

Similar to the clustered index, a non-clustered index also contains the index also contains the index key values and the row locators that point to the storage location of the data in a table. However, in a non-clustered index, the physical order of the rows is not the same as the index order.

Non-clustered indexes are typically created on columns used in joins and the WHERE clause. These indexes can also be created on columns where the values are modified frequently. The SQL Server creates non-clustered indexes by default when the CREATE INDEX command is given. There can be as many as 249 non-clustered indexes per table.

The data in a non-clustered index is present in a random order, but the logical ordering is specified by the index. The data rows may be randomly spread throughout a table. The non-clustered index tree contains the index keys in a sorted order, with the leaf level of the index containing a pointer to the data page and the row number in the data page.
  • The SQL Server perform the following steps when it uses a non-clustered index to search for a value:
  • The SQL Server obtains the address of the root page from the sysindexes table.
  • The search value is compared with the key values on the root page.
  • The page with the highest key value less than or equal to the search value is found.
  • The page pointer is followed to the next lower level in the index.
  • Steps 3 and 4 are repeated until the data page is reached.
  • The rows are searched on the leaf page for the specified value. If a match is not found, the table contains no matching rows. If a match is found, the pointer is followed to the data page and row-ID in the table and requested row is retrieved. 
Search Value using Non-Clustered index: SQL Server

The figure displays a non-clustered index present on the Eid attribute o the Employee table. To search for any value, the SQL Server would start from the root page and move down the B-Tree until it reaches a leaf page that contains a pointer to the required record. It would then use this pointer to access the record in the table. For example, to search for the record containing Eid E006 by using the non-clustered index, the following steps would be performed by the SQL Server:

  • The SQL Server starts from page 603, which is the root page.
  • It searches for the highest key value on the page, the page with a key value less than or equal to the search value, that is, to the page containing the pointer to Eid E005.
  • The search continues from page 602.
  • Eid E005 is found and the search continues to page 203.
  • Page 203 is searched to find a pointer to the actual row. Page 203 is the last page, or the leaf page, of the index.
  • The search then moves to page 302 of the table to find the actual row.

In an index, more than one row can contain duplicate values. However, if you configure an index to contain unique values, the index will also contain unique values. Such an index is called a unique index. You can create a unique index on a columns that contain unique values, such as the primary key columns.
A unique index can be clustered or non-clustered depending on the nature of the column

Types of Indexes provided by SQL Server

As described in the earlier article indexes can be managed easily. The SQL Server allows you to create the following types of indexes:

Clustered Index

A clustered index is an index that sorts and stores the data rows in the table based on their key values. Therefore, the data is physically sorted in the table when a clustered index is defined on it. Only one clustered index can be created per table. Therefore, you should build the index on attributes that have a high percentage of unique values and are not modified often.

In a clustered index, data is stored at the leaf level of the B-Tree. The SQL Server performs the following steps when it uses a clustered index to search for a value:
  • The SQL Server obtains the address of the root page from the sysindexes table, which is a system table containing the details of all the indexes in the database.
  • The search value is compared with the key values on the root page.
  • The page with the highest key value less than or equal to the search value is found.
  • The page pointer is followed to the next lower level in the index.
  • Steps 3 and 4 are repeated until the data page is reached.
  • The rows of data are searched on the data page until the search value is found. If the search value is not found on the data page, no rows are returned by the query.
Consider the following figure where the rows of the Employee table are sorted according to the Eid attribute and stored in the table.
Types of Indexes provided by SQL Server

Working of a Clustered Index

The preceding figure displays a clustered index on the Employee table. To search for any record, the SQL Server would start at the root page. It would then move down the B-Tree and the data values would be found on the leaf pages of the B-Tree. For example, if the row containing Eid E006 was to be searched by using a clustered index (refer to the preceding figure), the SQL Server perform the following steps:
  • The SQL Server starts from page 603, the root page.
  • The SQL Server searches for the highest key value on the page, which is less than or equal to the search value. The result of this search is the page containing the pointer to Eid E005.
  • The search continues from page 602. There, Eid E005 is found and the search continues to page 203.
  • Page 203 is searched to find the required row.
A clustered index determines the order in which the rows are actually stored. Therefore, you can define only one clustered index on a table.

How to Create and Manage Indexes in SQL Server

Database developer is often required to improve the performance of queries. SQL Server allows implementing indexes to reduce the execution time of queries. In addition they can restrict the view of data to different users by implementing views.

The SQL Server also provides an in-built full-text search capability that allows fast searching of data. This article discusses how to create and manage indexes and views.

Creating and Managing Indexes

When a user queries data from a table based on conditions, the server scans all the data stored in the database table. With an increasing volume of data, the execution time for queries also increases. As a database developer, you need to ensure that the users are able to access data in the least possible time. SQL Server allows you to create indexes on tables to enable quick access to data. In addition, SQL Server allows you to create XML indexes for columns that store XML data.

At times, the table that you need to search contains voluminous data. In such cases, it is advisable to create partitioned indexes. A partitioned index makes the index more manageable and scale able as they store only data of a particular partition.

As a database developer, you need to create and manage indexes. Before creating an index, it is important to identify the different types of indexes.

Identifying the Types of Indexes

Before identifying the types of indexes, it is important to understand the need to implement an index.
The data in the database tables is stored in the form of data pages. Each data page is 8 KB in size. Therefore, data of the complete table is stored in multiple data pages. When a user queries a data value from the table, the query processor searches for the data value in all the data pages. When it finds the value, it returns the result set. With an increasing volume of data, this process of querying data takes time.

To reduce the data query time, the SQL Server allows you to important indexes on tables. An index is a data structure associated with a table that helps in fast search of data in the table. Indexes in the SQL Server are like the indexes at the back of a book that you can use to locate text in the book.

Benefits provided by using Indexes:


  • Accelerate queries that join tables, and perform sorting and grouping
  • Enforce uniqueness of rows, (if configured for that)

An index contains a collection of keys and pointers. Keys are values built from one or more columns in the table with which the key is associated. The column on which the key is built is the one on which the data is frequently searched. Pointers store the address of the storage location where a data page is stored in the memory, as depicted in the following figure.

How to Create and Manage Indexes in SQL Server

When the users query data with conditions based on the key columns, the query processor scans the indexes, retrieves the address of the data page where the required data is stored in the memory, and accesses the information. The query processor does not need to search for data in all the data pages. Therefore, the query execution time is reduced.

The keys in the indexes are stored in a B-Tree in the memory. A B-Tree is a data-indexing method that organizes the index into a multi-level set of nodes. Each page in an index B-Tree is called an index node. Each index contains a single root page at the top of the tree. This root page, or root node, branches out into n number of pages at each intermediate level until it reaches the bottom, or leaf level, of the index. The index tree is traversed by following pointers from the upper-level pages down through the lower-level pages.

The key values in the root page and the intermediate pages are sorted in the ascending order. Therefore, in the B-Tree structure, the set of nodes on which the server will search for data values is reduced. This enables the SQL Server to find the records associated with the key values quickly and efficiently. When you modify the data of an indexed column, the associated indexes are updated automatically.

Complaints Management Project in ASP.NET

Download this project

Project cost : 200Rs or $8
Pay me at:
PayPal id : saini1987tarun@gmail.com

Via bank transfer

ICICI bank account number is :    153801503056
Account holder name is :                 Tarun kumar saini
IFSC code is :                                   ICIC0001538

SBBJ bank detail :                             61134658849
Account holder name:                        Tarun kumar saini
IFSC code :                                        SBBJ0010398

CONTACT ME

narenkumar851@gmail.com

Introduction

In this project, you can create your complaints to admin department. Review your complaints by the admin department and try to solve the problem.

Project Module

I have two module in this project first one is consumer module and last one admin module.

How to work(Step by step guide)

Step-1 : First to complete the consumer registration.
Step-2 :  Login in your account using consumer login panel.
Step-3 : Fill the complaints form, after login.
Step-4 : Check Status after few time in consumer panel.
Step-5 : Open Admin account using admin login panel.
Step-6 : Check New or old consumer complaints and try to solve the problem if possible.
Step-7 : Update the pending status

Requirements

Software : Visual Studio 2010

Project Screen

Home page
Complaints Management Project in ASP.NET
Code 
<%@ Page Title="Home Page" Language="C#" MasterPageFile="~/Site.master" AutoEventWireup="true"
    CodeFile="Default.aspx.cs" Inherits="_Default" %>

<%@ Register src="UserControl/complaintform.ascx" tagname="complaintform" tagprefix="uc1" %>

<asp:Content ID="HeaderContent" runat="server" ContentPlaceHolderID="HeadContent">
</asp:Content>
<asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent">
    <h2>
        Complaint Form Fill by Consumer</h2>
    <p>
        <table style="width:100%;">
            <tr>
                <td>
                    <uc1:complaintform ID="complaintform1" runat="server" />
                </td>
                <td valign="top">
                    <asp:Image ID="Image1" runat="server" Height="526px" 
                        ImageUrl="~/images/complaint-handling-cartoon.jpg/" Width="340px" />
                </td>
            </tr>
        </table>
    </p>
<p>
        &nbsp;</p>
    </asp:Content>

Consumer login Form
consumer login panel of complaint management

Solution Explorer View
Complaints Management Project in ASP.NET


How to download this project

Step-1 : mail to me  ( narenkumar851@gmail.com)
Step-2 : Project Cost $10  or 400 Rs

How to Modify XML Data using Functions in SQL Server

Similar to any other type of data, programmer might also need to modify the XML data. To modify data, you can use the modify function provided by the XML data type of the SQL Server. The modify function specifies an XQuery expression and a statement that specifies the kind of modification that needs to be done.

This function allows you to perform the following modifications:

  • Insert: Used to add nodes to XML in an XML column or variable. For example, the management of AdventureWorks wants to add another column specifying the type of customer, in the CustDetails table. The default value in the Type column should be ‘Credit’. To resolve this problem, the database developer of AdventureWorks will create the following query:

    UPDATE CusomtDetails SET Cust_Details.modify (‘ inser attribute Type{“Credit”} as first into (/Customer) [1]’)
  • Replace: Used to update the XML data. For example, James Stephen, one of the customers of AdventureWorks, has decided to change his customer type from Credit to Cash. As a database developer, you can create the following query to reflect this change:
  • Delete: Used to remove a node from the XML data. For example, the management of AdventureWorks has decided to remove the ‘City’ column from the customer details. You can write the following query to display the results:

    UPDATE CustomDetails SET Cust_Details.modify (‘delete (/Customer/@City) [1]’)

Add 3 months in current month in asp.net

 <form id="form1" runat="server">
    <div>
   
        <asp:Button ID="Button1" runat="server" onclick="Button1_Click" Text="Click" BackColor="#99CCFF" />
   
    </div>
    <asp:Label ID="Label1" runat="server" BackColor="Yellow"></asp:Label>
    </form>
Code Behind
 protected void Button1_Click(object sender, EventArgs e)
    {
        {        
            DateTime now = DateTime.Now;        
            DateTime after3Months = now.AddMonths(3);
            Label1.Text = "now = " + now.ToLongDateString();
            Label1.Text += "<br /><br />after added 3 months to now= ";
            Label1.Text += after3Months.ToLongDateString();
        }

    }
Code Generate the following output

Add 3 months in current month in asp.net

Example of Append string using StringBuilder class in asp.net

 <form id="form1" runat="server">
    <asp:Button ID="Button1"
     runat="server"
     onclick="Button1_Click"
     Text="Click"
        Width="74px" BackColor="#FF6666" />
    <div style="width: 93px">
   
        <asp:Label ID="Label1"
         runat="server"
         Text="Label" BackColor="Yellow" ForeColor="Black"></asp:Label>
   
    </div>
    </form>

 Code Behind

 protected void Button1_Click(object sender, System.EventArgs e)  
       {

        StringBuilder stringA = new StringBuilder();
        stringA.Append("those are text. ");
        StringBuilder stringA2 = new StringBuilder(" another text.");

        stringA.Append(stringA2);

        Label1.Text = stringA.ToString(); 
    }

Code Generate the following outputExample of Append string using StringBuilder class in asp.net

Monday, May 26, 2014

How to Retrieve XML Data Using XQuery

In addition to FOR XML, SQL Server allows programmer to extract data stored in variables or columns with the XML data type by using XQuery. XQuery is a language that uses a set of statements and functions provided by the XML data type to extract data. As compared to the FOR XML clause of the SELECT statement, the XQuery statements allow you to extract specific parts of the XML data.

Each XQuery statement consists of two parts, prolog and body. In the prolog section, you declare the namespaces. In addition, schemas can be imported in the prolog. The body parts specifies the XML nodes to be retrieved. The XQuery language includes the following statements:

  • For: Used to iterate through a set of nodes at the same level as in an XML document.
  • Let: Used to declare variables and assign values.
  • Order by: Used to specify a sequence.
  • Where: Used to specify criteria for the data to be extracted.
  • Return: Used to specify the XML returned from a statement.

The XQuery statements also use the following functions provided by the XML data type:

Query: Used to extract XML from an XML data type. The XML to be retrieved is bicycle is manufactured at AdventureWorks, it passes through a series of work centre locations. Each work centre location produces a different cycle component. Therefore, the number of production steps varies between different work centres.

To analyse the production process, the management of AdventureWorks needs to retrieve a list of the location IDs of all the work centers, which have more than four steps. You need to generate the list displaying the location ids in the ascending order of the steps included in the work centres.

To perform this task, the database developer can create the following query:

SELECT Instructons.query
(‘ declare namespace
ns=http://schemas.microsoft.com/sqlserver/2004/07/adventure-works/ProductModelManuInstructions:
for $work in /ns:root/ns:Location
where count(#work/ns:step) > 4
order by count ($work/ns:step)
return
count($work/ns:step)’) AS Result
FROM Production.ProductModel
WHERE Instructions IS NOT NULL

Value: Used to return a single value from an XML document. To extract a single value, you need to specify an XQuery expression that identifies a single node and a data type of the value to be retrieved.

For example, the management of AventureWorks, Ins. Wants a list containing the product model id, product name, machine hours, and labour hours. However, not all product have production instructions. As a database developer, you have stored this data in the XML format in the ProductModel table. You can create the following query to display the results:

SELECT ProductModelID, Name, Instructions.value (‘declare namespace ns=”http//schemas.microsoft.com/sqlserver/2004/07/adventure-works/ProductManuInstructions”;
(/ns:root/ns:Location/@LaborHours) [1]’, ‘float’)AS
LaborHours,
Instructions.value(declare namespace
Ns=”http://schemas.microsoft.com/sqlserver/2004/07/adventure-works/ProductModelManuInstructions”;
(/ns:root/ns:Location/@MachineHours) [1]’, ‘float’) AS MachineHours
FROM Production.ProductModel
WHERE Instructions IS NOT NULL

Exist: Used to check the existence of a node in an XML data. The function returns I if the specified node exists else it returns 0. For example, the management of AdventureWorks, wants the details of all the customers in the city ‘NJ’. The details of all the customers are stored in an XML format in the CustDetails table. You can use the following query to display the results:

SELECT Cust_ID, Cust_Details.exist
(‘Customer[@City=’NJ”]’) AS ‘True’ FROM CustDetails

Retrieve XML data from DataSet

How to Define Methods with Behavior: Java

Objects have behavior that is implemented by its methods. Other objects can ask an object to do something by invoking its methods. This section tells you everything you need to know about writing methods for your Java classes.

In Java, you define a class’s methods in the body of the class for which the method implements some behavior. Typically, you declare a class’s methods after its variables in the class body although this is not required.

Implementing Methods

Similar to a class implementation, a method implementation consists of two parts: the method declaration and the method body

methodDeclaration {
        methodBody
}

The Method Declaration

At minimum, a method declaration has a name and a return type indicating the data type of the value returned by the method:

returnType methodName( ) {
. . .
}

This method declaration is very basic. Methods have many other attributes such as arguments, access control, and so on.

Objects as Instances of Class

A class defines only a blueprint and its concrete version comes into effect only through objects that implement the functionality as defined by class. Recall our class example of City class. The objects created from this class will have two variables: name and population; and they will be able to represent cities. The object of City class will also have a method namely display ( ). An object of a class is typically named by a variable of the class type. For example, the program CityTrial in Example 4.7 declares the two variables metl1 and metro2 to be of type City, as follows;

City metro1, metro2;

This gives us variables of the class City, but so far there are no objects of the class. Objects are class value that are named by the variables. To obtain an object you must use the new operator to create a “new” object. For example, the following creates an object of the class City and names it with the variable metro1:

Metro = new city ( );

For now you need not go into details, simply note that the statement like:

Class-variable = new class-Name ( );

Creates a new object of the specified class and associates it with the class type variables. Since the class variable now names an object of the class, we will often refer to the class variable as an object of the class. (This is really the same usage as when we refer to an int variable n as “the integer n”, even though the integer is strictly speaking not n but the value of n.)

Unlike what we did in previous lines, the declaration of a class type variable and the creation of the object are more typically combined into one statement as follows:
City metro1 = new City( );
To instantiate an object, Java uses the keyword new.

How to Declare Member Variables in Classes: JAVA

A class’s state is represented by its member variables. You declare a class’s member variables in the body of the class. Typically, programmer declare a class’s variables before you declare its methods, although this is not required.

classDeclaration {
        member variable declarations
        method declarations
}
To declare variables that are members of a class, the declarations must be within the class body, but not within the body of a method. Variables declared within the body of a method are local to that method i.e., available and accessible only inside the method.

Types


  • Class variable (static variable): A data member that is declared once for a class. All objects of the class type, share these data members, as there is single copy of them available in memory. The class variables are declared by adding keyword static in front of a variable declaration.
  • Instance variable: A data member that is created for every object of the class. For example, if there are 10 objects of a class type, there would be 10 copies of instance variables, one each for an object.
Consider the following code.


Public class sample {
        int anInt; // instance variable
        float aFloat; // instance variable
        static float anotherFloat; // class variable
};

Suppose there are five objects created for class type Sample. Then there would be five copies of variables anInt and aFloat but there would be one copy of variable anotherFloat which all five objects can share.

Notice that class variables are declared by adding a keyword static before the variable declaration. Keyword static in the variable declaration makes it class variable.

Method are similar: your classes can have instance methods and class methods. Instance methods operate on the current object’s instance variables but also have access to the class variables. Class methods (also called static methods), on the other hand, cannot access the instance variables declared within the class (unless they create a new object and access them through the object). Also, class methods can be invoked on the class, you don’t need an instance to call a class method.

A class method can be invoked by:

  • Just its name within its own class e.g., check( ).
  • Class-name.method-name outside its class e.g., Sample.check ( )

In above two lines, we assume that method check( ) is a static method in class Sample.

Implement Object-Oriented in JAVA

Fix A table control was not found in the template for data list


<!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>
    <style type="text/css">
        #form1
        {
            width: 162px;
            height: 384px;
        }
    </style>
</head>
<body>
    <form id="form1" runat="server">
   <asp:DataList ID="DataList1" runat="server" DataKeyField="Sno" 
        DataSourceID="SqlDataSource1" CellPadding="0" ExtractTemplateRows="True">
        <ItemTemplate>
            Sno:
            <asp:Label ID="SnoLabel" runat="server" Text='<%# Eval("Sno") %>' />
            <br />
            name:
            <asp:Label ID="nameLabel" runat="server" Text='<%# Eval("name") %>' />
            <br />
            address:
            <asp:Label ID="addressLabel" runat="server" Text='<%# Eval("address") %>' />
            <br />
<br />
        </ItemTemplate>
    </asp:DataList>
    <asp:SqlDataSource ID="SqlDataSource1" runat="server" 
        ConnectionString="<%$ ConnectionStrings:ConnectionString %>" 
        DeleteCommand="DELETE FROM [User] WHERE [Sno] = @Sno" 
        InsertCommand="INSERT INTO [User] ([name], [address]) VALUES (@name, @address)" 
         SelectCommand="SELECT * FROM [User]" 
        UpdateCommand="UPDATE [User] 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>
    
    </div>
    </form>
</body>
</html>


solved code

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <style type="text/css">
        #form1
        {
            width: 162px;
            height: 384px;
        }
    </style>
</head>
<body>
    <form id="form1" runat="server">
  <asp:DataList ID="DataList1" runat="server" DataKeyField="Sno" 
        DataSourceID="SqlDataSource1" CellPadding="0" ExtractTemplateRows="False">
        <ItemTemplate>
            Sno:
            <asp:Label ID="SnoLabel" runat="server" Text='<%# Eval("Sno") %>' />
            <br />
            name:
            <asp:Label ID="nameLabel" runat="server" Text='<%# Eval("name") %>' />
            <br />
            address:
            <asp:Label ID="addressLabel" runat="server" Text='<%# Eval("address") %>' />
            <br />
<br />
        </ItemTemplate>
    </asp:DataList>
    <asp:SqlDataSource ID="SqlDataSource1" runat="server" 
        ConnectionString="<%$ ConnectionStrings:ConnectionString %>" 
        DeleteCommand="DELETE FROM [User] WHERE [Sno] = @Sno" 
        InsertCommand="INSERT INTO [User] ([name], [address]) VALUES (@name, @address)" 
         SelectCommand="SELECT * FROM [User]" 
        UpdateCommand="UPDATE [User] 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>
    
    </div>
    </form>
</body>
</html>

Solution of the problem

set ExtractTemplateRows="False" in data list, like
<asp:DataList ID="DataList1" runat="server" DataKeyField="Sno" 
        DataSourceID="SqlDataSource1" CellPadding="0" ExtractTemplateRows="False">


© Copyright 2013 Computer Programming | All Right Reserved