Building simple FAQ section using Linq2Xml and jquery

by Neon Quach 5. March 2010 19:58

Building simple FAQ section using Linq2Xml and jquey

FAQ are answers of common question in your website , it’s very helpful for the user who want to understand clearly about the website.

In this post I will show you how to implement it using Linq2Xml and then using jquery for face-in and face-out effect.

Take a look at Faq xml data , and I put it in the App_Date folder

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

<faqs>

  <faq id="1" question="1.Lorem ipsum dolor sit amet, consectetur adipiscing elit tortor in imperdiet placerat?" answer="Lorem ipsum dolor sit amet, consectetur adipiscing elit. Pellentesque vitae dolor in quam vestibulum consequat a in lacus. Nulla cursus, tortor in imperdiet placerat, massa lacus sagittis urna, quis tincidunt elit mauris porttitor lorem. Nulla gravida lacinia ornare. Duis nec lorem lacus, a feugiat lacus">

  </faq>

  <faq id="2" question="2.Lorem ipsum dolor sit amet, consectetur adipiscing elit." answer="Lorem ipsum dolor sit amet, consectetur adipiscing elit. Pellentesque vitae dolor in quam vestibulum consequat a in lacus. Nulla cursus, tortor in imperdiet placerat, massa lacus sagittis urna, quis tincidunt elit mauris porttitor lorem. Nulla gravida lacinia ornare. Duis nec lorem lacus, a feugiat lacus">

  </faq>

  <faq id="3" question="3.Lorem ipsum dolor sit amet, consectetur adipiscing elit in quam vestibulum consequat a in lacus?" answer="Lorem ipsum dolor sit amet, consectetur adipiscing elit. Pellentesque vitae dolor in quam vestibulum consequat a in lacus. Nulla cursus, tortor in imperdiet placerat, massa lacus sagittis urna, quis tincidunt elit mauris porttitor lorem. Nulla gravida lacinia ornare. Duis nec lorem lacus, a feugiat lacus">

  </faq>

  <faq id="4" question="4.Lorem ipsum dolor sit amet, consectetur adipiscing elit." answer="Lorem ipsum dolor sit amet, consectetur adipiscing elit. Pellentesque vitae dolor in quam vestibulum consequat a in lacus. Nulla cursus, tortor in imperdiet placerat, massa lacus sagittis urna, quis tincidunt elit mauris porttitor lorem. Nulla gravida lacinia ornare. Duis nec lorem lacus, a feugiat lacus">

  </faq>

</faqs>


Create a new ASP.NET website and write the code in the Page Load event like bellow:

using
System;

using System.Collections.Generic;

using System.Xml.Linq;

 

public partial class _Default : System.Web.UI.Page

{

    public IEnumerable<XElement> faqsElement;

    protected void Page_Load(object sender, EventArgs e)

    {

        if (!Page.IsPostBack)

        {

            XElement element = XElement.Load(Server.MapPath("~/App_Data/Faq.xml"));

            faqsElement = element.Elements("faq");

        }

    }

}


When the default page has loaded, it will return a list of faq element, and I will get faq data in the aspx code:

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>

 

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">

<head runat="server">

    <title>Building faq page using Linq2Xml and Jquery</title>

    <script src="jquery-1.2.6.min.js" type="text/javascript"></script>

    <style type="text/css">

        .divAnswer

        {

            display: none;

        }

    </style>

</head>

<body>

    <form id="form1" runat="server">

    <h1>

        FAQ</h1>

    <div class="faqs">

        <% foreach (var item in faqsElement)

           { %>

        <div class="faq">

            <a href="#" class="question">

                <%= item.Attribute("question").Value %></a><br />

            <div class=" divAnswer">

                <%= item.Attribute("answer").Value%>

            </div>

        </div>

        <% } %>

    </div>

    </form>

</body>

<script type="text/javascript">

    $(document).ready(function () {

        $("a.question").click(function () {

            $(this).parent().find("div.divAnswer").slideToggle();

        })

    });

</script>

</html>

 
Answer section only show when user clicks on the hyperlink question, so the divAnswer css class hides it for this purpose.

Run this page you will the result as above

faq-linq2xml-and-jquery.rar (19.41 kb)

Tags: , , ,

ASP.NET | JQuery | LINQ | LINQToSQL | C#

Tạo Google Translate Widget in BlogEngine

by Neon Quach 5. March 2010 01:32

BlogEngine hổ trợ built-in widget framework, nên chúng ta có thể xây dựng 1 widget rất dể dàng, cách làm như sau:


Ở đây mình sẻ tạo 1 Widget Google Translate

Tạo 1 thư mục Google Translate trong thư mục widgets, tạo 1 user control đặt tên widget.ascx, user control này sẻ kế thừa từ WidgetBase, sau đó thực thi lại 1 số hàm của widget base, đoạn code look like this:

using System;

 

public partial class widgets_GoogleTranslare_widget : WidgetBase

{

    protected void Page_Load(object sender, EventArgs e)

    {

 

    }

 

    public override string Name

    {

        get { return "Google Translate"; }

      

    }

 

    public override bool IsEditable

    {

        get { return false; }

    }

 

    public override void LoadWidget()

    {

    }

}


Chú ý: chúng ta override thuộc tính Name và trả về Google Translate là tên của thư mục chứ widget.

Copy script google translate tại: http://translate.google.com/translate_tools

Code của user control như sau:

<%@ Control Language="C#" AutoEventWireup="true" CodeFile="widget.ascx.cs" Inherits="widgets_GoogleTranslare_widget" %>

<div id="google_translate_element">

</div>

 

<script>

    function googleTranslateElementInit() {

        new google.translate.TranslateElement({

            pageLanguage: 'en'

        }, 'google_translate_element');

    }

</script>

 

<script src="http://translate.google.com/translate_a/element.js?cb=googleTranslateElementInit"></script>


Vậy là xong 1 widget, chúng ta có thể render lại nội dụng của widget bằng cách override lại phương thức OnLoad của WidgetBase.

Rỏ rang hơn chúng ta có thể xem code của các Widget khác trong cùng Folder.

Regards,

Google_Translate.rar (737.00 bytes)

Tags: , ,

ASP.NET | BlogEngine | C#

Nhúng bộ gõ Mudim vào BlogEngine

by Neon Quach 3. March 2010 04:27

Nhằm support khách Việt viếng thăm và gõ tiếng Việt có dấu, mình vừa embed bộ gõ Mudim vào Blog, giờ mình muốn share cách làm mình thế nào để embed bộ gõ vào Blog bằng cách lập trình và hổ trợ nén (compress).


Download Mudim: http://code.google.com/p/mudim/

Bỏ nó vào root của Blog, navigate tới BlogEngine.Core\Web\Controls\BlogBasePage.cs, make sure that you download source code version, trong sự kiện OnLoad add dòng sau

AddJavaScriptInclude(Utils.RelativeWebRoot + "mudim-0.8-r153.js", true, true);

Phía duới

AddJavaScriptInclude(Utils.RelativeWebRoot + "blog.js", true, true);

Hàm AddJavaScriptInclude nhận vào 4 tham số: 1.đường dẩn tập tin js cần add, 2.tên tập tin js, 3.có đặt file js phía dưới trang boolen, 4.tham số cuối cùng là có add deferattribute vào thẻ script hay không (defer là attribute cho biết trình duyệt sẻ load trang trước khi run đoạn js đó)

Vào web.config add thêm dòng mudim-0.8-r153.js trong appSettings

    <!--A comma separated list of script names to hard minify. It's case-sensitive. -->

    <add key="BlogEngine.HardMinify" value="blog.js,widget.js,mudim-0.8-r153.js,WebResource.axd"/>

Xong giờ có thể gõ tiếng Việt có dấu.
Regards,

 

Tags: , , , ,

ASP.NET | BlogEngine | open source | C#

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

4 Bước cài đặt nopCommerce trên localhost.

by Neon Quach 2. January 2010 19:31

nopCommerce là phần mềm shopping cart mã nguồn mở, được viết bằng ASP.NET C#, đơn giản, linh động, customize, giao diện thân thiện, trong bài blog này mình sẻ hướng dẫn cài nopCommerce trên localhost với 4 bước.

Chuẩn bị
Visual Studio 2008 or latest.
Sql Server Express 2005 or latest.
IIS installed.

Download nopCommerce package
Đăng nhập và tải về version mới nhất tại: http://www.nopcommerce.com/Downloads.aspx
Cấu hình IIS http://localhost/nop

Bước 1: duyệt http://localhost/nop, nopCommerce sẻ tự động redirect user đến trang install Nop



Chọn install nopCommerce và click Next

Bước 2: Cầu hình sql server

Bước 3: Tạo Nop database



Click Next, nếu không gì trở ngại trong quá trình cài đặt thì chúng ta sẻ bắt gặp màng hình này.

Bước 4: Màng hình cài đặt thành công vào trang chủ.

Tài khoản admin mặc định : admin@yourstore.com pass: admin

Kết luận: nopCommerce đơn giản, linh hoạt, và dể dàng tùy biến theo yêu cầu nghiệp vụ của từng site (từng khách hàng).

Tags: , , ,

ASP.NET | C#

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

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