ASP.NET Role Membership Provider phần I

by Neon Quach 10. March 2010 04:50

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

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

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

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

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



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



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



Màng hình config database setting




Màng hình confirm setting db




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




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

 

 

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

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

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

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

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

Tags: , , ,

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

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#

Sử dụng custom error pages trong ASP.NET

by Neon Quach 7. February 2010 00:00

Giới thiệu:
Sau khi triển khai ứng dụng asp.net lên mạng, thế nào ứng dụng của chúng ta sẻ gặp 1 số lổi không mong đợi, chẳng hạn như thay đổi chuổi kết nối, sai mật khẩu trong chuổi kết nối ....

Một trong những số lổi đó, có thể chứa những thông tin nhạy cảm, mà có thể hacker cố gắng tìm ra lổi đó và tấn công website của chúng ta. Chính vì thể khi có lổi xãy ra, chúng ta không nên show hết các lổi đó, mà chúng ta should chuyển hướng user sang 1 trang khác, chứa thông điệp lổi đó.

Chẳng hạn khi chúng ta input giá trị không hợp lệ trên URL (Query String Injection)

Tất cả các lổi hiển thị hết cho end user


Nếu sử dụng custom error thì chúng ta sẻ redirect end user sang 1 trang lổi do mình định nghỉa.

Khi đó URL của ứng dụng chúng ta cũng được chuyển sang trang Custom Error Page.



Cách làm:
Chúng ta có thể dể dàng cấu hình Custom Error Page trong web.config qua thẻ customErrors.

Đầu tiên chúng ta tạo 1 ứng dụng asp.net, ở đây mình đặt tên là CustomError



Sau đó mình thêm 1 page gọi là ErrorPage.aspx, khi có lổi xãy ra, end user sẻ được chuyển sang trang này. Và trong trang ErrorPage.aspx mình put đoạn text để thông báo có lổi xãy ra.

Opps ! Đả có lổi xãy ra trong quá trình thực thi xin vui lòng thực hiện lại.

Mở file web.config tìm đến dòng customErrors và thêm mode và defaultRedirect như hình sau:


Chú ý: Mode: Off luôn luôn hiển thị thông điệp lổi đến end user. On: định nghỉa 1 trang custom error và chuyển end user sang trang error này. RemoteOnly: mặc định được thiết lập trong file machine.config, sẻ hiển thị lổi to end user nếu được truy cập từ local, và redirect to end user nếu truy cập từ bên ngòai.

Xử lý lổi bằng cách lập trình

Tạo file Global.asax và viết code trong hàm Application_Error, chúng ta get mã lổi và rediect user sang trang thích hợp

protected void Application_Error(object sender, EventArgs e)

{

    Exception ex = HttpContext.Current.Server.GetLastError();

    if (ex.InnerException != null)

    {

        ex = ex.InnerException;

        log.Error(ex);

    }

    if (ex is HttpException)

    {

        if (((HttpException)ex).GetHttpCode() == 404)

        {

            Response.Redirect("~/PageNotFound.aspx");

        }

        else

        {

            Response.Redirect("~/ErrorPage.aspx");

        }

    }

 

    HttpContext.Current.Server.ClearError();

}

History version:
√ 06/05/2009: Config custom error on web.config (dd/mm/yyyy)
√ 07/02/2010: Show error page by programmatically

Hope this help,
Neon Quach

Tags:

ASP.NET

How to add rss icon to the address bar

by Neon Quach 3. February 2010 17:48

Your website has rss channel which used to publish frequently works, articles or news, if you want to give the alternate step to navigate to rss chanel section, or show to the user whether your website has rss channel or not, just add it in the address bar when user visit your site, by putting bellow makup code link bellow:

    <link rel="alternate" type="application/rss+xml" title="Your titile goes here"
        href="<%=Page.ResolveUrl("~/RSS.aspx")%>" />

I put this code in the Master page in order that user can see rss icon in all page.

Hope this help,

Tags:

ASP.NET

BlogEngine.NET 1.6 is Released

by Neon Quach 3. February 2010 03:05

The team is proud to announce the release of BlogEngine.NET version 1.6.  With several new features and numerous improvements and bug fixes, this is a must upgrade version for current BlogEngine.NET users and those interested in entering the blog scene.

For those who receive a steady dose of comment spam (and who doesn't!), a new powerful Comment Management and Comment Spam Filtering infrastruture has been added in version 1.6.  Comments across all posts can be viewed, edited, deleted or approved in one convenient area.  Comments can still be manually moderated, but now moderation can be automated by running comments thru remote or local comment spam validation services.  Anyone can easily build new comment spam filters and plug them into BlogEngine.NET.  It's just as simple as adding custom Extensions and Widgets is.

The other notable feature in version 1.6 is support for multiple widget zones.  You can now place widgets anywhere on your site, and even move widgets from one zone to another.

A complete list of new features can be found here.

If you're upgrading from BlogEngine.NET version 1.5 or earlier, please take a minute to read these upgrade instructions.

Download it from codeplex

Reference

Tags: , , ,

ASP.NET | open source

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

Tự động chèn dấu ngoặc kép cho control trên asp.net

by Neon Quach 27. January 2010 23:36

Tự động chèn dấu ngoặc kép cho control trên asp.net

Vấn đề: Có rất nhiều cách để thêm các controls vào web form, mình lại thích gõ bằng code trực tiếp, và khi làm bằng cách này thì gặp phải vấn đề là mình phải gõ bằng tay hết các thuộc tính của control. Kể cả dấu ngoặc kép chẳng hạn như runat="server".

Bây mình muốn là sau khi gõ thuộc tính của control và dấu bằng là Visual Studio sẻ tự động chèn 2 dấu ngoặc kép cho mình.

Cách làm: Tools → Option..
Text Editor HTML Format check vào checkbox insert attribute value quotes when typing Ok.

Giờ thì khi gõ thuộc tính xong và dấu bằng thì nó sẻ chèn vào 2 dấu ngoặc kép cho bạn.

Tip: Click chuột phải mặt trước file source code html chọn Formatting and Validation..và làm tương tự các bước trên.

best

Tags: ,

ASP.NET

Redirect to another page using Html

by Neon Quach 23. January 2010 22:44

If you want to redirect your current user to anther page from aspx page, here is html snippets code which can accomplish this task.


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

 

<!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>Welcome page</title>

    <meta http-equiv="refresh" content="5; url=http://code2code.info" />

</head>

<body>

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

    <div>

        This page will be redirect to http://code2code.info in 5 seconds

    </div>

    </form>

</body>

</html>


When you run this code, after 5 second, this page will be redirected to http://code2code.info
Regards

 

Tags: ,

ASP.NET

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