Escolar Documentos
Profissional Documentos
Cultura Documentos
Date :
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.
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.
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 :
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).
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
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.
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:
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.
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
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.
Result:
The program was successfully executed.
Ex No : 3
Date :
Aim
To develop a web application which authenticates using LDAP.
Procedure
Configure Realm in the Glassfish Application Server
Create a new LDAP Realm.
1.
2.
Add the configuration settings as per the configurations set up done for the LDAP server.
SampleWebApp Directory
Form based authentication mechanism will be used for authentication of the users.
1.
2.
Let us explain the whole process with help of above diagram and the code.
3.
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 :
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.
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<String, String> env = new Hashtable<String, String>();
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 :
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.
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.
{
this.addition=addition;
}
public int getAddition()
{
return addition;
}
public void setSubtraction(int subtraction)
{
this.subtraction=subtraction;
}
public int getSubtraction()
{
return subtraction;
}
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:
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.
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:
Result
The program was successfully executed.
Ex No:6
Date:
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.
ControlToValidate=DayOff
</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;
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:CompareValidator runat=server
ControlToValidate=Password2
ControlToCompare=Password
Type=String
ErrorMessage=The passwords dont match
Display=dynamic
ID=Comparevalidator1
Name=Comparevalidator1>
</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: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:RequiredFieldValidator runat=server
ID=ValidateEmpID
ControlToValidate=EmpID
ErrorMessage=ID is required
Display=dynamic>*
</asp:RequiredFieldValidator>
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;
}
}
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 :
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).
2.
Airthmatic.cs (the code file for the service; it will be in the "App_code" folder).
{
//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
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
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).
<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.
Result
Ex No : 8
Date :
OBJECT MODEL
Aim
To create a Silverlight Application for the SharePoint Client Object Model.
Procedure
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.
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.
Server
}
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);
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.
Result
The program was successfully executed.
Ex No : 9
Date :
Aim
To create a graph using the SharePoint Object Model and Silverlight Graphing controls.
Procedure
6.
Press OK to continue.
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
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);
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:
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.
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.
S.No
1
2
3
4
5
6
7
8
9
Date
Page
no
Marks
awarded
Signature of
the staff