Thursday, November 20, 2014

Mã hóa dữ liệu khi lưu trữ trong ứng dụng Java + SQL Server

Thông thường dữ liệu các nhân của người dùng khi lưu trữ vào csdl chúng ta nên che đi những dữ liệu nhạy cảm, trong ví dụ sau đây chúng ta cùng làm một demo nhỏ để che đi dữ liệu email và ngày sinh của người dùng (chỉ có ứng dụng của chúng ta mới giải mã được)

Tạo bảng để lưu được thông tin sau:
Order.    Name        Type
1.    Username    Text
2.    Password    Text
3.    Fullname    Text
4.    Address     Text
5.    Email       Text
6.    Birthdate   Date

Yêu cầu

Thiết kế form thêm thông tin người dùng vào bảng trên với các yêu cầu sau:
    1.    Mã hóa Password bằng giải thuật MD5
    2.    Mã hóa email và birthdate bằng giải thật mã hóa 02 chiều

Thiết kế form hiển thị ds người dùng thể hiện các cột: Username, Fullname và Address
Thiết kế form tìm người dùng dựa vào Username, kết quả hiển thị chi tiết người dùng gồm thông tin
       Username
    •    Fullname
    •    Address
    •    Email và Birthdate đã được giải mã

Giao diên thêm và tìm thông tin

image Dữ liệu đã mã hóa

image Dữ liệu được giải mã (nhấn nút find)

image

Bước 1: Tạo CSDL tên data và bảng nguoidung

1 SET ANSI_NULLS ON
2 GO
3
4 SET QUOTED_IDENTIFIER ON
5 GO
6
7 SET ANSI_PADDING ON
8 GO
9
10 CREATE TABLE [dbo].[users](
11 [username] [varchar](50) NULL,
12 [password] [varchar](100) NULL,
13 [fullname] [varchar](100) NULL,
14 [address] [varchar](250) NULL,
15 [email] [varbinary](max) NULL,
16 [birthdate] [varbinary](max) NULL
17 ) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
18
19 GO
20
21 SET ANSI_PADDING OFF
22 GO

Bước 2: Tạo cập khóa cho ứng dụng và lưu trữ lại để sử dụng (file)


1 class KeyGen {
2 public static void main(String[] args) {
3 try {
4 if (!new File("src/lib/pri.key").exists()) {
5 KeyPairGenerator key = KeyPairGenerator.getInstance("RSA");
6 key.initialize(512);
7 KeyPair keys = key.genKeyPair();
8 // Tạo cặp khóa
9 PrivateKey privateKey = keys.getPrivate();
10 PublicKey publicKey = keys.getPublic();
11 // Lưu thông tin khóa để tái sử dụng, khóa công khai để giải mã
12 X509EncodedKeySpec x509EncodedKeySpec =
13 new X509EncodedKeySpec(publicKey.getEncoded());
14 FileOutputStream fos = new FileOutputStream("src/lib/pub.key");
15 fos.write(x509EncodedKeySpec.getEncoded());
16 fos.close();
17 // khóa mật để mã hóa
18 PKCS8EncodedKeySpec pkcs8EncodedKeySpec =
19 new PKCS8EncodedKeySpec(privateKey.getEncoded());
20 fos = new FileOutputStream("src/lib/pri.key");
21 fos.write(pkcs8EncodedKeySpec.getEncoded());
22 fos.close();
23 } else {
24 System.out.println("Khoa da co");
25 }
26 } catch (IOException ex) {
27 Logger.getLogger(KeyGen.class.getName()).log(Level.SEVERE, null, ex);
28 } catch (NoSuchAlgorithmException ex) {
29 Logger.getLogger(KeyGen.class.getName()).log(Level.SEVERE, null, ex);
30 }
31 }
32 }






Tới đây chúng ta đã có được cặp khóa để có thể mã hóa và giải mã những dữ liệu cần thiết.


Bước 3: Xây dựng lớp Encode để phục hồi khóa từ tập tin và tạo phương thức mã hóa, giải mã.



1 public class Encode {
2 private PrivateKey priKey;
3 private PublicKey pubKey;
4 public Encode() {
5 getKeys();
6 }
7 private void getKeys() {
8 try {
9 File pubKeyFile = new File("src/lib/pub.key");
10 File privKeyFile = new File("src/lib/pri.key");;
11 // đọc dữ liệu từ file và khởi tọa lại khóa công khai
12 DataInputStream dis = new DataInputStream(new FileInputStream(pubKeyFile));
13 byte[] pubKeyBytes = new byte[(int) pubKeyFile.length()];
14 dis.readFully(pubKeyBytes);
15 dis.close();
16
17 // đọc dữ liệu từ file và khởi tọa lại khóa mật
18 dis = new DataInputStream(new FileInputStream(privKeyFile));
19 byte[] privKeyBytes = new byte[(int) privKeyFile.length()];
20 dis.read(privKeyBytes);
21 dis.close();
22 //
23 KeyFactory keyFactory = KeyFactory.getInstance("RSA");
24 // Tạo khóa công khai
25 X509EncodedKeySpec pubSpec = new X509EncodedKeySpec(pubKeyBytes);
26 pubKey = (RSAPublicKey) keyFactory.generatePublic(pubSpec);
27 // tạo khóa mật
28 PKCS8EncodedKeySpec privSpec = new PKCS8EncodedKeySpec(privKeyBytes);
29 priKey = (RSAPrivateKey) keyFactory.generatePrivate(privSpec);
30 } catch (Exception ex) {
31 System.out.println("ERR: " + ex.toString());
32 }
33 }
34 // hàm mã hóa
35 public byte[] TwowayEncrypt(byte[] data) {
36 try {
37 Cipher c = Cipher.getInstance("RSA");
38 c.init(Cipher.ENCRYPT_MODE, priKey);
39 byte[] rs = c.doFinal(data);
40 return rs;
41 } catch (Exception ex) {
42 System.out.println("Err: " + ex.toString());
43 }
44 return null;
45 }
46 // hàm giải mã
47 public byte[] TwowayDecrypt(byte[] data) {
48 try {
49 Cipher c = Cipher.getInstance("RSA");
50 c.init(Cipher.DECRYPT_MODE, pubKey);
51 byte[] rs = c.doFinal(data);
52 return rs;
53 } catch (Exception ex) {
54 System.out.println("Err: " + ex.toString());
55 }
56 return null;
57 }
58 // dùng cho mã hóa mật khẩu
59 public byte[] OnewayEncrypt(byte[] data){
60 try {
61 MessageDigest dig = MessageDigest.getInstance("MD5");
62 return dig.digest(data);
63 } catch (Exception ex) {
64 System.out.println("ERR: "+ ex.toString());
65 }
66 return null;
67 }
68 }


Bước 4: Tích hợp lên giao diện


Xử lý sự kiện Click nút Add new


1 private void btnAddActionPerformed(java.awt.event.ActionEvent evt) {
2 try {
3 Connection conn = DriverManager.getConnection("jdbc:sqlserver://ntdan;databasename=data;", "sa", "sa");
4 PreparedStatement comm = conn.prepareStatement("Insert into users values(?,?,?,?,?,?)");
5 comm.setString(1, txtUser.getText());
6
7 byte[] ba1 = Charset.forName("UTF-8").encode(CharBuffer.wrap(txtPass.getPassword())).array();
8
9 comm.setString(2, new String(encode.OnewayEncrypt(ba1), "UTF-8"));
10 comm.setString(3, txtFull.getText());
11 comm.setString(4, txtAdd.getText());
12
13 comm.setBytes(5,encode.TwowayEncrypt(txtEmail.getText().getBytes("UTF-8")));
14 comm.setBytes(6, encode.TwowayEncrypt(txtBirth.getText().getBytes("UTF-8")));
15
16 comm.executeUpdate();
17 } catch (Exception ex) {
18 System.out.println("ERR: " + ex.toString());
19 }
20 }

Xử lý sự kiện Click nút Find


1 private void btnFindActionPerformed(java.awt.event.ActionEvent evt) {
2 try {
3 Connection conn = DriverManager.getConnection("jdbc:sqlserver://ntdan;databasename=data;", "sa", "sa");
4 PreparedStatement comm = conn.prepareStatement("Select * from Users where username=?");
5 comm.setString(1, txtUser.getText());
6 ResultSet rs = comm.executeQuery();
7 String found="";
8 if(rs.next())
9 {
10 found = "User: ";
11 found += rs.getString(1);
12 found += "\nFullname: "+rs.getString(3);
13 found += "\nAddress: "+rs.getString(4);
14 found += "\nEmail: "+ new String(encode.TwowayDecrypt(rs.getBytes(5)),"UTF-8");
15 found += "\nBirthDate: "+ new String(encode.TwowayDecrypt(rs.getBytes(6)),"UTF-8");
16 }
17
18 JOptionPane.showMessageDialog(this, found);
19 } catch (Exception ex) {
20 System.out.println("Err: "+ ex.toString());
21 }
22 }



OK, như vậy là cơ bản chúng ta đã một phần nào đó che đi dữ liệu email và ngày sinh khi lưu vào SQL Server.


 


Đây là một ví dụ nhỏ hi vọng sẽ giúp chúng ta có cái nhìn rất cơ bản về việc bảo vệ dữ liệu riêng tư cho ứng dụng.

Tuesday, November 18, 2014

Sử dụng thư viện PhpMailer để gởi thư

 

Sử dụng thư việc PhpMailer để gởi thư. Chúng ta sử dụng tài khoản gmail để gởi thư.

Thư viện phpmailer download từ website sourceforge.net

1 $mail = new PHPMailer(true);
2 $mail->IsSMTP();
3 try {
4 $mail->CharSet = "UTF-8";
5 $mail->Host = "salomon.com";
6 $mail->SMTPDebug = 1;
7 $mail->SMTPAuth = true;
8 $mail->SMTPSecure = "ssl";
9 $mail->Host = "smtp.gmail.com";
10 $mail->Port = 587;
11 $mail->Username = "ngotuongdan04";
12 $mail->Password = "ngotuongdan";
13 $mail->AddReplyTo('ntdan@ctu.edu.vn', 'Web master');
14 $mail->AddAddress($email, "Web master");
15 $mail->SetFrom('ntdan@ctu.edu.vn', 'Web master');
16 $mail->AddReplyTo('ntdan@ctu.edu.vn', 'Web master');
17 $mail->Subject = 'M?t kh?u m?i';
18 $mail->AltBody = 'S? d?ng tr?nh duy?t tương ?ng!';
19 $mail->Body = $newpass;
20 $mail->Send();
21 } catch (phpmailerException $e) {
22 echo $e->errorMessage();
23 } catch (Exception $e) {
24 echo $e->getMessage();
25 }
26


Lưu ý thay thế tài khoản và mật khẩu mail của bạn

Thursday, November 13, 2014

Demo phần làm Game 2D (thuần java) trên Android

 

gacon_

https://play.google.com/store/apps/details?id=vn.cusc.game2d

Code nhỏ gởi email với java

Sử dụng thư viện mail của Java và tài khoản gmail để gởi thư điên.

1 package javamaildemo;
2 import java.util.Properties;
3 import java.util.logging.Level;
4 import java.util.logging.Logger;
5 import javax.mail.Authenticator;
6 import javax.mail.Folder;
7 import javax.mail.Message;
8 import javax.mail.PasswordAuthentication;
9 import javax.mail.Session;
10 import javax.mail.Store;
11 import javax.mail.Transport;
12 import javax.mail.internet.InternetAddress;
13 import javax.mail.internet.MimeMessage;
14
15 public class JavaMailDemo {
16 public static void main(String[] args) {
17 try {
18 // Authenticated and send mail
19 Properties props = System.getProperties();
20 props.put("mail.smtp.host", "smtp.gmail.com");
21 props.put("mail.smtp.port", "587");
22 props.put("mail.transport.protocol", "smtp");
23 props.put("mail.smtp.starttls.enable", "true");
24 props.put("mail.smtp.auth", "true");
25 props.put("mail.debug", "true");
26
27 Authenticator auth;
28 auth = new Authenticator() {
29 public PasswordAuthentication getPasswordAuthentication() {
30 return new PasswordAuthentication("ngotuongdan04@gmail.com", "ngotuongdan");
31 }
32 };
33
34 Session session = Session.getInstance(props, auth);
35 Message msg = new MimeMessage(session);
36
37 msg.setFrom(new InternetAddress("ngotuongdan04@gmail.com"));
38 msg.setSubject("Java mail demo");
39 msg.setRecipient(Message.RecipientType.TO, new InternetAddress("ntdan@ctu.edu.vn"));
40 msg.setContent("<h1>Hello ! How are you ?</h1>", "text/html");
41
42 Transport.send(msg);
43
44 /* check mail
45
46 props.put("mail.pop3.host", "pop.gmail.com");
47 props.put("mail.pop3.starttls.enable", "true");
48 props.put("mail.debug", "true");
49 props.put("mail.transport.protocol", "pop3");
50 props.put("mail.pop3.port", "995");
51
52 Session session = Session.getInstance(props);
53
54 Store stored = session.getStore("pop3");
55 stored.connect("pop.gmail.com",995,"ngotuongdan04@gmail.com", "ngotuongdan");
56 Folder folder = stored.getDefaultFolder();
57 folder.open(Folder.READ_ONLY);
58 System.out.print(folder.getMessageCount());
59 */
60 } catch (Exception ex) {
61 System.out.print(ex.toString());
62 }
63 }
64 }
65

Cần phải tham chiếu thêm thư viện mail.jar vào ứng dụng.

Wednesday, November 12, 2014

Winform C# 1 – Questions

Câu 1 _____is any action directed at the application.

[A] Event

[B] Method

[C] Class

[D] Object

Câu 2____property is used to get or set the object that contains data about the control.

[A] Value

[B] Tag

[C] Text

[D] Name

Câu 3 Which of the following statement with respect to Data Grid control are True? (Choose all correct answers)

[A] By default, the DataGrid display 1 page at a time.

[B] When the DataGrid control is set to a valid data source, the control is populated automatically

[C] Each field in the DataGrid is bound to a single column based on the DataSource

[D] The DataGrid control display data in tabular format and optionally supports data editing.

Câu 4 When an MDI parent form is closed, the Closing event of all MDI child forms are raised before the MDI parent form’s Closing event is raised

[A] False

[B] True

Câu 5 What of the followings is correct for creating a command object with the connection con?

[A] SqlCommand Cmd = con.SetSqlCommand(“Select * From Student”);

[B] SqlCommand Cmd = con.GetSqlCommand(“Select * From Student”);

[C] SqlCommand Cmd = new SqlCommand(con,”Select * From Student”);

[D] SqlCommand Cmd = new SqlCommand(“Select * From Student”, con);

Câu 6 The method can be used to draw a rectangle or a square depending on the coordinates passed as its argument.

[A] FillSquare

[B] FillRectangle

[C] DrawSquare

[D] DrawRetangle

Câu 7 General Project Properties are applicable to all project configurations and are set in the properties window.

[A] False

[B] True

Câu 8 Name the object which notifes other objects about an event

[A] Consumer

[B] Publisher

[C] Subscriber

[D] Tester

Câu 9 _____it the normal ouput type for a WinForm project

[A] Windows Application

[B] Console Application

[C] Class Library

[D] Windows Forms

Câu 10 We can generate Typed Dataset from a Datadapter

[A] False

[B] True

Câu 11 To preserve screen space on the monitor, VS.NET provides us with (Choose all answers) Note

[A] Class View Window

[B] Command Window

[C] Solution Explorer Window

[D] Auto-Hide Window

[E] Properties Window

[F] Tabbed Windows

Câu 12Images can be drawn using the _____method to of the Graphics class.

[A] PaintImage()

[B] DrawImage()

[C] CreateImage()

[D] FromImage()

Câu 13 DataSet store its data in XML

[A] False

[B] True

Câu 14 The ____control groups a set of controls within a non-labeled an scrollable frame

[A] PictureBox

[B] Tab

[C] Frame

[D] Panel

Câu 15 The ____feature of Windows Installer provider a standard method for distributing components and ensures that the installed component is of the correct version.

[A] VersionUpdate

[B] CAB

[C] Msi

[D] Merge Modules

Câu 16 To create an instance of the Font class using existing Font and FontStyle, the constructor is:

[A] public void Font(string fontname, float size);

[B] public Font(FontStyle fs, Font f);

[C] public void Font(Font f, FontStyle fs);

[D] public Font(Font f, FontStyle fs);

[E] public Font(string fontname, float size);

Câu 17 Which control is used to display a short, customized help message for individual controls on a form?

[A] ToolTip

[B] HelpText

[C] HelpTool

[D] ToolClass

Câu 18 For using SQL.NET Data Provider what using statement of the following is correct?

[A] using System.Data;

[B] using System.Data.SqlServer;

[C] using System.Data.OleDb;

[D] using System.Data.SqlClient;

Câu 19 OLE is the abbreviation for ____

[A] Object Like Environment

[B] Object Linking and Embedding

[C] Object Linking Environment

[D] Object Linking and Empower

Câu 20 Microsoft Windows Installer is shipped along with Windows 2000, Windows ME and Windows XP as an installation and configuration service.

[A] False

[B] True

Câu 21 Which namespace is VS.NET contains classes that help in constructing and sending emails?

[A] System.Web.Mail

[B] System.Mail

[C] System.Web.MailMessage

[D] System.Web.MailMessages

Câu 22 Statement 1: Tree View displays items like folders, drives etc.

Statement 2: List View display items like current folder contents.

[A] Only statement 2 is true

[B] Both the statements are true

[C] Only statement 1 is true

[D] Both the statements are false

Câu 23 The DataAdapter method is used to fetch the values from the data source to the DataSet and also to update the data source with the DataSet data.

[A] False

[B] True

Câu 24 To perform a change to a table using the Command object named Cmd, what statement of the following correct?

[A] Cmd.ExecuteReader()

[B] Cmd.ExecuteScalar()

[C] Cmd.ExecuteQuery()

[D] Cmd.ExecuteNonQuery()

[E] Cmd.ExecuteUpdate()

Câu 25 When a Data Form is created using the Data Form Wizard, which of the following classes are used by default?(Choose all correct answers)

[A] OleDbDataWriter

[B] OleDbDataAdapter

[C] OleDbStatement

[D] OleDbDataReader

[E] OleDbConnection

[F] OleDbCommand

Câu 26 ____property of a connection object is used to get or set the string used to open a database

[A] ConnectionParams

[B] ConnectionInfo

[C] StringConnection

[D] ConnectionString

Câu 27 property is used to get or set the data source that the grid is displaying data for.

[A] DataSrc

[B] DataSource

[C] DataSet

[D] DataMember

[E] DataSender

Câu 28 _____property is used to get or set the edges of the control are anchored to the edges of its container.

[A] Hang

[B] Fixed

[C] Anchor

[D] Dock

Câu 29 MessageBox is a type of dialog box

[A] False

[B] True

Câu 30 OLE is the abbreviation for Object Linking and Embedding

[A] False

[B] True

Câu 31 ____property is used to get or set the shortcut menu associated with the control.

[A] PopUpMenu

[B] SubMenu

[C] ContextMenu

[D] MainMenu

Câu 32 The DataReader component is used to get the read-only and forward-only data from the data source.

[A] False

[B] True

Câu 33 System.Windows.Forms is an important____of the class libraries in .NET framework?

[A] Namespace

[B] Class

Câu 34 To get values of the columns of the i-th row in a DataTable object named datatable, what of the follwings is correct?

[A] DataColumn array = datatable.Rows[i].ItemArray;

[B] String[]array = datatable.Rows[i].ItemArray;

[C] Object[]array = datatable.Rows[i].ItemArray;

[D] DataRow array = datatable.Rows[i].ItemArray;

Câu 35 What mode is VS.NET allow you to step through each line of code and trace the execution of your application?

[A] Neither Debug Mode nor Release Mode

[B] Both Debug Mode and Release Mode

[C] Release Mode

[D] Debug Mode

Câu 36 Link Lable is commands control?

[A] False

[B] True

[C] There is no link label control

Câu 37 Brushes can be created using one of the following classe(Choose all correct answers)

[A] ThinBrush

[B] ThickBrush

[C] PlainBrush

[D] TextureBrush

[E] SolidBrush

[F] LinearGradientBrush

[G] GradientBrush

Câu 38 What mode is VS.NET allow you create a portable exe(EXE) file?

[A] Neither Debug Mode nor Release Mode

[B] Debug Mode

[C] Both Debug Mode and Release Mode

[D] Release Mode

Câu 39 What statement in the followings is correct

I. The instance properties and methods are those, which are common to all the instances of the class.

II. The shared properties and methods are those, which are specific to a particular instance.

[A] Both of I and II statements are correct

[B] Both of I and II statements are incorrect

[C] Only II statement is correct

[D] Only I statement is correct

Câu 40 ADO.NET provides features for accessing traditional databases like SQL Server as well as databases, which are accessed using ____.(choose all correct answers)

[A] ODBC

[B] VB.NET

[C] OLEDB

[D] XML

[E] DataSets

Câu 41 Name the .NET data providers which are available is VS.NET?(Choose all correct answers)

[A] ODBC.NET Framework Data Provider

[B] SQL.NET Framework Data Provider

[C] OLEDB.NET Framework Data Provider

[D] Oracle.NET Framework Data Provider

[E] Access.NET Framework Data Provider

Câu 42 You can create your own table in DataSet

[A] False

[B] True

Câu 43 The____ event of the PrintDocument class is triggered immediately before each PrintPage event ocurs.

[A] StartPrint

[B] BeginPrint

[C] PrintPage

[D] QueryPageSettings

Câu 44 ___is the easiest way to allow the user to interact with the application.

[A] Label control

[B] Text control

[C] Button control

[D] Form

Câu 45 The term packaging imlies bundling up all the files in the application into a single file called a Distribution Unit

[A] False

[B] True

Câu 46 Which namespace does the class ListView belong to?

[A] System.Windows.Lists

[B] System.Windows.Drawing

[C] System.Windows.Paint

[D] System.Windows.Forms

Câu 47 The____property of a DataGrid control, allow filling various kinds of data in a DataGrid including data from a DataSet, DataViewManager, Arrays, Lists etc.

[A] DataRecords

[B] FillSchema

[C] Fill

[D] FillData

[E] DataSource

Câu 48 The Pen class belongs to the ____namespace and cannot be inherited

[A] System.Painting

[B] System.GraphicsObjects

[C] System.Graphics

[D] System.Drawing

Câu 49 ____are the visual effects supported in WinForms (Choose all correct answers).

[A] Collections

[B] Class Libraries

[C] Opaque Forms

[D] Visual Inheritance

[E] Control Anchoring

[F] Cotrol Docking

[G] Transparent Forms

Câu 50 Help is one of the most important but then also mostly forgotten part of any application

[A] False

[B] True

Câu 51 Which class represents shortcut menus that can be displayed when the user clicks the right mouse button over a control or area of the form?

[A] ToolMenu

[B] MainMenu

[C] ContextMenu

[D] FileMenu

Câu 52 The value of the HelpButton property is ignored if the maximize of minimize boxes are shown.

[A] False

[B] True

Câu 53 List the key elements of COM (choose all correct answers)

[A] A set of theorems which must be proven for checking the correctness of the object model

[B] A set of graphical symbol for modeling the objects

[C] A set of services for creating and exposing the classes

[D] A set of specifications defining the programming protocol

Câu 54 ____ are the Print support controls provided by WinForms.(Choose all correct answers)

[A] PrintPreview

[B] PrintFile

[C] PrintPreviewControl

[D] PrintDirectory

[E] PrintDocument

Câu 55 What of the followings are data validation mode in WinForms?(Choose all correct answers)

[A] Form-Level Validation

[B] There is no Data validation mode in Winforms

[C] Control-Level Validation

[D] Field-Level Validation

Câu 56 What of the folllowings is correct if we want to set the Achild form as a child form of the parent form named TheParent?

[A] AChild.MdiParent = TheParent;

[B] AChild.TheParent = true;

[C] Achild.MdiChild = AChild;

[D] TheParent.MdiChild = AChild;

[E] TheParent.AChild = true;

Câu 57 Class Library is one of the main components of the .NET framework and is divided in to ____

[A] Namespaces

[B] DLL components

[C] GUI components

Câu 58 To bind data to controls as ListBox, ComboBox, DataGrid, what type of data bindings shoud you use?

[A] Hybrid Data Binding

[B] Complex Data Binding

[C] Simple Data Binding

[D] Structured Data Binding

Câu 59 The ____control groups a set of controls within a non-labeled and scrollable frame

[A] PictureBox

[B] CheckedBox

[C] Panel

[D] Frame

Câu 60 ____property is used to get or set a value that is returned to the parent form when the button is clicked.

[A] ButonResult

[B] DialogResult

[C] ButtonValue

[D] ResultValue

[E] ResultDialog

Câu 61 Arrange the sequence in which the key events are triggered

[A] KeyPress, KeyUp, KeyDown

[B] KeyUp, KeyPress, KeyDown

[C] KeyDown, keyPress, KeyUp

[D] KeyPress, keyDown, KeyUp

[E] KeyUp, KeyDown, KeyPress

[F] KeyDown, KeyUp, KeyPress

Câu 62 The types of list box supported in Winforms are(Choose all correct answers)

[A] ListBox

[B] CheckedListBox

[C] ComboBox

[D] DropDownbox

Câu 63 What are thee steps involved involved in calling one from another form?(choose all answers)

[A] Create an instance of the calling form

[B] Create an instance of the form to be called

[C] Invoke Show

Câu 64 Which Control is used to display the current status of the application using framed windows?

[A] TreeView

[B] StatusBar

[C] ToolBar

[D] ListView

Câu 65 Which of the following objects can we use to read data from a Micorosoft SQL Server 2000 database? (choose all correct answers)

[A] SQLDataAdapter

[B] DataSet

[C] OleDbDataAdapter

[D] ADORecordSet

[E] XmlTextReader

Câu 66 Use DataReader when we want to have data scrollable

[A] False

[B] True

Câu 67 What is component is used to fetch the values from the data source to DataSet and also update the data source with data in the DataSet?

[A] DataWriter

[B] DataReader

[C] DataAdapter

[D] DataCommand

Câu 68 The ____property of the Form control is used to determine whether there are any MDI child forms open in your MDI application.

[A] ActiveMdiChildren

[B] ActiveMdiChild

[C] IsMdiChild

[D] IsMdiChildren

Câu 69 ____are the collection of reusable classes or types

[A] Namespaces

[B] Collections

[C] Class libraries

Câu 70 ____control combines the features of the TextBox and the ListBox controls

[A] ToolBar

[B] StatusBar

[C] Label

[D] ComboBox

Câu 71 A custom control should you use to verify an authorized aplication user called as _____

[A] Composite Custom Control

[B] Standard Control

[C] Single Control

[D] Complex Control

Câu 72 Each Merge Module holds distinctive version details that are used by Windows Installer

[A] False

[B] True

Câu 73 Which of the following statements with respect to ADO.Net are True? (Choose all correct answers)

[A] System built on ADO.NET are intrinsically highly scaleable

[B] ADO.NET objects are all strongly typed.

[C] When we use the DataSet object, ADO.NET is based on disconnected data access.

[D] in ADO.NET, the RecordSet is bound to the data source

Câu 74 The method ____of the Control class conceals the control from the user.

[A] Close

[B] visible

[C] Dispose

[D] Hide

Câu 75 What control support us to display the list items in different types as text only, text with small icons, text with large icons and report views?

[A] ListView

[B] ListBox

[C] CheckedListBox

[D] ComboBox

Câu 76 IntelliSence pops up a list of _____that can be called on an object (Choose all correct answers). Xem lai

[A] Hints

[B] Values

[C] Properties

[D] Links

[E] Tags

Câu 77 The____ control is used to display text when the mouse points to a particular control

[A] Toolbar

[B] StatusBar

[C] Menu

[D] ToolTip

Câu 78 What are the types of Dialog boxes?(choose all correct answers)

[A] Custom dialog boxes

[B] Common dialog boxes

[C] Modeless dialog boxes

[D] Modal dialog boxes

Câu 79 which class is the base class for all the controls that can be used in Windows Forms?

[A] Control

[B] Controls

[C] Forms

[D] Objects

Câu 80 GDI + resides in _____ assembly.

[A] System.Painting

[B] System

[C] System.Graphics

[D] System.Drawing

Câu 81 The ____ property of the LinkLabel control is used to specity the text, which has to be displayed as a link.

[A] HyperLink

[B] URLName

[C] LinkName

[D] LinkArea

Câu 82 What of the following are correct for creating a connection object to database named MyDB? (Choose all correct answers)

[A] SqlConnection con = new SqlConnection(“server=myserver;

Integrated Security = SSPI; database=MyDB”);

[B] SqlConnection con = new SqlConnection(“server=myserver”

Intergrated Security=SSPI; Data Source=MyDB);

[C] SqlConnection con = new SqlConnection(“Data Source=myserver;

Integrated Sercurity=SSPI; Initial Catalog=MyDB”);

C©u 83 List the advantages of DCOM (Choose all correct answers)

[A] Provides Location Transparency(Distributed Architecture)

[B] Platform independent

[C] Fully Language Independent

[D] Supports version compatibility

C©u 84 The view types supported in Winforms are (choose all correct answers)

[A] Text with large icons

[B] Text only

[C] Text with small icons

[D] Report view

C©u 85 If maximize and minimize buttons are displayed then the HelpButton property is ignored.

[A] False

[B] True

C©u 86 The ____ event of the Form control is used to perform tasks such as allocating resources used by the form

[A] Allocate

[B] Activate

[C] Load

[D] Activated

C©u 87 To get values of the colums of the i-th row in a DataTable object named datatable, what of the followings is correct?

[A] Object [] array = datatable.Rows[i].ItemArray;

[B] DataColumn array = datatable. Rows[i].ItemArray;

[C] String[] array = datatable. Rows[i].ItemArray;

[D] DataRow array = datatable. Rows[i].ItemArray;

Monday, November 10, 2014

JComboBox – Display and Value from Item

Do quá trình làm đồ án Java có nhiều bạn gặp khó khăn trong việc load dữ liệu vào JComboBox. Trong bài này tôi hướng dẫn một đoạn code nhỏ để các bạn tham khảo.

image

Bước 1: Định nghĩa nội dung cho một phần tử trong ds của JComboBox

1 class Item {
2 public Item(int id, String name, int price) {
3 this.id = id;
4 this.name = name;
5 this.price = price;
6 }
7
8 private int id;
9 private String name;
10 private int price;
11
12 public int getId() {
13 return id;
14 }
15
16 public void setId(int id) {
17 this.id = id;
18 }
19
20 public String getName() {
21 return name;
22 }
23
24 public void setName(String name) {
25 this.name = name;
26 }
27
28 @Override
29 public String toString() {
30 return getName() + "\t" + getPrice();
31 }
32
33 public int getPrice() {
34 return price;
35 }
36
37 public void setPrice(int price) {
38 this.price = price;
39 }
40 }
Bước 2: Gán dữ liệu vào danh sách và đưa lên JComboBox


1 private void load()
2 {
3 DefaultComboBoxModel model = new DefaultComboBoxModel();
4 model.addElement(new Item(1,"Mit",8000));
5 model.addElement(new Item(2,"Cam", 15000));
6 model.addElement(new Item(2,"Xoai", 20000));
7 jComboBox1.setModel(model);
8 }

Bước 3: Nhận giá trị (khóa, ID) của từ JComboBox khi chọn một phần từ từ giao diện


- Đăng ký sự kiện chọn phần tử từ ds





1 private void jComboBox1ItemStateChanged(java.awt.event.ItemEvent evt) {
2 this.setTitle( ((Item)jComboBox1.getSelectedItem()).getId()+"");
3 }


Tới đây chạy lại from để quan sát kết quả.


 


Mã nguồn tham khảo ở đây


http://1drv.ms/10JvXRm


Video tham khảo


http://youtu.be/wvJ155iuni0?list=UUQ8F8U5jZwjS4MZ5JYX5W2A

Translate