Sunday, June 19, 2011

Trước tiên: tạo file Global.asax có nội dung như sau:


 <%@ Application Language="C#" %>   


Trong file Webconfig chúng ta thêm:

                   


Để hiển thị trên site chúng ta làm như sau, tôi sẽ cho hiển thị ra bảng:

<%= Application["OnlineUsers"].ToString() %> Users Online
Has :<%=Application["count_visit"].ToString()%> Visitors


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

1 Nêu vấn đề Ý tưởng như sau:
Tôi có 3 User Control (UC) là Menu, Welcome, Login và chỉ một trang default.aspx để xây dựng một ứng dụng web đơn giản.
UC Menu sẽ chứa 2 link: Home, Login
UC Welcome : Chứa nội dung chính của trang
UC Login: Chứa form login
Vậy làm thế nào để khi mới vào trang default.aspx chúng ta sẽ có một trang gồm menu và phần home. Khi nhấp vào link login, thì form login sẽ được thay thế cho phần home.

2 Thiết kế
* Có UC Login.ascx đơn giản như sau:

* UC Menu.ascx như sau:
HTML Code:

<%@ Control Language="C#" AutoEventWireup="true" CodeFile="Menu.ascx.cs" Inherits="Menu" ClassName="Menu" %>
Home Login

Trang default.aspx sẽ được thiết kế như sau:

HTML Code:
<%@ Page Language="C#" AutoEventWireup="true"  CodeFile="Default.aspx.cs" Inherits="_Default" %> <%@ Register Src="Menu.ascx" TagName="Menu" TagPrefix="uc1" %>          User Control       

Chào mừng bạn đến với User Control trong ASP.NET Tutorial



Hãy quan tâm đến đoạn code:

HTML Code:
 

Tôi sẽ nói với bạn nó hoạt động như thế nào sau khi ta xem code ở phần Page_Load của trang Default.aspx.cs :

Visual C# Code:
01
02
protected void Page_Load(object sender, EventArgs e){
03
04//HttpContext context = new HttpContext();
05 string module = null; Control ct;
06if (!IsPostBack)
07 {
08module = Request.QueryString["mod"].ToString().Trim(); HtmlGenericControl gel = new HtmlGenericControl("div");
09if (module == "Login")
10{
11 ct = Page.LoadControl("Login.ascx");
12}
13else {
14ct = Page.LoadControl("Welcome.ascx");
15}
16gel.Controls.Add(ct); Body.Controls.Add(gel);
17 }
18}

3 Giải thích hoạt động

* Trong Page_Load() của trang default.aspx :
- Khởi tạo một biến kiểu string là module nhằm mục đích lưu giữ tham số module mà người dùng request đến các trang.
- Khai báo một biến kiểu Control là ct;
- Câu lệnh:

HTML Code:
module = Request.QueryString["mod"].ToString().Trim();

Nhằm mục đích lấy vào giá trị tham số “mod” được truyền thông qua địa chỉ url. Và vì là demo và mục đích là vận hành việc sử dụng control động nên tôi đã lược bỏ việc bắt và xử lý lỗi.
- Dòng tiếp theo:

HTML Code:
HtmlGenericControl gel = new HtmlGenericControl("div");

Khởi tạo một biến gel kiểu là HtmlGenericControl đưa vào tham số “div” nhằm mục đích khi ta add biến này vào trang nó sẽ tương ứng với việc ta khởi tạo một thẻ div trong trang html vậy.
- Lệnh kiểm tra if … else … tiếp theo kiểm tra giá trị của biến module, từ đó sẽ load các UC nào tương ứng với request từ phía client.
- 2 câu lệnh

HTML Code:
ct = Page.LoadControl("Login.ascx"); ct = Page.LoadControl("Welcome.ascx");

sẽ có tác dụng load các UC tương ứng lên trang.
- Lệnh
gel.Controls.Add(ct);
có chức năng đưa UC đã được load ở bước trước vào giữa thẻ .
- Và cuối cùng:
Body.Controls.Add(gel);
Đây mới là bước để đưa các công đoạn mà ta đã làm lên trang. Như tôi đã lưu ý ở phía trên, ở đây Body chính là ID của PlaceHolder mà ta đã đặt trong mã Html của trang.
Điều này có ý nghĩa gì?
+ Bất cứ khi nào bạn muốn đặt (muốn UC hiển thị) ở đâu, hãy để vào đó một PlaceHolder, đặt tên (ID) cho nó. Tiếp theo load UC lên và add vào trang. Nó sẽ hiển thị đúng chỗ đó.

4 Hoạt động
* Mở Browser và gõ vào địa chỉ trang để xem :
http://localhost/UserControls/Default.aspx?mod=home
Home.ascx được Load
* Bấm vào Login:
Login.ascx được Load
* Kết luận:
- Khi nhấn vào nút login, phần nội dung welcome đã được thay thế bởi bởi phần login. Nghĩa là các control đã được hiển thị đúng với yêu cầu từ phía client.

5 Nhận xét và Mở rộng
Lợi điểm của phương pháp sử dụng UC so với các trang aspx thông thường:
+ Khả năng reuse cao
+ Giảm tối đa việc viết các trang aspx. Việc liên kết trang sẽ được thay thế bằng việc gọi các module tương ứng.
+ Dễ sửa đổi code
+ Dễ phân quyền cho user, tùy theo quyền mà các US sẽ được nạp vào trang tương ứng.
Mở rộng:
- Bạn có thể dùng phương pháp này để xây dựng một ứng dụng như forum, bán hàng, hoặc lớn hơn là một portal chẳng hạn. Đặc điểm chung của các ứng dụng đó là chúng có rất nhiều module, nhiều chức năng khác nhau, và hiển thị theo quyền truy cập. Nếu viết theo các trang aspx thông thường. Bạn sẽ phải mất nhiều thời gian cho việc kéo thả, thậm chí là copy & paste cho các phần chung như header, footer, hay menu chính.
- Thay vào đó bạn hãy thực hiện phân quyền, load các role tương ứng và các UC cũng lần lượt hiển thị cho các bạn với các chức năng tương ứng. Tất nhiên phương thức xử lý các UC cũng khác đi một chút so với demo. Nhưng ý tưởng chung là vậy.

6 Tổng kết
- Thực sự rất động, bạn hãy thử bắt tay vào thực hiện một lần để hiểu hơn nữa hiệu quả và giá trị của nó

Dù bạn đến với lập trình (Programming) như thế nào chúng tôi cũng hy vọng với hiểu biết giới hạn cùng cố gắng nhỏ nhoi của mình sẽ giúp bạn một phần nào đó.

Tất cả những gì ở đây là sự chia sẻ. Chúng ta sẽ cùng nhau đi vào thế giới lập trình theo một cách đơn giản nhất.

Mỗi người trong chúng ta đến với lập trình (Programming) theo những cách khác nhau. Người thì vì sự mê say , người thì tò mò, người lại muốn tìm một nghề nghiệp...Mặc dù vậy, theo chúng tôi, chúng ta cần xác định một điều:

Nếu thật sự mong muốn học được một ngôn ngữ lập trình, đừng bao giờ chạy theo "phong trào"

Nếu bạn quyết định chọn C thì cố gắng theo đến cùng, hay ít nhất cũng nắm vững nền tảng cơ bản của ngôn ngữ C. Nếu bạn quyết theo ASP thì nên tìm hiểu đến nơi đến chốn.

Không có ngôn ngữ nào hơn ngôn ngữ nào cả nếu bạn không nắm rõ.

Khi bạn thật sự thuần thục một ngôn ngữ, việc chuyển qua tìm hiểu một ngôn ngữ khác sẽ rất dễ dàng với bạn.

Chúng ta sẽ cũng nhau thảo luận về ASP.NET. ASP.NET là Active Server Pages .NET (.NET ở đây là .NET framework). Nói ngắn gọn thì ASP.NET là một công nghệ dùng để phát triển các ứng dụng về mạng. Bạn lưu ý ở chổ ASP.NET là một phương pháp tổ chức hay framework để thiết lập các ứng dụng cho mạng dựa trên CLR (Common Language Runtime) chứ không phải là một ngôn ngữ lập trình. Ngôn ngữ lập trình được dùng để diển đạt ASP.NET thông thường là Visual Basic .NET, C# (C sharp), C++, JScript ...Bạn có thể viết ASP.NET bằng VB.NET hay C# chẳng hạn và chúng sẽ được compiled at run time, chứ không phải là Script như trong ASP

Tuy mang tên gần giống như ASP cổ điển nhưng ASP.NET không phải là ASP.ASP (Active Server Pages)
là ngôn ngữ lập trình web được viết bởi hãng Microsoft. Chính xác hơn thì ASP không hẳn là một ngôn ngữ lập trình, nó là môi trường kịch bản trên máy chủ (Server-side Scripting Environment) dùng để tạo và chạy các ứng dụng Web động và có tương tác. Các trang web viết bằng ngôn ngữ này có phần mở rộng là .asp (ví dụ HelloWorld.asp) thay vì .htm hay .html. Nội dung file ASP về cơ bản rất giống file Html bình thường, nó bao gồm các cú pháp html trộn lẫn các mã lập trình ASP (còn gọi là các script, được viết bằng VBScript hay JavaScript). Các Script trong ASP thực thi trên server.


còn tiếp ...



Saturday, June 4, 2011

I get asked this question a lot as I go around demonstrating the benefits of using URL Rewriting in ASP.NET, how can I process wildcard extensions and just directories in IIS 6.0 on Windows 2003 and ASP.NET? It is very simple, but not obvious at all. This entry will walk you through configuring IIS to process all request through the ASP.NET engine.

The first thing you must have is access to the IIS Management console and Administrator privileges to the web server. Once you have these things in place you need to open the properties dialog for the Web site you will be configuring.

IIS Web Site Properties Dialog

IIS Web Site Properties Dialog

Select the 'Home Directory' tab. Once on this tab select the 'Configuration' Button. This will display a three tab dialog, the first tab, Mappings is what we are interested in. Notice the lower portion of the tab list 'Wildcard Application Maps', here we will want to add a reference to the ASP.NET engine. The easy way to do this is to double click on one of the ISAPI extensions in the top portion and copying the path to the ASP.NET .dll file. You will need to select one of the ASP.NET file extensions, like .ascx or .asax to do this. The path should look something like this: DRIVE:\%windows%\microsoft.net\framework\v2.0.50727\aspnet_isapi.dll.

IIS Web Site Configuration Dialog

IIS Web Site Configuration Dialog

Now that we have copied the path to the .NET engine we need to add it to the Wildcard mappings. Select the Insert button to the right of the mappings list. Now you will have an Add/Edit Application Extension Mapping dialog displayed. There are two pieces of information you need to supply, the ASP.NET engine path and uncheck 'Verify File Exists'. Now select 'OK' until all the property windows are closed.

IIS Wildcard Application Extension Mapping Dialog

IIS Wildcard Application Extension Mapping Dialog

Now all URL requests to the web site will be processed by ASP.NET no matter what the extension or lack of extension. Pay attention for my next entry on how to leverage this feature to map URLs without extensions to actual dynamic pages on your Web site.

Reference - Installing Wildcard Mappings in IIS 6.0


http://professionalaspnet.com/archive/2007/07/27/Configure-IIS-for-Wildcard-Extensions-in-ASP.NET.aspx

Clean Code by "Uncle Bob" Martin
A must for any developer with an interest in producing better code. Read Reviews or Buy Now

URL Rewriting with URLRewriter.Net

URL Rewriting has lots of benefits, listing its main benefits

  • SEO Friendly URL
  • Secured URL
  • No need to change bookmark with change in site structure.

Before URL Rewriting my URL looks like
http://localhost:2661/URLRewrite2/DynamicPage.aspx?MyTitleId=1

After URL Rewriting URL is changed to

http://localhost:2661/URLRewrite2/Article/Asp-Net-website-paths-1.aspx


Lets Understand URL Rewriting with Simple Example

A Website displaying articles list in a gridview on clicking the article link, it will display dynamically generated article content.

Before URL Rewriting when you mouse-over 1st Article Link, "Asp.net Website Path" it uses query string to display the article content.


Dynamic page display Querysting, before URL Rewriting.



After URL Rewriting we will achieve how SEO Friendly URL is used to display article content.


Now, lets understand how we can achieve it.

For URL Rewriting we are using URLRewriter.Net which is available free. Download URLRewriter.Net

Step-by-Step Explanation

Step 1: Download Binary Files for URLRewriter.Net

Step 2: Add Reference to Binary Files, Right click project "Add Reference" and add binary files.


Step 3: Update Web.Config File to make URLRewriter.Net works.
<configuration>

<configSections>
<section name="rewriter"
requirePermission="false"
type="Intelligencia.UrlRewriter.Configuration.RewriterConfigurationSectionHandler, Intelligencia.UrlRewriter" />
configSections>

<system.web>

<httpModules>
<add name="UrlRewriter" type="Intelligencia.UrlRewriter.RewriterHttpModule, Intelligencia.UrlRewriter" />
httpModules>

system.web>

<system.webServer>

<modules runAllManagedModulesForAllRequests="true">
<add name="UrlRewriter" type="Intelligencia.UrlRewriter.RewriterHttpModule" />
modules>

<validation validateIntegratedModeConfiguration="false" />

system.webServer>

<rewriter>
<rewrite url="~/Article/(.+)-(.+).aspx" to="~/DynamicPage.aspx?MyTitleId=$2"/>
rewriter>

configuration>


Step 4: Adding Function to Generate SEO Friendly URL from given Title

public static string GenerateURL(object Title, object strId)
{
string strTitle = Title.ToString();

#region Generate SEO Friendly URL based on Title
//Trim Start and End Spaces.
strTitle = strTitle.Trim();

//Trim "-" Hyphen
strTitle = strTitle.Trim('-');

strTitle = strTitle.ToLower();
char[] chars = @"$%#@!*?;:~`+=()[]{}|\'<>,/^&"".".ToCharArray();
strTitle = strTitle.Replace("c#", "C-Sharp");
strTitle = strTitle.Replace("vb.net", "VB-Net");
strTitle = strTitle.Replace("asp.net", "Asp-Net");

//Replace . with - hyphen
strTitle = strTitle.Replace(".", "-");

//Replace Special-Characters
for (int i = 0; i < chars.Length; i++)
{
string strChar = chars.GetValue(i).ToString();
if (strTitle.Contains(strChar))
{
strTitle = strTitle.Replace(strChar, string.Empty);
}
}

//Replace all spaces with one "-" hyphen
strTitle = strTitle.Replace(" ", "-");

//Replace multiple "-" hyphen with single "-" hyphen.
strTitle = strTitle.Replace("--", "-");
strTitle = strTitle.Replace("---", "-");
strTitle = strTitle.Replace("----", "-");
strTitle = strTitle.Replace("-----", "-");
strTitle = strTitle.Replace("----", "-");
strTitle = strTitle.Replace("---", "-");
strTitle = strTitle.Replace("--", "-");

//Run the code again...
//Trim Start and End Spaces.
strTitle = strTitle.Trim();

//Trim "-" Hyphen
strTitle = strTitle.Trim('-');
#endregion

//Append ID at the end of SEO Friendly URL
strTitle = "~/Article/" + strTitle + "-" + strId + ".aspx";

return strTitle;
}


Step 5: Changing DataBinder.Eval Function in .Aspx Page to reflect changes in URL of Grid.
Note: Learn more about DataBinder.Eval Function


<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" BackColor="#DEBA84" BorderColor="#DEBA84" BorderStyle="None" BorderWidth="1px" CellPadding="3" CellSpacing="2" Width="788px">
<FooterStyle BackColor="#F7DFB5" ForeColor="#8C4510" />
<Columns>
<asp:TemplateField HeaderText="Title">
<ItemTemplate>
<asp:HyperLink ID="hlTitle" runat="server" Text='<%#DataBinder.Eval(Container.DataItem,"Title")%>' NavigateUrl='<%#GenerateURL(DataBinder.Eval(Container.DataItem,"Title"),DataBinder.Eval(Container.DataItem,"Id"))%>'>asp:HyperLink>
ItemTemplate>
asp:TemplateField>
<asp:TemplateField HeaderText="Description">
<ItemTemplate>
<asp:Label ID="lblDesc" runat="server" Text='<%#DataBinder.Eval(Container.DataItem,"Description")%>'>asp:Label>
ItemTemplate>
asp:TemplateField>
Columns>
<RowStyle BackColor="#FFF7E7" ForeColor="#8C4510" />
<SelectedRowStyle BackColor="#738A9C" Font-Bold="True" ForeColor="White" />
<PagerStyle ForeColor="#8C4510" HorizontalAlign="Center" />
<HeaderStyle BackColor="#A55129" Font-Bold="True" ForeColor="White" />
asp:GridView>


Now, Lets Check the stuff so far developed.

Assigning SEO Friendly URL in to grid.


On clicking URL inside grid it will point to Dynamically Generated Page with SEO Friendly URL, rather than QueryString.


Things to consider while URL Rewriting.

Problem 1: Page Postback, will turns User Friendly URL into Original URL.
Problem 2: CSS, Image Files pointing to URL Rewriting Page won't work, as they might be pointing with absolute path.

Problem 1: Page Postback for Page displaying URL Rewritten URL
Page Postback of Page displaying User friendly URL will turns into original state when same page postback occurs. In our example, I am adding one button and trying to make Page Postback. You will notice that Page Postback will turns the User Friendly URL into original URL containing QueryString.


For Resolving Page PostBack problem for Page displaying URL Rewritten URL

This article is inspired from Scott's URL Rewritten article. Adding two files as mentioned by scott. If you are developing code in VB download files from Scott's article, else for C# download files with Sourcecode at the end of this article.



Now, lets test the Page Postback by clicking on Button, you will notice this time, URL remains the same.




Problem 2: Image Display Problem
Now, lets display image on for this page and lets observe what problem we may run into. I have added following line to display image, but it won't works.
<img src="Images/article.gif" />


Resolve Problem, by refrencing file from root.
<img src="../Images/article.gif" />



Download Source-Code for URL Rewriting

http://dotnetguts.blogspot.com/2008/07/url-rewriting-with-urlrewriternet.html