Thursday, October 31, 2013

Java server face (JSF) - trang đa ngôn ngữ

OBJECTIVES

  1. -Create jsf web page support multi language interface

  2. -Using Face component Event

  3. -Setting current Locale and Global Locale


Hints:

  1. Create JSF web site

  2. Create 03 jsp page and configure navigation rule for them from properties file support two language Vietnam and English

  3. Setting current Locale and Global Locale at runtime and design time


Create JSF website



  • Create 03 jsp file: index.jsp, add.jsp, list.jsp

  • Open Face-config.xml, design navigation rule as figure 01 and insert new code as code 01


page-flow


[sourcecode language="xml"]
<application>
<view-handler>com.sun.facelets.FaceletViewHandler</view-handler>
<resource-bundle>
<var>bundle</var>
<base-name>code.guiMessage</base-name>
</resource-bundle>
<locale-config>
<default-locale>vi</default-locale>
</locale-config>
</application>
[/sourcecode]

Code 01: Register bundle file


Create properties file



  • Name: guiMessage in side package code

  • Add two Locale vi_VN and en_US

  • Rename file as figure 02


bundle

Right click o guiMessage file select open and insert some key as figure 03

properties

Create manage bean



  • Language in code package

  • Modified code as



[sourcecode language="java"]
package code;

import java.util.Locale;
import javax.faces.context.FacesContext;
import javax.faces.event.ValueChangeEvent;

public class language {

public String getLang() {
return lang;
}

public void setLang(String lang) {
this.lang = lang;
}
String lang = &amp;amp;quot;vi&amp;amp;quot;;

/**
* Creates a new instance of language
*/
public language() {
}

public void change(ValueChangeEvent event) {
lang = event.getNewValue().toString();
FacesContext.getCurrentInstance().getApplication().setDefaultLocale(new Locale(lang));
FacesContext.getCurrentInstance().getViewRoot().setLocale(new Locale(lang));
}
}
[/sourcecode]

This code allow we setting Local and Global Locale of websie

Open index.jsp


Modified as figure 03 (using EL language: after bundle. Using Ctrl+Space bar for virtual code)

index

Index.jsp with two language

index1

Add Add.jsp page

add

[sourcecode language="html"]
<%@page contentType="text/html"%>
<%@page pageEncoding="UTF-8"%>
<%@taglib uri="http://java.sun.com/jsf/html" prefix="h"%>
<%@taglib uri="http://java.sun.com/jsf/core" prefix="f"%>
<f:view>
<h:form>
<table>
<tr>
<td align="center" colspan="2">
<h1><h:outputText value="#{bundle.register}"/></h1>
<h4><h:commandLink value="#{bundle.home}" action="home"/></h4>
<h:messages layout="table"/>
</td>
</tr>
<tr>
<td>
<h:outputText>
<f:attribute name="value" value="#{bundle.id}"/>
</h:outputText>
</td>
<td>
<h:inputText value="#{Customer.customerID}">

</h:inputText>
</td>
</tr>
<tr>
<td><h:outputText value="#{bundle.CompanyName}"/></td>
<td><h:inputText value="#{Customer.companyName}"/></td>
</tr>
<tr>
<td><h:outputText value="#{bundle.Address}"/></td>
<td><h:inputText value="#{Customer.address}"/></td>
</tr>
<tr>
<td></td> <td><h:commandButton value="#{bundle.register}" action="list"
actionListener="#{Customer.AddNew}"/></td>
</tr>
</table>
</h:form>
</f:view>
[/sourcecode]

Đổi không khí học winform C# - Sử dụng timer control viết game click to win

Bắt đâu: Giao diện game

Game

Click các số 0 cho đến khi chúng mất hêt

win

Vậy là thắng rồi :D (chỉ để đổi không khí học một tí nhe các bạn)

Source nguồn đây.

Friday, October 11, 2013

Xây dựng và sử dụng WCF đơn giản (WCF basic demo for student)

Objectives

1. Create WCF service (host on web server )

2. Using WCF service from window form application

Hits: Step for create and using service
  • Create WCF service “Student” with two operations “list()” and “detail(id)”
    1. Define service interface (ServiceContract)
    2. Define class describe detail of student (DataContract)
    3. Define Service by implement from server interface
  • Using WCF service from window form application
    1. Find service description of WCF “student”
    2. Reference WCF service
    3. Call operations of student service

Student table

No. Data field Data type
1. S_ID Int
2. S_FullName Text
3. S_Birthdate DateTime
4. S_Address Text

WCF basic demo 2013 (PDF version of this post)

http://www.mediafire.com/?ji9uiz5l70d8n (Source code of this post)

BEGIN

Open visual studio 2008 (or later)

File -> Create Project

clip_image002

Select as figure

Right click on project -> Add new Item

clip_image004

Select as figure

Right click on project -> Add new Item

clip_image006

Select as figure

Modified class as

1 namespace students
2 {
3 [DataContract]
4 public class StudentDetail
5 {
6 [DataMember]
7 public int ID;
8 [DataMember]
9 public string FullName;
10 [DataMember]
11 public DateTime Birthdate;
12 [DataMember]
13 public string Address;
14 }
15 }
16
17 Modified IStudent interface as
18
19 namespace students
20 {
21 [ServiceContract]
22 public interface IStudent
23 {
24 [OperationContract]
25 DataSet List();
26 [OperationContract]
27 StudentDetail Detail(int ID);
28 }
29 }

Edit Student service as


clip_image002[4]



1 namespace students
2 {
3 public class Student : IStudent
4 {
5 public DataSet List()
6 {
7 DataSet dsS = new DataSet();
8 // insert C# code to get data from student table
9 return dsS;
10 }
11 public StudentDetail Detail(int ID)
12 {
13 StudentDetail sDetail = new StudentDetail();
14 return sDetail;
15 }
16 }
17 }
18
Now right click on service and select view in browser


clip_image005


Right click on solution -> add new project


clip_image007


Select as figure


Design form as


clip_image010


GUI of client


Add service reference as


clip_image012


Modify form load event:


1 wcf.StudentClient proxy;
2 private void Form1_Load(object sender, EventArgs e)
3 {
4 proxy = new WCF_Client.wcf.StudentClient();
5 }

Double click on button Find and insert code as


1 private void btnFind_Click(object sender, EventArgs e)
2 {
3 wcf.StudentDetail detail = proxy.Detail(Convert.ToInt32(txtID.Text));
4 MessageBox.Show("Student id: " + detail.ID + "\nStudent fullname: " + detail.FullName);
5 }
6

Double click on button List and insert code as


1 private void btnList_Click(object sender, EventArgs e)
2 {
3 dgrStudent.DataSource = proxy.List();
4 dgrStudent.DataMember = "student";
5 }

Now run client


clip_image014


Client at runtime








Xem hướng dẫn video trên


Mã nguồn:  http://www.mediafire.com/download/f4l6dpz2wla513w/WebApplication1.rar

Wednesday, October 9, 2013

Very simple.net web service exception handling


  1. Create header exception

  2. Assign header  for special web method

  3. Exception handling at client: SoapException and SoapHeaderException



Header definition
[sourcecode language="csharp"]
public class WSHeader: SoapHeader
{
public WSHeader()
{

}
private DateTime _CallTime;
public DateTime CallTime
{
get { return _CallTime; }
set { _CallTime = value; }
}
}
[/sourcecode]

Webservice difinition and header assignment
[sourcecode language="csharp"]
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
public class TimingService : System.Web.Services.WebService
{
public WSHeader DiscountHeader;
public TimingService()
{

//Uncomment the following line if using designed components
//InitializeComponent();
}

[WebMethod]
[SoapHeader("DiscountHeader", Direction = SoapHeaderDirection.In)]
public double Discount(DateTime birthdate)
{
if (DiscountHeader == null)
throw new SoapHeaderException("User invalid", SoapException.ClientFaultCode);
else if (birthdate > DateTime.Now)
{
throw new SoapException("Birthdate invalid", SoapException.ClientFaultCode);
}
else
{
if (DateTime.Now.Year - birthdate.Year < 18)
return 0.1;
else
return 0.0;
}
}
}
[/sourcecode]

Call method from client
[sourcecode language="csharp"]
namespace Client
{
class Program
{
static void Main(string[] args)
{
try
{
WS.WSHeader header = new Client.WS.WSHeader();
header.CallTime = DateTime.Now.AddDays(-1);

WS.TimingService client = new Client.WS.TimingService();

client.WSHeaderValue = header;

Console.WriteLine("Discount per: "+ client.Discount(new DateTime(2013, 1, 1))*100 + "%");
}
catch (SoapHeaderException ex)
{
Console.WriteLine("Header error: " + ex.Message);
}
catch(SoapException ex)
{
Console.WriteLine("Call error: " + ex.Message);
}
}
}
}
[/sourcecode]

Friday, October 4, 2013

Lab – JSP - custom tag

Objectives


1. Create custom tag: Basis, Iteration and Complex tag


- Implement Interface
- Extend from Build in class

2. Using custom tag in JSP pages


Hits: Steps to create and call custom tag
1. Describe tag structure (Tag Library Description)
2. Process tag (Tag handler)
3. Register and call custom tag on JSP pages (<%@taglib ......%>

Custom tag 2013 (pdf version)


Source code

Create custom tag


1. Empty tag: header tag, footer tag
2. If – then – else tag
3. Iteration tag: loop tag
4. Employee list tag

HEADER tag (Implement Tag interface)


Create Tag Library Descriptor (customTag.tlb) file and insert xml section below
<tag>
<name>header</name>
<tag-class>MySource.header</tag-class>
<body-content>empty</body-content>
<attribute>
<name>companyname</name>
<required>true</required>
</attribute>
</tag>
Create tag handler
Create java class (header.java) in MySource package implement Tag interface
clip_image002
package MySource;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.PageContext;
import javax.servlet.jsp.tagext.Tag;
public class header implements Tag{
String companyname ="";
public void setCompanyname(String companyname) {
this.companyname = companyname;
}

PageContext context;
Tag parrent;
public void setPageContext(PageContext pc) {
context = pc;
}

public void setParent(Tag t) {
parrent = t;
}

public Tag getParent() {
return parrent;
}

public int doStartTag() throws JspException {
try {
context.getOut().print("<h1>"+companyname+"</h1>");
context.getOut().print("<h3>Education Department</h3>");
} catch (IOException ex) {
Logger.getLogger(header.class.getName()).log(Level.SEVERE, null, ex);
}

return SKIP_BODY;
}

public int doEndTag() throws JspException {
return SKIP_BODY;
}

public void release() {
}

}

Call header from jsp page


Create jsp page (home.jsp), using taglib tag register header tag
<%@page contentType="text/html" pageEncoding="windows-1252"%>
<%@taglib prefix="my" uri="/WEB-INF/MyLib.tld" %>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=windows-1252">
<title>Home</title>
</head>
<body>
<my:header companyname="Can Tho University Software Center (CUSC)"/>
</body>
</html>

Now build and run home.jsp page


clip_image004

Home.jsp

FOOTER tag (extend from Simple Tag Support class)


Create Tag Handler (footer.java)
clip_image006
Select Tag Handler from netbean template
clip_image008
Provide tag name as footer and click next
clip_image010
Click Browse to select tld file, click New to add companyname attribute as figure

Modified home.jsp as below


<%@page contentType="text/html" pageEncoding="windows-1252"%>
<%@taglib prefix="my" uri="/WEB-INF/MyLib.tld" %>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=windows-1252">
<title>Home</title>
</head>
<body>
<my:header companyname="Can Tho University Software Center (CUSC)"/>
<my:footer companyname="Can Tho University Software Center (CUSC)"/>
</body>
</html>

Now build and run home.jsp page


clip_image012
Home.jsp

Loop tag


Create Tag Handler (loop.java) extend from Simple Body Tag Support, with 2 attribute start and end
clip_image014
clip_image016

Modified writeTagBodyContent as below

private void writeTagBodyContent(JspWriter out, BodyContent bodyContent) throws IOException {
if(start < end)
{
out.print("<ol>");
while(start < end)
{
out.print("<li>");
bodyContent.writeOut(out);
out.print("</li>");
start++;
}

out.print("</ol>");
}
bodyContent.clearBody();
}

Modified home.jsp as below
<%@page contentType="text/html" pageEncoding="windows-1252"%>
<%@taglib prefix="my" uri="/WEB-INF/MyLib.tld" %>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=windows-1252">
<title>Home</title>
</head>
<body>
<my:header companyname="Can Tho University Software Center (CUSC)"/>
<hr/>
<my:loop start="0" end="10">
<%= new java.util.Date()%>
</my:loop>
<my:footer companyname="Can Tho University Software Center (CUSC)"/>
</body>
</html>

Now build and run home.jsp page


clip_image018

Employee list tag


Create Tag Handler (employee.java) extend from Simple Body Tag Support (same above)
Modified employee.java as:
private void writeTagBodyContent(JspWriter out, BodyContent bodyContent) throws IOException {
try {
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
Connection conn;
conn = DriverManager.getConnection("jdbc:sqlserver://ntdan-lt;user=sa;password=Admin@123;database=NorthWind;");
PreparedStatement command = conn.prepareStatement(bodyContent.getString());
java.sql.ResultSet result = command.executeQuery();
ResultSetMetaData meta = result.getMetaData();
out.print("<table border='1px'>");
out.print("<tr bgcolor='#ACE768'>");
int count = 1;
while(count <= meta.getColumnCount()) {
out.print("<td>"+meta.getColumnName(count)+"</td>");
count++;
}

out.print("</tr>");
while(result.next()) {
count=1;
out.print("<tr>");
while(count <= meta.getColumnCount()) {
out.print("<td>"+result.getString(meta.getColumnName(count))+"</td>");
count++;
}
out.print("</tr>");
}
out.print("</table>");
conn.close();
} catch(Exception ex) {
out.print(ex.toString());
}
bodyContent.clearBody();
}

Open home.jsp, insert code as

<body>
<my:header companyname="Can Tho University Software Center (CUSC)"/>
<hr/>
<my:loop start="0" end="2">
<%= new java.util.Date()%>
</my:loop>
<my:employee>Select Top 5 EmployeeID, FirstName, LastName From Employees</my:employee>
<my:footer companyname="Can Tho University Software Center (CUSC)"/>
</body>

Now build and run home.jsp page


clip_image020

Translate