Você está na página 1de 70

Ex No : 1

Date :

WEB APPLICATION WITH 2-TIER ARCHITECTURE UISNG JSP AND


JDBC

Aim
To develop a web application with 2-tier architecture using JSP and JDBC.
Procedure
1. Start your net beans application.
2. Make your new Project, Click File-New Project.

3. Choose Java Web-Web Application when New Project Windows appear then click Next.

4. Fill the name of your new Project and define the place where you want to place your project.
Click Next.

4.
The Next Page is Server setting; just leave them alone if you dont have another web server you
want to use.
5.
I use the default setting and just click next to the next page.

6. Just Click finish in this Page.

7. When its done, Look at the up left panel of your workspace, click the + symbol near your
project name, then right click on a library tree, Click Add JAR/Folder button.

8. When the windows is open, locate your mysql connector Library you donwload and click
Open.

9.

Your left panel will be like this, after you add the mysql connector.

10.
Then you need to make the connection in order to connect to the database you wish. so, Click
Service tab menu.

11.

Right Click on Database tree menu and choose New Connection

12.
In the first Page of New Connection Wizard you have to define the driver you will use. I choose
Mysql (Connector / J driver) then click next

13.

Fill the Host name, username and password of your database then click Test Connection button.

14.
When the connection succeeded information has been appear, means that you can click the
Finish button

15. Back to your Database tree menu, several database name will appear according to your
current database. Right click on the database you will use, choose Connect and the last part
is, Write the code. I used the following syntax to view the record from my siswa table from
database osis.

Coding
<%@page contentType=text/html pageEncoding=UTF-8%>
<%@ page import=java.sql.* %>
<%@ page import=java.io.* %>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv=Content-Type content=text/html; charset=UTF-8>
<title>JSP Page</title>
</head>
<body>
<%
try
{
String Host = jdbc:mysql://localhost:3306/osis;
Connection connection = null;
Statement statement = null;
ResultSetrs = null;
Class.forName(com.mysql.jdbc.Driver);
connection = DriverManager.getConnection(Host, root, );
statement = connection.createStatement();
String Data = select * from pil;
rs = statement.executeQuery(Data);
%>
<TABLE border=1>
<tr width=10 bgcolor=#9979>
<td>Kode</td>
<td>Nama</td>
<td>Count</td></tr>
<%
while (rs.next())
{
%>
<TR>
<TD><%=rs.getString(kd)%></TD>
<TD><%=rs.getString(nama)%></TD>
<TD><%=rs.getString(count)%></TD>
</TR>
<% } %>
</table>
<%
rs.close();
statement.close();
connection.close();
} catch (Exception ex) {
out.println(Cant connect to database.);}
%>
<h1>Hello World!</h1></body>
</html>
Result
The program was successfully executed.

Ex No : 2
Date :

WEB APPLICATION WITH N-TIER ARCHITECTURE USING JSP,


SERVLETS AND JDBC

Aim
To develop a web application with n-tier architecture using JSP, Servlets and JDBC.
Procedure
1. Choose File > New Project to open the New Project Wizard. Under Categories, select Java EE;
under Projects select Enterprise Application. Click Next
2. Select the project location and name the project, CustomerApp, and click Next
3. Select the installed Glassfish server v2.1 or v2.1.1 as the server, and Java EE 5 as the Java EE
Version,and click Finish. Netbeans will create 3 projects namely CustomerApp (Enterprise Application
project), CustomerApp-ejb (EJB project) and CustomerApp-war (Web project).

Creating the Entity Classes from the Database


Before anything else, we first need to create the Entity Classes and because in this demo, the Session
Beans are responsible for manipulating the data, they will be created in the EJB project.

1. In the Projects view, right-click on the CustomerApp-ejb project and select New > Entity Classes
from Database
2. Select Data Source (Radio button) and in the corresponding dropdown list, select New Data
Source
3. Specify the JNDI name to be jdbc/sample, and select jdbc:derby://localhost:1527/sample [app on
APP] as the Database Connection and click OK
4. Under the Available Tables list box, select CUSTOMER and click on Add button so that it appears in
the Selected Tables list box (Note that the related table, DISCOUNT_CODE is also added
automatically) and click Next.

5. Click on the Create Persistence Unit... button, select jdbc/sample as the Data Source and leave
the rest as default.

6. Provide a package name, e.g. com.customerapp.entity in the Package field and click Next.
7. Change the Collection Type to java.util.List and click Finish
8. Take note of the new classes created under the Source Packages in the Projects view

9. Add the following code in the DiscountCode class.


/**
* Default constructor
*/
public DiscountCode()
{

this.discountCode = new Character('N');


this.rate = new BigDecimal(0.0);
//Added the above 2 lines so that the variables are not null when used by the IDE to
//display default values in the Visual JSF pages
}
10. Add the following code in the Customer class
/**
* Default constructor
*/
public Customer()
{
this.discountCode = new DiscountCode();
}
/**
* This method is added here (Customer entity class) because we want to
* include this field (discount rate) as a column in the Customer Listing table later.
*/
public BigDecimalgetDiscountRate()
{
if (discountCode != null)
{
return discountCode.getRate();
}
return new BigDecimal(0.0);
}
Creating the Session Bean, CustomerSession to provide the CRUD methods for Customer objects:
Now that we have the Entity classes, the next thing is to create the Session (Stateless) Bean that will
manipulate and provide the CRUD functionalities on the Customer objects. In this demo, the client that
uses these functions are the JSF pages. One of the benefits of doing this (i.e. to provide the CRUD
functionalities in the EJB layer) is reusability because the same functions can be used by more than 1
JSF pages, other EJBs, Enterprise Application Clients and Web Services Clients when exposed as web
services. Other benefits include scalability because the EJB container can easily be tuned and scaled up
when load increases.

1. In the Projects view, right-click on the CustomerApp-ejb project and select New > Session Bean.
2. Specify the EJB Name as CustomerSession and the package as com.customerapp.ejb, and keep the
rest of the options as default, and click Finish.

3. From the Projects view, navigate to the source of the newly created Session Bean (skeleton) by
double clicking on the CustomerSessionBean item.

4. In the code editor, right-click and select Persistence > Use Entity Manager; the
@PersistenceContext notation is inserted automatically, so now the EntityManager is ready to be
used.
5. Create the business methods for the Session Bean: Create, Retrieve, Update and Delete; right-click
in the code editor (find an appropriate placeholder for the method), select Insert Code..., under the
Generate list, select Add Business Method
6. In the Add Business Method... dialog, provide the Name, Return Type and Parameters for the
method.

7. Repeat the steps for the rest of the CRUD functions.


8. Edit the methods so that they implement the intended functions as shown below.
@Stateless
public class CustomerSessionBean implements CustomerSessionLocal
{
@PersistenceContext
private EntityManagerem;
public void create(Customer customer)
{
em.persist(customer);
}

public List<Customer>retrieve()
{
Query query = em.createNamedQuery("Customer.findAll");
return query.getResultList();
}
public Customer retrieve(String customerId)
{
Query query = em.createNamedQuery("Customer.findByCustomerId");
query.setParameter("customerId", new Integer(customerId));
return (Customer)query.getSingleResult();
}
public Customer update(Customer customer)
{
return em.merge(customer);
}
public void delete(Customer customer)
{
Customer managedCustomer = em.merge(customer);
em.remove(managedCustomer);
}
/**
* Included here for convenience rather than creating a new Session Bean
* @return List<DiscountCode>
*/
public List<DiscountCode>getDiscountCodes()
{
Query query = em.createNamedQuery("DiscountCode.findAll");
return query.getResultList();
}
}
9. Up to this point, the tasks required to be done in the EJB project are completed, we will move on to
the next tier, JSF pages.
Preparing the Web Project to use Visual JSF
To create the JSF pages to present the screens to perform the CRUD functions. To achieve this, we will
be creating 3 web pages:

CustomerList listing of all Customer records in the database in a tabular form.

CustomerDetails view/edit the details of a selected Customer record and deletion.

CustomerNew creation of a new Customer record.

Before creating the web pages, ensure the Visual Web JavaServer Faces framework is added to the Web
project, CustomerApp-war.

1. In the Projects view, right-click on the Web project, CustomerApp-war, and select Properties (last
item).
2. Under the Categories items, select Frameworks, and ensure the Visual Web JavaServer Faces is
added to the Used Frameworks list, and name the Default Java Package as com.customerapp.web.

Creating the Customer Listing Web Page


Now, we are ready to create the first web page that lists the Customer records in the database in a tabular
form.

1. In the Projects view, right-click on the Web project, CustomerApp-war, and select New > Visual
Web JSF Page..., specify CustomerList as the File Name.
2. Go to the Java view (by clicking on the button labeled, Java near the top of the editor pane) of the
new created page (CustomerList), right-click within the class and select Insert Code
3. Under the Generate list, select Call Enterprise Bean.... Expand the CustomerApp-ejb project and
select the CustomerSessionBean and click OK.
4. Notice the automatically generated variable that represents an instance of the session bean, at the top
of the class.
@EJB

private CustomerSessionLocalcustomerSessionBean;
5. Manually add the following code at the end of the class.

/**
* Return a list of all customers found in the database. This becomes a
* property that can be used by the JSF page to bind to the data table.
* @return
*/
public List<Customer>getCustomers()
{
//Call Session Bean
return customerSessionBean.retrieve();
}
6. Go back to the Design view of the JSF page, and drag a Data Table from the palette into the editor
pane

7. Right-click on the table (title bar), and select Table Layout


8. Select customers (CustomerList) from the Get Data From dropdown list and select the
column fields you want to display in the table. The existence of this data is the result of step 5
(added getCustomers() method in the class). The sequence of the columns and their names to be
displayed can be specified in this dialog. Click OK when done.

9. Drag a Button from the palette into the editor below the table and change the ID to
newCustomer and label to New Customer. The screen should look like this now.

10. To create an action handler for the new button, double-click on the button, and the editor will
bring you to a newly generated method, newCustomer_action() in the Java view, just take note of
it for now.
11. Next, we want to be able to navigate to the Customer Details page from the list, so drag a
Hyperlink from the Palette and drop it into the Customer ID column of the table.

12. Go to the JSP view and notice the hyperlink tag is added to the Customer ID column. Edit the
code so that the hyperlink displays the Customer ID as the text and CustomerDetails.jsp (a new
page that will be created later) as the target URL with the parameter, custId. The result should
look like this.
<webuijsf:tableColumnheaderText="Customer ID" id="tableColumn1"
sort="customerId">
<webuijsf:hyperlink id="hyperlink1" text="#{currentRow.value['customerId']}"
url="CustomerDetails.jsp?custId=#{currentRow.value['customerId']}"/>
</webuijsf:tableColumn>
13. Up to this point, we are ready to see the result of the artifacts created so far. In the Projects
view, right-click on the CustomerApp project and select Clean and Build, and select Deploy
(Ensure all the projects have the same Glassfish v2.1/2.1.1 server as the target server). To
confirm, navigate to the Enterprise Applications folder in the Glassfish server under the Services
view and check if the application, CustomerApp exist.

14. Open the browser and go to URL, http://localhost:8080/CustomerApp-ar/faces/CustomerList.jsp and


you should see the following screen.
Output

Result:
The program was successfully executed.

Ex No : 3
Date :

WEB APPLICATION WHICH AUTHENTICATES USING LDAP

Aim
To develop a web application which authenticates using LDAP.
Procedure
Configure Realm in the Glassfish Application Server
Create a new LDAP Realm.

1.

Create new LDAP Realm.

2.

Add the configuration settings as per the configurations set up done for the LDAP server.

Glassfish Web App LDAP Realm


JAAS Context: Identifier which will be used in the application module to connect with the LDAP server.
(e.g. ldapRealm).
Directory: LDAP server URL path (e.g. ldap://localhost:389)
Base DN: Distinguished name in the LDAP directory identifying the location of the user data.
Applying JEE security to the web application.

Create a sample web application as per the following structure:

SampleWebApp Directory
Form based authentication mechanism will be used for authentication of the users.

1.

JEE Login and Authentication

2.

Let us explain the whole process with help of above diagram and the code.

3.

Set up a sample web application in Netbeans IDE.

SampleWebApp in Netbeans IDE

SampleWebApp Configuration(web.xml)
Step 1: As explained in the above diagram a client browser tries to request for a protected resource from
the website http://{samplewebsite.com}/{contextroot}/index.jsp. The webserver goes into the web
configuration file and figures out that the requested resource is protected.
Code:
<security-constraint>
<display-name>SecurityConstraint</display-name>
<web-resource-collection>
<web-resource-name>Secured resources</web-resource-name>
<url-pattern>/*</url-pattern>
</web-resource-collection>
<auth-constraint>
<role-name>GeneralUser</role-name>
<role-name>Administrator</role-name>
</auth-constraint>
<user-data-constraint>
<transport-guarantee>NONE</transport-guarantee>
</user-data-constraint>
</security-constraint>

Step2: The webserver presents the Login.jsp as a part of the Form based authentication mechanism to
the client. These configurations are checked from the web configuration file.

Code
<login-config>
<auth-method>FORM</auth-method>
<realm-name>ldapRealm</realm-name>
<form-login-config>
<form-login-page>/Login.jsp</form-login-page>
<form-error-page>/LoginError.jsp</form-error-page>
</form-login-config>
</login-config>
Step3: The client submits the login form to the web server. When the servers finds that the form action
is j_security_check it processes the request to authenticate the clients credential. The jsp form must
contain the login elements j_username and j_password which will allow the web server to invoke the
login authentication mechanism.
Login.jsp
Code
<form action="j_security_check"method=post>
<p>username: <input type="text"name="j_username"></p>
<p>password: <input type="password"name="j_password"></p>
<input type="submit"value="submit">
<input type="reset"value="Reset">
</form>
While processing the request the webserver will send the authentication request to the LDAP server
since LDAP realm is used in the login-config.The LDAP server will authenticate the user based on the
username and password stored in the LDAP repository.
Step 4: If the authentication is successful the secured resource (in this case index.jsp) is returned to the
client and the container uses a session id to identify a login session for the client. The container
maintains the login session with a cookie containing the session-id. The server sends this cookie back to
the client, and as long as the client is able to show this cookie for subsequent requests, then the container
easily recognize the client and hence maintains the session for this client.
Step 5: Only if the authentication is unsuccessful the user will be redirected to the LoginError.jsp as per
the configuration in the web.xml.

Code

<form-error-page>/LoginError.jsp</form-error-page>
This shows how to apply form based security authentication to a sample web application. Now let us get
a

brief

look

on

the

secured

resource

which

is

used

for

this

project.

In this project the secured resource is index.jsp which accepts a username and forwards the request to
LoginServlet. Login servlet dispatches the request to Success.jsp which then prints the username to the
client.
Code
<body>
<h2>Please type your name</h2>
<formmethod="POST"action="LoginServlet">
<inputtype="text"name="username"size="25">
<p></p>
<inputtype="submit"value="Submit">
<inputtype="reset"value="Reset">
</form>
</body>
LoginServlet.java
Code
protectedvoidprocessRequest(HttpServletRequest
request,
HttpServletResponse
response) throwsServletException, IOException
{
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
try
{
RequestDispatcherrequestDispatcher = getServletConfig().getServletContext().
getRequestDispatcher("/Success.jsp");
requestDispatcher.forward(request, response);
}
finally
{
out.close();
}
Success.jsp
Code
<body>
<h1>You have been successfully logged in as ${param.username}</h1>
</body>
Web.xml

Code
<servlet>
<servlet-name>LoginServlet</servlet-name>
<servlet-class>com.login.LoginServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>LoginServlet</servlet-name>
<url-pattern>/LoginServlet</url-pattern>
</servlet-mapping>
Result
The program was executed successfully.

Ex No : 4
Date :

STANDALONE JAVA APPLICATION USING LDAP

Aim
To develop a standalone java application to add, modify and delete the LDAP attributes of the given
input.
Procedure
1.
2.
3.
4.
5.

Start the program.


Establish the connection with Java and LDAP.
Develop a program for manipulation operation such as add, delete etc...
Print the result.
Stop the process.

Coding
import java.util.Hashtable;
import javax.naming.Context; import
javax.naming.NamingEnumeration; import
javax.naming.NamingException; import
javax.naming.directory.Attributes; import
javax.naming.directory.SearchControls; import
javax.naming.directory.SearchResult; import
javax.naming.ldap.InitialLdapContext; import
javax.naming.ldap.LdapContext; public class
RetrieveUserAttributes
{
public static void main(String[] args)
{
RetrieveUserAttributesretrieveUserAttributes = new RetrieveUserAttributes();
retrieveUserAttributes.getUserBasicAttributes("testuser", retrieveUserAttributes.getLdapContext());
}
public LdapContextgetLdapContext()
{
LdapContextctx = null;
Try
{
Hashtable&lt;String, String&gt; env = new Hashtable&lt;String, String&gt;();
env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
env.put(Context.SECURITY_AUTHENTICATION, "Simple");
env.put(Context.SECURITY_PRINCIPAL, "your username");
env.put(Context.SECURITY_CREDENTIALS, "Password");
env.put(Context.PROVIDER_URL,@ !&);; !
).AB@);
ctx = new InitialLdapContext(env, null);
System.out.println("Connection Successful.");
}
catch(NamingExceptionnex)

{
System.out.println("LDAP Connection: FAILED"); nex.printStackTrace();
}
return ctx;
}
private User getUserBasicAttributes(String username, LdapContextctx)
{
User user=null;
try
{
SearchControls constraints = new SearchControls();
constraints.setSearchScope(SearchControls.SUBTREE_SCOPE); String[] attrIDs =
{
"distinguishedName",
"sn",
"givenname",
"mail",
"telephonenumber"};
constraints.setReturningAttributes(attrIDs);
//First input parameter is search bas, it can be "CN=Users,DC=YourDomain,DC=com"
//Second Attribute can be uid=username
NamingEnumeration answer = ctx.search("DC=YourDomain,DC=com", "sAMAccountName="
+ username, constraints);
if (answer.hasMore())
{
Attributes attrs = ((SearchResult) answer.next()).getAttributes();
System.out.println("distinguishedName "+ attrs.get("distinguishedName"));
System.out.println("givenname "+ attrs.get("givenname"));
System.out.println("sn "+ attrs.get("sn"));
System.out.println("mail "+ attrs.get("mail"));
System.out.println("telephonenumber "+ attrs.get("telephonenumber"));
}
else
{
throw new Exception("Invalid User");
}
}
catch (Exception ex) { ex.printStackTrace();

}
return user;
}
}
Result
The program was successfully executed.

Ex No : 5
Date :

WEB APPLICATION USING STRUTS FRAMEWORK

Aim
To design a web application using struts framework.
Procedure
Step 1: Create a Web application by selecting the Web Application project from the Web category and
click Next.

Step 2: Type the project name and project location and keep all other options default as shown in the
following figure.

Step 3: Select the Struts 1.2.9 checkbox as shown in the following figure. Also select the Add Struts
TLDs checkbox and click Finish.

Step 4 : From the Projects window open the struts-config.xml file.

Step 5: Edit the form-beans and action-mappings as follows:

A form bean is a class that specifies the data of our application. In the form bean class, we have to
declare private properties and accessor (get) and mutator (set) methods for each property.
In the form bean element, we specify the name and type attributes for our form bean. The name
attribute specifies the name of our form bean and the type attribute specifies the fully qualified name
(package.class) of our form bean.
The action element specifies the attributes of our action class like path, type, name and input. The
forward element specifies the success path for our application.
All other elements in the struts-config.xml file need not be changed.
Step 6: Add a new Java Class to the project giving it the class name and package name as specified
in the form-bean element and click Finish. This class represents our form bean.

Step 7: Write the following code in the CalcForm class.


Coding
package calc;
import org.apache.struts.action.ActionError;
import org.apache.struts.action.ActionErrors;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionMapping;
public class CalcForm extends ActionForm
{
private int n1,n2,addition,subtraction;
public void setN1(int n1)
{
this.n1=n1;
}
public int getN1()
{
return n1;
}
public void setN2(int n2)
{
this.n2=n2;
}
public int getN2()
{
return n2;
}
public void setAddition(int addition)

{
this.addition=addition;
}
public int getAddition()
{
return addition;
}
public void setSubtraction(int subtraction)
{
this.subtraction=subtraction;
}
public int getSubtraction()
{
return subtraction;
}

public ActionErrors validate(ActionMappingmapping,HttpServletRequest request)


{
ActionErrors errors=new ActionErrors();
if(n1==0)
{
errors.add("error.n1",new ActionError("error.n1"));
}
if(n2==0)
{
errors.add("error.n2",new ActionError("error.n2"));
}
return errors;
}
}
The form bean class contains the definitions for the private properties and the corresponding set and gets
methods. The validate method is used to handle errors in the program.
Step 8: From the projects window edit the ApplicationResource.properties file.

Step 9: Add the following code in the file:

These errors will be displayed when data is not entered while executing the application.
Step 10: Now from the Projects window add a new Java Class as specified in the action-mappings
element as follows and click Finish:

Step 11: Write the following code in the class:


package calc;
import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;
import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
public class MyAction extends Action
{
public ActionForward execute(ActionMappingmapping,ActionFormform,HttpServletRequestrequest,
HttpServletResponse response)
{
CalcFormcalcForm=(CalcForm)form;
int n1=calcForm.getN1();
int n2=calcForm.getN2();
calcForm.setAddition(n1+n2);
calcForm.setSubtraction(n1-n2);
return mapping.findForward("success");
}
}
The program represents the action controller. It retrieves data from the form bean, performs the
calculation and stores the results in the form bean.
Step 12: From the Projects window, edit the index.jsp file under the Web Pages folder.

Step 13: Add the following code to the index.jsp file:

The taglib directive is used to include the struts html library. The prefix attribute specifies the prefix to
be used and the uri attribute specifies the html library.
We create the user interface using the html library.
Step 14: Execute the application. Following are the output windows:

If the input is not specified, you get error as follows:

Result
The program was successfully executed.

Ex No:6
Date:

USING VALIDATION CONTROLS AVAILABLE IN ASP.NET

Aim
To develop a web application using validation controls available in ASP.NET.

Procedure
Step1: Create an ASP.NET Website and name is ValidationControls.
Step2: Create a table and input control like below.

1. Name: RequiredFieldValidator
2. Server Tag: <asp:RequiredFieldValidator>
Purpose: Checks that the control it has to validate is not empty when the form is submitted.

Select Required Filed Validator from Toolbox , and drag it to name textbox.

<asp:TextBox runat=server Width=200px ID=Name />


<asp:RequiredFieldValidator ID=ValidateName
ControlToValidate=Name
runat=server ErrorMessage=Name is Required
Display=Dynamic>
</asp:RequiredFieldValidator>
This is preetystraight , we can do same for other textboxes.
3. Name: Range Fields Validator
4. Server Tag : <asp:RangeValidator>
Description: Checks that the value of the associated control is within a specified range. The value and
the range can be numerical-a date or a string.
We can use this to allow user to input Date Off between specified datetime, say between 08/05/0808/20/08. So lets drag range Validator next to Date Off textbox.
<asp:TextBox runat=server Width=200px ID=DayOff />

<asp:RequiredFieldValidator runat=server ID=ValidateDayOff

ControlToValidate=DayOff

ErrorMessage=Day Off is required


Display=dynamic>*

</asp:RequiredFieldValidator>
<asp:RangeValidator ID=ValidatedateOff2
ControlToValidate=ValidateDayOff
ErrorMessage=Date off is not within the valid interval
MinimumValue=08/05/2008
MaximumValue=08/20/2008
SetFocusOnError=true
Display=Dynamic
runat=server
></asp:RangeValidator>

5. Name : CompareValidator
6. Server Tag: <asp:CompareValidator>
Description: Checks that the value of the associated control matches a specified comparison (less than,
greater than, and and so on) against another constant value or control.
Using this validator we can ask user to input age more than 18, i.e. > 18
<asp:TextBox runat=server Width=200px ID=Age />
<asp:RequiredFieldValidator runat=server ControlToValidate=Age
required Display=dynamic
ID=Requiredfieldvalidator1>*

ErrorMessage=Age is

</asp:RequiredFieldValidator>
<asp:CompareValidator ID=CompareValidator2 runat=server
ControlToValidate=Age
ValueToCompare=18
Operator=GreaterThanEqual
ErrorMessage=You must be at least 18-year-old
Display=Dynamic
Type=Integer>
</asp:CompareValidator>

You notice here we have many operators to use, we have used GreaterThan Equal;

Similarly , we can assign Type of value with which we are comparing.

Same we can do for re-password to compare with password, which should match it.
<asp:TextBox runat=server TextMode=Password Width=200px ID=Password2 />

<asp:RequiredFieldValidator runat=server ControlToValidate=Password2


ErrorMessage=Password2 is required Display=dynamic ID=Requiredfieldvalidator4
Name=Requiredfieldvalidator4>
<img src=imgError.gif alt=Missing required field. />
</asp:RequiredFieldValidator>

<asp:CompareValidator runat=server
ControlToValidate=Password2
ControlToCompare=Password
Type=String
ErrorMessage=The passwords dont match
Display=dynamic
ID=Comparevalidator1
Name=Comparevalidator1>

<img src=imgError.gif alt=Fields dont match. />

</asp:CompareValidator>
You can notice here that we have set ControlToValidate= Password2
And have used ControlToCompare = Password

7. Name: RegularExpressionValidator
8. Server Tag : <asp:RegularExpressionValidator>
Description: Checks if the value of the control it has to validate matches the specified regular
expression. They allow you to specify complex rules that specify the characters, and in what sequence
(position and number of occurrences) they are allowed, in the string. For example, the following control
checks that the text input in the text box is a valid e-mail address. So here we will try to validate the
email textbox, using regular expression validator

<asp:TextBox runat=server Width=200px ID=Email />

<asp:RequiredFieldValidator runat=server ControlToValidate=Email


required Display=dynamic
ID=Requiredfieldvalidator2>*

</asp:RequiredFieldValidator>

<asp:RegularExpressionValidator runat=server
ID=ValidateEmail
ControlToValidate=Email
validationExpression=.*@.{2,}\..{2,}
ErrorMessage=E-mail is not in a valid format

ErrorMessage=E-mail is

Display=dynamic>*

</asp:RegularExpressionValidator>

9. Name: CustomValidator
10. Server Tag : <asp:CustomValidator>
Description: Allows you to specify any client-side JavaScript validation routine and its server-side
counterpart to perform your own custom validation logic. CustomValidator allows you to execute your
custom client-side and server-side validation routines. The client-side and server-side validation routines
for the CustomValidator are declared similarly.

<asp:TextBox runat=server Width=200px ID=EmpID />

<asp:RequiredFieldValidator runat=server

ID=ValidateEmpID

ControlToValidate=EmpID

ErrorMessage=ID is required
Display=dynamic>*

</asp:RequiredFieldValidator>

<asp:CustomValidator runat=server ID=ValidateEmpID2


ControlToValidate=EmpID
ClientValidationFunction=EmpIDClientValidate
ErrorMessage=ID must be a multiple of 5
Display=dynamic

OnServerValidate=ValidateEmpID2_ServerValidate>*

</asp:CustomValidator>
The client side javascript function is as below;
<script type=text/javascript>
function EmpIDClientValidate(ctl, args)
{
// the value is a multiple of 5 if the module by 5 is 0
args.IsValid=(args.Value%5 == 0);
}
</script>
And , the server side validation handler is as below;
protected void ValidateEmpID2_ServerValidate(object source, ServerValidateEventArgsargs)
{
try
{
args.IsValid = (int.Parse(args.Value) % 5 == 0);
}
catch
{
args.IsValid = false;
}
}

11. Name : ValidationSummary

12. Server tag: <asp:ValidationSummary>

Description: Shows a summary with the error messages for each failed validator on the page (or in a
pop-up message box). This actually doesnt perform any validation. The summary display error message
for each failed validation for validator controls.

<asp:ValidationSummary runat=server
ID=Summary
DisplayMode=BulletList
HeaderText=<b>Please review the following errors:</b>
ShowSummary=true />

That all here, so finally we can write code for Submit Button click,
protected void Submit_Click(object sender, EventArgs e)
{
if (Page.IsValid)//If everything is fine.
Result.Text = Thanks for sending your data;
else
Result.Text = There are some errors, please correct them and re-send the form.;
}

Result
The program was successfully executed.

Ex No : 7
Date :

ARITHMETIC OPERATION USING WEB FORM

Aim
To create a component that receives two numbers from the user through a Web Form and perform
arithmetic operations and display the result.
Procedure
Step1: Go to Visual Studio then click on "File" -> "Website" -> "ASP.NET empty website template".
Then provide the website name (for example: WebServiceSample).

Step2: Add a Web Service File


Go to Solution Explorer, then select the solution then click on "Add new item".
Choose the Web Service template.Enter the name (for example: Airthmatic.cs) then click on "Add".

This will create the following two files:


1.

Airthmatic.asmx (the service file).

2.

Airthmatic.cs (the code file for the service; it will be in the "App_code" folder).

Open the file Airthmatic.cs and write the following code:


using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
/// <summary>
/// used for Airthmatic calculation
/// </summary>
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
// To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following
line.
// [System.Web.Script.Services.ScriptService]
public class Airthmatic : System.Web.Services.WebService
{
public Airthmatic()

{
//Uncomment the following line if using designed components
//InitializeComponent();
}
[WebMethod]
public int Add(int x, int y)
{
return x + y;
}
[WebMethod]
public int Sub(int x, int y)
{
return x - y;
}
[WebMethod]
public int Mul(int x, int y)
{
return x * y;
}
[WebMethod]
public int Div(int x, int y)
{
return x / y;
}
}
Attaching the WebMethod attribute to a Public method indicates that you want the method exposed as
part of the XML Web service. You can also use the properties of this attribute to further configure the
behavior of the XML Web service method. The WebMethod attribute provides the following properties:

BufferResponse
CacheDuration
Description
EnableSession
MessageName
TransactionOption

For more details of web methods click here.

Step 3: To see whether the service is running correctly go to the Solution Explorer then open
"Airthmatic.asmx" and run your application. Now you will find all the method names in the browser.

To see the WSDL format click on the service description link or add "?WSDL" to the URL.
Example: http://localhost:65312/WebServiceSample/Airthmatic.asmx?WSDL

It will show the WSDL.

To determine whether the functions are working, click on one of the functions (for example:
"Add").

Now you will see two TextBoxes for checking. Enter the value for x and y and click on the
"Invoke" button.

Now you will see the result in an open standard form (XML).

Now your service is ready for use.

Step 4: Creating the client application


Now create a website and design your form as in the following screen.

Or you can copy the following source code.


<body>
<form id="form1" runat="server">
<div>
<table border="2" cellpadding="2" cellspacing="2">
<tr>
<td align="right">
<asp:Label ID="Label1" runat="server" Text="Enter 1st Number"></asp:Label>
</td>
<td align="left">
<asp:TextBox ID="txtFno" runat="server"></asp:TextBox>
</td>
</tr>
<tr>
<td align="right">
<asp:Label ID="Label2" runat="server" Text="Enter 2nd Number"></asp:Label>
</td>
<td align="left">
<asp:TextBox ID="txtSno" runat="server"></asp:TextBox>
</td>
</tr>
<tr>
<td align="right">
<asp:Label ID="Label3" runat="server" Text="Result"></asp:Label>
</td>
<td align="left">
<asp:Label ID="lblResult" runat="server"></asp:Label>
</td>
</tr>
<tr>
<td align="center">
<asp:Button ID="btnAdd" runat="server" Text="Add(+)" OnClick="btnAdd_Click" />
</td>
<td align="center">
<asp:Button ID="btnSub" runat="server" Text="Sub(-)" OnClick="btnSub_Click" />
</td>
</tr>

<tr>
<td align="center">
<asp:Button ID="BtnMul" runat="server" Text="Mul(*)" OnClick="BtnMul_Click" />
</td>
<td align="center">
<asp:Button ID="btnDiv" runat="server" Text="Div(/)" OnClick="btnDiv_Click" />
</td>
</tr>
</table>
</div>
</form>
</body>
Step 5: Add a web reference to the Website
Go to Solution Explorer then select the solution then click on "AddWeb Reference" then within the
URL type the service reference path.
(For example: http://localhost:65312/WebServiceSample/Airthmatic.asmx) then click on the "Go"
button.
Now you will see your service methods. Change the web reference name from "localhost" to any
other name as you like (for example: WebAirthmatic).
Click on the "Add Reference" button. It will create a Proxy at the client side.

Now go to the cs code and add a reference for the Service.

Example: using WebAirthmatic;

Write the following code.


using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using WebAirthmatic;
public partial class _Default : System.Web.UI.Page
{
Airthmatic obj = new Airthmatic();
int a, b, c;
protected void Page_Load(object sender, EventArgs e)
{
}
protected void btnAdd_Click(object sender, EventArgs e)
{
a = Convert.ToInt32(txtFno.Text);
b = Convert.ToInt32(txtSno.Text);
c = obj.Add(a, b);
lblResult.Text = c.ToString();
}
protected void btnSub_Click(object sender, EventArgs e)
{
a = Convert.ToInt32(txtFno.Text);
b = Convert.ToInt32(txtSno.Text);
c = obj.Sub(a, b);
lblResult.Text = c.ToString();
}
protected void BtnMul_Click(object sender, EventArgs e)
{
a = Convert.ToInt32(txtFno.Text);
b = Convert.ToInt32(txtSno.Text);
c = obj.Mul(a, b);
lblResult.Text = c.ToString();
}
protected void btnDiv_Click(object sender, EventArgs e)
{
a = Convert.ToInt32(txtFno.Text);
b = Convert.ToInt32(txtSno.Text);
c = obj.Div(a, b);
lblResult.Text = c.ToString();
}
}
Now first run the Web service then the application.

Result

The program was successfully executed.

Ex No : 8

SILVERLIGHT APPLICATION FOR THE SHAREPOINT CLIENT

Date :

OBJECT MODEL

Aim
To create a Silverlight Application for the SharePoint Client Object Model.
Procedure

Task 1 Create a Silverlight Application Project


Will start by creating a standard Silverlight application project.
1. Open Visual Studio 2010 from Start | All Programs | Microsoft Visual Studio 2010 | Microsoft
VisualStudio 2010.
2. From the menu, select File | New | Project.
3. In the New Project dialog box, expend the Installed Templates left hand menu to Other Project
Types | Visual Studio Solutions | Blank Solution.
4. Name the solution Begin.
5. Change the location to C:\SPHOLS\HOL8\CS\Ex1\

6. Press OK to continue.
7. From the menu, select File | Add | New Project.

8. In the New Project dialog box, expand the Installed Templates left hand menu to Visual C# |
Silverlight, and choose the Silverlight Application project type in the project type list in the middle
section of the screen.
9. Name the project SPSilverlightExample.
10. Leave the location unchanged.

11. Press OK to continue.

12. Press OK to create the project.


13. Within the SPSilverlightExample project we will now add the reference assemblies to the
SharePoint Silverlight Client Object Model. Right click References in the SPSilverlightExample
project and select Add References.

14. Browse

to

the

C:\Program

Files\Common

Files\Microsoft

Shared\Web

Extensions\14\TEMPLATE\LAYOUTS\ClientBin folder.
15. Select Microsoft.SharePoint.ClientSilverlight.dll and
Microsoft.SharePoint.Client.Silverlight.Runtime.dll (hold CTRL to select multiple files)
16. Press OK to add the select dll references.

Task 2 Write code to access and render SharePoint List Data


1. In Visual Studio open the Toolbox and expand Silverlight Controls.
2. Drag a DataGrid control onto the Page.xaml Silverlight Designer.

Server

3. Expand the DataGrid to take up the entire page.


4. Open App.xaml.cs and add the following using statements to the top of the file:
using Microsoft.SharePoint.Client;
using System.Threading;
Code Snippet: My Code Snippets | lab08_ex1_app_namespaces
5. Add the following code to the beginning of the Application_Startup method.
ApplicationContext.Init(e.InitParams, SynchronizationContext.Current);
Code Snippet: My Code Snippets | lab08_ex1_application_startup
6. Open Page.xaml.cs and add the following using statement to the top of the file:
using Microsoft.SharePoint.Client;
Code Snippet: My Code Snippets | lab08_ex1_page_namespaces
7. Add the following class before the Page class:
public class Project
{
public string Title
{
get;
set;
}
public DateTimeDueDate
{
get;
set;

}
public string Description
{
get;
set;
}
}
Code Snippet: My Code Snippets | lab08_ex1_classes
8. Add the following variable to the Page class:
private ListItemCollection _projects;
Code Snippet: My Code Snippets | lab08_ex1_property
9. Add the following code to the Page constructor below the call to InitializeComponent:
ClientContext context = newClientContext(ApplicationContext.Current.Url);
context.Load(context.Web);
List Projects = context.Web.Lists.GetByTitle("Projects"); context.Load(Projects);
CamlQuery query = newMicrosoft.SharePoint.Client.CamlQuery(); stringcamlQueryXml =
"<View><Query><Where><Gt>" +
"<FieldRef Name='Due_x0020_Date' />" +
"<Value Type='DateTime'>2008-01-1T00:00:00Z</Value>" +
"</Gt></Where></Query><ViewFields>" +
"<FieldRef Name=\"Title\" /><FieldRef Name=\"Description\" />" +
"<FieldRef Name=\"Due_x0020_Date\" />" +
"</ViewFields></View>";
query.ViewXml = camlQueryXml;
_projects = Projects.GetItems(query); context.Load(_projects);
context.ExecuteQuery(newClientRequestSucceededEventHandler(OnRequestSucceeded), null);

Code Snippet: My Code Snippets | lab08_ex1_initializecomponent

Add the following code after the constructor:


privatevoidOnRequestSucceeded(Object sender, ClientRequestSucceededEventArgsargs)
{
// this is not called on the UI thread
Dispatcher.BeginInvoke(BindData);
}
privatevoidBindData()
{
List<Project> projects = newList<Project>(); foreach (ListItem li in _projects)
{
projects.Add(newProject()
{
Title = li["Title"].ToString(),
DueDate = Convert.ToDateTime(li["Due_x0020_Date"].ToString()),
Description = li["Description"].ToString()
});
}
dataGrid1.ItemsSource = projects; // must be on UI thread
}
Code Snippet: My Code Snippets | lab08_ex1_methods
This code initializes the SharePoint Silverlight client object model context (ClientContext). It then gets
a reference to the Projects list and runs a simple CAML query against the list to pull all projects with a
due date greater than 1/1/2008. The results are converted into a list of Projects and bound to the
Silverlight DataGrid control.

Task 3 Deploy and Test using the SharePoint Silverlight web part
To deploy the solution to SharePoint the resulting .xap file created by the Silverlight project needs to
be

in

the

C:\Program

Files\Common

Files\Microsoft

Shared\Web

Server

Extensions\14\TEMPLATE\LAYOUTS\ClientBin folder.
1. Right click the SPSilverlightExample project, select properties and select the Build tab.
2. Change the output path to C:\Program Files\Common Files\Microsoft Shared\Web Server
Extensions\14\TEMPLATE\LAYOUTS\ClientBin.

3. Build the solution. The .xap file has been copied to the required SharePoint directory and you are ready
to add the Silverlight web part to the SharePoint website.
4. Open Internet Explorer and browse to http://intranet.contoso.com.
5. Select the Edit tab at the top of the page and then click the Edit button to put the page in edit mode.
6. Select the Insert tab and the click Web Part.
7.From the Category list select Authoring, choose the Silverlight Web Part from the web part list
and click Add.
8. In the Silverlight Web Part dialog that pops up enter
/_layouts/ClientBin/SPSilverlightExample.xap as the URL.

9. Exit edit mode.


10. The final web part will look like this on the SharePoint page:
Output

Result
The program was successfully executed.

Ex No : 9
Date :

SHAREPOINT OBJECT MODEL AND SILVERLIGHT


GRAPHING CONTROLS

Aim
To create a graph using the SharePoint Object Model and Silverlight Graphing controls.
Procedure

Task 1 Create a Silverlight Application Project


1. Open Visual Studio 2010 from Start | All Programs | Microsoft Visual Studio 2010 | Microsoft
VisualStudio 2010.

2. From the menu, select File | New | Project.


3. In the New Project dialog box, expend the Installed Templates left hand menu to Other Project
Types | Visual Studio Solutions | Blank Solution.
4. Name the solution Begin.
5. Change the location to C:\SPHOLS\HOL8\CS\Ex2\

6.

Press OK to continue.

7. From the menu, select File | Add | New Project.


8. In the New Project dialog box, expand the Installed Templates left hand menu to Visual C# |
Silverlight, and choose the Silverlight Application project type in the project type list in the middle
section of the screen.
9. Name the project SilverlightEmployeeContributionsGraph.
10. Leave the location unchanged.

11. Click OK.

12. Press OK to create the project.


13. Within the SPSilverlightExample project we will now add the reference assemblies to the
SharePoint Silverlight Client Object Model. Right click References in the SPSilverlightExample
project and select Add References.
14. Browse

to

the

C:\Program

Files\Common

Files\Microsoft

Shared\Web

Extensions\14\TEMPLATE\LAYOUTS\ClientBin folder.
15. Select Microsoft.SharePoint.ClientSilverlight.dll and
Microsoft.SharePoint.Client.Silverlight.Runtime.dll (hold CTRL to select multiple files).

Server

16. Press OK to add the select dll references.

17. Add a reference to the Silverlight Charting Controls assembly. It is available on the .NET tab and is
called the System.Windows.Controls.DataVisualization.Toolkit.

Task 2 Write code to access Employee SharePoint List Data and display it in a Silverlight Graph
Control
1. Open App.xaml.cs and add the following using statements to the top of the file:
usingMicrosoft.SharePoint.Client;
usingSystem.Threading;
Code Snippet: My Code Snippets | lab08_ex2_app_namespaces
2. Add the following code to the beginning of the Application_Startup method.
ApplicationContext.Init(e.InitParams, SynchronizationContext.Current);

Code Snippet: My Code Snippets | lab08_ex2_application_startup


3. Open the Page.xaml file and add the following XML namespace in the UserControl element:
xmlns:chartingToolkit="clrnamespace:System.Windows.Controls.DataVisualization.Charting;assembly=System.Wind
ows.Controls.DataVisualization.Toolkit"
4. Add the following Silverlight Charting control inside the Grid element:
<chartingToolkit:Chart x:Name="chart" Width="350" Height="250" Title="Team
Contributions">
<chartingToolkit:Chart.Series>
<chartingToolkit:ColumnSeriesItemsSource="{Binding}"
DependentValuePath="Contributions"
IndependentValuePath="Name"
AnimationSequence="FirstToLast"
Title="Contributions" IsSelectionEnabled="True" />
</chartingToolkit:Chart.Series>
</chartingToolkit:Chart>

5. Open Page.xaml.cs and add the following using statement to the top of the file:
usingMicrosoft.SharePoint.Client;
Code Snippet: My Code Snippets | lab08_ex2_page_namespaces
6. Add the following classes before the Page class:
public class EmployeeContributions
{
Public string Name
{
get;
set;
}
Public string TeamName
{
get;

set;
}
Public decimal Contributions
{
get;
set;
}
}
public class TeamContributions
{
Public string Name
{
get;
set;
}
Public decimal Contributions
{
get;
set;
}
}
Code Snippet: My Code Snippets | lab08_ex2_classes
7. Add the following variable to the Page class:
privateListItemCollection _employees;
Code Snippet: My Code Snippets | lab08_ex2_property
8. Add the following code to the Page constructor below the call to InitializeComponent:
ClientContext
context
=
newClientContext(ApplicationContext.Current.Url);
context.Load(context.Web);
List employees = context.Web.Lists.GetByTitle("Employees"); context.Load(employees);
CamlQuery
query
=
stringcamlQueryXml = null;

newCamlQuery();

query.ViewXml = camlQueryXml;
_employees = employees.GetItems(query); context.Load(_employees);
context.ExecuteQuery(newClientRequestSucceededEventHandler(OnRequestSucceeded), null);
9. Code Snippet: My Code Snippets | lab08_ex2_initializecomponent
10. Add the following code after the constructor:

privatevoidOnRequestSucceeded(Object sender, ClientRequestSucceededEventArgsargs)


{
// this is not called on the UI thread
Dispatcher.BeginInvoke(BindData);
}
privatevoidBindData()
{
List<EmployeeContributions> employees = new List<EmployeeContributions>();
// get list item values into a strongly typed class
foreach (ListItem li in
_employees)
{
employees.Add(newEmployeeContributions
{
Name = li["Title"].ToString(), TeamName = li["Team"].ToString(),
Contributions = Convert.ToDecimal(li["Contribution_x0020__x0028_in_x00"])});
}
// use linq to group employees on team name and then total team contributions
List<TeamContributions> teams = employees
.GroupBy(e =>e.TeamName)
.Select(t =>newTeamContributions
{
Name = t.Key,
Contributions = t.Sum(e =>e.Contributions)}).ToList();
chart.DataContext = teams; // must be on UI thread
}
11. Code Snippet: My Code Snippets | lab08_ex2_methods
Like the previous exercise the SharePoint Silverlight client object model is used to retrieve data from a
SharePoint list. Once the employee contribution items have been populated into a list, LINQ is then
used to group employees into teams and their contributions summed together. Team contributions are
then set as the charts data source.

Task 3 Deploy and Test using the SharePoint Silverlight Charting web part:
To deploy the solution to SharePoint the resulting .xap file created by the Silverlight project needs to be
in the C:\Program Files\Common Files\Microsoft Shared\Web Server
Extensions\14\TEMPLATE\LAYOUTS\ClientBin folder.
1. Right click the SilverlightEmployeeContributionsGraph project, select properties and select the Build
tab.
2. Change the output path to C:\Program Files\Common Files\Microsoft Shared\Web Server
Extensions\14\TEMPLATE\LAYOUTS\ClientBin.

3. Build the solution. The .xap file has been copied to the required SharePoint directory and you are ready
to add the Silverlight web part to the SharePoint website.
4. Open Internet Explorer and browse to http://intranet.contoso.com.
5. We will update the Silverlight web part added in the previous exercise to point toward the new
Silverlight Charting control we have just made. Click the cog icon in the top right hand corner of the
Silverlight web part and select Modify Shared Web Part.

6. Click the Configure button and then enter


/_layouts/ClientBin/SilverlightEmployeeContributionsGraph.xap in the Silverlight Web Part dialog.

7. Click OK.
8. Click OK at the bottom of the Silverlight Web Part sidebar.
9. The final web part will look like this:

Result
The program was successfully executed.

MC7511 ADVANCED INTERNET PROGRAMMING LABORATORY


TABLE OF INDEX

S.No
1
2
3
4
5
6
7
8
9

Date

Name of the Experiment

Page
no

Marks
awarded

Signature of
the staff

Você também pode gostar