Thứ Tư, 28 tháng 1, 2009

Sử dụng Delegate trong lập trình

Bên cạnh Generic Programming (Template Programming), thì Delegate cũng là một trong advanced technique trong lập trình C#. Lần trước tôi đã giới thiệu mọi người Generic Programming, lần này tôi xin giới thiệu Delegate trong C#, trong Java chưa có kỹ thuật tương tự. Nếu biết tận dụng delegate, việc code sẽ trở nên tổng quát hơn, ngắn gọn hơn, tính tái sử dụng tăng cao, và performance giảm ko đáng kể.
Hiểu một cách đơn giản, Delegate tương tự như con trỏ hàm trong C++, nó là con trỏ hàm bởi nó có thể trỏ vào các hàm khác nhau (nếu các hàm đó có cùng giao diện), và người ta có thể gọi một hàm thông qua con trỏ hàm, bằng cách cho con trỏ hàm trỏ vào hàm đó, và call con trỏ hàm cũng tương đương việc call hàm được con trỏ hàm trỏ đến.

Khai báo delegate, chú ý delegate ngang hàng với khai báo class tương tự enum và struct, hãy khai báo delegate bên ngoài class, ex :

public delegate int Compare(int inA, int inB);

Hoặc tốt nhất là khai báo khai báo dạng template, tăng tính tái sử dụng.

public delegate int Compare<T>(T inA, T inB);
public delegate int Compare<T, E>(T inA, E inB);

public delegate T DFunc0Para<T>();
public delegate T DFunc1Para<E, T>(E x);
public delegate T DFunc2Para<E, F, T>(E x, F y);
public delegate void DProc1Para<E>(E x);
public delegate void DProc2Para<E, F>(E x, F y);

Giao diện một delegate sẽ đại diện cho các hàm mà delegate này có thể trỏ tới, gồm kiểu trả về và danh sách tham số, còn tên delegate hay tên hàm ko quan trọng.

Khai báo một biến có kiểu Delegate :

Compare<string> compare;

Thực hiện trỏ một delegate tới một hàm, ex :

compare = Compare;

Call một hàm thông qua delegate :

compare("heno", "hi");

Ví dụ đơn giản :

// ham dc khai bao de cho delegate tro toi
private int CompareFunc(string x, string y)
{
return x.CompareTo(y);
}
public void testDelegate()
{
// khai bao bien kieu Delegate
Compare<string> compare;

// thuc hien tro bien delegate den ham Compare ben tren,
// giao dien cua ham va Delegate phai tuong thich thi moi tro dc

compare = CompareFunc;

// thuc hien call delegate
int val = compare("heno", "hi");
}

Một số ví dụ sử dụng delegate :
- List.RemoveAll và List.ConvertAll : List là lớp sẵn có của C#, và giao diện của RemoveAll và ConvertAll như sau :

public int RemoveAll(Predicate<T> match);
public delegate bool Predicate<T>(T obj);

public List<TOutput> ConvertAll<TOutput>(Converter<T, TOutput> converter);
public delegate TOutput Converter<TInput, TOutput>(TInput input);

Và sau đây là ví dụ đoạn code sử dụng chúng, cho thấy cách sử dụng delegate, ví dụ sau cho thấy là ta có thể truyền một function như là tham số của function khác.

public class Test{
public void testListAndDelegate()
{
List<int> listNo = new List<int> (new int[]{1, 2, 3, 3, 4, 5, 6, 5, 3});

// thuc hien xoa cac element co gia tri 3 trong listNo
// trong do equalThree la mot function dc khai bao ben duoi
listNo.RemoveAll(equalThree);

// thuc hien chuyen listNo thanh mot danh sach List tuong ung
// trong do Convert.ToString la mot function cua C# co
// khai bao "public static string ToString(int no)"

List<string> listStr = listNo.ConvertAll<int, string>(Convert.ToString);
}
private bool equalThree(int no)
{
return (no == 3);
}
}

- Tìm kiếm sử dụng Delegate thay vì sử dụng IComparer :
Đây lại là một ví dụ sử dụng Template Delegate, dc dùng trong hàm LinearSearch, hàm này viết dưới dạng Template, nên có thể thích ứng với rất nhiều input khác nhau

public class CommonFunction{
// ham nay tra ve vi tri cua phan tu thuoc array of type tuong ung voi key of type
// trong do E va K la hai kieu bat ki
// Compare la delegate da dc khai bao ben tren
public static int linearSearch<E, K>(List list, K key, Compare<E, K> compare)
{
for (int i = 0; i < list.Count; i++) {
if (compare(list[i], key) == 0) {
return i;
}
}
return CommonConstant.UNFOUND;
}
}// end of CommonFunction
/////////////

public struct Pair{
public int no;
public string name;
public Pair(int inNo, string inName){
no = inNo;
name = inName;
}
}

public class Test{

// khai nay dc khai bao de su dung nhu la tham so
// cho ham linearSearch ben duoi
private int compareFunc (Pair x, int y)
{
return x.no.CompareTo(y);
}

public void testLinearSearch()
{
List<Pair> list = new List<Pair>();
list.Add(new Pair(1, "Mot"));
list.Add(new Pair(3, "Ba"));
list.Add(new Pair(4, "Bon"));
list.Add(new Pair(2, "Hai"));

// tiep theo, ta muon tim index cua phan tu tuong ung voi "no" = 3,
// ta chi can code nhu sau, compareFunc chinh la ham ben tren
int index = CommonFunction.linearSearch(list, 3, compareFunc);
}

}// end of Test

Chủ Nhật, 25 tháng 1, 2009

7 Element of Highly Successfull Software Projects

Successfully executing a software project, requires a clearly defined plan that all parties understand and endorse. It also requires effective teamwork and people who are willing to put their shoulder against the work everyday. Once a team is ready to execute the work project, the focus needs to be on doing the right things and having systems in place to compensate for inevitable miscommunication and human errors.

Before laying out the game plan necessary for successful project execution, though, I’d like to share a broader thought about getting things done at work: Just do it! In my experience, it’s far better to take action than to procrastinate while obsessing about making things perfect. Perfection is nearly impossible to achieve, although it’s a worthy goal and one we strive for when developing software for our customers. Rather than software, I’m referring to general business decisions about priorities. I’ve seen too many organizations virtually grind to a halt over a single issue, or the inability of top managers to make a tough decision. Don’t let this happen to you. It’s better to move and get things done than to let organizational rigor mortis set in.

Few professionals readily admit to being “process oriented,” which connotes images of anal-retentive individuals who are so busy cataloguing trees they completely miss the proverbial forest. I’d like to challenge that perception. People who can follow a carefully designed process are most likely to achieve success. This is a fact CEOs understand. When asked to name the main reason for the success of their companies, 75 percent of the CEOs leading Inc magazine’s top 500 companies said “superior execution in a mundane business.”

That’s pretty mind boggling, but it makes sense when you consider that more businesses face being reduced to a commodity due to global competition. When every corner shop can offer gourmet coffee, it’s the shop whose employees remembers customers, greets them sincerely and serves orders in record time that stands out from its competition. Taking the time to focus on the little things can add up to big profits over time.

The rest of this chapter will focus on the best process for writing software and successfully launching a major software initiative. When viewed broadly, these steps are just as valid for any type of business initiative or major project. In fact, the process I advocate has a lot in common with best practices used in building anything.

Finally, as a side note, there’s been and continues to be different approaches on how to manage projects—waterfall, agile, lean, and the list goes on. While these different approaches each have their merits, as it relates to this chapter, I’m not advocating a specific method. And, while a lot more needs to be done to make projects successful, I haven’t seen a project that lacks one of the “7” elements missing and be successful.

Projects are tough. For software, Gartner Group estimates that approximately 75 percent of software projects fail due to lack of technical consideration or poor business planning. Why is it so hard? What can be done? Here are the common elements of every project that we’ve shipped:

  1. Getting the right team
  2. Defining the problem
  3. Working effectively together
  4. Communicating frequently
  5. Working smart
  6. Constantly improving the process
  7. Understanding the end game

Miss one or two of the above, you join the majority in the 75 percent.

1. Getting the right team

The topic of human capital (recruiting, motivating, retaining, etc.) fills bookshelves at the local Barnes and Noble. And it should. Studies show that top performers out produce low performers by a factor. In software it is a factor of eight-to-ten times. I won’t try to cover this in depth but below are a few of the big rocks to get the best people:

  • Get the best work. Great talent is drawn to great work. For Generation Y, get ready. Research suggests they are as committed to the work as the firm. When the work goes bad, they go (Generation Y is the age of five to the mid-20s).
  • Take the time. I attended a class at Harvard. Several case studies had recruiting in the study. One of the firms, known for having the best-of-the-best talent, does 25-40 interviews. Yes, you read that right. When adding to your team, honor your interview process (don’t skip steps) and invest the time on the front end to ensure a tight fit between the new employees’ and your company’s values and performance.
  • People leave people. People don’t leave companies—people leave people. Pick your leaders wisely and employee retention is simple.

2. Defining the Problem

Ever heard the adage “a problem defined is half solved”? This is especially true in software. An IBM study by Felix & Watson found that well-defined objectives were the number one factor in successful projects. Expect the following in your plan:

  • Project plan. This high-level document defines the project vision and Critical Success Factors—i.e., what the project must deliver to be considered a success, and areas of responsibility.
  • A requirements document. This defines “project complete.”
  • A prototype, mock-up, or demo. Most people are visual. A visual tool is a clear way to communicate and take care of misunderstandings.
  • A Gantt chart or Sprint Plan. A Gantt chart states who, what, when and defines interdependencies. In other methodologies, like Agile, a formal Gantt chart may be replaced by a simpler “Sprint”—a list of the highest priority development items to tackle in the next 30 days.
  • A risk plan. It should define what’s likely to go wrong and what happens when it does.

Depending on the project, there may be additional documents required. For example, in software there are additional documents like a functional design specification, a logical and physical model of the problem, and test scripts to define what complete and functional means. Beginning without a clear plan is like building a house without a blueprint.

3. Working Effectively Together

Expect small teams, phased releases and frequent deliverables. An ideal project team is four to six. This size is large enough to have effective dialogue and collaborative thought, but small enough to be efficient. If the project is large, break it up into pieces tackled by teams of four-to-six people.

Working with an outside vendor introduces challenges. All are manageable. To work effectively:

  • Define clear lines of responsibility. To stop turf wars before they start, clearly define the role of vendor and communicate this with your staff.
  • Clearly state expectations. The documents shared in 2. Defining the Problem, puts everyone on the same page.
  • Choose a central point of contact. This should happen on both ends.
  • Clearly state priorities. When flushing out the functional requirements, prioritize features. When the releases are being defined, it is key to know what is a “go” vs. “no go” feature.
  • Constantly communicate (see next section for more on this important topic).

4. Communicating Early and Often

In fast-moving environments—most companies today—daily huddles can keep communication consistent and effective. Intertech uses huddles. In huddles, which take no more than 15 minutes:

  • Each team member gives an update. This streamlines communication and reduces one person having to retell their story throughout the day.
  • The daily number is shared. This is a number that measures the bottleneck or health of the project. The number changes throughout the project. For example, in software beta testing, this could be number of outstanding bugs. If you have six data consecutive points in any direction, you have a trend.
  • Each team member shares a stuck item. Sharing a stuck item brings up issues early, often and enables the slaying of monsters (problems) while they’re little.

Huddles can cascade to keep everyone on the same page. For example, if there are three project teams working on the overall project, the separate project teams have a huddle followed by a huddle of the three project leads and their superior.

It can be tempting to forgo communication tools, like huddles, when you’re in the end game and near project finish. This is when you need them most. If you’re working on a longer project, build in systems that create a frictionless environment. At Intertech, twice per year, we ask our people:

    • Name one thing we should stop doing, start doing, and continue doing.
    • Name a hassle for you, a hassle for our team, and a hassle for our customer (internal or external). A hassle is a second wasted doing something that could be avoided by making a change to how work is done.

The above help remove the “noise” that stops people from doing their work effectively.

5. Working Smart

IBM built an empire on the word “think.” Thinking is key to deploying applications on time. To get people thinking:

  • Encourage team members to constantly ask “What could be done today that would have greatest impact on the future of the project?” For example, I’ve seen expensive developers without computers because a manager was “too busy” to order them a few weeks back.
  • Keep meetings, including daily huddles, focused. Set meetings for first or last thing in the day or right before lunch. Cut off talkers. Honor time.
  • Don’t let meetings make more work. If you have the decision makers together in a huddle and a decision needs to be made, do it.
  • Remember 12-hour workdays aren’t 12-hour workdays. If projects are being completed because the modus operandi is ongoing 12-hour workdays, the real work accomplished in the day will cease to happen during the entire12 hours. People still need to eat, see their families, have friends, get their clothes cleaned, etc., and they’ll find ways to do just that even if you expect a 12-hour work day. In other words, don’t encourage an environment where “crunch time” is “business as usual”—it loses its meaning and effectiveness.
  • Remember there is no silver bullet. Success is the result of series of things consistently done well. If in the heat of the project, there’s an idea, solution, team member, or vendor that has “the fix” and it sounds too good to be true (you know what’s coming) it probably is!

6. Constantly Improving the Process

Because this isn’t the last project you’ll be delivering:

  • Be prepared to change. For example, in software, good software doesn’t die it just changes a lot (think of MS Word). Factor in ongoing maintenance and changes from the start.
  • Follow some process. Before we can improve something, we need to understand what it is. Follow a process proscribed by your vendor then make it your own and constantly improve upon it.
  • Encourage reviews. No one has the corner on good ideas. Even if you are moving fast, get buy in and check off.
  • At project end, make sure that you’ve got the completed set of documentation.
  • Do a post mortem. Don’t blame. Ask “What could be done to make it better?”

7. Understanding the End Game

The End Game, the time right before the project finishes, can be difficult. It’s manageable if you follow a few simple steps:

  • Keep teams on track. Tell them to turn off e-mail and voice mail, and stay focused. Beyond the huddles, hold off on other meetings that may be “fluff.”
  • Keep the work in a known state. With multiple people making changes to a project, ensure that the details are pulling together. For example, in software, this means building the entire application daily.
  • Everyone should ask, “Is what I’m doing going to help us complete the project?” This may mean skipping helping out with interviews, sitting through all company meetings, etc.
  • Ask, “Does the problem need to be fixed?” For example, in software when a project is nearing completion and there are small things that are not quite right, sometimes fixing the bug can introduce more bugs. Is the problem something you can live with and fix at a later time or is it critical?
  • At the end of the project, when people are verifying the work is complete (in software this is QA), this is not the time to solicit and add more to the project. It’s the time to nail the requirements and get to done.
  • If a project deliverable date needs to be changed, don’t change one bad date for another. If a revised date is set, get the team involved in setting the date, and the hit it no matter what.

Celebrate and recognize team members when the project is finished. Whether it’s formal or a beer out with the team, it matters. While there are more things we need to do to be successful in managing projects, these guidelines cover the minimum basics needed to finish on time and on schedule.

---

Trích CodeProject, một bài viết hay, có nhiều kinh nghiệm bổ ích, hi vọng trong tương lai chúng ta sẽ ko mắc phải những sai lầm cơ bản mà article này đã đề cập. Tôi đang xem xét dịch bài này sang Tiếng Việt cho anh chị em dễ đọc. Tuy nhiên, nếu đọc tiếng Anh thì version tiếng Anh có lẽ vẫn hay hơn.

Thứ Ba, 9 tháng 12, 2008

Các câu hỏi thường gặp với phần mềm Quản Lí Thuốc

1. Lỗi không kết nối với Database "SQL Server does not exist or access denied"

Lỗi này xuất hiện khi cài đặt đến bước chọn kết nỗi Database, người dùng chọn next khi chưa chọn kết nối. Để khắc phục, chỉ đơn giản là chọn đúng kết nối, click vào hộp lựa chọn "May chu ket noi" và chọn như hình sau :

Mọi lỗi xuất hiện khi cài đặt cũng như khi sử dụng, bạn có thể viết mail gửi mô tả về hòm thư quanlithuoc@gtid.com.vn, chúng tôi sẽ khắc phục sớm nhất có thể.

Xin chân thành cảm ơn

Thứ Hai, 8 tháng 12, 2008

Sử dụng Twitter để nâng cao collaboration

Lần trước họp, mình đã giới thiệu mọi người Yammer, một công cụ online giúp nâng cao thông tin giữa các thành viên trong nhóm, Yammer đã giành dc thành công nhanh chóng chỉ sau 3 tháng, đạt giải thưởng của TechCrunch. Rất tiếc Yammer ko miễn phí, nhưng ko sao, tôi mới tìm ra một cách sử dụng twitter (free :D) theo cách nhóm giống với Yammer (tuy chưa chuyên nghiệp bằng). Một cách dễ hình dung, đây là phương thức trao đổi tin tức nhóm trung bình cộng giữa YahooChat và mail group.
1. Lợi ích :
- Chia sẽ những câu nói vui.
- Sử dụng status để xả stress.
- Thông tin khó khăn, tất cả mọi người đều có thể biết mà hỗ trợ.
- Thông báo tin vui, và tất cả mọi người đều biết mà chúc mừng.
- Xóa dần cảm giác về khoảng cách vật lí khi làm việc.
- Các thông báo hoàn toàn ko làm phiền người khác như chat bởi chúng ta có thể chủ động nhận tin khi nào muốn (giống mail).
- Với sự hỗ trợ của TwitterFox, việc post và đọc message trở lên rất dễ dàng và nhanh chóng (dễ dàng và nhanh chóng như chat mà ko phải bật thêm ct mới, vì nó tích hợp vào bên trong Firefox).
- Chúng ta cũng có thể nhắn riêng cho một ai đó nhanh chóng(post nhanh như chat), và quên đi nỗi lo sợ mất tin nhắn offline như YahooChat (giống như mail :D).
- Các tin nhắn cũ ko bị mất đi, trừ khi ta xóa (giống mail).
- Cải thiện hiệu quả làm việc nhóm => rất rõ ràng.

2. Các bước cần làm để tham gia :
- Tạo một account twitter, vào trang http://twitter.com đăng kí một acc, chú ý nên chọn tên dễ nhớ, là tên mail gtid của bạn hoặc tên đầy đủ của bạn vì người khác cần biết nick của bạn thì mới gửi mess đến dc. Cách đăng kí chỉ mất 3 phút, thậm trí nó chằng thèm gửi mail activate cho bạn, đăng kí phát là dùng dc luôn :D

- Follow acc gtider (chỉ member của GTID mới có thể follow gtider, tôi sẽ kiểm soát điều này).
Vào trang http://twitter.com/gtider và follow như sau :

- Follow tất cả các Follower của gtider (các Follower của gtider đều là member của GTID).

- Cài đặt TwitterFox.
Dùng firefox mở trang https://addons.mozilla.org/en-US/firefox/addon/5081, và cài đặt.

- Cấu hình Twitterfox với account của bạn.

Khi cài đặt xọng bạn sẽ thấy logo của twitter xuất hiện bên góc dưới bên phải status bar của firefox. Chuột phải chọn Reference, vào cấu hình như sau :

chuột phải vào icon của Twitterfox, chọn Preference.

và cấu hình như sau

3. Cách sử dụng :

a. Đọc message

Click vào icon của Twitter trên firefox, và đọc tin gồm message chung, message đến bạn dùng @ và message gửi riêng cho bạn.

b. Post message
- Post status, funny message, link hay ... : click vào icon của Twitter trên Firefox cứ việc đánh như bình thường vào phần để post của TwitteFox. Khi này mọi follower của bạn (gồm tất các các member của GTID) đều có thể đọc dc message này.

- Thông báo message đến cho ai đó nhưng các người bạn chung của bạn và bạn của bạn đều biết (như kiểu chúng ta nói chuyện, thì những người ngồi cạnh cũng có thể nghe thấy).
Ví dụ mình muốn gửi message đến quyettn, ta viết như sau : @quyettn nội dung message. Khi này, anh Ha cũng có thể biết nội dung tin nhắn này, vì anh Ha cũng follow tôi và quyettn.

- Thông báo message chỉ trong nội bộ GTID, tức là chỉ thành viên của GTID nhận dc thôi.
Viết như sau : @gtider nội dung message.
- Gửi message đến riêng ai đó, và chỉ người đó nhận dc mà thôi.
Viết như sau : d quyettn nội dung tin nhắn riêng.

c. Reply message

Go Together In Development

Thứ Bảy, 29 tháng 11, 2008

Đoạn mã chống copy bài viết và hình ảnh

<script language="JavaScript1.2">
var message="Text Here";
function click(e) {
if (document.all) {
if (event.button==2||event.button==3) {
alert(message);
return false;
}
} else {
if (e.button==2||e.button==4) {
e.preventDefault();
e.stopPropagation();
alert(message);
return false;
}
}
}
if (document.all) { // for IE
document.onmousedown=click;
} else { // for FF
document.onclick=click;
}
</script>

<script type="text/javascript">
function ehan( evnt )
{
if( evnt.which == 3 )
{
alert( "Text Here" );
return false;
}
return true;
}
function ocmh()
{
alert( "Text Here" );
return false;
}
document.oncontextmenu = ocmh;
document.captureEvents( Event.MOUSEDOWN );
if( document.layers ) document.onmousedown = ehan;
</script>

<script language="JavaScript">
if (window!=top){top.location.href=location.href;}
</script>

<script type="text/javascript">
<!--
var omitformtags=["input", "textarea", "select"]
omitformtags=omitformtags.join("|")
function disableselect(e){
if (omitformtags.indexOf(e.target.tagName.toLowerCase())==-1)
return false
}
function reEnable(){
return true
}
if (typeof document.onselectstart!="undefined")
document.onselectstart=new Function ("return false")
else{
document.onmousedown=disableselect
document.onmouseup=reEnable
}
-->
</script>

<script language="JavaScript">
if (window!=top){top.location.href=location.href;}
</script>

<script type="text/javascript">
<!--
var omitformtags=["input", "textarea", "select"]
omitformtags=omitformtags.join("|")
function disableselect(e){
if (omitformtags.indexOf(e.target.tagName.toLowerCase())==-1)
return false
}
function reEnable(){
return true
}
if (typeof document.onselectstart!="undefined")
document.onselectstart=new Function ("return false")
else{
document.onmousedown=disableselect
document.onmouseup=reEnable
}
-->
</script>

Đặc điểm của một số thuộc tính CSS - Sự khác nhau của IE và chuẩn chung

Các vấn đề sẽ đề cập
1. IE and the box model
2. IE versions and Doctype modes

IE and the box model

Cho dù bạn có thích hoặc căm ghét, Internet Explorer của Microsoft vẫn là một trình duyệt chính đựơc sử dụng hiện nay. Điều đó có nghĩa là vài điểm bạn cần xem xét khi thiết kế để khắc phục một vài điểm chưa hợp lý về CSS.
Một ví dụ dơn giản là một số phiên bản của IE thể hiện các hộp (box model) một cách khác biệt so với các trình duyệt chuẩn. Và các file CSS của bạn nhìn trên IE sẽ khác so với các trình duyệt còn lại như: firefox, opera.
Với một hộp vuông có chiều rộng 200px và được bạn gán thuộc tính "padding:20px; border:20px;" thì chiều rộng chuẩn của nó sẽ được tính như sau
Chiều rộng thể hiện
chiều rộng chuẩn (200px) + padding (20px+20px) + borders (20px+20px) = 280px.
Thế nhưng một vài phiên bản của IE sẽ tính ra chiều rộng bằng công thức: content, padding and borders together = 200px.
Nguồn:http://css.maxdesign.com.au/listamatic/about-boxmodel.htm

Chủ Nhật, 23 tháng 11, 2008

Sử dụng Connection Strings với CSDL SQL Server 2005

SQL Native Client ODBC Driver:

Standard security:
Driver={SQL Native Client};Server=myServerAddress;Database=myDataBase;Uid=myUsername;Pwd=myPassword;

Trusted Connection:
Driver={SQL Native Client};Server=myServerAddress;Database=myDataBase;Trusted_Connection=yes;

Ghi chú: "Integrated Security=SSPI" tương tự như "Trusted_Connection=yes"

Connecting to an SQL Server instance:
Driver={SQL Native Client};Server=myServerName\theInstanceName;Database=myDataBase;Trusted_Connection=yes;

Prompt for username and password:

oConn.Properties("Prompt") = adPromptAlways
Driver={SQL Native Client};Server=myServerAddress;Database=myDataBase;
Enabling MARS (multiple active result sets):
Driver={SQL Native Client};Server=myServerAddress;Database=myDataBase;Trusted_Connection=yes;MARS_Connection=yes;

Ghi chú:

"MultipleActiveResultSets=true" tương tự như "MARS_Connection=yes"

Sử dụng ADO.NET 2.0 cho MARS. MARS không hỗ trợ ADO.NET 1.0 và ADO.NET 1.1.

Encrypt data sent over network:
Driver={SQL Native Client};Server=myServerAddress;Database=myDataBase;Trusted_Connection=yes;Encrypt=yes;

Attach a database file on connect to a local SQL Server Express instance:
Driver={SQL Native Client};Server=.\SQLExpress;AttachDbFilename=c:\asd\qwe\mydbfile.mdf; Database=dbname;Trusted_Connection=Yes;

Attach a database file, located in the data directory, on connect to a local SQL Server Express instance:
Driver={SQL Native Client};Server=.\SQLExpress;AttachDbFilename=|DataDirectory|mydbfile.mdf; Database=dbname;Trusted_Connection=Yes;

Database mirroring:
Data Source=myServerAddress;Failover Partner=myMirrorServer;Initial Catalog=myDataBase;Integrated Security=True;

SQL Native Client OLE DB Provider:

Standard security:
Provider=SQLNCLI;Server=myServerAddress;Database=myDataBase;Uid=myUsername;Pwd=myPassword;

Trusted connection:
Provider=SQLNCLI;Server=myServerAddress;Database=myDataBase;Trusted_Connection=yes;

Connecting to an SQL Server instance:
Provider=SQLNCLI;Server=myServerName\theInstanceName;Database=myDataBase;Trusted_Connection=yes;

Prompt for username and password:
oConn.Properties("Prompt") = adPromptAlways
oConn.Open "Provider=SQLNCLI;Server=myServerAddress;DataBase=myDataBase;

Enabling MARS (multiple active result sets):
Provider=SQLNCLI;Server=myServerAddress;Database=myDataBase;Trusted_Connection=yes;MarsConn=yes;

Ghi chú:

"MultipleActiveResultSets=true" tương tự như "MARS_Connection=yes"

Sử dụng ADO.NET 2.0 cho MARS. MARS không hỗ trợ ADO.NET 1.0 và ADO.NET 1.1.

Encrypt data sent over network:
Provider=SQLNCLI;Server=myServerAddress;Database=myDataBase;Trusted_Connection=yes;Encrypt=yes;

Attach a database file on connect to a local SQL Server Express instance:
Provider=SQLNCLI;Server=.\SQLExpress;AttachDbFilename=c:\asd\qwe\mydbfile.mdf; Database=dbname;Trusted_Connection=Yes;

Attach a database file, located in the data directory, on connect to a local SQL Server Express instance:
Provider=SQLNCLI;Server=.\SQLExpress;AttachDbFilename=|DataDirectory|mydbfile.mdf; Database=dbname;Trusted_Connection=Yes;

Database mirroring:
Data Source=myServerAddress;Failover Partner=myMirrorServer;Initial Catalog=myDataBase;Integrated Security=True;

SqlConnection (.NET):

Standard Security:
Data Source=myServerAddress;Initial Catalog=myDataBase;User Id=myUsername;Password=myPassword;

hoặc:

Server=myServerAddress;Database=myDataBase;User ID=myUsername;Password=myPassword;Trusted_Connection=False;

Trusted Connection:
Data Source=myServerAddress;Initial Catalog=myDataBase;Integrated Security=SSPI;

hoặc:

Server=myServerAddress;Database=myDataBase;Trusted_Connection=True;

Connecting to an SQL Server instance:
Server=myServerName\theInstanceName;Database=myDataBase;Trusted_Connection=True;

Trusted Connection from a CE device:
Data Source=myServerAddress;Initial Catalog=myDataBase;Integrated Security=SSPI;User ID=myDomain\myUsername;Password=myPassword;

Connect via an IP address:
Data Source=190.190.200.100,1433;Network Library=DBMSSOCN;Initial Catalog=myDataBase;User ID=myUsername;Password=myPassword;

Ghi chú: 1433 là cổng mặc định của SQL Server.

Enabling MARS (multiple active result sets):
Server=myServerAddress;Database=myDataBase;Trusted_Connection=True;MultipleActiveResultSets=true;

Ghi chú:

"MultipleActiveResultSets=true" tương tự như "MARS_Connection=yes"

Sử dụng ADO.NET 2.0 cho MARS. MARS không hỗ trợ ADO.NET 1.0 và ADO.NET 1.1.

Attach a database file on connect to a local SQL Server Express instance:
Server=.\SQLExpress;AttachDbFilename=c:\asd\qwe\mydbfile.mdf;Database=dbname;Trusted_Connection=Yes;

Attach a database file, located in the data directory, on connect to a local SQL Server Express instance:
Server=.\SQLExpress;AttachDbFilename=|DataDirectory|mydbfile.mdf; Database=dbname;Trusted_Connection=Yes;

Using an User Instance on a local SQL Server Express instance:
Data Source=.\SQLExpress;Integrated Security=true;AttachDbFilename=|DataDirectory|\mydb.mdf;User Instance=true;

Database mirroring:
Data Source=myServerAddress;Failover Partner=myMirrorServer;Initial Catalog=myDataBase;Integrated Security=True;

Asynchronous processing:
erver=myServerAddress;Database=myDataBase;Integrated Security=True;Asynchronous Processing=True;

SQL Server 2005 special:
C#
using(SqlConnection connection = new SqlConnection("context connection=true"))
{
connection.Open();
// Use the connection
}

VB.Net
Using connection as new SqlConnection("context connection=true")
connection.Open()
' Use the connection
End Using

Link tham khảo