Giảm kích thước CSS StyleSheet Using .Net

by Neon Quach 3. March 2010 02:15

Giảm khoảng 5% kích thước CSS làm cho tốc độ load CS Strong trang web giảm đáng kể

public static string RemoveWhiteSpaceFromStylesheets(string body)

{

    body = Regex.Replace(body, @"[a-zA-Z]+#", "#"); // ul#

    body = Regex.Replace(body, @"[\n\r]+\s*", string.Empty); // space

    body = Regex.Replace(body, @"\s+", " ");

    body = Regex.Replace(body, @"\s?([:,;{}])\s?", "$1");

    body = body.Replace(";}", "}");

    body = Regex.Replace(body, @"([\s:]0)(px|pt|%|em)", "$1");

    // Remove comments from CSS

    body = Regex.Replace(body, @"/\*[\d\D]*?\*/", string.Empty);

    return body;

}

static void Main(string[] args)

{

    string minstyle = RemoveWhiteSpaceFromStylesheets(File.ReadAllText(@"..\..\style.css"));

    File.WriteAllText(@"..\..\style-min.css", minstyle);

    Console.WriteLine("Done!");

    Console.Read();

}

VB.NET

Imports System.IO

Imports System.Text.RegularExpressions

 

Module MinCSS

 

    Sub Main()

        Dim minstyle As String = RemoveWhiteSpaceFromStylesheets(File.ReadAllText("..\..\style.css"))

        File.WriteAllText("..\..\style-min.css", minstyle)

        Console.Write("Done!")

        Console.Read()

    End Sub

 

    Public Function RemoveWhiteSpaceFromStylesheets(ByVal body As String) As String

        body = Regex.Replace(body, "[a-zA-Z]+#", "#")

        body = Regex.Replace(body, "[\n\r]+\s*", String.Empty)

        body = Regex.Replace(body, "\s+", " ")

        body = Regex.Replace(body, "\s?([:,;{}])\s?", "$1")

        body = body.Replace(";}", "}")

        body = Regex.Replace(body, "([\s:]0)(px|pt|%|em)", "$1")

        ' Remove comments from CSS

        body = Regex.Replace(body, "/\*[\d\D]*?\*/", String.Empty)

        Return body

    End Function

 

End Module


Press F5 chúng ta sẻ có 1 file style-min.css với kích thước nhỏ hơn so với file gốc.

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

Reference

MinimizeCSS.rar (75.41 kb)

Tags: , ,

C# | VB.NET

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

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

C# | VB.NET

ASP.NET Role Membership Provider phần I

by Neon Quach 21. January 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

Hướng dẫn cài đặt DotNetNuke trên localhost

by Neon Quach 8. January 2010 23:52

DotNetNuke (DNN) phần mềm mã nguồn mở viết bằng ASP.NET (VB code), dễ dàng cài đặt, hổ trợ module, big community support, ổn định… Hôm nay mình sẻ hướng dẫn mọi người cách cài đặt DNN trên localhost và các bài viết tiếp theo mình sẻ hướng dẫn mọi người cách viết module..

Download source code:
Hiện nay DNN có 2 version: community(free) và professional , bài viết này giới thiệu cách cài đặt phiên bản DNN community.

Tải mã nguồn miễn phí tại:
đây
Sau khi download source code về, tiến hành giải nén và open website (thư mục Website), không cần load tất cả các thư viện.

Chú ý: chúng ta có thể cài mà không cần Visual Studio, nhưng phải cần IIS.

Bước 1: setup DNN database sử dụng sql server 2005 or latest.
Bước 2: Thay đổi tên tập tin release.config thành Web.config.
Bước 3: Thay đổi connection string trỏ đến database đả tạo ở bước 1.



h1: chuổi kết nối trước khi trỏ đến database được tạo ở b1.



h2: chuổi kết nối đả được config.

Bước 4: Install DNN
Từ VS open trang Default.aspx lên thì DNN sẻ redirect user sang trang ~/Install/Default.aspx, màng hình đầu tiên là màng hình xác nhận chế độ install db.


Mình chọn method là typical, click Next.


Bước 5: Xác nhận quyền ghi xuống thư mục cài đặt.

Click vào Test permission sau đó click Next.

Bước 6: Cấu hình chuổi kết nối tới database



Điền những thông tin cần thiết để kết nối tới database đả tạo ở b1, click vào test database để xác nhận database đả được config chính xác, click Next để install db script

Bước 7: Sau khi click Next DNN sẻ install db script



Đ
ợi 1 lát chúng ta sẻ thấy message: Installation of Database Complete

Bước 8: Cấu hình tài khoản host



Bước 9: Cấu hình tài khoản admin


Bước 10: Thành công message và go to home page


Chú y: Nếu chúng ta open DNN solution = Visual studio thì nếu chúng ta message lổi này thì vào Control Panel intall IIS 6 Metadata nhé.



Happy DotNetNuking…

Tags: , , , , ,

ASP.NET | VB.NET

Nhúng reCaptcha vào ASP.NET

by Neon Quach 2. January 2010 05:04

reCaptcha là 1 dịch vụ giúp chúng ta có thể chống lại bot, và những submit không phải do con người (do engine).

Bài viết này mình sẻ hướng dẫn mọi người cách nhúng reCaptcha vào ASP.NET sử dụng both C# và VB.NET.

Các bước thực hiện:
1. Sign up để lấy private và public key

https://admin.recaptcha.net/accounts/signup/

2. Tạo key

Vào https://admin.recaptcha.net/recaptcha/createsite/ và nhập domain name, sau đó chúng ta sẻ có private và public key.

3. Download thư viện reCaptcha

Phiên bản mới nhất có thể được download từ google code.

4. Tạo 1 ứng dụng ASP.NET C# or VB.NET.

5. Add Recaptcha.dll vào toolbox và kéo thả vào WebForm, tiếp theo dán 2 giá trị private và public key từ bước 2.

6. Kéo button và code cho sự kiện click, 1 label notify thông báo thành công or not.

    protected void ButtonSubmit_Click(object sender, EventArgs e)

    {

        if (Page.IsValid)

        {

            LabelResult.Visible = true;

            LabelResult.ForeColor = System.Drawing.Color.Green;

            LabelResult.Text = "Captcha match!";

        }

        else

        {

            LabelResult.Visible = true;

            LabelResult.ForeColor = System.Drawing.Color.Red;

            LabelResult.Text = "Captcha invalid.";

        }

    }

VB.NET

    Protected Sub ButtonSubmit_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles ButtonSubmit.Click

        If Page.IsValid Then

            LabelResult.Visible = True

            LabelResult.ForeColor = Drawing.Color.Green

            LabelResult.Text = "Captcha match!"

        Else

            LabelResult.Visible = True

            LabelResult.ForeColor = Drawing.Color.Red

            LabelResult.Text = "Captcha invalid."

        End If

    End Sub



Và đây là kết quả, khi nhập đúng giá trị captcha

 

Và đây là kết quả, khi nhập sai giá trị captcha

Chúc các bạn thành công!

Tags: , , ,

ASP.NET | C# | VB.NET

Từ khoá let trong Linq

by Neon Quach 10. December 2009 20:09

Sau 1 thời gian làm việc với Linq, mình phát hiện ra là trong LINQ chúng ta có thể dùng từ khoá let, nào chúng ta cùng rảo qua ví dụ sau để hiểu rỏ từ khoá let được dùng như thế nào.


List<int> lstInt = new List<int> { 1, 2, 3 };

var query = from i in lstInt

            let m = i * 2

            select m;

foreach (var item in query)

{

    Console.WriteLine(item);

}

Console.Read();

Ở đây mình tạo 1 danh sách các phần tử kiểu int lần 1, 2, 3. Nhìn và dòng code let m = i * 2 Chúng ta có thể thấy là chúng ta lấy tất cả các giá trị i đem nhân cho 2, mà i tập hợp các giá trị 1, 2, 3, như thế chúng ta sẻ có các giá trị tương ứng là: 2, 4, 6, và cuối cùng chúng ta lặp (foreach) và hiển thị lên màng hình. Take a look at diassembly code chúng ta có thể thấy rằng compiler sẻ tạo ra 1 đối tượng m và cất giữ giá trị trên đó.

Happy programming@

 

Tags: , ,

C# | VB.NET | Visual Studio Tips | LINQ

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

Binding Installed fonts in dropdownlist using LINQ

by Neon Quach 18. November 2009 04:20

In this blog I will give you snippet code which fetches installed font in dropdownlist in .NET using both C# and VB.NET.

Start with creating a new website using asp.net C# and VB.NET.
Drag a dropdownlist from toolbox into web page.

Here is markup:

<asp:DropDownList ID="DropDownList1" runat="server" AppendDataBoundItems="true">

    <asp:ListItem>--- Please select font ---</asp:ListItem>

</asp:DropDownList>

Paste code bellow and put on your page load event.

C#
    protected void Page_Load(object sender, EventArgs e)

    {

        if (!Page.IsPostBack)

        {

            InstalledFontCollection instedFontColl = new InstalledFontCollection();

            DropDownList1.DataSource = from font in instedFontColl.Families

                                       select font.Name;

            DropDownList1.DataBind();

        }

    }

VB.NET
    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load

        If Not Page.IsPostBack Then

            Dim fonts As New InstalledFontCollection()

 

            DropDownList1.DataSource = From font In fonts.Families _

                                       Select font.Name

            DropDownList1.DataBind()

        End If

    End Sub

Press F5 or Ctrl + F5 you will see the result like screenshot bellow.



Happy programming

 

Binding-Installed-fonts-in-dropdownlist-using-LINQ.rar (8.77 kb)

Tags: , , ,

ASP.NET | C# | VB.NET | Visual Studio Tips

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