các thống kê hấp dẫn của .net framework 4

by Neon Quach 13. July 2010 04:13

Có đến 44.346 kiểu (được load từ 130 assemblies), trong đó có 33.152 lớp, 2.398 interfaces, 4.828 kiểu liệt kê (enum) và 3.968 kiểu cấu trúc.

Xem phân tích thống kê đầy đủ ở dưới đây:



Trong số 33.152 lớp có đến 564 là kiểu biệt lệ (exceptions) bao gồm 428 là public và 136 biệt lệ không public.



Reference

Tags:


Categories: net framework

việt hóa asp.net website sử dụng visual studio

by Neon Quach 12. June 2010 15:48

Xây dựng ứng dụng web đa ngôn ngữ hiện nay là 1 trong những công việc bình thường và phổ biến nhất hiện nay, trong bài blog này mình sẻ hướng dẫn các cách có thể việt hóa 1 cách để dàng 1 asp.net website sử dụng Resource được build in sẵn trong visual studio.

Trong visual studio có 2 dạng resource: App_GlobalResources và App_LocalResources, tên gọi khác nhau nên cách sử dụng cũng khác nhau

App_GlobalResources: resource file được dùng cho toàn bộ website.
App_LocalResources: resource file cục bộ, phạm vi sử dụng trong 1 trang hoặc 1 user control.

Bắt đầu bằng việc tạo mới 1 website (blank website - ở đây mình sử dụng visual studio 2010)

Add new Item: default.aspx Page, folder App_GlobalResources, sau đó add 1 file resource với tên code2code.resx



Add 1 text resource mới cho code2code.resource name là hello và value là Hello world



Từ trang default.aspx add 1 label mới

<asp:Label ID="lblHello" runat="server" Text="<%$ Resources:code2code, hello%>"></asp:Label>

code behine:


lblHello.Text = (string)GetGlobalResourceObject("code2code", "hello");

Để có thể thấy được sự thay đổi chúng ta modify trong web.config như sau:

<globalization culture="vi-vn" uiCulture="vi-vn"/>


Chúng ta cũng có thể thiết lập bằng cách lập trình.

Đối với file việc việt hóa bằng App_LocalResources, chúng tiến hành thêm mới 1 trong login.aspx chẳng hạn, thêm 2 lable username, password, và 2 textboxes như hình sau:



Sau đó tiến hành generate ra file resource bằng cách chọn Tools → Generate Local Resource



Sau đó visual studio sẻ tự thêm 1 folder App_LocalResources và bên trong chứa file login.aspx.resx, mục đích cho việc việt hóa dành cho trang login.aspx, và visual studio sẻ tự động thêm code binding resource cho các text:

    <div>

        <p>

            <asp:Label ID="lblUsername" runat="server" Text="Username:" meta:resourcekey="lblUsernameResource1"></asp:Label>

            <asp:TextBox ID="txtUsername" runat="server" meta:resourcekey="txtUsernameResource1"></asp:TextBox></p>

        <p>

            <asp:Label ID="lblPassword" runat="server" Text="Password:" meta:resourcekey="lblPasswordResource1"></asp:Label>

            <asp:TextBox ID="txtPassword" runat="server" meta:resourcekey="txtPasswordResource1"></asp:TextBox></p>

    </div>

 

Mở file login.aspx.resx ta thấy chúng chứa tất cả những text cần thiết cho việc localize, tương tự như App_GlobalResources chúng ta cũng sẻ phải thêm mới 1 file resource cho ngôn ngữ tiếng Việt, bằng cách thêm 1 file resource với tên là: login.aspx.vi-vn.resx, sau đó thay đổi nội dung bằng tiếng Việt.

Và đây code behind giải quyết cho việc binding local resource cho trang login.aspx

lblUsername.Text = (string)GetLocalResourceObject("lblUsernameResource1.Text");


Tóm lại: làm bằng cách nào đi chăng nữa thì localize bằng các file resource built-in trong visual studio cũng là cách đơn giản nhất, nhanh nhất và hiệu quả nhất.

Hope this help!

Localization.rar (12.04 kb)

Tags: , , ,


Categories: asp.net | net framework | visual studio 2010 | c#

chuyển đổi datetime từ timezone này sang timezone khác trong .net

by Neon Quach 23. May 2010 17:58

Time là 1 vấn đề yêu cầu chung của các ứng dụng hiện nay, chẳng hạn như khi bạn develop ứng dụng cho Netherlands liên quan đến thời gian hiển thị trên website trên mấy với timezone khác (GMT+07:00) Bangkok, Hanoi, Jakarta) chẳng hạn, đó là vấn đề thường xảy ra, may thay .Net hổ trợ chúng ta việc chuyển đổi qua lại dự trên TimeZone ID.

C# Snippet code

DateTime
now = DateTime.Now;
Console
.WriteLine(TimeZoneInfo.ConvertTimeBySystemTimeZoneId(now, "SE Asia Standard Time").ToString("yyyy-MM-dd HH-mm-ss"));
Console
.Read();

 


VB.NET Snippet code

Dim
now As DateTime = DateTime.Now
Console.WriteLine(TimeZoneInfo.ConvertTimeBySystemTimeZoneId(now, "SE Asia Standard Time").ToString("yyyy-MM-dd HH-mm-ss"))
Console
.Read()

Và đây là danh sách các timezone ID được .net support

 

Time Zone ID

Time Zone Display Name

Morocco Standard Time

(GMT) Casablanca

GMT Standard Time

(GMT) Greenwich Mean Time : Dublin, Edinburgh, Lisbon, London

Greenwich Standard Time

(GMT) Monrovia, Reykjavik

W. Europe Standard Time

(GMT+01:00) Amsterdam, Berlin, Bern, Rome, Stockholm, Vienna

Central Europe Standard Time

(GMT+01:00) Belgrade, Bratislava, Budapest, Ljubljana, Prague

Romance Standard Time

(GMT+01:00) Brussels, Copenhagen, Madrid, Paris

Central European Standard Time

(GMT+01:00) Sarajevo, Skopje, Warsaw, Zagreb

W. Central Africa Standard Time

(GMT+01:00) West Central Africa

Jordan Standard Time

(GMT+02:00) Amman

GTB Standard Time

(GMT+02:00) Athens, Bucharest, Istanbul

Middle East Standard Time

(GMT+02:00) Beirut

Egypt Standard Time

(GMT+02:00) Cairo

South Africa Standard Time

(GMT+02:00) Harare, Pretoria

FLE Standard Time

(GMT+02:00) Helsinki, Kyiv, Riga, Sofia, Tallinn, Vilnius

Israel Standard Time

(GMT+02:00) Jerusalem

E. Europe Standard Time

(GMT+02:00) Minsk

Namibia Standard Time

(GMT+02:00) Windhoek

Arabic Standard Time

(GMT+03:00) Baghdad

Arab Standard Time

(GMT+03:00) Kuwait, Riyadh

Russian Standard Time

(GMT+03:00) Moscow, St. Petersburg, Volgograd

E. Africa Standard Time

(GMT+03:00) Nairobi

Georgian Standard Time

(GMT+03:00) Tbilisi

Iran Standard Time

(GMT+03:30) Tehran

Arabian Standard Time

(GMT+04:00) Abu Dhabi, Muscat

Azerbaijan Standard Time

(GMT+04:00) Baku

Mauritius Standard Time

(GMT+04:00) Port Louis

Caucasus Standard Time

(GMT+04:00) Yerevan

Afghanistan Standard Time

(GMT+04:30) Kabul

Ekaterinburg Standard Time

(GMT+05:00) Ekaterinburg

Pakistan Standard Time

(GMT+05:00) Islamabad, Karachi

West Asia Standard Time

(GMT+05:00) Tashkent

India Standard Time

(GMT+05:30) Chennai, Kolkata, Mumbai, New Delhi

Sri Lanka Standard Time

(GMT+05:30) Sri Jayawardenepura

Nepal Standard Time

(GMT+05:45) Kathmandu

N. Central Asia Standard Time

(GMT+06:00) Almaty, Novosibirsk

Central Asia Standard Time

(GMT+06:00) Astana, Dhaka

Myanmar Standard Time

(GMT+06:30) Yangon (Rangoon)

SE Asia Standard Time

(GMT+07:00) Bangkok, Hanoi, Jakarta

North Asia Standard Time

(GMT+07:00) Krasnoyarsk

China Standard Time

(GMT+08:00) Beijing, Chongqing, Hong Kong, Urumqi

North Asia East Standard Time

(GMT+08:00) Irkutsk, Ulaan Bataar

Singapore Standard Time

(GMT+08:00) Kuala Lumpur, Singapore

W. Australia Standard Time

(GMT+08:00) Perth

Taipei Standard Time

(GMT+08:00) Taipei

Tokyo Standard Time

(GMT+09:00) Osaka, Sapporo, Tokyo

Korea Standard Time

(GMT+09:00) Seoul

Yakutsk Standard Time

(GMT+09:00) Yakutsk

Cen. Australia Standard Time

(GMT+09:30) Adelaide

AUS Central Standard Time

(GMT+09:30) Darwin

E. Australia Standard Time

(GMT+10:00) Brisbane

AUS Eastern Standard Time

(GMT+10:00) Canberra, Melbourne, Sydney

West Pacific Standard Time

(GMT+10:00) Guam, Port Moresby

Tasmania Standard Time

(GMT+10:00) Hobart

Vladivostok Standard Time

(GMT+10:00) Vladivostok

Central Pacific Standard Time

(GMT+11:00) Magadan, Solomon Is., New Caledonia

New Zealand Standard Time

(GMT+12:00) Auckland, Wellington

Fiji Standard Time

(GMT+12:00) Fiji, Kamchatka, Marshall Is.

Tonga Standard Time

(GMT+13:00) Nuku'alofa

Azores Standard Time

(GMT-01:00) Azores

Cape Verde Standard Time

(GMT-01:00) Cape Verde Is.

Mid-Atlantic Standard Time

(GMT-02:00) Mid-Atlantic

E. South America Standard Time

(GMT-03:00) Brasilia

Argentina Standard Time

(GMT-03:00) Buenos Aires

SA Eastern Standard Time

(GMT-03:00) Georgetown

Greenland Standard Time

(GMT-03:00) Greenland

Montevideo Standard Time

(GMT-03:00) Montevideo

Newfoundland Standard Time

(GMT-03:30) Newfoundland

Atlantic Standard Time

(GMT-04:00) Atlantic Time (Canada)

SA Western Standard Time

(GMT-04:00) La Paz

Central Brazilian Standard Time

(GMT-04:00) Manaus

Pacific SA Standard Time

(GMT-04:00) Santiago

Venezuela Standard Time

(GMT-04:30) Caracas

SA Pacific Standard Time

(GMT-05:00) Bogota, Lima, Quito, Rio Branco

Eastern Standard Time

(GMT-05:00) Eastern Time (US & Canada)

US Eastern Standard Time

(GMT-05:00) Indiana (East)

Central America Standard Time

(GMT-06:00) Central America

Central Standard Time

(GMT-06:00) Central Time (US & Canada)

Central Standard Time (Mexico)

(GMT-06:00) Guadalajara, Mexico City, Monterrey

Canada Central Standard Time

(GMT-06:00) Saskatchewan

US Mountain Standard Time

(GMT-07:00) Arizona

Mountain Standard Time (Mexico)

(GMT-07:00) Chihuahua, La Paz, Mazatlan

Mountain Standard Time

(GMT-07:00) Mountain Time (US & Canada)

Pacific Standard Time

(GMT-08:00) Pacific Time (US & Canada)

Pacific Standard Time (Mexico)

(GMT-08:00) Tijuana, Baja California

Alaskan Standard Time

(GMT-09:00) Alaska

Hawaiian Standard Time

(GMT-10:00) Hawaii

Samoa Standard Time

(GMT-11:00) Midway Island, Samoa

Dateline Standard Time

(GMT-12:00) International Date Line West

Refereence

Tags: , ,


Categories: net framework | c# | vb.net

send email với attachment

by Neon Quach 9. April 2010 02:42

Ở bài viết trước Gửi Email động trong ASP.NET chúng ta đả được làm quen với đối tượng MailMessage và 1 số thuộc tính quan trong của nó trong việc gửi email.

Giờ chúng ta sẻ làm quen với việc làm thế nào để đính kèm tập tin khi send mail.

Tại source code tại: http://code2code.info/post/send-dynamic-email-in-aspnet.aspx và thêm mới 1 section bao gồm 1 nhãn named là Đính kèm và 1 FileUpload control.

            <tr>

                <td>Đính kèm:</td>

                <td>

                    <asp:FileUpload ID="FileUpload1" runat="server" Width="250px" />

                </td>

            </tr>
Chỉnh sửa 1 tí về cấu hình smtp, mình sẻ send mail dùng stmp của google, vì có rất nhiều bạn send mail và message cho mình nhờ giúp đở về việc send email sử dụng mail server của google.

  <system.net>

    <mailSettings>

      <smtp>

        <network host="smtp.gmail.com" port="587" userName="quachngochoangnguyen@gmail.com" password="your password"/>

      </smtp>

    </mailSettings>

  </system.net>

Ở đây mình cũng sẻ nói thêm luôn là nếu send mail thông qua mail server của google thì chúng ta sẻ phải enable SSL của đối tượng SmtpClient.

Chúng ta sẻ chỉnh sửa hàm SendMail để nhận đính kèm:

C#:
                if (FileUpload1.HasFile)

                {

                    mail.Attachments.Add(new Attachment(FileUpload1.PostedFile.InputStream, FileUpload1.FileName));

                }

                client.Send(mail);
VB:
                client.EnableSsl = isSSL

                If FileUpload1.HasFile Then

                    mail.Attachments.Add(New Attachment(FileUpload1.PostedFile.InputStream, FileUpload1.FileName))

                End If

                client.Send(mail)
Constructor của Attachment nhận vào 2 tham số bao gồm: nội dụng dạng Stream của file, và tên file, Press F5 lên và tiến hành send mail có đính kèm:



và kết quả:


Hope this help
Check out my code:http://code2code.googlecode.com/svn/trunk/SendingDynamicEmailWithAttachment

SendingDynamicEmailWithAttachment.rar (8.38 kb)

Tags: , ,


Categories: asp.net | net framework | c#

asp.net role membership provider phần 2

by Neon Quach 7. April 2010 02:34

Đây là bài viết nằm trong tập bài viết về asp.net role membership.
asp.net role membership provider phần 1

Trong phần 1 chúng ta đả làm quen với việc tạo asp.net membership database, trong phần 2 này chúng ta sẻ bắt đầu việc tạo user, login, logout và display user sau khi login thành công.

Vì do chúng ta đả tạo membership database trước nên bước đầu tiên chúng ta phải cấu hình connection string và membership.

  <connectionStrings>

    <add name="aspnetdbcon" connectionString="Data Source=localhost\sqlexpress;Initial Catalog=aspnetdb;uid=sa;pwd=111111"/>

  </connectionStrings>

Cấu hình chế độ chứng thực:

    <authentication mode="Forms">

      <forms loginUrl="~/login.aspx" timeout="2880"/>

    </authentication>

Config membership:

    <membership>

      <providers>

        <clear/>

        <add name="AspNetSqlMembershipProvider" type="System.Web.Security.SqlMembershipProvider, System.Web, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" connectionStringName="aspnetdbcon" enablePasswordRetrieval="false" enablePasswordReset="true" requiresQuestionAndAnswer="false" requiresUniqueEmail="false" passwordFormat="Hashed" maxInvalidPasswordAttempts="5" minRequiredPasswordLength="6" minRequiredNonalphanumericCharacters="0" passwordAttemptWindow="10" passwordStrengthRegularExpression="" applicationName="/"/>

      </providers>

    </membership>

Trong đó:

connectionStringName: tên của connection string (string)

enablePasswordRetrieval: Có hổ trợ chức năng nhận lại password (true/false)
enablePasswordReset: Cho phép reset password (true/false)
requiresQuestionAndAnswer: Có buộc nhập câu hỏi và câu trả lời bảo mật hay không
requiresUniqueEmail: Có bắt buộc 1 địa chỉ email cho 1 user hay không?
passwordFormat: Định dạng của password (Hashed, SHA1, Clear)
maxInvalidPasswordAttempts: Số lượng cho phép nhập sai password, ví dụ = 5, thì sau 5 lần đăng nhập thất bại, user phải đợi tới 15’ sau mới có thể đăng nhập lại.
minRequiredPasswordLength: Số lượng tối đa của mật khẩu

minRequiredNonalphanumericCharacters: Số lượng ký tự đặc biệt cho phép.
passwordAttemptWindow: Mặc định là 10’ là khoảng cách giửa lần đăng nhập thất bại đầu tiên và lần cuối cùng, nếu lớn hơn 10’ thì user sẻ bị log.
passwordStrengthRegularExpression: Expression cho password.
applicationName: Tên của ứng dụng (default là root /)


Bắt đầu tạo user

Từ version 2.0 trở đi thì ASP.NET cung cấp 1 số control cho việc tạo user, đăng nhập, quên mật khẩu, thay đổi mật khẩu (Create User Wizard, Login, ChangePassword…)

Để cho phép tạo mới user, chúng ta add 1 page mới và đặt tên là createuser.aspx và kéo control CreateUserWizard vào set thuộc tính ContinueDestinationPageUrl="~/login.aspx"

        <asp:CreateUserWizard ID="CreateUserWizard1" runat="server"

 

            ContinueDestinationPageUrl="~/login.aspx">

            <WizardSteps>

                <asp:CreateUserWizardStep ID="CreateUserWizardStep1" runat="server">

                </asp:CreateUserWizardStep>

                <asp:CompleteWizardStep ID="CompleteWizardStep1" runat="server">

                </asp:CompleteWizardStep>

            </WizardSteps>

        </asp:CreateUserWizard>

Ở màng hình create user wizard, chúng ta không thấy textbox nhập câu hỏi bảo mật và câu trả vì trong file web.config chúng ta không enable nó requiresQuestionAndAnswer="false". Sau khi create user xong chúng ta nhấn Continue chúng ta sẻ được chuyển sang trang login, nơi mà ta sẻ thực thi chức năng đăng nhập.

Tạo trang login.aspx và kéo Login control, ở đây tình huống là khi user chưa đăng nhập thì chúng ta hiển thị login control, ngược lại nếu user đả đăng nhập rồi và quay lại trang login thì chúng ta hiển thị message welcome + name chẳng hạn.

Chúng ta có thể để dàng làm được nhờ vào LoginView control, Click vào smart tag của LoginView chúng ta có thể thấy 2 template: AnonymousTemplate và  LoggedInTemplate.

 


Ở mode AnonymousTemplate chúng ta thêm Login control và ở mode LoggedInTemplate chúng ta thêm loginstatus và loginname, loginstatus là control sẻ hiển thị trạng thái của user đả login hay chưa, nếu login rồi thì nó sẻ hiển thị logout, và ngược lại, còn loginname nó sẻ hiển thị tên của user hiện tại login.

History version: 2010-04-07 02:34 first release

Tags: , , , ,


Categories: asp.net | net framework | open source | vs .net

Phân biệt HOA thường với StringComparer.OrdinalIgnoreCase

by Neon Quach 1. April 2010 03:24

Nếu bạn so sánh 1 chuổi nào đó có trong mãng các ký tự hay không, nhưng phất lờ việc phân biệt Hoa thường, thì đây sẻ là cách

 

using System;

using System.Linq;

 

namespace CS

{

    class Program

    {

        static void Main(string[] args)

        {

            string[] name = { "NeonQuach", "QuachNguyen" };

            if (name.Contains("neonquach",StringComparer.OrdinalIgnoreCase))

            {

                Console.WriteLine("compare with no case-sensitive, neonquach exits in name array");

            }

            else if (name.Contains("neonquach"))

            {

                Console.WriteLine("compare with case-sensitive");

            }

            Console.Read();

        }

    }

}


VB.NET
Module Module1

 

    Sub Main()

        Dim name As String() = {"NeonQuach", "QuachNguyen"}

        If name.Contains("neonquach", StringComparer.OrdinalIgnoreCase) Then

            Console.WriteLine("compare with no case-sensitive, neonquach exits in name array")

        ElseIf name.Contains("neonquach") Then

            Console.WriteLine("compare with case-sensitive")

        End If

        Console.Read()

    End Sub

 

End Module


Mặc định nếu không có StringComparer.OrdinalIgnoreCase thì chuổi chúng ta đem đi so sánh nó phân biệt Hoa thường

http://code2code.googlecode.com/svn/trunk/StringComparerOrdinalIgnoreCase

Tags: , ,


Categories: net framework | c# | vb.net

Employee Info Starter Kit v4.0.0

by Neon Quach 27. March 2010 16:35

Employee Info Starter Kit is a ASP.NET based web application, which includes very simple user requirements, where we can create, read, update and delete (crud) the employee info of a company. Based on just a database table, it explores and solves most of the major problems in web development architectural space. 

This open source starter kit extensively uses major features available in latest Visual Studio, ASP.NET and Sql Server to make robust, scalable, secured and maintainable web applications quickly and easily.

Since it's first release, this starter kit achieved a huge popularity in web developer community and includes 1,50,000+ downloads from project web site.

Visual Studio 2010 and .NET 4.0 came up with lots of exciting features to make software developers life easier.  A new version (v4.0.0) of Employee Info Starter Kit is now available in both MSDN Code Gallery and CodePlex. Checkout the latest version of this starter kit to enjoy cool features available in Visual Studio 2010 and .NET 4.0.


[ Release Notes ]

Architectural Overview

  • Simple 2 layer architecture (user interface and data access layer) with 1 optional cache layer
  • ASP.NET Web Form based user interface
  • Custom Entity Data Container implemented (with primitive C# types for data fields)
  • Active Record Design Pattern based Data Access Layer, implemented in C# and Entity Framework 4.0
  • Sql Server Stored Procedure to perform actual CRUD operation
  • Standard infrastructure (architecture, helper utility) for automated integration (bottom up manner) and unit testing

Technology Utilized

Programming Languages/Scripts

  • Browser side: JavaScript
  • Web server side: C# 4.0
  • Database server side: T-SQL

.NET Framework Components

  • .NET 4.0 Entity Framework
  • .NET 4.0 Optional/Named Parameters
  • .NET 4.0 Tuple
  • .NET 3.0+ Extension Method
  • .NET 3.0+ Lambda Expressions
  • .NET 3.0+ Anonymous Type
  • .NET 3.0+ Query Expressions
  • .NET 3.0+ Automatically Implemented Properties
  • .NET 3.0+ LINQ
  • .NET 2.0 + Partial Classes
  • .NET 2.0+ Generic Type
  • .NET 2.0+ Nullable Type
  • ASP.NET 3.5+ List View (TBD)
  • ASP.NET 3.5+ Data Pager (TBD)
  • ASP.NET 2.0+ Grid View
  • ASP.NET 2.0+ Form View
  • ASP.NET 2.0+ Skin
  • ASP.NET 2.0+ Theme
  • ASP.NET 2.0+ Master Page
  • ASP.NET 2.0+ Object Data Source
  • ASP.NET 1.0+ Role Based Security

Visual Studio Features

  • Visual Studio 2010 CodedUI Test
  • Visual Studio 2010 Layer Diagram
  • Visual Studio 2010 Sequence Diagram
  • Visual Studio 2010 Directed Graph
  • Visual Studio 2005+ Database Unit Test
  • Visual Studio 2005+ Unit Test
  • Visual Studio 2005+ Web Test
  • Visual Studio 2005+ Load Test

Sql Server Features

  • Sql Server 2005 Stored Procedure
  • Sql Server 2005 Xml type
  • Sql Server 2005 Paging support

Reference

Tags: , , ,


Categories: net framework | asp.net | vs .net | vb.net | visual studio 2010

Page RedirectPermanent trong asp.net 4.0

by Neon Quach 23. March 2010 02:26

ASP.NET 4.0 giới thiệu 1 phương thức của đối tượng Redirect, giúp cho search engine nhận biết rằng đây là redirect permanent có status code là 301.



Response.RedirectPermanent("~/About.aspx");


Cách sử dụng cũng y chang như Response.Redirect,chỉ có 1 điểm khác biệt ở đâu là status code 301 thay vì 302, cũng tương đương như phương thức sau:

    public static void RedirectPermanent(this HttpResponseBase response, string url)

    {

        response.StatusCode = 301;

        response.Status = "301 Moved Permanently";

        response.RedirectLocation = url;

        response.End();

    }

Có 1 tình huống cho rằng website của bạn có 1 trang Abouts.aspx, và giờ bạn muốn chuyển sang About.aspx, nếu bạn dùng Response.RedirectPermanent như bên trên thì page rank hay page index của trang About sẻ không bị mất đi và search engine sẻ cập nhật lại link trong database của nó.

Tags: , ,


Categories: net framework | asp.net

CRUD với Linq2Xml sử dụng XElement

by Neon Quach 20. March 2010 22:48

Không có 1 thông tin chính thức từ Microsoft về sự thay thế của Linq2Xml cho XDocument  về việc thao tác với tài liệu Xml, trong bài blog này mình sẽ hướng dẫn các bạn các tác vụ cơ bản CRUD (create, retrieve, update, và delete) với Linq2Xml sử dụng XElement object.

Mình sẽ sử dụng Gridview vì nó support Edit và Delete xây dựng sẵn, và dùng gridview để hiển thị danh sách các elements.

Sử dụng Visual Studio tạo 1 website mới C# code.

Tạo dữ liệu xml với schema và data như sau:

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

<contacts>

  <contact id="f02c78b4956f4b2f9ecfb7a5bfbcfbf6" name="quachnguyen" email="quachnguyen@gmail.com"></contact>

  <contact id="f02c78b4956f4b2f0ecfb7a5bfbcfbf6" name="neonquach" email="neonquach@gmail.com"></contact>

  <contact id="f02c87b4956f4b2f9ecfb7a5bfbcfbf6" name="code2code" email="admin@code2code.info"></contact>

</contacts>

Mình save với tên là contact.xml và lưu trong App_Data.

Từ toolbox kéo gridview vào Visual Designer, set các thuộc tính như sau:

AutoGenerateColumns="False"
AutoGenerateDeleteButton="True"
AutoGenerateEditButton="True"
DataKeyNames="id"

Tiến hành add thêm 2 cột cho gridview và bind 2 thuộc tính name và email và markup language cho gridview như sau:

        <asp:GridView ID="grdContact" runat="server" AutoGenerateColumns="False" AutoGenerateDeleteButton="True"

            AutoGenerateEditButton="True" OnRowCancelingEdit="grdContact_RowCancelingEdit"

            OnRowDeleting="grdContact_RowDeleting" OnRowEditing="grdContact_RowEditing" OnRowUpdating="grdContact_RowUpdating"

            DataKeyNames="id">

            <Columns>

                <asp:TemplateField HeaderText="Name">

                    <EditItemTemplate>

                        <asp:TextBox ID="txtName" runat="server" Text='<%# Bind("name") %>'></asp:TextBox>

                    </EditItemTemplate>

                    <ItemTemplate>

                        <asp:Label ID="lblName" runat="server" Text='<%# Bind("name") %>'></asp:Label>

                    </ItemTemplate>

                </asp:TemplateField>

                <asp:TemplateField HeaderText="Email">

                    <EditItemTemplate>

                        <asp:TextBox ID="txtEmail" runat="server" Text='<%# Bind("email") %>'></asp:TextBox>

                    </EditItemTemplate>

                    <ItemTemplate>

                        <asp:Label ID="lblEmail" runat="server" Text='<%# Bind("email") %>'></asp:Label>

                    </ItemTemplate>

                </asp:TemplateField>

            </Columns>

        </asp:GridView>

Như chúng ta đả thấy gridview contact của chúng ta có 1 số sự kiện như:

OnRowCancelingEdit, OnRowUpdating, OnRowDeleting, OnRowCancelingEdit

Add new, chúng ta thêm 2 textbox, 2 label và 1 button, markup như sau:

    <asp:Label ID="lblName" runat="server" Text="Name:"></asp:Label>

    &nbsp;<asp:TextBox ID="txtUserName" runat="server"></asp:TextBox></p>

<p>

    <asp:Label ID="Label2" runat="server" Text="Email: "></asp:Label>

    &nbsp;<asp:TextBox ID="txtEmailAdress" runat="server"></asp:TextBox>

<p />

<asp:Button ID="btnAdd" runat="server" Text="Add" onclick="btnAdd_Click" />




Tiến hành viết 1 hàm load tất cả các danh sách contact như sau:

    public void LoadContacts()

    {

        string filePath = Server.MapPath("~/App_Data/contact.xml");

        XElement Contacts = XElement.Load(filePath);

        if (Contacts != null)

        {

            var query = from c in Contacts.Elements("contact")

                        select new

                        {

                            Id = (string)c.Attribute("id").Value,

                            Name = c.Attribute("name").Value,

                            Email = c.Attribute("email").Value

                        };

            grdContact.DataSource = query.ToList();

            grdContact.DataBind();

        }

    }

Load danh sách trong sự kiện Page_Load()

 

    protected void Page_Load(object sender, EventArgs e)

    {

        if (!IsPostBack)

        {

            LoadContacts();

        }

    }

Nhấn F5, chúng ta sẻ thấy màng hình như sau:



Thêm mới 1 contact, double click vào button add và paste đoạn code sau vào:

    protected void btnAdd_Click(object sender, EventArgs e)

    {

        string name = txtUserName.Text.Trim();

        string email = txtEmailAdress.Text.Trim();

        string FilePath = Server.MapPath("~/App_Data/contact.xml");

        XDocument doc = XDocument.Load(FilePath);

        IEnumerable<XElement> contacts = doc.Element("contacts").Elements("contact");

        var contact = new XElement("contact",

            new XAttribute("id", Guid.NewGuid().ToString().Replace("-","")),

            new XAttribute("name", name),

            new XAttribute("email",email));

        contacts.Last().AddAfterSelf(contact);

        doc.Save(FilePath);

        LoadContacts();

        txtUserName.Text = txtEmailAdress.Text = "";

    }

Chúng ta sẽ add vào thứ cuối cùng của danh sách với:

contacts.Last().AddAfterSelf(contact);

Sau khi add thành công chúng ta tiến hành Load lại danh sách để xem sự thay đổi và clear tất cả các textboxes để tiếp tục thêm 1 contact mới.

Delete 1 contact:

    protected void grdContact_RowDeleting(object sender, System.Web.UI.WebControls.GridViewDeleteEventArgs e)

    {

        string FilePath = Server.MapPath("~/App_Data/contact.xml");

        string contactId = (string)grdContact.DataKeys[e.RowIndex].Value;

        XElement element = XElement.Load(FilePath);

        var query = (from c in element.Descendants("contact")

                    where c.Attribute("id").Value == contactId

                    select c).Single();

        if (query != null)

        {

            query.Remove();

            element.Save(FilePath);

        }

        LoadContacts();

    }

Để delete thì chúng ta phải biết chính xác record nào chúng ta delete, string contactId = (string)grdContact.DataKeys[e.RowIndex].Value; sau đó chúng ta query trong danh sách với id là giá trị record mà ta nhấn delete.

Sau khi delete xong, chúng ta load lại danh sách để xem sự thay đổi.

Chỉnh sửa 1 contact:

khi user click vào link edit bắt đầu chỉnh sửa 1 contact

    protected void grdContact_RowEditing(object sender, System.Web.UI.WebControls.GridViewEditEventArgs e)

    {

        grdContact.EditIndex = e.NewEditIndex;

        LoadContacts();

    }

Không loại trừ trường hợp user cancel việc edit của mình:

    protected void grdContact_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)

    {

        grdContact.EditIndex = -1;

        LoadContacts();

    }

Một khi user hài lòng với thông tin mới của mình và click vào hyperlink update:

    protected void grdContact_RowUpdating(object sender, System.Web.UI.WebControls.GridViewUpdateEventArgs e)

    {

        string contactId = (string)grdContact.DataKeys[e.RowIndex].Value;

        string FilePath = Server.MapPath("~/App_Data/contact.xml");

 

        string name = (grdContact.Rows[e.RowIndex].FindControl("txtName") as TextBox).Text.Trim();

        string email = (grdContact.Rows[e.RowIndex].FindControl("txtEmail") as TextBox).Text.Trim();

 

        XDocument doc = XDocument.Load(FilePath);

        IEnumerable<XElement> contacts = doc.Element("contacts").Elements("contact");

        var contact = (from c in contacts

                       where c.Attribute("id").Value.Equals(contactId) == true

                       select c).SingleOrDefault();

        contact.SetAttributeValue("name", name);

        contact.SetAttributeValue("email", email);

        doc.Save(FilePath);

        LoadContacts();

    }


Các bạn có thể check out source code ta: http://code2code.googlecode.com/svn/trunk/CRUDLinq2Xml

 

Tags: , , ,


Categories: asp.net | linq | linq2xml | net framework | c#

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: , , ,


Categories: asp.net | net framework | c# | vb.net

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