3/30/09
Install Java for Ubuntu 8.04
$ sudo apt-get update
- After install the required packages:
$ sudo apt-get install fakeroot java-package java-common
- And finally, just tell it to install java :)
$ sudo apt-get install sun-java5-jdk
After this the rest of the process will display a dialog that will require you to accept the license agreement. When you do, the rest of the setup will happen on its own.
When you're on the command prompt type
$ java -version
$ sudo bash -c "echo JAVA_HOME=/usr/lib/jvm/java-6-sun/ >> /etc/environment"
or
$sudo gedit /etc/environment
Install Ant
$sudo apt-get install ant
Install Subversion
$sudo apt-get install subversion
3/28/09
Quản lý bản thân
- Hãy làm nhiều hơn những gì được mong đợi.
- Đừng bao giờ bị hạ gục.
- Đừng để tính cô lập giết chết chính mình.
3/24/09
Creating a .NET Web Service
Microsoft .NET marketing has created a huge hype about its Web Services. This is the first of two articles on Web Services. Here we will create a .NET Web Service using C#. We will look closely at the Discovery protocol, UDDI, and the future of the Web Services. In the next article, we will concentrate on consuming existing Web Services on multiple platforms (i.e., Web, WAP-enabled mobile phones, and windows applications).
Why do we need Web Services? After buying something over the Internet, you may have wondered about the delivery status. Calling the delivery company consumes your time, and it's also not a value-added activity for the delivery company. To eliminate this scenario the delivery company needs to expose the delivery information without compromising its security. Enterprise security architecture can be very sophisticated. What if we can just use port 80 (the Web server port) and expose the information through the Web server? Still, we have to build a whole new Web application to extract data from the core business applications. This will cost the delivery company money. All the company wants is to expose the delivery status and concentrate on its core business. This is where Web Services come in.
What is a Web Service?
Web Services are a very general model for building applications and can be implemented for any operation system that supports communication over the Internet. Web Services use the best of component-based development and the Web. Component-base object models like Distributed Component Object Model (DCOM), Remote Method Invocation (RMI), and Internet Inter-Orb Protocol (IIOP) have been around for some time. Unfortunately all these models depend on an object-model-specific protocol. Web Services extend these models a bit further to communicate with the Simple Object Access Protocol (SOAP) and Extensible Markup Language (XML) to eradicate the object-model-specific protocol barrier (see Figure 1). Web Services basically uses Hypertext Transfer Protocol (HTTP) and SOAP to make business data available on the Web. It exposes the business objects (COM objects, Java Beans, etc.) to SOAP calls over HTTP and executes remote function calls. The Web Service consumers are able to invoke method calls on remote objects by using SOAP and HTTP over the Web. How is the user at Location A aware of the semantics of the Web Service at Location B? This question is answered by conforming to a common standard. Service Description Language (SDL), SOAP Contract Language (SCL) and Network Accessible Specification Language (NASSL) are some XML-like languages built for this purpose. However, IBM and Microsoft recently agreed on the Web Service Description Language (WSDL) as the Web Service standard. The structure of the Web Service components is exposed using this Web Service Description Language. WSDL 1.1 is a XML document describing the attributes and interfaces of the Web Service. The new specification is available at msdn.microsoft.com/xml/general/wsdl.asp.
Figure 1. SOAP calls are remote function calls that invoke method executions on Web Service components at Location B. The output is rendered as XML and passed back to the user at Location A.
The task ahead
The best way to learn about Web Services is to create one. We all are familiar with stock quote services. The NASDAQ, Dow Jones, and Australian Stock Exchange are famous examples. All of them provide an interface to enter a company code and receive the latest stock price. We will try to replicate the same functionality. The input parameters for our securities Web service will be a company code. The Web service will extract the price feed by executing middle-tier business logic functions. The business logic functions are kept to a bare minimum to concentrate on the Web service features.
Tools to create a Web Service
The core software component to implement this application will be MS .NET Framework SDK, which is currently in beta. You can download a version from Microsoft. I used Windows 2000 Advance Server on a Pentium III with 300 MB of RAM. The preferred Integration Development Environment (IDE) to create Web Services is Visual Studio .NET. However, you can easily use any text editor (WordPad, Notepad, Visual Studio 6.0) to create a Web Service file. I assume you are familiar with the following concepts:
Creating a Web Service
We are going to use C# to create a Web Service called "SecurityWebService." A Web Service file will have an .ASMX file extension. (as opposed to an .ASPX file extension of a ASP.NET file). The first line of the file will look like Dot-net Web Services are intelligent enough to cast basic data types. Therefore, if we return "int," "float," or "string" data types, it can convert them to standard XML output. Unfortunately, in most cases we need get a collection of data regarding a single entity. Let's take an example. Our SecurityWebService stock quotes service requires the user to enter a company code, and it will deliver the full company name and the current stock price. Therefore, we have three pieces of information for a single company: We can use the business logic in this function to get the newest stock price quote. For the purpose of this article I have added some text to the company code to create the company name. The price value is generated using a random number generator. We may save this file as "SampleService.asmx" under an Internet Information Service (IIS)-controlled directory. I have saved it under a virtual directory called "/work/aspx." I'll bring it up on a Web browser. This is a Web page rendered by the .NET Framework. We did not create this page. (The page is generated automatically by the system. I did not write any code to render it on the browser. This graphic is a by-product of the previous code.) This ready-to-use functionality is quite adequate for a simple Web Service. The presentation of this page can be changed very easily by using ASP.NET pagelets and config.web files. A very good example can be found at http://www.ibuyspy.com/store/InstantOrder.asmx. Notice a link to "SDL Contract." (Even if we are using WSDL, .NET Beta still refers to SDL. Hopefully this will be rectified in the next version). This is the description of the Web Service to create a proxy object. (I will explain this in the next article.) This basically gives an overview of the Web Service and it's public interface. If you look closely, you will only see the "Web-only" methods being illustrated. All the private functions and attributes are not described in the SDL contract. The SDL contract for the SecurityWebService can be found in Appendix A.
This line will instruct the compiler to run on Web Service mode and the name of the C# class. We also need to access the Web Service namespace. It is also a good practice to add a reference to the System namespace. <%@ WebService Language="C#" class="SecurityWebService" %>
The SecurityWebService class should inherit the functionality of the Web Services class. Therefore, we put the following line of code: using System;
using System.Web.Services;
Now we can use our object-oriented programming skills to build a class. C# classes are very similar to C++ or Java classes. It will be a walk in the park to create a C# class for anyone with either language-coding skills. public class SecurityWebService : WebService
We need to extract all this data when we are referring to a single stock quote. There are several ways of doing this. The best way could be to bundle them in an enumerated data type. We can use "structs" in C# to do this, which is very similar to C++ structs.
Now we have all the building blocks to create our Web Service. Therefore, our code will look like. public struct SecurityInfo
{
public string Code;
public string CompanyName;
public double Price;
}
Remember, this Web Service can be accessed through HTTP for any use. We may be referring to sensitive business data in the code and wouldn't want it to fall into the wrong hands. The solution is to protect the business logic function and only have access to the presentation functions. This is achieved by using the keyword "[Web Method]" in C#. Let's look at the function headers of our code.
<%@ WebService Language="C#" class="SecurityWebService" %>
using System;
using System.Web.Services;
public struct SecurityInfo
{
public string Code;
public string CompanyName;
public double Price;
}
public class SecurityWebService : WebService
{
private SecurityInfo Security;
public SecurityWebService()
{
Security.Code = "";
Security.CompanyName = "";
Security.Price = 0;
}
private void AssignValues(string Code)
{
// This is where you use your business components.
// Method calls on Business components are used to populate the data.
// For demonstration purposes, I will add a string to the Code and
// use a random number generator to create the price feed.
Security.Code = Code;
Security.CompanyName = Code + " Pty Ltd";
Random RandomNumber = new System.Random();
Security.Price = double.Parse(new System.Random(RandomNumber.Next(1,10)).NextDouble().ToString("##.##"));
}
[WebMethod(Description="This method call will get the company name and the price for a given security code.",EnableSession=false)]
public SecurityInfo GetSecurityInfo(string Code)
{
AssignValues(Code);
SecurityInfo SecurityDetails = new SecurityInfo();
SecurityDetails.Code = Security.Code;
SecurityDetails.CompanyName = Security.CompanyName;
SecurityDetails.Price = Security.Price;
return SecurityDetails;
}
}
This function is exposed to the public. The "description" tag can be used to describe the Web Service functionality. Since we will not be storing any session data, we will disable the session state. [WebMethod(Description="This......",EnableSession=false)]
public SecurityInfo GetSecurityInfo(string Code)
This is a business logic function that should not be publicly available. We do not want our sensitive business information publicly available on the Web. (Note:- Even if you change the "private" keyword to "public," it will still not be publicly available. You guessed it, the keyword "[Web Method]" is not used.) private void AssignValues(string Code)
How do we use a Web Service?
Now we can use this Web Service. Let's enter some values to get a bogus price feed. By clicking the Invoke button a new window will appear with the following XML document This is how the Web Service releases information. We need to write clients to extract the information from the XML document. Theses clients could be You can also call the Web Service directly using the HTTP GET method. In this case we will not be going through the above Web page and clicking the Invoke button. The syntax for directly calling the Web Service using HTTP GET is http://server/webServiceName.asmx/functionName?parameter=parameterValue Therefore, the call for our Web Service will be http://localhost/work/aspx/SampleService.asmx/GetSecurityInfo?Code=IBM This will produce the same result as clicking the Invoke button. Now we know how to create a Web Service and use it. But the work is half done. How will our clients find our Web Service? Is there any way to search for our Web Service on the Internet? Is there a Web crawler or a Yahoo search engine for Web Services? In order to answer these questions we need to create a "discovery" file for our Web Service.
I will explain this process in the next article.
Creating a Discovery file
Web Service discovery is the process of locating and interrogating Web Service descriptions, which is a preliminary step for accessing a Web Service. It is through the discovery process that Web Service clients learn that a Web Service exists, what its capabilities are, and how to properly interact with it. Discovery file is a XML document with a .DISCO extension. It is not compulsory to create a discovery file for each Web Service. Here is a sample discovery file for our securities Web Service. There have been a lot of Web Services written by developers. www.xmethods.com is one of the sites that has an index of Web Services. Some developers are building WSDL search engines to find Web Services on the Web.
We can name this file "SampleService.disco" and save it to the same directory as the Web Service. If we are creating any other Web Services under the "/work/aspx" directory, it is wise to enable "dynamic discovery." Dynamic discovery will scan for all the *.DISCO files in all the subdirectories of "/work/aspx" automatically. <?xml version="1.0" ?>
<disco:discovery xmlns:disco="http://schemas.xmlsoap.org/disco/">
<scl:contractRef ref="http://localhost/work/aspx/SampleService.asmx?SDL"/>
</disco:discovery>
An example of an active discovery file can be found at http://services3.xmethods.net/dotnet/default.disco. By analyzing the discovery file we can find where the Web Services reside in the system. Unfortunately both these methods require you to know the exact URL of the discovery file. If we cannot find the discovery file, we will not be able to locate the Web Services. Universal Description, Discovery, and Integration (UDDI) describes mechanisms to advertise existing Web Services. This technology is still at the infant stage. UDDI is an open, Internet-based specification designed to be the building block that will enable businesses to quickly, easily, and dynamically find and transact business with one another using their preferred applications. A reference site for UDDI is http://uddi.microsoft.com. <?xml version="1.0" ?>
<dynamicDiscovery xmlns="urn:schemas-dynamicdiscovery:disco.2000-03-17">
</dynamicDiscovery>
Deploying a Web Service
Deploying the Web Services from development to staging or production is very simple. Similar to ASP.NET applications, just copy the .ASMX file and the .DISCO files to the appropriate directories, and you are in business. The future of the Web Services The future looks bright for the Web Service technology. Microsoft is not alone in the race for Web Service technology. Sun and IBM are very interested. There are SOAP toolkits available for Apache and Java Web servers. I believe Web Services needs a bit of work, especially the Web Service discovery process. It is still very primitive. On a positive note, Web Services have the potential to introduce new concepts to the Web. One I refer to as "pay per view" architecture. Similar to pay-TV, we can build Web sites that can generate revenue for each request a user sends (as opposed to a flat, monthly subscription). In order to get some data, we can sometimes pay a small fee. Commercially this could be handy for a lot of people.
Examples
On a very optimistic note, Web Services can be described as the "plug and play" building blocks of enterprise Business to Business (B2B) Web solutions. Appendix A
And the list goes on ...
<?xml version="1.0" ?>
<serviceDescription xmlns:s0="http://tempuri.org/" name="SecurityWebService" targetNamespace="http://tempuri.org/"
xmlns="urn:schemas-xmlsoap-org:sdl.2000-01-25">
<soap xmlns="urn:schemas-xmlsoap-org:soap-sdl-2000-01-25">
<service>
<addresses>
<address uri="http://localhost/work/aspx/SampleService.asmx" />
</addresses>
<requestResponse name="GetSecurityInfo" soapAction="http://tempuri.org/GetSecurityInfo">
<request ref="s0:GetSecurityInfo" />
<response ref="s0:GetSecurityInfoResult" />
<info>This method call will get the company name and the price for a given security code.</info>
</requestResponse>
</service>
</soap>
<httppost xmlns="urn:schemas-xmlsoap-org:post-sdl-2000-01-25">
<service>
<requestResponse name="GetSecurityInfo" href="http://localhost/work/aspx/SampleService.asmx/GetSecurityInfo">
<request>
<form>
<input name="Code" />
</form>
</request>
<response>
<mimeXml ref="s0:SecurityInfo" />
</response>
<info>This method call will get the company name and the price for a given security code.</info>
</requestResponse>
</service>
</httppost>
<httpget xmlns="urn:schemas-xmlsoap-org:get-sdl-2000-01-25">
<service>
<requestResponse name="GetSecurityInfo" href="http://localhost/work/aspx/SampleService.asmx/GetSecurityInfo">
<request>
<param name="Code" />
</request>
<response>
<mimeXml ref="s0:SecurityInfo" />
</response>
<info>This method call will get the company name and the price for a given security code.</info>
</requestResponse>
</service>
</httpget>
<schema targetNamespace="http://tempuri.org/" attributeFormDefault="qualified"
elementFormDefault="qualified" xmlns="http://www.w3.org/1999/XMLSchema">
<element name="GetSecurityInfo">
<complexType>
<all>
<element name="Code" xmlns:q1="http://www.w3.org/1999/XMLSchema" type="q1:string" nullable="true" />
</all>
</complexType>
</element>
<element name="GetSecurityInfoResult">
<complexType>
<all>
<element name="result" type="s0:SecurityInfo" />
</all>
</complexType>
</element>
<complexType name="SecurityInfo">
<all>
<element name="Code" xmlns:q2="http://www.w3.org/1999/XMLSchema" type="q2:string" nullable="true" />
<element name="CompanyName" xmlns:q3="http://www.w3.org/1999/XMLSchema" type="q3:string" nullable="true" />
<element name="Price" xmlns:q4="http://www.w3.org/1999/XMLSchema" type="q4:double" />
</all>
</complexType>
<element name="SecurityInfo" type="s0:SecurityInfo" />
</schema>
</serviceDescription>
About the Author
Chris Peiris is a systems architect for IT & E-Commerce in Melbourne, Australia. He has been designing and developing MS Web solutions since 1995. His expertise lies in developing scalable, high-performance Web solutions for financial institutions and media groups. He also teaches at Monash University in Caulfield, Australia. His core skills are C++, Java, .NET, DNA, MTS, Site Server, Data Warehousing, WAP, and SQL Server. Hobbies include cricket, teaching, and reading books. Chris has a Bachelor of Computing, Bachelor of Business (Accounting), and Masters of Information Management Systems. He can be reached at chris_peiris@yahoo.com.
3/19/09
Save binary in MySQL by PHP
For TEXT fields (max 65535 bytes), LONGTEXT fields (max 4GBytes) you must convert to base64 in PHP
$binary_data = file_get_contents($file);
$string_data = base64_encode($binary_data
and save the contents to the column
$sql = "
For BLOB fields (MAx 65535 bytes) or LONGBLOB (Max 4 GB) just put the contents directly to the SQL
$sql ="INSERT INTO table (text_field) VALUES('".$binary_data ."')";
Have some issues about put binary content in a
Its better don't use mysal_query function. If you use some Abstraction Layer Like PDO or ADODB, it will escape correctly the content to prevent this kind of trouble.
NOTE FROM the MySQL manual: The maximum size of a BLOB or TEXT object is determined by its type, but the largest value you actually can transmit between the client and server is determined by the amount of available memory and the size of the communications buffers. You can change the message buffer size by changing the value of the max_allowed_packet variable, but you must do so for both the server and your client program
3/18/09
ghi ra word file dùng PHP header
header("Content-Disposition: attachment; filename=\"laporan10.doc\"");
header("Content-Type: application/vnd.ms-word");
header("Pragma: no-cache");
header("Expires: 0");
echo '<table cellpadding="0" cellspacing="0" border="1">';
echo '<tr> <th><b>User-ID</b> </th> <th><b>Name</b></th> <th><b>Wohnort</b></th></tr>';
echo '<tr> <td>243</td> <td>Homer Simpson</td> <td><font color ="red">Springfield</font></td></tr>';
echo '<tr> <td>265</td> <td>Fred Feuerstein</td> <td><i>Felsental</i></td></tr>';
echo '</table>';
?>
3/17/09
FPDF -- good lib
What is FPDF?
FPDF is a PHP class which allows to generate PDF files with pure PHP, that is to say without using the PDFlib library. F from FPDF stands for Free: you may use it for any kind of usage and modify it to suit your needs.
FPDF has other advantages: high level functions. Here is a list of its main features:
- Choice of measure unit, page format and margins
- Page header and footer management
- Automatic page break
- Automatic line break and text justification
- Image support (JPEG, PNG and GIF)
- Colors
- Links
- TrueType, Type1 and encoding support
- Page compression
FPDF requires no extension (except zlib to activate compression and GD for GIF support) and works with PHP4 and PHP5.
Minimal example
Let's start with the classic example:
<?php
require('fpdf.php');
$pdf=new FPDF();
$pdf->AddPage();
$pdf->SetFont('Arial','B',16);
$pdf->Cell(40,10,'Hello World!');
$pdf->Output();
?>
3/12/09
Những thứ có học cũng như không
Verbs that are normally followed by the gerund form:-
acknowledge | admit | adore | anticipate | appreciate | avoid | celebrate | confess | contemplate
delay | deny | describe | detest | discuss | dislike | dread | endure | enjoy
fancy | finish | imagine | involve | keep | justify | mention | mind | miss | omit | postpone | practise
quit | recall | recommend | regret | report | resent | resume | risk | suggest | tolerate | understand
For example:
- I adore reading your books.
- They anticipated winning the election.
- I detest going to discos.
- We postponed making any decision in the meeting.
- I quit smoking.
- Do you recall seeing someone like that?
Verbs which are normally followed by the infinitive form:-
afford | agree | appear | arrange | ask | attempt | care | choose | claim | come | consent
dare | decide | demand | deserve | determine | elect | endeavour | expect | fail | get | guarentee
hate | help | hesitate | hope | hurry | incline | intend | learn | long | manage | mean | need
offer | plan | prepare | pretend | promise | refuse | resolve | say | seem | tend | threaten | want | wish
For example:
- I can't afford to go to the pub.
- He agreed to practise more.
- You should learn to express yourself.
- They managed to fix the problem.
Verbs which can be followed by the gerund or infinitive form:-
Some verbs can be followed by the gerund or infintive
With no change in meaning
begin | continue | hate | like | love | neglect | prefer | start | try
For example:-
- He began to learn English when he was eight.
- He began learning English when he was eight.
- I hate to leave.
- I hate leaving.
!Note - We often use the gerund when we speak about things in general, and the infinitive for particular situations.
With a change in meaning
forget | remember | stop
For example:-
- I forgot to feed the cat. (The cat is hungry - he has not been fed)
- I forgot feeding the cat. (The cat is ok - I fed him and then forgot about it)
3/11/09
DATE TIME in JAVA
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.Date;
public class date_time {
public static void main ( String [ ] args ) {
try
{
// String to Timestamp
String st = "16/08/2007 09:04:34";
SimpleDateFormat form_sdf = new SimpleDateFormat("dd/MM/yyyy hh:mm:ss");
Date form_date = form_sdf.parse(st);
Timestamp timestamp = new Timestamp(form_date.getTime());
System.out.println(timestamp.toString());
//Timestamp to String
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
Date date = sdf.parse("2005-04-06 09:01:10");
System.out.println(date.getDate() + "/" + (int)(date.getMonth() + 1) + "/" + (int) (date.getYear() + 1900));
}catch (Exception e) {
// TODO: handle exception
System.out.print(e);
}
}
}
Làm việc với LINQ trên Visual Studio 2008
LINQ và Visual Studio 2008 IDE khiến cho việc lấy dữ liệu trở nên khá dễ dàng từ một cơ sở dữ liệu SQL Server. Visual Studio bao gồm một mục khung mẫu có tên gọi LINQ to SQL Classes mà bạn có thể thêm vào trong dự án.
O/R Designer
LINQ và Visual Studio 2008 IDE khiến cho việc lấy dữ liệu trở nên khá dễ dàng từ một cơ sở dữ liệu SQL Server. Visual Studio bao gồm một mục khung mẫu có tên gọi LINQ to SQL Classes mà bạn có thể thêm vào trong dự án. Một tài nguyên dbml được tạo ra khi bạn thêm vào kiểu mục này với một tên mặc định (mà bạn có thể thay đổi) của DataClasses1.dbml.
Khi mục đó được bổ sung thì ô O/R Designer sẽ được mở ra bên trong Visual Studio. Điều này sẽ cho phép bạn kéo và thả các mục cơ sở dữ liệu (bảng, xem, thủ tục lưu trữ) tới O/R Designer. O/R Designer tạo ra tập tin dbml, tập tin này sẽ cung cấp kết nối giữa các lớp LINQ to SQL Classes và các đối tượng cơ sở dữ liệu. O/R Designer đồng thời cũng tạo ra DataContext và các lớp thực thể.
Có hai khu vực chính bên trong O/R Designer là Entities và Methods. Khu vực chính của cùng thiết kế dành cho các thực thể như Tables và Viewa, cùng với sự phân cấp và mọi thứ có liên quan. Ô Methods bao gồm các thủ tục và chức năng được lưu trữ đã được nối kết tới các phương pháp của lớp DataContext. O/R Designer hiện thời hỗ trợ SQL Server 2000, SQL Server 2005 và SQL Express Edition.
Trước đi đi sâu vào xem xét ví dụ, chúng ta hãy cùng tìm hiểu kĩ hơn về truy vấn LINQ.
Truy vấn
Bạn cần thực hiện ba bước để truy nhập dữ liệu thông qua LINQ: Thu thập nguồn dữ liệu, tạo các truy vấn và thực hiện truy vấn. Một truy vấn được dùng để định nghĩa xem dữ liệu nào đã được khôi phục từ nguồn dữ liệu. Ngoài ra, bạn có thể thao tác dữ liệu thông qua việc sắp xếp, nhóm và những thứ tương tự. Một truy vấn được lưu trữ trong một biến truy vấn và được khởi tạo với một biểu thức truy vấn.
Truy vấn có những cú pháp riêng, những cú pháp này mạnh giống với chuẩn SQL. Một biểu thức truy vấn có ba mệnh đề: from, where và select. Mệnh đề form định nghĩa nguồn dữ liệu; Mệnh đề select định nghĩa những cái quay trở lại; Và mệnh đề where (không bắt buộc) giúp bạn làm rõ hơn một tìm kiếm bao gồm chỉ các dữ liệu phù hợp với tiêu chuẩn nhất định.
Truy vấn sẽ không được thực hiện cho đến khi nó đã được truy nhập; Điều này giống như là hoãn lại quá trình thực hiện. Ví dụ tiếp theo sẽ cung cấp nhanh việc sử dụng truy vấn.
Ví dụ
Tạo một dự án trang web bao gồm một mục LINQ to SQL Classes, mục này kết nối tới cơ sở dữ liệu chuẩn Northwind trên SQL Server 2000. Một thực thể được tạo ra cho bảng Customers. O/R Designer tạo ra tập tin dbml đặt tên là DataClasses1.dbml.
Khi lớp DataContext được tạo ra trên bảng và thủ tục lưu trữ trên cơ sở dữ liệu Northwind, bạn có thể sử dụng lớp này trong đoạn mã khác. Khi sử dụng lớp DataContext được tạo, nó phải bao gồm tên với DataContext được bổ sung vào sau. Trong ví dụ này bạn phải sử dụng tên DataClasses1DataContext. (Visual Studio IntelliSense hỗ trợ đầy đủ LINQ và tất cả các lớp của nó, vì vậy bạn có thể dễ dàng tránh được lỗi cho gõ phím).
Tôi sử dụng ASP.NET WEB Form trong ví dụ sau:
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="LINQTest._Default" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>LINQ Example</title></head>
<body>
<form id="frmLINQTest" runat="server">
<div>
<asp:GridView ID="gvCustomers" runat="server"></asp:GridView>
</div></form></body></html>
Web Form có chứa một trường hợp của điều khiển GridView; Điều khiển này hiển thị dữ liệu thông qua LINQ. Đoạn mã được đặt bên trong sự kiện Page_Load, vì vậy dữ liệu sẽ được tải vào khi bạn mở trang web.
Bước đầu tiên bạn sẽ tạo ra một thể hiện của lớp DataContext. Điều này sẽ cung cấp sự truy nhập cơ sở dữ liệu, vì vậy bạn có thể truy nhập vào bảng của nó như một thuộc tính của lớp DataContext. Ngay khi lớp DataContext được tạo ra thì bạn có thể lấy dữ liệu từ đây thông qua một truy vấn.
Đoạn mã bao gồm một truy vấn kéo mọi bản ghi dữ liệu và các cột từ bảng Customers. Dữ liệu được sắp xếp bởi cột thứ hai và truy vấn được thực hiện khi nó tác động lên điều khiển GridView trên trang.
protected void Page_Load(object sender, EventArgs e) {
DataClasses1DataContext db = new DataClasses1DataContext();
var customers = from p in db.Customers
orderby 1
select p;
gvCustomers.DataSource = customers;
gvCustomers.DataBind();
}
Đây là đoạn mã tương ứng trên Visual Basic:
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Dim db As DataClasses1DataContext = New DataClasses1DataContext()
Dim customers As Object
customers = From p In db.Customers Order By 1 Select p
gvCustomers.DataSource = customers
gvCustomers.DataBind()
End Sub
Khi tải trang web, mọi dữ liệu từ bảng Customers sẽ được hiển thị trên điều khiển GridView.
Như trong ví dụ thì bạn có thể dễ dàng gọi thủ tục lưu trữ trên SQL Server như là một phương pháp của đối tượng DataContext. Những kết quả của phương pháp này - thủ tục lưu trữ - có thể được dùng chứa một điều khiển dữ liệu tương tự như điều khiển mà trước đó sử dụng GridView, như trong đoạn mã tiếp theo sau đây:
protected void Page_Load(object sender, EventArgs e) {
DataClasses1DataContext db = new DataClasses1DataContext();
var top_customers = db.Ten_Most_Expensive_Products();
gvCustomers.DataSource = top_customers;
gvCustomers.DataBind();
}
Đây là đoạn mã tương ứng trên Visual Basic:
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Dim db As DataClasses1DataContext = New DataClasses1DataContext()
Dim customers As Object
customers = db.Ten_Most_Expensive_Products()
gvCustomers.DataSource = customers
gvCustomers.DataBind()
End Sub
Những ví dụ đơn giản này đã biểu thị cú pháp truy vấn và cách sử dụng O/R Designer như thế nào trên Visual Studio 2008. LINQ cho phép bạn thao tác cập nhật, xóa, thêm (update, delete, add) và đọc dữ liệu.
Theo Techrepublic
3/6/09
How to Install & Configure Microsoft SQL Server 2000
If you will be utilizing the Resource Manager summary database feature of Feature Release 2 and above, you will need to create a database on a SQL Server and of course, MetaFrame XP Server itself requires a Data Store and SQL Server is a prime candidate. Knowing this, I recommend utilizing the following procedures to install Microsoft SQL Server 2000.
1. Insert the Microsoft SQL Server 2000 Standard or Enterprise Edition CD and click the SQL Server 2000 Components button.
2. Click the Install Database Server button to continue.
3. Click Next
4. Click Next
5. Click Next to continue
6. Enter you name and company and click Next.
7. Click Yes to agree to the license agreement.
8. Click to select the Server and Client Tools radio button and click Next.
9. Click Next
10. Click the Browse button(s) to change the destination folder for SQL Server and its databases.
11. Click the Use a Domain User Account radio button and enter a username and password for the associated service account. Click Next when finished.
12. Click to select the Mixed Mode radio button and enter a password for the SA account. Click Next when finished.
Note: A password is required in order to keep with basic security best practices
13. Click Next.
14. Enter the appropriate Microsoft SQL Server licenses and Click Continue when finished.
15. Click Finish
You have now successfully installed Microsoft SQL Server 2000 and are ready to apply any service packs (SP3a) and create the MetaFrame XP IMA database.
4. 1. 1 How to Install Service Pack 3a for Microsoft SQL Server 2000
For security, stability and functionality reasons I recommend keeping current with the latest SQL Server service pack level. Service Pack 3a also is a requirement to prevent against the Slammer worm.
To download the latest service pack please visit: http://www.microsoft.com/sql/downloads/2000/sp3.asp
The following details how to install Service Pack 3a for Microsoft SQL Server 2000
1. Extract the contents of the download and double click on setup.bat to install Service Pack 3a.
2. Click Next to continue.
3. Click Yes to agree to the license agreement.
4. Select the instance you want to apply the service pack to and click Next.
5. Select the account that has access to update the SQL server and click Next.
6. Verify the Upgrade Microsoft Search and apply SQL Server 2000 SP3 (required) check box is checked and click Continue.
7. Click the OK button to continue.
Note: I also recommend keeping the check box enabled so any possible issues you run in to will be sent to Microsoft so they can begin to addresses their bugs.
8. Click Next to start the installation.
9. Setup reminds you to backup the databases and prompts you to click OK to continue.
10. Click Finish to complete the installation of Microsoft SQL Server Service Pack 3.
4. 1. 2 How to Change the Default Login Authentication Mode
If you installed Microsoft SQL Server 2000 using the Typical installation option or via unattended installation procedures (sqlins.iss file) then you will need to set the default SQL authentication mode. By default Windows Authentication is the default security model therefore, when you try to connect a MetaFrame XP Server to the newly created data store by using a standard SQL login like system administrator (SA), you will receive the following error message:
| Unable to connect to server SERVER_NAME: |
Note: This behavior is different from Microsoft SQL Server 7.0. In SQL Server 7.0, the default authentication mode is Mixed (Windows NT Authentication Mode and SQL Server Authentication).
To prevent this behavior you will need to change the authentication mode to Mixed.
To change the authentication mode from Windows NT Authentication Mode (only) to Mixed Mode, use the following steps:
1. Run SQL Enterprise Manager on your SQL server (Start Programs Microsoft SQL Server 2000 Server Enterprise Manager)
2. Expand a Server group and right click a server name, and then click Properties.
3. Click the Security tab and under Authentication, click the SQL Server and Windows radio button.
4. Restart SQL Server in order for the changes to take effect.
Note: For additional information, please refer to the following Microsoft support articles:
INF: How to Change the Default Login Authentication Mode to SQL While Installing SQL Server 2000 Desktop Engine by Using Windows Installer (Q285097)
http://support.microsoft.com/default.aspx?scid=kb;en-us;Q285097
INF: Windows Authentication is the Default Mode After a SQL Server 2000 Typical Installation (Q269587)
http://support.microsoft.com/search/preview.aspx?scid=kb;en-us;Q269587
4. 1. 3 How to Create the MetaFrame XP Data Store with SQL Server 2000
The following table documents how to create a data store database with Microsoft SQL Server 2000
1. Click Start click Programs click Microsoft SQL Server click Enterprise Manager).
2. In the Enterprise Managers left pane, expand the tree until you reach the folder level.
3. Right-click the Databases folder and choose New Database
4. A dialog box appears. In the Name box, enter a name and click OK.
5. Click the Data Files tab and click the Space allocated (MB) text field assoicated with the new XP Datastore database and enter the space needed for the IMA database. For more information on IMA datastore file usage please refer to the Citrix MetaFrame Advanced Concepts guide found on www.citrix.com.
6. Click the Transaction Log tab and click the Space allocated (MB) text field assocated with the new XP Datastore database and enter the space needed for the IMA database. For more information on IMA datastore file usage please refer to the Citrix MetaFrame Advanced Concepts guide found on www.citrix.com.
7. Expand the Security folder
8. Right-click Logins and choose New Login.
9. A dialog box appears with the General tab displayed. In the Name box, enter a name. Make note of the name because you will need to enter it during the MetaFrame XP installation.
In the Authentication section of the General tab, click SQL Server authentication and enter a password. Remember the password. You will also want to document the username and password you choose as you must enter it during the MetaFrame XP installation and any future installations.
In the Defaults area of the General tab, change the Database to the name you specified in Step 4.
10. Click the Database Access tab. In the Database list, select the database name specified in Step 4.
In the Database Roles list, select DB_Owner. Leave other selected roles checked.
11. Click OK. You are prompted to confirm your password. Doing so completes database creation.
Cách fix lỗi Error establishing socket
Sau mấy ngài khốn khổ với cái lỗi này,mình xin chỉ ra 1 số kinh nghiệm sau để fix cái lỗi ấy.
Điều kiện cần:
_Win server 2003 (cái này cần nhất,XP pack1 và 2 đều ko đc,đã test) hoặc server 2000 pack4
_SQL server 2000 Devlopper Edition (bản Pesonal Edition bị lỗi ko open port 1433 mặc dù đã upgrade lên Pack 4)
_Bản fix lỗi SQL pack 4 (SQL2000-KB884525-SP4-x86-ENU.exe down trên trang chủ Microsoft)
_Bản Microsoft SQL Server 2000 Driver for JDBC service pack 3 của microsoft
Chú ý:
_sau khi cài xong bản fix lỗi pack 4 for SQL các bạn nên telnet cái port 1433 xem có connect đc ko?( vào start/run/cmd rồi gõ lệnh telnet localhost 1433 nếu ko thấy gì =>>connect thành công)
_khi cài xong cái JDBC bridge bạn vào đường dẫn chứa ..../Microsoft SQL Server 2000 Driver for JDBC/lib chép 3 file msbase.jar mssqlserver.jar msutil.jar vào thư mục lib/ của tomcat và jre/lib/ của JDK 1.x
Set CLASSPATCH thì ko biết cần ko nhưng nếu có thì vẫn tốt.
Đôi điều chia xẻ .
3/5/09
cakePhp authentication example continued
In previous post I discuss the basic and general usage of cakephp authentication. In this post I am going to code and explain how to write a simple sign up application. This article will not only cover authentication but also models, forms and view etc.
So lets get started.
First of all create a table named “user” by executing the following sql query.
CREATE TABLE 'user' (
‘id’ int(11) NOT NULL auto_increment,
‘username’ varchar(30) NOT NULL,
‘password’ varchar(30) NOT NULL,
‘email’ varchar(255) NOT NULL,
‘created’ datetime NOT NULL,
‘modified’ datetime NOT NULL,
PRIMARY KEY (’id’)
)
Now create a model in app/models with name user.php and write following code in that model.
Zend Pagination example
Posted by Faheem Abbas on November 12, 2008
Paginator component is available with Zend Framework v1.6. This component wasn’t available in v1.5. I appreciate Zend for provide such a nice component for pagination. This component, like other component, is so loosely coupled that you can use it wherever you want without worrying about any other component at all.
If you have already created pages and you want to apply pagination to them, it would not be a big deal.
Pagination is three step process.
1. you will need to create template file. In template file you can specify layout of your pagination. i.e. how your first, previous, next and last etc will be displayed.
2. instantiate your pagination class in the controller and pass data source- data source can be an array, values fetched form the database etc.
3. make some change in your template file, where you are showing your records.
Lets have a simple example.
First create a template file pagination.phtml in your “/application/view/script/” folder and place the following code.
<div class=”pagination” style=”width:100%”>
<div style=”float:left;width:28%”>
</div>
<div style=”float:right;width:70%;”>
<!– First page link –>
<?php if (isset($this->previous)): ?>
<a href<?= $this->url(array('page' => $this->first)); ?>">Start</a> |
<?php else: ?>
<span class=”disabled”>Start</span> |
<?php endif; ?>
<!– Previous page link –>
<?php if (isset($this->previous)): ?>
<a href="<?= $this->url(array('page' => $this->previous)); ?>">< Previous</a> |
<?php else: ?>
<span class=”disabled”>< Previous</span> |
<?php endif; ?>
<!– Numbered page links –>
<?php foreach ($this->pagesInRange as $page): ?>
<?php if ($page != $this->current): ?>
<a href="<?= $this->url(array('page' => $page)); ?>"><?= $page; ?></a>
<?php else: ?>
<?= $page; ?>
<?php endif; ?>
<?php endforeach; ?>
<!– Next page link –>
<?php if (isset($this->next)): ?>
| <a href="<?= $this->url(array('page' => $this->next)); ?>">Next ></a> |
<?php else: ?>
| <span class=”disabled”>Next ></span> |
<?php endif; ?>
<!– Last page link –>
<?php if (isset($this->next)): ?>
<a href="<?= $this->url(array('page' => $this->last)); ?>">End</a>
<?php else: ?>
<span class=”disabled”>End</span>
<?php endif; ?>
Page <?= $this->current; ?> of <?= $this->last; ?>
</div>
</div>
The code above is self explanatory. We are creating links for the pagination.
Next add the following code in your controller.
$sql = 'SELECT * FROM table_name ';
$result = $db->fetchAll($sql);
$page=$this->_getParam(’page’,1);
$paginator = Zend_Paginator::factory($result);
$paginator->setItemCountPerPage(10));
$paginator->setCurrentPageNumber($page);
$this->view->paginator=$paginator;
In the code above we first fetch records from our database. Then instantiate our paginator by writing
$paginator = Zend_Paginator::factory($result);
And pass it results we have fatched.
We then set number of items per page and current page. On our first visit $page will have value 1.
At the end we assign this paginator to our view template.
And now in view template add the following code
foreach($this->paginator as $record)
{
echo $record[‘firstname’].’\n’;
echo $record[‘lastname’]. ‘\n’
…
…
}
<?= $this->paginationControl($this->paginator, ‘Sliding’, ‘pagination.phtml’); ?>
We are applying foreach loop to our paginator and echo our records. I assume that you have fistname, lastname columns in your table where you are fetching records form.Last line is compulsory. you need to call the paginator contorller and give it the $paginator, style of the pagination and the file name of the pagination template.