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

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


Categories: net framework | visual studio 2010

Visual Studio 2010 RC is available

by Neon Quach 9. February 2010 01:07

Visual Studio 2010 RC is available

VS2010 RC is out now and available for MSDN users since now. Other guys have to wait until tomorrow when VS2010 RC is made publically available. Reading first news I discovered that most important thing is hardly improved performance of VS2010 RC IDE. All your feedback is welcome to VS2010 RC Connect site.

To find out more follow these links:

Before installing RC you must uninstall all previous versions of VS2010 and .NET Framework 4.0. It seems like another long nights of hacking and discovering new stuff are waiting for us. :)

Reference

Tags: , , ,


Categories: visual studio 2010

convert asp.net page to user control

by Neon Quach 31. January 2010 00:04

Nếu bạn muốn reuse lại các asp.net page bằng cách chuyển đổi chúng thành các user control, sau đó add chúng vào page để sử dụng thì các bước sau đây sẻ giúp bạn hòan thành việc đó.

Giả sử bạn có 1 asp.net page like this:

Đầu tiên chúng ta rename chúng lại thành ví dụ: default.aspx -> default.ascx, remove các thẻ: html, head, body, form, DOCTYPE. Sau đó đổi directive Page -> Control, remove tất cả các thuộc tính trên @Control directive trừ: Language, AutoEventWireup, CodeFile, Inherits.

Chuyển sang code behine chuyển thành kế thừa từ UserControl thay vì Page như hình sau:

Xong giờ có thể add user control này vào web form.

Reference

Tags: , , ,


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

Get Url from sitemap.xml using Linq2Xml

by Neon Quach 23. January 2010 18:35

Problem
You want to get url link from sitemap.xml file.

Solution:
After downloading sitemap.xml string from internet by using WebClient, you can easy get url link form it by using Linq2Xml.

Here is the snippets code both C# and VB.NET

For demo purpose I use Console application.

C#
using System;

using System.Linq;

using System.Net;

using System.Xml.Linq;

 

namespace CS

{

    class Program

    {

        static void Main(string[] args)

        {

            WebClient client = new WebClient();

            string sitemap = client.DownloadString("http://code2code.info/sitemap.xml");

            XElement element = XElement.Parse(sitemap);

            var e = from i in element.Elements()

                    select i.FirstNode;

            foreach (XNode item in e)

            {

                string url = ((XElement)(item)).Value;

                Console.WriteLine(url);

            }

            Console.Read();

        }

    }

}

VB.NET
Imports System.Net

Imports System.Linq

 

Module Module1

 

    Sub Main()

        Dim client As New WebClient

        Dim str As String = client.DownloadString("http://code2code.info/sitemap.xml")

        Dim element As XElement = XElement.Parse(str)

        Dim e = From i In element.Elements() _

            Select i.FirstNode

        For Each item As XNode In e

            Dim url As String = (DirectCast(item, XElement)).Value

            Console.WriteLine(url)

        Next

        Console.Read()

    End Sub

 

End Module


When you run this code, you will see the result like screenshot below

Don’t forget checkout my code at: http://code2code.googlecode.com

GetUrlFromSitemap.rar (62.55 kb)

Tags: , , ,


Categories: c# | vb.net

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


Categories: net framework | c# | vb.net

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