ASP.NET Role Membership Provider phần I

by Neon Quach 10. March 2010 04:50

Xây dựng 1 website, chắc chắn cũng có người dùng, việc có người dùng thì cũng sẻ phải quản lý, ít nhất là tài khoản admin, biết được đó là 1 phần tất yếu của 1 website, Microsoft’s team đả xây dựng Role Membership Provider như 1 phần không thể tách rời của .Net Framework.

Mặc dù cũng không quá dài dòng để nói về Role và Membership trong ASP.NET, nhưng mình muốn nói chi tiết và hướng dẫn cụ thể cho các bạn, người đả và đang biết ASP.NET, cho nên mình chia làm nhiều phần.

Điểm mạnh của Role và Membership provider là cho phép chúng ta có thể kế thừa và viết lại custom provider, cái mà cách đây hơn 1 năm mình đả làm, và giờ mình đang làm custom provider cho MySql.

Cài đặt database
Nói đến quản lý người dùng, chúng ta cần phải có csdl để lưu giử dử liệu, asp.net cung cấp 1 công cụ để cài đặt csdl, để lưu trữ SQL Provider là: Aspnet_regsql.exe, chúng ta có thể chạy nó từ C:\WINDOWS\Microsoft.NET\Framework\<versionNumber>\aspnet_regsql.exe

Chạy aspnet_regsql.exe lên chúng ta sẻ thấy màng hình.



Màng hình welcome khi cài run aspnet_regsql.exe



Màng hình install mới hay remove membership



Màng hình config database setting




Màng hình confirm setting db




Màng hình thành công install aspnet_regsql.exe




Màng hình schema của aspnet_regsql database

 

 

Chúng ta cũng có thể chạy bằng command line của hộp thoại Visual Studio

aspnet_regsql.exe -E -S localhost\sqlexress -A mr

Các tham số sẻ là:
-E: Chứng thực bằng tài khoản hiện tại login vào window
-S: Server chứa database
-A: Những feature của Membership, default là all, còn tham số m là membership, r là role, như vậy chúng ta chỉ cài membership và role, nếu chạy dòng lệnh này.

Chi tiết thêm dòng lệnh của aspnet_regsql, chúng ta có thể tham khảo thêm tại đây

Giờ đả có database, bài viết tiếp theo mình sẻ hướng

Tags: , , ,

.Net Framework | ASP.NET | C# | VB.NET

Named và Optional Arguments trong C# 4.0

by Neon Quach 6. March 2010 22:00

Khi làm việc với Com đặc biệt là Office Com Component, có rất nhiều phương thức của Com đòi hỏi nhiều tham số truyền vào.

Named và Optional Arguments là 1 đặc trưng mới của C# 4.0, về mặt ý nghỉa thì mình tạm đặt là Các tham số tùy chọn và tham số được đặt tên,
Cả hai kỹ thuật này có thể sử dụng đối với các phương thức, indexers, constructores và delegates, để cho đơn giản chúng ta nhìn vào phương thực này.

        // A method with nameed and optional parameters

        public static void Search(string name, int age = 21, string city = "Pueblo")

        {

            Console.WriteLine("Name = {0} - Age = {1} - City = {2}", name, age, city);

        }


Ở phương thức Search các tham số tùy chọn là age và city (có thể có hoặc không), và nó được đặt tên tương ứng với tên tham số.

Và đây là cách gọi phương thức Search

            // 1. Standard call

            Search("Sue", 22, "New York");

 

            // 2. Omit city parameter

            Search("Mark", 23);

 

            // 3. Explicitly name the city parameter

            Search("Lucy", city: "Cairo");

 

            // 4. Use named parameters in reverse order

            Search("Pedro", age: 45, city: "Saigon");


Lúc nào chúng ta cũng truyền vào name vì name không phải là optional parameter.
Giải thích các phương thức:

1. Cách gọi thông thường à không cần phải bàn.

2.Gọi phương thức Search mà không cần truyền vào tham số city à nó sẻ lấy default value là “Pueblo

3.Tường minh truyền vào tham số như vậy Cairo sẻ là giá trị của tham số city truyền vào cho phương thức.

4.Gọi phương thức mà không cần phải truyền đúng theo thứ tự của phương thức, giá trị của tham số sẻ tương ứng với tên phía trước nó.

Name = Sue - Age = 22 - City = New York

Name = Mark - Age = 23 - City = Pueblo

Name = Lucy - Age = 21 - City = Cairo

Name = Pedro - Age = 45 - City = Saigon

Nhấn F5, chúng ta sẻ có kết quả như trên.

Chú ý: optional parameter luôn luôn lúc nào cũng nào phía sau required parameter

Chúng ta sẻ bị lổi biên dịch khi

public static void Search(int age = 21, string city = "Pueblo",string name)


Regards,

 

Tags: , ,

.Net Framework | Visual Studio 2010

Applying an XSLT Transform to a DataSet

by Neon Quach 24. November 2009 04:45

The WriteXml method of the DataSet enables you to write the contents of a DataSet as XML data. A common task is to then transform that XML to another format using XSL Transformations (XSLT). However In .NET, the DataSet is synchronized with the XmlDataDocument which enables you to apply an XSLT stylesheet to the contents of a DataSet without having to first write the contents of the DataSet as XML data using WriteXml.

Let’s get started with small C# and VB.NET console application.

The following example uses a single XSLT stylesheet to transform the XML for the HumanResources.Contact table in the AdventureWorks database into HTML displaying the contact data in an HTML table.

<?xml version="1.0" encoding="utf-8"?>

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"

    xmlns:msxsl="urn:schemas-microsoft-com:xslt" exclude-result-prefixes="msxsl"

  <xsl:template match="/">

    <html>

      <STYLE>

        BODY {font-family:verdana;font-size:12px}

        TD   {font-size:10pt}

      </STYLE>

      <BODY>

        <TABLE BORDER="1">

          <tr bgcolor="#AAAAAA">

            <td>Contact ID</td>

            <td>Title</td>

            <td>First Name</td>

            <td>Last Name</td>

            <td>Email Address</td>

          </tr>

          <xsl:for-each select="/ContactDS/Contact">

            <tr>

              <td style="text-align:center">

                <xsl:value-of select="ContactID" />

              </td>

              <td style="text-align:center">

                <xsl:value-of select="Title" />

              </td>

              <td>

                <xsl:value-of select="FirstName" />

              </td>

              <td>

                <xsl:value-of select="LastName" />

              </td>

              <td>

                <xsl:value-of select="EmailAddress" />

              </td>

            </tr>

          </xsl:for-each>

 

        </TABLE>

      </BODY>

    </html>

  </xsl:template>

 

</xsl:stylesheet>


By creating a new style sheet file, named it to Contact.xslt and save it in the same directory as the project file.

[C#]
            string xsltContactFile = "../../Contact.xslt";

            string strConn = @"Data Source=.\sqlexpress;Initial Catalog=AdventureWorks;Persist Security Info=True;Integrated Security=True;";

            string strComm = "select top 10 ContactID,Title,FirstName,LastName, EmailAddress from Person.Contact";

            using (SqlConnection sqlConn = new SqlConnection(strConn))

            {

                SqlDataAdapter dap = new SqlDataAdapter(strComm, sqlConn);

                DataSet ds = new DataSet("ContactDS");

                dap.Fill(ds, "Contact");

                XmlDataDocument dataDoc = new XmlDataDocument(ds);

                XslCompiledTransform transform = new XslCompiledTransform();

                transform.Load(xsltContactFile);

                XmlTextWriter xmlWriter = new XmlTextWriter("../../Contact.html", Encoding.UTF8);

                transform.Transform(dataDoc,null,xmlWriter);

                xmlWriter.Close();
                Console.Write("DataSet transformed to HTML in file " + xsltContactFile + " Successful!");

                Console.Read();

            }

[VB.NET]
        Dim xsltContactFile As String = "../../Contact.xslt"

        Dim strConn As String = "Data Source=.\sqlexpress;Initial Catalog=AdventureWorks;Persist Security Info=True;Integrated Security=True;"

        Dim strComm As String = "select top 10 ContactID,Title,FirstName,LastName, EmailAddress from Person.Contact"

        Using sqlConn As New SqlConnection(strConn)

            Dim dap As New SqlDataAdapter(strComm, sqlConn)

            Dim ds As New DataSet("ContactDS")

            dap.Fill(ds, "Contact")

            Dim XmlDataDocument As New XmlDataDocument(ds)

            Dim transform As New XslCompiledTransform()

            transform.Load(xsltContactFile)

            Dim xmlWriter As New XmlTextWriter("../../Contact.html", System.Text.Encoding.UTF8)

            transform.Transform(XmlDataDocument, Nothing, xmlWriter)

            xmlWriter.Close()

            Console.Write("DataSet transformed to HTML in file " & xsltContactFile & " Successful!")

            Console.Read()

        End Using

To use XSLT to transform the contents of a DataSet, create an XslCompiledTransform object and call the Transform() method on that object.

This code above fills a DataSet with a several fields from the TOP 10 rows of the Person.Contact table in the AdventureWorks database. The style sheet Contact.xslt used to transform the DataSet into a HTML file named Contact.html written to the same directory of project file.

Press F5 then you can open Contact.html file you can see the result like:



Applying-an-XSLT-Transform-to-a-DataSet.rar (67.29 kb)

Tags: , , ,

.Net Framework | C# | VB.NET

Reading XML Data Directly from SQL Server

by Neon Quach 20. November 2009 18:46

SQL Server 2000 introduced support for retrieving data in XML format using the FOR XML clause. The .NET SQL Server data provider SqlCommand object has an ExecuteXmlReader() that allows you to retrieve an XML value directly from SQL Server. The method returns an XmlReader , which contains the XML value that is the result of the SQL query. The ExecuteXmlReader() method returns a single XML value and can only be used with SQL statements that return XML data: SQL statements with a FOR XML clause, ntext or nvarchar data type fields containing valid XML, or XML data type fields.

Now, start with creating an example with your favorite ASP.NET C# or VB.NET programming.
Using or import some namespace below:

C#
using System;

using System.Data;

using System.Data.SqlClient;

using System.Xml;
VB
Imports System.Data

Imports System.Data.SqlClient

Imports System.Xml

In this example, I get CustomerID, CompanyName and ContactName from Customers table in Northwind database.

C#
            string sqlConnectString = @"Data Source=.\sqlexpress;Initial Catalog=Northwind;Integrated Security=True;";

            string sqlSelect = "select CustomerID,CompanyName,ContactName from customers for xml auto, XMLDATA";

            DataSet ds = new DataSet();

            using (SqlConnection connection = new SqlConnection(sqlConnectString))

            {

                // Create the command.

                using (SqlCommand command = new SqlCommand(sqlSelect, connection))

                {

                    // Read the XML data into a XML reader.

                    connection.Open();

                    using (XmlReader xr = command.ExecuteXmlReader())

                    {

                        // Read the data from the XML reader into the DataTable.

                        ds.ReadXml(xr, XmlReadMode.Fragment);

                        xr.Close();

                    }

                }

            }

            foreach (DataRow rows in ds.Tables[0].Rows)

            {

                Response.Write(rows["CustomerID"].ToString() + "\t"

                    + "<b>" + rows["CompanyName"].ToString() + "</b>" + "\t"

                    + rows["ContactName"].ToString() + "</br>");

            }

        }

VB.NET
        Dim sqlConnectString As String = "Data Source=.\sqlexpress;Initial Catalog=Northwind;Integrated Security=True;"

        Dim sqlSelect As String = "select CustomerID,CompanyName,ContactName from customers for xml auto, XMLDATA"

        Dim ds As New DataSet()

        Using connection As New SqlConnection(sqlConnectString)

            ' Create the command.

            Using command As New SqlCommand(sqlSelect, connection)

                ' Read the XML data into a XML reader.

                connection.Open()

                Using xr As XmlReader = command.ExecuteXmlReader()

                    ' Read the data from the XML reader into the DataTable.

                    ds.ReadXml(xr, XmlReadMode.Fragment)

                    xr.Close()

                End Using

            End Using

        End Using

        For Each rows As DataRow In ds.Tables(0).Rows

            Response.Write(rows("CustomerID").ToString() + vbTab + "<b>" + rows("CompanyName").ToString() + "</b>" + vbTab + rows("ContactName").ToString() + "</br>")

        Next

Put above code on page load event, you will the result like:

ALFKI Alfreds Futterkiste Maria Anders
ANATR Ana Trujillo Emparedados y helados Ana Trujillo
ANTON Antonio Moreno Taquería Antonio Moreno
AROUT Around the Horn Thomas Hardy
…………………………….
AUTO: Returns query results in a simple, nested XML tree. Each table in the FROM clause for which at least one column is listed in the SELECT clause is represented as an XML element. The columns listed in the SELECT clause are mapped to the appropriate element attributes.

XMLDATA: Specifies that an inline XML-Data Reduced (XDR) schema should be returned. The schema is prepended to the document as an inline schema.
When System.Data.XmlReadMode is set to Fragment, which Reads XML fragments, such as those generated by executing FOR XML queries, against an instance of SQL Server. the default namespace is read as the inline schema.

For more information about the FOR XML clause, see Microsoft SQL Server Books Online.

Happy programming!

Reference: ADO.NET 3.5 CookBook, MSDN

Reading-XML-Data-Directly-from-SQL-Server.rar (6.57 kb)

Tags: , , ,

.Net Framework | ASP.NET | Visual Studio .NET | C# | VB.NET

Partial method new feature Net 3.0

by Neon Quach 4. May 2009 17:19

Nếu bạn đả từng làm việc trên dự án Window Form , trên nền NET FRAMEWORK 2.0 chắc hẳn các bạn từng nghe qua partial Classe, partial Classes cho phép chúng ta 1 phần của class ở 1 nơi và phần khác ở 1 nơi đâu đó, thường là 1 file khác, chẳng hạn như Form1.Designer.cs và Form1.cs.

Trong đó Form1.Designer.cs quản lý các khai báo, trong khi đó Form1.cs cho phép bạn viết code trên đó. Rỏ ràng ta thấy Form1.Designer.cs chứa sự khai báo partial method, và trong Form1.cs chứa phần còn lại của phương thức đó.

Partial method được định nghỉ trong partial class, nó cho phép bạn trình bày, và phần còn lại sẻ được thực thi ở 1 nơi khác.

Một số ràng buộc khi bạn sử dụng partial method :
1. Bạn phải dùng bổ từ truy cập là partial cho class và cho phương thức gốc.
(Phương thức gốc chỉ được định nghỉa)
2. Partial method có thể là Shared (VB) hoặc Static (C#).
3. Partial method cũng có thể có đối số là các từ khóa như : Ref hay params
4. Partial method phải là private.
5. Partial method phải chứa thủ tục con.
6. Partial method phải trả về kiểu void.

Đoạn mã mẩu sau đây sẻ giúp bạn hiểu hơn về partial method :













 Happy programming!

Tags:

.Net Framework

Powered by BlogEngine.NET 1.6.0.0 - Eco Theme by n3o Web Designers