Wednesday, April 6, 2011

The GridView in ASP.NET seems to give the programmer few configurable options at first, but when you start using the DataBound events, then it starts to become surprisingly versatile.

Manipulate the GridView control in ASP.NET to display your data the right way

The GridView in ASP.NET is a very powerful control that provides an easy interface to add, update, delete, and display data. The GridView also lets you perform other tasks very easily, such as paging and sorting your data, but not everything is as straightforward as it seems. Most of the time, we would display the data exactly as it comes out of our datasources, but sometimes we may need to manipulate the text, cells, and rows to fit our needs. In this article I will explain how to use the events and properties of the GridView to allow us to customise the way the data appears.

Taking advantage of the GridView events and properties

GridView is great for very simple tables, but the real world is not always as straightforward as we would like it to be. Sometimes we need to specify the format of the data, and the way it is rendered in the table, more exactly. Many people will tell you to use other type of controls such as the DataList for this, because it gives the user more choices in the way that the grid is rendered. Unfortunately the DataList, unlike the Gridview, does not have all the features such as paging and sorting that are commonly required. So if you still need or want to use the GridView, but also need more control on the way that the table is rendered, you can use the GridView events and properties.

The most used event of the GridView is the RowDataBound. This event is fired every time a row is bound to data. What does this mean to us, the developers? This means that, whenever this event is fired, we will have access to the current row and all of its data, so we can manipulate the table, row, cells, and or controls of the table accordingly. I will come back to this later.

Other important events are the DataBound and the Load event. The Load event fires when the GridView is loaded and has not been attached to any data yet. In this event the user can set properties such as the color of the border, themes, or any other rendering options that are not dependent on the data itself. The DataBound is similar to the RowDataBound in that both are fired after a bound event has happened. The difference is that DataBound is fired once after the entire Grid has been bound; while the RowDataBound is fired every time a row is bound, meaning it will almost always be fired more than once. So you can use the DataBound to manipulate the table based on the data contained in it.

image


FIGURE 4: Events of the GridView

The RowDataBound is your friend.

Let’s look at the parameters needed for the RowDataBound event. Like every .NET event it has two parameters: sender of type object and e of type GridViewRowEventArgs. The sender parameter contains a reference of the GridView that is firing the event and e contains a very important property named Row which references the row that is being bound. The Row property is very important. Table 1 contains the most used properties of the GridViewRow taken from the MSDN documentation.

Property Description
Attributes Gets the collection of arbitrary attributes (for rendering only) that do not correspond to properties on the control.(inherited from WebControl)
Cells Gets a collection of TableCell objects that represent the cells of a row in a Table control.(inherited from TableRow)
DataItem Gets the underlying data object to which the GridViewRow object is bound.
RowIndex Gets the index of the GridViewRow object in the Rows collection of a GridView control.
RowType Gets the row type of the GridViewRow object.

Table 1: Most used properties of the Row

Imagine that your boss asks you to create a table of all the products with their price and Units in Stock and Units on Order. So you would simply create a GridView with a SqlDataSource with the following query: select ProductName, UnitPrice, UnitsInStock, UnitsOnOrder from Products. This is a very easy and straightforward task. Figure 5 displays the end result.

image

FIGURE 5: End result of the GridView displaying the products.

Your boss sees the page and says he would love to be able to quickly distinguish all the products that need to be reordered, and also the products that have already been reordered. So you could then simply tell him that not only will you display the numbers as they are, but also display the products that need to be reordered in red and the ones that have been reordered in blue. Your boss loves the idea, but you have no clue how to do that with a GridView. The way to do this is to use the RowDataBound event. The code on Figure 6 shows how to accomplish this simple, but not intuitive task.


protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)

{

if (e.Row.RowType == DataControlRowType.DataRow)

{

//We're only interested in Rows that contain data

//get a reference to the data used to databound the row
DataRowView drv = (DataRowView)e.Row.DataItem;
if (Convert.ToInt32(drv["UnitsInStock"]) == 0)

{

//The current product has 0 items in stock
e.Row.Font.Bold = true; //Make the font bold
e.Row.ForeColor = System.Drawing.Color.Red; //Set the text color red
if (Convert.ToInt32(drv["UnitsOnOrder"]) > 0)

{

//The current out of stock item has already been ordered
//Make it blue
e.Row.ForeColor = System.Drawing.Color.Blue;

}

}

}

}

FIGURE 6: Code for setting fore color of each row.

The GridView fires the RowDataBound event on every row, including the header and footer. Therefore we need to make sure, when the event is fired, that it is fired on a DataRow. If it is, then we get a reference to the DataRowView, which represents the row of the datasource to which the row of the GridView was tied to. In our case this represents a row from the database result set. Please note that the e.Row.DataItem returns an object. The reason for that is that you can bind a GridView to any item that implements the ICollection interface: DataTable, DataSet, List, Array, etc. The type of the DataItem will vary with the DataSource used. Once we get a reference to the DataRowView, we then check to see if that Product is out of stock or if it is in the process of restocking and set the ForeColor of the row equal to the correct color. Figure 7 shows the end result.

image

Figure 7: The new GridView with the color change

Your boss is now in a good mood, and knows that you can do a lot for him: He therefore wants a new report. This new report will include all the products by Category. He does not want to see the category repeated every time. Your data comes in the format displayed in Figure 8.

image

FIGURE 8: Data from datasource

The idea is the same as in the previous example. We need to implement the RowDataBound event and check when the CategoryName changes. If it does, then we will display it, if it does not, then we hide it. But to make it more complicated, not only are we going to hide it, but we are going merge the rows together. Figure 9 displays the code needed to make this happened and Figure 10 displays the end result.


string previousCat = "";

int firstRow = -1;

protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)

{

if (e.Row.RowType == DataControlRowType.DataRow)

{

//We're only interested in Rows that contain data
//get a reference to the data used to databound the row
DataRowView drv = ((DataRowView)e.Row.DataItem);



if (previousCat == drv["CategoryName"].ToString())

{

//If it's the same category as the previous one
//Increment the rowspan
if (GridView1.Rows[firstRow].Cells[0].RowSpan == 0)

GridView1.Rows[firstRow].Cells[0].RowSpan = 2;

else
GridView1.Rows[firstRow].Cells[0].RowSpan += 1;

//Remove the cell
e.Row.Cells.RemoveAt(0);

}

else //It's a new category
{

//Set the vertical alignment to top
e.Row.VerticalAlign = VerticalAlign.Top;

//Maintain the category in memory
previousCat = drv["CategoryName"].ToString();

firstRow = e.Row.RowIndex;

}

}

}

FIGURE 9: Code to get rid of the repeated category

image

FIGURE 10: Products by Category

The code is very similar to the previous example. This time we are using the help of two global variables: previousCat and firstRow. The variable previousCat is used to save the category of the previous row, so if the category is the same we increment the row span of the row containing the category and then delete the first cell of the current row. Whenever a new category arrives we leave the row intact and save the previousCat and firstRow to their corresponding values. Please note that this code will only work correctly if the data is sorted by the category name.

Your boss is now ecstatic; he knows he had made a great investment by hiring you. He knows you are on a roll and that is why he wants to change the first report by adding an image right next to the discontinued products. Figure 11 shows the code to accomplish the task and Figure 12 shows the end result.


protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)

{

if (e.Row.RowType == DataControlRowType.DataRow)

{

//We're only interested in Rows that contain data

//get a reference to the data used to databound the row
DataRowView drv = (DataRowView)e.Row.DataItem;
if (Convert.ToInt32(drv["UnitsInStock"]) == 0)

{

//The current product has 0 items in stock
e.Row.Font.Bold = true; //Make the font bold
e.Row.ForeColor = System.Drawing.Color.Red; //Set the text color red
if (Convert.ToInt32(drv["UnitsOnOrder"]) > 0)

{

//The current out of stock item has already been ordered
//Make it blue
e.Row.ForeColor = System.Drawing.Color.Blue;

}

}

if ((bool)drv["Discontinued"])

{

//Discontinued product

//Add the image
Image img = new Image();

img.AlternateText = "Discontinued Product";

img.ImageAlign = ImageAlign.AbsMiddle;

img.ImageUrl = "arrow_down.gif";

img.Width = Unit.Pixel(10);

img.Height = Unit.Pixel(11);

e.Row.Cells[0].Controls.Add(img);



//Add the text as a control
e.Row.Cells[0].Controls.Add(new LiteralControl(" " + e.Row.Cells[0].Text));

}

}

}

FIGURE 11: Code for setting fore color and discontinued image.

image

FIGURE 12: End result of the discontinued product

The code is the same code as in the first example with the addition of the discontinued part. We first have to check whether the current product is discontinued. If it is, then we create a new image and add it to the controls collection of the cell. Since we are adding a control to the collection, the GridView gives priority to the controls and ignores the text property, which is why we need to add the text as a control. This makes the GridView render the cell as an image with text right next to it.

Conclusion

From design time to run time formatting, from declarative programming to imperative programming, the GridView is one of the most complex and simple controls in the ASP.NET arsenal. It allows you to create simple tables with very little programming and also allows you to have full control of its formatting to create very complicated grids. Not only is the GridView a very powerful control for normal day to day functions such as displaying, adding, updating, and deleting data or for nice features such as paging and sorting, but also is a very powerful control in that it enables you to have full control of how it renders itself. I hope the next time you are creating a grid for your boss you can play around with the GridView Events and properties to come up with a neat solution.

Happy Programming!

http://www.simple-talk.com/dotnet/asp.net/take-row-level-control-of-your-gridview/

Tuesday, April 5, 2011

A piece of code today broke that didn't make sense at first. It was so ridiculous that I had to post about it. This isn't a C# is better than VB.NET entry. It's a legitimate "I thought I was supposed to be able to accomplish the same thing in VB.NET as I can in C# and vice-versa" entry. No flame-wars here!

The code was similar to this:

<ItemTemplate>
<%# IIf(IsDBNull(Eval("foo")), String.Empty, Eval("foo")) %>
ItemTemplate>

This is something that I do all the time in my C# UI. The C# conditional syntax lends itself nicely to this sort of deal.

<ItemTemplate>
<%# Eval("foo") == null ? String.Empty : Eval("foo") %>
ItemTemplate>

I used to get code where developers would literally have a TextBox or Label in the ItemTemplate and on RowDataBound or ItemDataBound cast the DataItem to T, analyze the value of a certain property or properties, and set the property of the TextBox, Label, etc... accordingly. Not cool with me. I opt for one-lining it whenever humanly possibly; which is what I tried to do earlier today. Only thing is, today I failed miserably.

I knew the code was broken because everything up until this column rendered as it should have. From this column-on everthing stopped. The results set consisted of at least 30 rows. Sweet. Since the code was in my presentation layer I couldn't really breakpoint it so I moved it to my code-behind. I found that there was a NullReferenceException. Really? I resorted to a different method of accomplishing this task via .aspx page.

<%#IIf(String.IsNullOrEmpty(Eval("foo").ToString), "A", Eval("foo"))%>

Wow. This failed miserably. Let's try something else.

<%#IIf(Eval("foo").ToString.Length = 0, "A", Eval("foo"))%>

This worked... NOT! In case you're curious, I resorted to using "A", "B", "C" for the 3 columns so I know which conditional broke. The first one broke every time.

I know that some of you are thinking that this problem shouldn't even filter down to the UI. By this I mean others have suggested that I take care of this problem in SQL. I already tried this using COALESCE and then with ISNULL.

ISNULL(FooColumn, '') AS FooColumn

There's a problem with this. What if FooColumn is of type money or integer? The example above wouldn't work (I tried) when the column is of type money or some type of numeric. AFAIK, there is no way to return an empty money value aside from 0.00 (if there is PLEASE let me know!). One of the requirements for this project was that NULL are valid for fields and nothing else should be displayed. That means the following wouldn't work.

ISNULL(FooColumn, 0) AS FooColumn

This would be misleading when the data is displayed because when the customer looked at the data they would think that FooColumn's value was actually 0 when in fact the zero is nothing more than an arbitrary value.

Another "fix" would be to just call ToString in the false part of my IIf statement. That works, to an extent. As soon as you introduce string formatting it won't work as it should.

I could, if I was absolutely desperate; enumerate the rows in the DataSet, check each column for NULL and replace with an empty string. Although it is a very nasty suggestion it would work.

Time for another test scenario. I created 2 console apps: 1 VB, 1 C#. Each does nothing more than declare an object that happens to be null as well as a SqlParameter that sets the value depending on the null'ity of said object.

First with the VB.

Dim foo As Object = Nothing

Dim parameter As SqlParameter = New SqlParameter()
parameter.ParameterName = "foo"
parameter.Value = IIf(foo Is Nothing, "NULL", "NOT NULL")

Console.WriteLine(IIf(foo Is Nothing, "NULL", foo.ToString))Console.WriteLine(parameter.Value)

C# equivalent.

object foo = null;

SqlParameter parameter = new SqlParameter();
parameter.ParameterName = "foo";
parameter.Value = foo == null ? "NULL" : "NOT NULL";

Console.WriteLine(foo == null ? "NULL" : foo.ToString());
Console.WriteLine(parameter.Value);

I usually have the parameter name and value taken care of in the constructor as I am a self-confessed one-liner but opted for a more blog-friendly version (i.e. no text-wrapping). Anyway, the results surprised me. Surprised in a "are you f**king kidding me?" and not "This is f**king awesome!" way. To prove that there is no bias, I created the C# version first and used Reflector to disassemble and pasted the VB.NET version into my VB.NET console app.

I ran the C# version first to make sure I wasn't getting frustrated over nothing. As expected the console output was 2 NULL's. Now time for the VB version; unhandled exception (NullReference) at line 12. Line 12 is this gem right here:

Console.WriteLine(IIf(foo Is Nothing, "NULL", foo.ToString))

Hmmm. WTF would I get an exception when I am checking for NULL? Why is foo.ToString even being interpreted? In other words, how can foo NOT be null? At least that's how I looked at this.

After doing a little bit of research I have found that the IIf function will actually analyze the true and the false part of the expression. In other words, it doesn't behave anything like a conditional in C# and is merely a throwback to the VB language.

Further reading of WHY this doesn't work resulted in the fact that if IIf functioned like a C# conditional then code that was ported from VB to VB.NET would break. This is an example of how an explanation can make sense and at the same time not make any sense at all. On the one hand I can see the possible need to make code portable. On the otherhand why would you switch to VB.NET if you expect to write classic VB code? I thought the purpose of going .NET was to embrace the .NET framework, not rely on backwards compatibility.

Again I'll pose the question: Is there a way to accomplish what I am trying to do without abstracting out the functionality to a helper method consisting of a full-blown IF THEN ELSE statement? Is there a way to one-line this functionality?

As it stands now I have created a RetrieveFooValue function that takes my object, interprets, and returns an appropriate value. This is the best I could come up with. Again, if there's a more efficient way to do this PLEASE let me know.

<ItemTemplate>
<%# RetrieveFooValue(Eval("foo")) %>
ItemTemplate>

RetrieveFooValue contains a full-blown IF THEN ELSE statment.

Monday, April 4, 2011

In this PHP MySQL tutorial I will show you how to use basic database manipulation features in PHP.

Inserting data into the database

In this topic we will create a code to insert new records into our MySQL database. This is very similar to the select version. Also in this case we need to build up a database connection and we will use the mysql_query() function again. However in this case we will use it with an insert sql statement. Now let's try to insert a new user to our table. The sql statement is the following:

INSERT INTO users (name,city,web,age) VALUES ('Tom','Vegas','www.tom.com',44);

Now store this SQL statements in a variable and pass this as parameter of mysql_query like this:

Code:
  1. $sql = "INSERT INTO users (name,city,web,age) VALUES ('Tom','Vegas','www.tom.com',5)";
  2. $result = mysql_query($sql);

Besides this we need to check the result and inform the user if an error was occurred. A complete insert code is the following:

Updating a record
The update is almost the same as the insert. You only need to change the sql statement and use it as before:
  1. $sql = "UPDATE users SET age=45 WHERE name='Tom'";
  2. $result = mysql_query($sql);
Deleting a record
As you may know it is again the same as before. Only the sql needs to be changed like this:

Code:
  1. $sql = "DELETE FROM users WHERE name='Tom'";
  2. $result = mysql_query($sql);

Bạn muốn lập trình cho phép Export dữ liệu từ Datatable, Gridview ra Excel, Word hay PDF? Trong bài viết này mình sẽ giới thiệu với các bạn cách thực hiện điều đó bằng cách sử dụng thư viện itextsharp.dll.

Trước tiên bạn cần download thư viện itextsharp.dll về tại đây.
Sau khi down về giải nén và Add vào thư mục bin của ứng dụng. Sau đó khi cần thực hiện việc Export dữ liệu ra các định dạng khác nhau bạn thực hiện như bài minh họa sau. Trong bài này mình chỉ minh họa cách Export dữ liệu ra các định dạng word, Excel, PDF. Bạn có thể tìm hiểu thêm về thư viện itextsharp.dll để có thể export ra nhiều định dạng khác cùng như tìm hiểu các component khác của thư viện này.

Trước tiên bạn cần tạo một Form gồm một Gridview, và các Button (ExportToRord, ExportToExcelm ExportToPDF) như sau:

Trong code bạn thực hiện như sau: (Minh họa này mình lấy Database Northwind làm ví dụ và dữ liệu Export là các trường CustomerID, CompanyName, ContactName, ContactTitle)

1. Hàm GetDataToTable
private DataTable GetDataToTable(SqlCommand cmd)
{
DataTable dt = new DataTable();
// Khai báo chuỗi kết nối
String strConnString = @"Server =.SQL2005;Initial Catalog=Northwind;User SqlConnection con = new SqlConnection(strConnString);
SqlDataAdapter sda = new SqlDataAdapter();
cmd.CommandType = CommandType.Text;
cmd.Connection = con;
try
{
// Mở kết nối và đổ dữ liệu vào bảng
con.Open();
sda.SelectCommand = cmd;
sda.Fill(dt);
return dt;
}
catch (Exception ex)
{
throw ex;
}
finally
{
//Đóng kết nối
con.Close();
sda.Dispose();
con.Dispose();
}
}

Trong hàm Page_Load bạn thực hiện truy vấn và Bind dữ liệu như sau

protected void Page_Load(object sender, EventArgs e)
{
// Truy vấn và đổ dữ liệu vào Gridview
string TruyVan = @"SELECT c.CustomerID, c.CompanyName,
c.ContactName, c.ContactTitle FROM Customers c";
SqlCommand cmd = new SqlCommand(TruyVan);
DataTable dt = GetDataToTable(cmd);
grvExport.DataSource = dt;
grvExport.DataBind();
}
2. Hàm xuất dữ liệu từ 1 gridview ra word
/// 
/// Xuất dữ liệu từ GridView ra word
///

private void XuatDuLieuRaWord(GridView MyGridview)
{
Response.Clear();
Response.Buffer = true;
Response.AddHeader("content-disposition", "attachment;filename=GridViewExport.doc");
Response.Charset = "";
Response.ContentType = "application/vnd.ms-word ";
StringWriter sw = new StringWriter();
HtmlTextWriter hw = new HtmlTextWriter(sw);
// Bỏ phân trang - Nếu chỉ muỗn Export Trang hiện hành thì chọn =true
MyGridview.AllowPaging = false;
MyGridview.DataBind();
MyGridview.RenderControl(hw);
Response.Output.Write(sw.ToString());
Response.Flush();
Response.End();
}
3. Hàm xuất dữ liệu từ một gridview ra Excel
/// 
/// Xuất dữ liệu từ GridView ra Excel
///

private void XuatDuLieuRaExcel(GridView MyGridview)
{
Response.Clear();
Response.Buffer = true;
Response.AddHeader("content-disposition",
"attachment;filename=GridViewExport.xls");
Response.Charset = "";
Response.ContentType = "application/vnd.ms-excel";
StringWriter sw = new StringWriter();
HtmlTextWriter hw = new HtmlTextWriter(sw);
// Bỏ phân trang - Nếu chỉ muỗn Export Trang hiện hành thì chọn =true
MyGridview.AllowPaging = false;
MyGridview.DataBind();
MyGridview.RenderControl(hw);
//Thay đổi Style
string style = @"";
Response.Write(style);
Response.Output.Write(sw.ToString());
Response.Flush();
Response.End();
}
4. Hàm xuất dữ liệu từ gridview ra PDF
/// 
/// Hàm xuất dữ liệu từ gridview ra pdf
///

private void XuatDuLieuGridRaPDF(GridView MyGridview)
{
Response.ContentType = "application/pdf";
Response.AddHeader("content-disposition", "attachment;filename=GridViewExport.pdf");
Response.Cache.SetCacheability(HttpCacheability.NoCache);
StringWriter sw = new StringWriter();
HtmlTextWriter hw = new HtmlTextWriter(sw);
MyGridview.AllowPaging = false;
MyGridview.DataBind();
MyGridview.RenderControl(hw);
StringReader sr = new StringReader(sw.ToString());
Document pdfDoc = new Document(PageSize.A4, 10f, 10f, 10f, 0f);
HTMLWorker htmlparser = new HTMLWorker(pdfDoc);
PdfWriter.GetInstance(pdfDoc, Response.OutputStream);
pdfDoc.Open();
htmlparser.Parse(sr);
pdfDoc.Close();
Response.Write(pdfDoc);
Response.End();
}

Trong các sự kiện click của các nut button bạn thực hiện như sau:

protected void btnExportWord_Click(object sender, EventArgs e)
{
XuatDuLieuRaWord(grvExport);
}
protected void btnExportExcel_Click(object sender, EventArgs e)
{
XuatDuLieuRaExcel(grvExport);
}
protected void btnExportPDF_Click(object sender, EventArgs e)
{
XuatDuLieuGridRaPDF(grvExport);
}

Bạn chú ý trong code của bạn cần có hàm sau để chứng thực việc sử dụng HtmlForm. Nếu không sẽ có lỗi "Control 'grvExport' of type 'GridView' must be placed inside a form tag with runat=server" khi thực hiện Export.

public override void VerifyRenderingInServerForm(Control control)
{
//Xác nhận điều khiển HtmlForm tại thời gian chạy ASP.NET
}

Sunday, April 3, 2011

Originally published on DataDeveloper.net

In this tutorial, you will create a new Entity Data Model inside an Class Library Project. The data model will be built from the AdventureWorksLT database.

The project can be used in (Windows, Console, Web, other class libraries etc) by referencing this project.

Create a new Class Library Project

  1. Select New Project from File Menu option
  2. Select your preferred project base: e.g. Visual Basic or C#
  3. Select Class Library
  4. Change the name of the application in the Name text box to DataDevEDM
  5. Click OK

Add an Entity Data Model Item

  1. In Solution Explorer, right click the project name.
  2. Click Add on the context menu that opens.
  3. Click New Item.
  4. In the Add New Item dialog, click ADO.NET Entity Data Model.
  5. Change the name from Model1.edmx to AWModel.edmx
    addnewitem
  6. Click the Add button
  7. In the Entity Data Model Wizard click Generate from Database, then click the Next button

Create a database connection for the Entity Data Model

If you have a database connection already created in Visual Studio, skip to Define Contents of an Entity Data Model

  1. On the Choose Your Data Connection page of the wizard, click the New Connection button.
  2. At the top of the connection properties window, click the Change button next to the Data Source
    clip_image004
  3. Select Microsoft SQL Server Database File from the Data source list, then click OK
  4. Click the Browse button to the right of Database file name
  5. Browse to the folder where you have saved the AdventureWorksLT database*.
  6. Select AdventureWorksLT.mdf then click Open.
    clip_image006
  7. At the bottom of the Connection Properties window, click OK

Define the contents of an Entity Data Model

  1. Select the database connection from the drop down.
  2. At the bottom of the Entity Data Model Wizard window, change the value of Entity connection settings to AWEntities then click Next.
    clip_image008

  3. On the next page, change the Model Namespace to AWModel.
  4. Check Tables, Views and Stored Procedures.
    This will include all of the items. You can expand these nodes to select only the specific tables, views and stored procedures that you want.
    clip_image010

  5. Click Finish.
  6. Note that in the solution explorer, a new file, AWModel.edmx has been created.
    explorer

View the model

  1. Double click the AWModel.emx file to open the model in the Entity Data Model designer.

model

ASP.NET MVC, Entity Framework, Modifying One-to-Many and Many-to-Many Relationships

see link: http://www.mikesdotnetting.com/Article/110/ASP.NET-MVC-Entity-Framework-Modifying-One-to-Many-and-Many-to-Many-Relationships

Sunday, January 16, 2011

Xử Lý Sự Cố Khi Không Vào Được Windows

Vào 1 ngày " đẹp trời " nào đó mà bạn bật máy lên, nó hiện những thông báo kỳ quặc, thay vì giao diên Windows quen thuộc của bạn. Nguyên nhân thì chỉ gồm có 2 phần chính là Hệ điều hành và những thiết bị phần cứng , hay có thể bị lỗi do vừa update windows mới. tuy nhiên đại đa số là máy bị virus phá hoại nhưng file hệ thống ( nguyên nhân này đc liệt vào diện cao nhất ), và chính vì mới quét virus toàn bộ máy, và sau khi khỏi động máy lại là bị tình trạng không vào được Windows.

Hẳn điều bạn nghĩ đầu tiên là cài lại windows, đây là giải pháp hữu hiệu nhất, hoặc Repair lại, tuy nhiên nó hay tốn thời gian và chưa nói đến việc phải tìm lại Dirver, nếu bị mất đĩa thì càng rắc rồi hơn.

Sau đây là 1 số Lỗi khi Không vào đc Windows và các khác phục. Và lỗi thường gặp cũng được sắp xếp theo thứ tự từ cao xuống thấp, các bạn xem mình có nằm trong trường hơp nào mà xem rồi tiến hành khắc phục trước khi nghĩ đến việc cài lại Windows.

Hỏng/không tìm thấy NTDETECT.COM NTLDR (can not/ Error)


- Khởi động máy cho boot vào CD Room
- Bỏ đĩa Windows tương ứng vào
- Giao diện cài Windows hiện ra, chọn nhấn phím R để vào chế độ Repair
- Chọn phân vùng để sữa Windows ( thường là đầu tiên)
- Gõ :
COPY *:\i386\NTLDR C:\
COPY *:\i386\NTDETECT.COM C:\
( * là tên ổ đĩa CD room của bạn )
exit


Hỏng/không tìm thấy CONFIG (can not/ Error)


Khởi động máy cho boot vào CD Room
- Bỏ đĩa Windows tương ứng vào
- Giao diện cài Windows hiện ra, chọn nhấn phím R để vào chế độ Repair
- Chọn phân vùng để sữa Windows ( thường là đầu tiên)
- Gõ :
CD \windows\system32\config
Ren software software.bad
Ren system system.bad


Copy \windows\repair\system
Copy \windows\repair\software
exit


Invalid Boot.ini
Windows could not start because the following file is missing or corrupt:
Windows\System32\Hal.dll


Khởi động máy cho boot vào CD Room
- Bỏ đĩa Windows tương ứng vào
- Giao diện cài Windows hiện ra, chọn nhấn phím R để vào chế độ Repair
- Chọn phân vùng để sữa Windows ( thường là đầu tiên)
- Gõ :
bootcfg /list
bootcft /rebuil
( nếu có 1 HĐH thì Yes)
giao diện tiếp theo gõ : /fastdetect
exit


Hỏng/không tìm thấy NTOSKRNL.EXE(can not/ Error)


Khởi động máy cho boot vào CD Room
- Bỏ đĩa Windows tương ứng vào
- Giao diện cài Windows hiện ra, chọn nhấn phím R để vào chế độ Repair
- Chọn phân vùng để sữa Windows ( thường là đầu tiên)
- Gõ :
CD i386
expand ntkrnlmp.ex_ C:\windows\System32\ntoskrnl.exe
exit


Windows could not start because the following file is missing or corrupt:System32\Drivers\Ntfs.sys


Khởi động máy cho boot vào CD Room
- Bỏ đĩa Windows tương ứng vào
- Giao diện cài Windows hiện ra, chọn nhấn phím R để vào chế độ Repair
- Chọn phân vùng để sữa Windows ( thường là đầu tiên)
- Gõ :
cd windows\system32\drivers
ren ntfs.sys
ren ntfs.old
copy E:\i386\ntfs.sys C:\Windows\System32\Drivers
exit


The file C:\windows\system32\c_1252.nls is missing or corrupt


Khởi động máy cho boot vào CD Room
- Bỏ đĩa Windows tương ứng vào
- Giao diện cài Windows hiện ra, chọn nhấn phím R để vào chế độ Repair
- Chọn phân vùng để sữa Windows ( thường là đầu tiên)
- Gõ :
cd system32
ren c_1252.nls
ren c_1252.old
expand E:\i386\c_1252.nl_ C:\Windows\System32
exit


STOP: 0x00000079 (0x00000003, parameter2, parameter3, parameter4).
MISMATCHED_HAL


Khởi động máy cho boot vào CD Room
- Bỏ đĩa Windows tương ứng vào
- Giao diện cài Windows hiện ra, chọn nhấn phím R để vào chế độ Repair
- Chọn phân vùng để sữa Windows ( thường là đầu tiên)
- Gõ :
ren ntldr oldntldr
copy E:\i386\ntldr
exit


Winlogon.exe could not locate component . This application has failed to start because comctl32.dll was not found . Re-installing the application may not fix this problem


Khởi động máy cho boot vào CD Room
- Bỏ đĩa Windows tương ứng vào
- Giao diện cài Windows hiện ra, chọn nhấn phím R để vào chế độ Repair
- Chọn phân vùng để sữa Windows ( thường là đầu tiên)
- Gõ :
expand E:\I386\comctl32.dl_ C:\Windows\System32
exit



STOP: c0000221 Unknown Hard Error \SystemRoot\System32\ntdll.dll

Khởi động máy cho boot vào CD Room
- Bỏ đĩa Windows tương ứng vào
- Giao diện cài Windows hiện ra, chọn nhấn phím R để vào chế độ Repair
- Chọn phân vùng để sữa Windows ( thường là đầu tiên)
- Gõ :

COPY *:\I386\NTDLL.DLL C:\WINDOWS\system32\dllcache\ntdll.dll
COPY *:\I386\NTDLL.DLL C:\WINDOWS\system32\ntdll.dll


( * : là tên ổ CD room)
exit

STOP c000026c unable to load device driver
\%SystemRoot%\System32\Drivers\xxxxx.sys. Device driver could not be loaded, error status 0xc000012F


Khởi động máy cho boot vào CD Room
- Bỏ đĩa Windows tương ứng vào
- Giao diện cài Windows hiện ra, chọn nhấn phím R để vào chế độ Repair
- Chọn phân vùng để sữa Windows ( thường là đầu tiên)
- Gõ :
disable xxxxx.sys
exit

tiến hành cài lại dirver.

Wednesday, June 30, 2010



Bạn nghĩ sao nếu như thiết kế một phần mềm mới cũng đơn giản như lắp một cái tivi? Chẳng hạn như bạn chỉ việc gắn bộ nguồn, mạch bắt sóng, mạch điều khiển, gắn đèn hình vào là xong. Bạn không cần phải đi thiết kế lại từng phần chi tiết tỉ mỉ làm gì cả. Giả sử bạn xoay sang lắp máy tính xách tay thì cũng thế, chỉ việc gắn bộ nguồn, đèn hình, mạch điều khiển. Điểm hay là ở chỗ một con transistor trong laptop hay tivi thì cũng y như nhau.

Quay lại ví dụ viết chương trình quản lý kho, giả sử ta có một máy tính siêu thông minh thì chỉ việc bảo nó: gắn "cục" Security A101, cục Data 2.0, cục Web GUI 8.1 rồi dán nhãn My Big Soft vào đó rồi nó tự động làm hết mọi chuyện cho ta. Rất tiếc, đây chỉ là ước mơ, còn thực tế thì lập trình viên vẫn phải còng lưng viết code đến mờ mắt, viết đi viết lại, viết tới viết lui như một điệp khúc bất tận.

May thay, thành phần phần mềm (component) có thể giải quyết vấn đề. Nếu bạn là dân Java, hãy nghĩ đến Java Beans. Nếu bạn là dân .NET, hãy nghĩ đến Application Block, đến Web-parts. Hay đơn giản hơn, ai cũng đã gặp nhiều lần: UI control (button, label, listbox, checkbox,...)

Một component không phải là một lớp (class), và lập trình thành phần (component-centric) cũng không phải là lập trình hướng đối tượng (OOP - Object Oriented Programming). Class đơn thuần chỉ là gom nhiều code có cùng mục đích vào chung một chỗ. OOP là xem vấn đề như một hoặc nhiều đối tượng (có thuộc tính, có method) để phân loại mối quan hệ của chúng. Còn component-centric có nghĩa là lập trình để mỗi phần mang tính độc lập, có thể thay thế, có thể sử dụng lại cho những vấn đề khác nhau.

Giả sử bây giờ bạn phải viết trò chơi Snake (người dùng điều khiển con rắn chạy ăn mồi, mỗi khi ăn được cục mồi thì con rắn dài thêm một đoạn).

1/ Class: bạn chỉ cần 1, cùng lắm là 2 class để viết trò chơi tí hon này.

2/ OOP: bạn sẽ viết các class Snake, Food, Player.

3/ Component-centric: Bạn sẽ ngồi phân tích xem đâu là điểm chung, đâu là điểm riêng, đâu là phần chi tiết chỉ áp dụng riêng cho trò chơi này, đâu là phần bạn có thể abstract nó. Có lẽ bạn sẽ thiết kế ra các component sau: Game Engine, Graphic Engine, Rule Engine, Resouces Manager, User Controller, v.v...

Như vậy sau khi thiết kế xong, trò Snake chỉ là sản phẩm phụ mà thôi. Với những component sẵn có, bạn dư sức viết DOOM 2006.

Phát triển thành phần phần mềm đang được đầu tư và phát triển rất nhiều. Nếu bạn có hứng thú, hãy tham khảo thêm các tài liệu sau: Microsoft Application Block; Enterprise Java Bean; Java Frameworks and Components: Accelerate Your Web Application Development – Michael Nash...

Lớp

Nếu như component là từng bộ phận nhỏ, đóng vai trò như một hộp đen "black-box", ta chỉ quan tâm tới chức năng của nó là chính, thì lớp (Layer) lại giống như một bản mạch in gồm nhiều component đã được thiết kế sẵn. Lấy ví dụ như card màn hình, mở các máy PC ra bạn sẽ thấy ngay card này. Điểm thú vị là bạn không phải "se duyên" với cái card ấy mãi mãi. Khi nào túi tiền rủng rỉnh, bạn có thể mua card khác mới hơn, nhanh hơn, xịn hơn để gắn vào và quên béng đi cái card cũ. Có khi nào bạn suy nghĩ lại và ngạc nhiên tại sao cái máy tính cũ kỹ đời 1998 của mình lại có khả năng chấp nhận card 3D đời 2006 không? Thật là một điều kỳ diệu, nhỉ!

Phần mềm cũng thế, nếu thiết kế chia một phần mềm ra thành nhiều layer thì sẽ tăng tính tái sử dụng, và quan trọng nhất là: chịu được sự thay đổi trong tương lai. Bạn hãy nghĩ thế này nhé: nếu Windows mà được thiết kế tốt hơn thì bạn đã có thể chơi game của Windows, chạy web server của Linux, và chạy chương trình đồ họa của Macintosh ngay trong hệ điều hành Windows.

Ở đây tôi giới thiệu 3 layer cơ bản nhất mà đa số chương trình từ bé đến khổng lồ, từ bài tập của sinh viên đến game online kinh phí hàng trăm triệu đô đều cần phải có.

Data Access Layer (DAL)

Nếu bạn biết "Select * from Products Where CustID = @ID" nghĩa là gì nhưng không cần phải dùng mỗi ngày thì bạn may mắn quá, bạn có thể bỏ qua phần này.

Nếu bạn không những biết mà còn thuộc nằm lòng đến 80% T-SQL 92, hoặc bạn nằm mơ cũng nghĩ đến SQL, đến Stored Procedure, đến Triggers, thì bạn rất cần phải dùng đến DAL. Có lẽ 90% dân lập trình, nhất là ở Việt Nam trong thời điểm hiện tại, rơi vào trường hợp này.

Trước hết, hãy nói Data Access Object là gì đã. Khi lập trình cơ sở dữ liệu, bạn phải lặp đi lặp lại thao tác sau:

- Create connection

- Create SQL command

- Execute SQL

- Process results

Chán quá, lỗi nhiều quá. CSDL bạn dùng là quan hệ (relational), mọi thứ đều trong table, table, table. Trong khi đó, bạn lại thích lập trình OOP cơ. Thế là bằng cách này hay cách khác, cho dù bạn biết hay không biết, bạn sẽ quay sang làm theo kiểu sau: định nghĩa class chuyên nói chuyện với CSDL. Lấy ví dụ như class sau:

Class ProductDAO

{ Connection GetConnection();

bool Insert(int ID, string Name);

DataSet GetAllProducts();

DataSet GetProductByName(string Name);

Bool Delete(int ID);

}

Phương pháp bạn vừa làm chính là Data Access Object. Bạn có thể viết tay, bạn cũng có thể dùng các công cụ như CodeSmith để làm giùm bạn. Xin chúc mừng! Bạn đã đỡ khổ hơn trước nhiều rồi đấy.

Nhưng mà, cũng xin... chia buồn với bạn luôn. Bạn nghĩ sao nếu CSDL bên dưới thay đổi? Bạn sẽ dùng CodeSmith để tạo lại ư? Thế mấy cái "business logic" (luận lý nghiệp vụ) đi tong hết thì sao? Lỡ năm sau CodeSmith dẹp tiệm thì sao, bạn phải sửa lại bằng tay à? Hoặc là CSDL không phải của bạn, mà bạn phải tích hợp vào CSDL "bự xự" có sẵn của khách hàng? Chua đấy bạn ạ. Chưa kể là dùng Data Access Object làm tăng số lượng class lên rất nhiều (cứ mỗi table trong CSDL cần ít nhất 1 class, thậm chí có thể là 3, 4 class). Mỗi class cần ít nhất 4 method (Create, Read, Update, Delete). Chưa kể là mỗi kiểu select khác nhau lại phải viết method mới. Điều này đồng nghĩa với việc kiểm thử (testing) cũng tăng lên đến chóng mặt.

Bạn nghĩ sao nếu bạn chỉ cần định nghĩa một class thế này:

Class Product

{ Int ID;

String Name;

String Description;

}

Xong, chỉ có thế thôi! Nếu cần thêm sản phẩm mới vào database thì làm như sau:

Product p = new Product();

p.Name = " Some product";

Database.AddNew(p);

Nếu cần truy vấn một sản phẩm thì chỉ cần thế này:

Product p = Database.Get(typeof(Product), Name = "ProductA");

Rất đơn giản, phải không bạn? Cái hay là ở chỗ nếu có thêm nhiều table nữa thì cũng thế, bạn chả phải viết thêm nhiều method chi cho mệt, chỉ định nghĩa class của bạn ở mức đơn giản nhất. Và "đã” nhất là bạn không cần phải viết thêm một mớ test để kiểm tra việc truy xuất class đó.

Đây chính là chức năng chính của Data Access Layer.

Nếu thích, bạn có thể tham khảo các tài liệu sau: Data Access Layer trong Microsoft Application Block; O/R Mapping (Object-to-Relational Mapping): Wilson O/R for .NET, ORM.Net, Object Space; Java Persistence for Relational Databases, Richard Sperko (Apress 2003- ISBN:1590590716).

Lưu ý: Persistence Layer về cơ bản có cùng tính năng như DAL. Tuy nhiên, Persistence Layer có khái niệm và cách thức thực hiện khác với DAL một ít, mỗi loại có cái hay và cái dở riêng.

Business Object Layer (BOL)

Business Object (đối tượng nghiệp vụ) rất thú vị ở chỗ chương trình nào cũng cần có nó, nhưng lại chẳng có framework hay chuẩn nào cho bạn cả. Đơn giản là vì business object thay đổi luôn tùy yêu cầu cụ thể của từng nghiệp vụ (business) khác nhau.

Trong đa số trường hợp, Business Object sẽ được thiết kế gần giống với Data Object (chỉ chứa dữ liệu hoặc nói chuyện với CSDL), chỉ khác ở chỗ thêm vào đó một ít quy tắc kiểm tra nghiệp vụ (ví dụ: nếu tài khoản chỉ có 1000 thì không cho phép rút 1 triệu đồng).

Tuy nhiên, có những vấn đề lặp đi lặp lại mà nghiệp vụ nào cũng gặp, chẳng hạn: transaction (giao tác), distribution (phân phối), validation (kiểm tra). Khi thiết kế Business Object, người thiết kế bao giờ cũng đau đầu với những câu hỏi như: nên tạo stored procedure hay không? Nên validate ở đâu (trong DBMS, trong server, hay trong client)? Object như thế có thể mở rộng không, có đáp ứng nhanh không? Vân vân và v.v...

BOL là một lớp abstraction cho phép giải quyết những vấn đề thường gặp khi thiết kế business logic. Với một framework tốt, BOL đóng vai trò rất quan trọng vì nó là "sợi chỉ đỏ xuyên suốt các layer".

Vì nhiệm vụ của Business Object rất đa dạng và cũng có nhiều khó khăn khác nhau nên BOL thường được đóng gói với tên gọi Application Frameworks. Lập trình viên bình thường và những dự án vừa và nhỏ ít có cơ hội tiếp xúc. Những framework thương mại chủ yếu dành cho các dự án lớn và đòi hỏi phải học chuyên sâu. Tuy nhiên, nếu đơn giản hóa vấn đề thì bạn cũng có thể tự viết một BOL cho riêng mình để tăng năng suất lập trình.

Tham khảo: C# Expert Business Object (cuốn này hơi khó kiếm, nhưng nên có)

Presentation Layer

Hồi lúc trước, mình là tín đồ của nàng Athena xinh đẹp (nói cách khác là dân ghiền Delphi). Khi chuyển sang C#, mình đã thất vọng tràn trề. Lẽ ra trong Delphi thiết kế một form có master/detail view chỉ mất 1 phút thì trong C#, phải mất 2 trang code (hồi mới học thì mất cả tuần vì không hiểu làm sao để sử dụng cái datagrid). Sau đó, chuyển sang ASP.NET thì càng đau khổ hơn nữa.

Tại sao ta lại phải khổ thế nhỉ? Viết form cực kỳ "chua" (hỏi mấy người lập trình Java với AWT thì biết). Với các ngôn ngữ hiện đại, ta có designer làm sẵn cho, chỉ việc kéo thả là xong. Các bộ "control" (thành phần điều khiển) thương mại hiện có rất nhiều, mỗi người một vẻ. Với những bộ lớn như của ComponentOne, Janus System, họ gắn luôn mác Presentation Layer vào sản phẩm. Có lý phần nào vì đó là những component phục vụ cho việc trình bày thông tin.

Nhưng vẫn còn nhiều vấn đề:

1/ Lệ thuộc vào control nhất định. Hãy quên chuyện thay thế grid của Winform bằng grid của Developer Express mà không cần phải sửa lại code đi nhé.

2/ Không có chuẩn. Mỗi bộ control là một framework mới cần phải học và không tương thích gì với nhau cả. Đừng mơ có chuyện viết code năm nay, 2 năm sau quay lại thay giao diện "cái rẹt".

3/ Logic code và UI code quyện lẫn, vào nhau. Visual Studio 2005 cố gắng giúp (lừa) bạn tránh chuyện này bằng partial class, chia code thành 2 file: aspx, code-behind (bắt chước asp.net).

4/ Visual rất luộm thuộm. Bạn nghĩ sao nếu bạn viết chương trình đồng hồ analog (có kim giờ, phút, giây quay vòng vòng), nhưng ngày mai bạn thích đồng hồ Digital (chỉ hiển thị số). Bạn có thể nào giữ nguyên logic code, chỉ cần thay thành phần màn hình trong 5 giây không?

5/ Data-binding: Rất phiền. Những control sẵn có khiến cho bạn trở thành "gà công nghiệp" và lệ thuộc vào nó. Điều đáng buồn là khi bạn cần nối kết dữ liệu hơi phức tạp thì vẫn cứ phải "chân lấm tay bùn", quay trở lại viết code từng dòng một, xử lý event từng chỗ một.

Những năm gần đây xu hướng Declarative Programming gây được nhiều sự chú ý. Lấy ví dụ như thay vì viết code tạo form như sau:

Button b = new Button();

b.SetBounds(100,100,50,25);

b.Text = "Click me";

b.Click += new EventHandler(b_OnClick);

Thì ta có thể tạo một file XML như sau:



Sao giống lập trình web quá vậy? Vâng, web chính là thuở ban đầu của declarative programming. Bạn thử tưởng tượng cũng một file XML đó, bạn có thể dùng làm Windows application, bạn có thể dùng làm webform, có thể dùng cho Flash, có thể dùng cho Macintosh thì sao? Có mà nằm mơ!

Vâng, rất tiếc rằng ở thời điểm hiện tại chưa có Presentation Layer nào thực hiện được mơ ước "viết một lần, hiển thị trên mọi hệ thống". Tuy nhiên, ít ra thì bạn không còn phải viết code từng dòng bằng tay nữa, bạn có thể nhờ Presentation Layer để tự kiểm tra đầu vào, tự sinh các form, tự dàn trang, v.v... Bạn hãy tìm hiểu thêm các chủ đề sau: Avalon, MyXaml, XAML, XAMLon, Flex, XUL...

Mẫu thiết kế

Mẫu thiết kế (Design Pattern) nôm na ra là cách thức giải quyết cho những vấn đề thường gặp. Điều đáng buồn là các sách về design pattern "khô như ngói, nhạt như nước ốc". Nhưng tin vui: design pattern là công cụ sẽ giúp bạn tăng lương lên gấp đôi (hoặc hơn). Đơn giản vì design pattern chính là kinh nghiệm xương máu của những người đi trước đúc kết được. Khi học design pattern, bạn sẽ có những kinh nghiệm vượt trước năng lực của mình.

Tài liệu để đọc về design pattern hiện có rất nhiều. Mình chỉ mạn phép góp ý với các bạn một câu khi học về lĩnh vực này: "hãy nắm lấy ý tưởng, đừng chú trọng vào code". Nếu bạn chỉ nhìn vào code ví dụ, bạn sẽ dễ bị "tẩu hỏa nhập ma", sẽ bị lệ thuộc vào code, nhìn thấy cái nào cũng na ná nhau, và tệ hại nhất là chẳng biết áp dụng cho cái gì khác ngoài ví dụ ra.

Hy vọng bài viết này sẽ giúp các bạn có được một số gợi ý để đào sâu nghiên cứu thêm. Chúc các bạn luôn "cháy bỏng" niềm đam mê lập trình.


Thegioiweb.vn (Theo asp.net.vn)

Friday, June 25, 2010

CuteFtp là một chương trình dùng để quản lý host ngay trên máy vi tính của bạn,rất tiện lợi.
Cài đặt:
Bạn tải file cuteftppro.rar về,chạy file cuteftppro.exe để cài đặt.Sau khi cài đặt xong,bạn mở file Serial.txt copy tất cả code rồi để vào Program
Vậy là bạn đã xong phần cài đặt của chương trình rồi đó.Bây giờ,chúng ta sẽ xem qua một số chức năng cơ bản của chương trình này nhé:
Kết nối với host của bạn:
Lần đầu xuất hiện,cửa sổ Connect Wizard sẽ hiện lên.Theo mình,bạn nên nhấn cancel vì cửa sổ này khá là phiền phưc.Sau đó,bạn nhấn Ctrl+N,màn hình sẽ hiện lên cửa sổ Site Properties.Bạn nhập đủ thông số về site và nhấn Connect:

This image has been resized. Click this bar to view the full image. The original image is sized 1024x768.


Sau khi đăng nhập thành công màn hình sẽ hiện lên:
This image has been resized. Click this bar to view the full image. The original image is sized 1024x768.


This image has been resized. Click this bar to view the full image. The original image is sized 1024x768.


Cách upload:
This image has been resized. Click this bar to view the full image. The original image is sized 1024x768.


Cách dowload từ host:
This image has been resized. Click this bar to view the full image. The original image is sized 1024x768.


This image has been resized. Click this bar to view the full image. The original image is sized 961x586.


Ngoài các thao tác trên bạn cũng có thể kéo thả file qua lại giữa Local Drivers và Host bình thường, nó sẽ tự hiểu là bạn Upload và ngược lại.

Vậy là bạn đã nắm bắt các tính năng chủ yếu của chương trỉnh
rồi đó.Chúc bạn thành công!

Link download (7.82Mb): http://www.mediafire.com/?ym7tltmgnmx

Friday, October 16, 2009

SQL Server 2005 không cho phép remote connection cho nên chúng ta cần phải active service này lên một cách thủ công. Message sau sẽ xuất hiện trong trường hợp service này chưa được start.

An error has occurred while establishing a connection to the server. When connecting to SQL Server 2005, this failure may be caused by the fact that under the default settings SQL Server does not allow remote connection. ….?"

SQL Server does not allow remote connection

Login failed for user ‘sa’. The user is not associated with a trusted SQL Server connection.�?

Login failed for 'sa'

Kiểm tra quyền truy cập vào hệ thống SQL Server với account trong hệ thống của SQL Server hoặc quyền của Windows Authentication.
Ví dụ: tài khoản ‘sa’.

    1. Login vào SQL Server sử dụng công cụ SQL Server Management Studio Express trên hệ thống SQL Server với tài khoản của Windows Authentication.
      Login using Windows authentication mode on local
    2. Trong phần cửa sổ Object Explorer, click chuột phải trên tên server đã connect và chọn Properties.
      Open SQL Server Properties
    3. Trên phần của sổ trái của cửa sổ Server Properties, chọn Security và thay đổi dạng truy cập Server authentication trở thành SQL Server and Windows Authentication mode.
      Change SQL Server authentication mode
    4. Của sổ thông báo kết quả thay đổi đã thành công và yêu cầu restart lại SQL Server để làm cho những thay đổi trên có hiệu lực.
      SQL Server need restart
    5. Click chuột phải trên tên server, chọn Restart để restart lại dịch vụ SQL Server.
      Restart SQL Server Service
    6. Chọn Yes.
      Confirmation
    7. Của sổ restart dịch vụ SQL Server.
      Restarting SQL Server Service
    8. Tất cả đã hoàn tất, dịch vụ SQL Server với quyền truy cập là tài khoản của SQL Server và Windows authentication đều đã được kích hoạt.
  • Kiểm tra dịch vụ remote connection vào server SQL trên công cụ SQL Server Surface Area Configuration
    1. Mở chương trình SQL Server Surface Area Configuration.
      Open SQL Server Surface Area Configuration
    2. Click vào chức năng Surface Area Configuration for Services and Connections (chọn lựa đầu tiên trong 2 chức năng).
      Open Surface Area Configuration for Services and ConnectionsTrên phần cửa sổ bên trái của cửa sổ vừa mở ra, chọn SQL Server instance -> Database Engine -> Remote Connections. Trên phần bên phải, chọn Local and remote connections -> using both TCP/IP and named pipes.
      Allow remote connections
    3. Tiếp theo trên phần trái của cửa sổ, chọn SQL Server Browser -> Service.
      Trên phần phải của cửa sổ, Hãy start dịch vụ và để nó ở chế độ Automatic. Sau đó nhấn OK.
      Start SQL Server Browser
    4. Sau khi tiến hành các bước cấu hình trên, hệ thống đã có thể tiến hành remote connect từ một máy khác trong hệ thống mạng.
      Login to remote SQL Server
    5. Trang login.
      Login succeeded

Monday, August 4, 2008

SQL Server 2005 Express Edition

Keywords: SQL Server 2005 Express, SQLExpress, SQLServer2005, SQL2005,

1. Cài đặt .NET Framework 2.0
2. Cài đặt Microsoft SQL Server 2005 Express Edition
3. Cài đặt SQL Server Management Studio Express

SQL Server 2005 Express Edition (SSE) là phiên bản desktop của sản phẩm cơ sở dữ liệu SQL Server 2005 rất phổ biến của Microsoft. Phiên bản SQL Server 2005 Express Edition được cung cấp miễn phí cho người sử dụng.

1. Cài đặt .NET Framework 2.0

SSE đi với bộ công cụ phát triển phần mềm Visual Studio.NET 2005 nên yêu cầu cần phải có .NET Framework 2.0. Link download .NET Framework 2.0: http://msdn2.microsoft.com/netframework/

2. Cài đặt Microsoft SQL Server 2005 Express Edition

SQL Server 2005 Express Edition là phiên bản desktop làm server dữ liệu SQL trên máy PC x86. SSE có đặc điểm là miễn phí, dễ sử dụng, kích thước file cài đặt nhỏ gọi chỉ với 36.5MB.

Link download : http://go.microsoft.com/fwlink/?LinkId=65212

3. Cài đặt SQL Server Management Studio Express

SQL Server Management Studio Express để dễ quản lý database, nó giúp bạn tạo database dễ dàng hơn. Trường hợp không cần công cụ quản lý dữ liệu thì không cần cài đặt phần này.

Link download: http://go.microsoft.com/fwlink/?LinkId=65110

Trước khi cài cần phải có MSXML 6.0.

(Link download : http://www.microsoft.com/downloads/details.aspx?familyid=993c0bcf-3bcf-4009-b...)



4. Câu lệnh kết nối đến SQL Express

SQLServer2000:

m_szConnectString.Format("Provider=SQLOLEDB;Data Source=%s; Trusted_Connection= yes; User Id = %s; Password=%s; Initial Catalog=%s", m_szServer, m_szUsername, m_szPassword, m_szDatabase);

SQLExpress2005:

m_szConnectString.Format("Provider=SQLNCLI; Server=HUNGNQ\\SQLEXPRESS; Trusted_Connection=yes; Database=%s; User Id=%s; Password=%s; Initial Catalog=%s", m_szUsername, m_szPassword, m_szDatabase);

m_szConnectString.Format("Provider=SQLNCLI; Server=HUNGNQ\\SQLEXPRESS; Persist Security Info=True; User Id=%s; Password=%s; Initial Catalog=%s;", m_szServer, m_szUsername, m_szPassword, m_szDatabase);