Wednesday, October 26, 2011

Huong dan lap trinh Android : 1. Gioi thieu ve Android SDK
Huong dan lap trinh Android : 2. Android Helloword
Huong dan lap trinh Android : 3. thiet ke giao dien ung dung android
Huong dan lap trinh Android : 4. Activity trong Android
Huong dan lap trinh Android : 5. BroadcastReceiver
Huong dan lap trinh Android : 6. Service trong Android
Huong dan lap trinh Android : 7. Xu ly bat dong bo trong Android
Giới thiệu về Android SDK

1. Cài đặt Android SDK

- Bạn có thể xem hướng dẫn cài đặt gốc tại đây http://developer.android.com/sdk/installing.html
- Hoặc có thể coi bản rút gọn tiếng Việt ở các slide sau
- Cần có eclipse 3.5 (3.4 cũng được) http://www.eclipse.org/downloads/
- Vào link bên trên, down eclipse classic 3.5 về rồi giải nén, vậy là đã có thể dùng được eclipse rồi.
2. Cài đặt ADT plugin
Mở eclipse lên, bấm vào Help > Install new software.
Ở cái form hiện lên đó, bạn chọn Add…
Ở mục Name, nhập tên gì cũng được, ví dụ như ADT plugin
Ở mục Location, nhập vào link này: http://dl-ssl.google.com/android/eclipse/
Sau đó bấm OK, có cho chọn gì thì cứ chọn hết rồi bấm next hoài cho đến lúc xong.

3. Cài đặt Android SDK
- Tải Android SDK tại link này http://developer.android.com/sdk/index.html (nhớ chú ý là nó chia ra Window, Mac và Linux nhé)
Mở Eclipse -> window -> preferences -> Android -> trong mục SDK location chọn Browse - đưa đường dẫn đến thư mục SDK -> bấm apply.
- Eclipse -> window -> Android SDK and AVD manager -> Available packages -> chọn hết và cài hết (hơi lâu một chút) hoặc bạn có thể chỉ chọn mấy cái liên quan đến Android 1.6 thôi cũng được (API level 4) vì khóa học này sẽ dùng SDK 1.6 đang thông dụng nhất nhé các bạn.
- Sau khi xong thì bấm vào Installed packages sẽ thấy thế này

4. Tạo một điện thoại ảo (AVD)
- Eclipse -> window -> Android SDK and AVD manager -> ở cái cửa sổ mới đó, chọn mục Virtual devices -> bấm nút New…
Mục Name: đặt tên gì cũng được, cốt là dễ nhớ và phân biệt nó đang là 1.6
Mục target: chọn anh nào có API level 4 là ok
Sdcard size: bạn gõ vào 256 (hoặc hơn thì tùy bạn)
Sau đó bấm Create AVD, thế là xong

5. Hello world
Xem link gốc tại đây hoặc đợi slide sau để xem bản tiếng Việt. http://

http://develope...llo-world.html

1. lap trinh mobile lap trinh android lap trinh iphonelap trinh j2me lap trinh symbianlap trinh windows mobileebook mobile - giao trinh lap trinh mobileebook j2me - giao trinh lap trinh j2me - Source code J2ME - Mã nguồn J2MEebook iphone - giao trinh lap trinh iphone - Source Code Iphone- Mã nguồn Iphone
ebook symbian - giao trinh symbian - Source Co Symbian- Mã nguồn Symbian

2. lap trinh mobile lap trinh android lap trinh iphone lap trinh j2me lap trinh symbian lap trinh win mobile

3. lap trinh mobile lap trinh android lap trinh iphonelap trinh j2me lap trinh symbianlap trinh windows mobile
ebook mobile - giao trinh lap trinh mobile
ebook j2me - giao trinh lap trinh j2me - Source code J2ME - Mã nguồn J2ME
ebook iphone - giao trinh lap trinh iphone - Source Code Iphone- Mã nguồn Iphone
ebook symbian - giao trinh symbian - Source Co Symbian- Mã nguồn Symbian

---------- Bài thêm lúc 15:24 ---------- Bài trước là lúc 15:01 ----------

Huong dan lap trinh Android : 1. Gioi thieu ve Android SDK
Huong dan lap trinh Android : 2. Android Helloword
Huong dan lap trinh Android : 3. thiet ke giao dien ung dung android
Huong dan lap trinh Android : 4. Activity trong Android
Huong dan lap trinh Android : 5. BroadcastReceiver
Huong dan lap trinh Android : 6. Service trong Android
Huong dan lap trinh Android : 7. Xu ly bat dong bo trong Android
Bắt đầu với Hello World
1. Tạo một project mới
- Ở màn hình eclipse, bấm File -> New -> Project -> Android -> Android Project -> Next
- Ở màn hình kế nhập liệu vào các ô như sau:
- Project name: HelloWorld (tên project hiển trị trên eclipse cũng sẽ là thư mục chứ ứng dụng trong workspace)
- Application name: Hello World (tên ứng dụng sẽ hiện thị trên điện thoại)
- Package name: org.multiuni.android.hellowrold (tên của package sẽ chứa source code, tương tự trong java http://en.wikipedia.org/wiki/Java_pa...ng_conventions)
- Create activity: HelloWorldActivity (tạo một lớp con của lớp Activity, dùng để hiển thị một màn hình ở đây là màn hình HelloWorld của chúng ta)
- Min SDK version: 4 (tức SDK 1.6, ở đây chúng ta khai báo là ứng dụng này có thể đáp ứng được phiên bản SDK cũ nhất là phiên bản nào)
- Sau khi hoàn tất bấm Finish, project mới đã được tạo.

2. Cấu trúc một project

- Thư mục src chứa source code ứng dụng. Gồm các package và các class.
- Thư mục gen chứa các file tự động phát sinh (mà thường gặp nhất là R.class)
- Thư mục res để chứa các resource dùng trong ứng dụng (thông qua ID)
- Thư mục assets chứa các resource file mà ứng dụng cần dùng (dưới dạng file)

- File Manifest là file khai báo thông tin về ứng với hệ thống (như ứng dụng gồm những màn hình nào, có service nào… xin các quyền gì, phiên bản bao nhiêu, dùng từ SDK phiên bản nào…)
- Ngoài ra còn có file thư viện.

3.Chạy ứng dụng Hello World
- Với ứng dụng vừa tạo nếu có báo lỗi thì bạn sửa lại thông số cho ứng dụng như sau: bấm chuột phải vào project à Properties à Java compiler à Compiler compliance settings: 1.6
- Bấm Ctrl + F11 để chạy ứng dụng, sẽ hiện lên emulator
4. Tạo UI trực tiếp từ code
Code ban đầu của ứng dụng:
HTML Code:

public class HelloWorldActivity extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
}

Sửa lại như bên dưới rồi chạy lại (nếu thấy báo lỗi thiếu thư viện, thử bấm Ctrl + Shift + O)
HTML Code:

public class HelloAndroid extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
TextView tv = new TextView(this);
tv.setText("Hello, Android");
setContentView(tv);
}
}

5. Thử xử lý sự kiện
Ở code bên trên, đổi TextView lại thành Button.
Button bt = new Button(this);
Sau đó, implement phương thức xử lý sự kiện khi user click vào nút này
HTML Code:

bt.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Toast.makeText(getApplicationContext(),
"Hello World", Toast.LENGTH_LONG).show();
}
});

6. Một số phím tắt

Để import các thư viện còn thiếu bấm Ctrl + Shift + O
Để xóa một dòng code bấm Ctrl + D
Để hiển thị bảng suggestion bấm Ctrl + Space
Để comment một dòng code Ctrl + /
7. Thử một chút về xoay màn hình

- Các bạn tạo 1 project mới tên là Orientaion.
- Sau đó, bấm phải chuột vào thư mục res -> new -> Folder -> nhập tên folder là layout-land (nhớ nhập chính xác nhé).
- Trong thư mục layout ban đầu có file main.xml, các bạn copy file đó, cho vào thư mục layout-land nhé, vậy là mỗi thư mục đều có một file main.xml
- Ở mỗi file main trong 2 thư mục đó, đều có đoạn này:
HTML Code:

android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text=“@string/hello"
/>

- Các bạn sửa cái nội dung android:text trong đoạn xml đó lại, để cho 2 file main đó có 2 nội dung text khác nhau là được.
- Chạy chương trình, sau khi màn hình hiển thị, các bạn bấm Ctrl + F11 (Ctrl bên trái nhé) thử xem kết quả nhé.

Để lập trình ứng dụng cho Android, bạn cần phải cài đặt các phần mềm cần thiết sau:

Các yêu cầu chuẩn bị cài đặt:

Các yêu cầu hệ thống (máy tính) để lập trình ứng dụng:
+ Hệ điều hành:
– Windows : XP (32-bit), Vista (32- or 64-bit), or Windows 7 (32- or 64-bit).
– Mac OS X 10.5.8 hoặc cao hơn (x86 only)
– Linux (đã test trên Linux Ubuntu Hardy Heron), nếu dùng phiên bản 64bit thì phải hỗ trợ ứng dụng chạy 32bit, tham khảo chi tiết tại Ubuntu Linux installation notes.
+ Môi trường lập trình (IDEs)
– Eclipse IDE: có thể sử dụng bản Eclipse 3.4 (Ganymede) or 3.5 (Galileo) download tại http://www.eclipse.org/downloads/.
Android SDK (Software Development Kit) – đây là bộ Kit dùng để phát triển ứng dụng cho Android, bạn có thể download phiên bản mới nhất tại Android SDK, có các phiên bản khác nhau dành cho cac hệ điều hành khác nhau.
ADT Plugin for Eclipse: Đây là plugin cho Eclipse để phát triển ứng dụng android. Download phiên bản mới nhất tại địa chỉ http://developer.android.com/sdk/eclipse-adt.html

Các bước cài đặt:
Sau khi download các phần mềm cần thiết, tiến hành các bước cài đặt như sau:

Cài đặt eclipse: Giải nén file eclipse vừa download về, vào thư mục eclipse->chạy file eclipse.exe (đối với windows và eclipse.dmg đối với mac os) có thể tạo shortcut ngoài desktop để dễ khởi động eclipse lần sau.

Cài đặt ADT Plugin for Eclipse:
+ Cài offline (không có internet): Giải nén file ADT vừa download về, vào thư mục ADT , copy tất cả file trong thư mục plugins rồi paste vào thư mục plugins của eclipse (Eclipse->Plugins).
+ Cài online (có internet): để cập nhật ADT bản mới nhất
– Windows:
—-1. Khởi động eclipse,
—-2. Chọn menu Help->Install New Software…
—-3. Sau khi hiển thị cửa sổ Install, tại trường Work with, nhấn nút Add, hiển thị cửa sổ Add Repository.
—-4. Tại cửa sổ Add Repository, tại Name gõ: ADT; tại Location chọn Archive và Browse đến file ADT.zip vừa download về (không giải nén nhé). Click OK. Nếu không có file ADT.zip thì có thể gõ địa chỉ này tại Location: http://dl-ssl.google.com/android/eclipse/ và chọn OK để cài online.
—-5. Trở lại cửa sổ Install, chọn như hình bên dưới:

-6. Chọn Next để cập nhật ADT, sau khi cập nhật xong là Finish.
- Mac OS: hướng dẫn sau.

Cấu hình android SDK:
Sau khi hoàn tất các bước trên, tiến hành các bước config android SDK.
+ Đối với windows:
—-1. Giải nén file android-sdk-windows.zip.
—-2. Khởi động eclipse, chọn menu Window -> Preferences ->Chọn Android.
—-3. Tại SDK Location, Browse… đến thư mục android-sdk-windows đã giải nén. Chọn Apply, nếu hiển thị list danh sách các target là đã thành công, chọn OK.

Hoàn tất và demo emulator
Sau khi cài đặt xong, bây giờ trên menu toolbar của eclipse xuất hiện thêm 1 icon SDK Manager
+ Tạo AVD để chạy giả lập
—-1. Click vào icon như hình trên để tạo 1 ADV (tức điện thoại android giả lập để chạy ứng dụng).
—-2. Tại cửa sổ SDK Manager, chọn Vitural Device và chọn New

Còn tiếp

Tuesday, August 23, 2011

asp IsValidEmail

Function IsValidEmail(Email As String) As Boolean
If InStr(1, Email, ".") = 0 Then
IsValidEmail = False
Exit Function
End If

If InStr(1, Email, "@") = 0 Then
IsValidEmail = False
Exit Function
End If
IsValidEmail = True
End Function

Function FormatTime(TimeElapsed As Integer) As String
Dim Seconds As Integer
Dim Minutes As Integer
Dim Hours As Integer

'Find The Seconds
Seconds = TimeElapsed Mod 60

'Find The Minutes
Minutes = (TimeElapsed \ 60) Mod 60

'Find The Hours
Hours = (TimeElapsed \ 3600)

'Format The Time
If Hours > 0 Then
FormatTime = Format(Hours,"00") & ":"
End If
FormatTime = Format(Hours, "00") & ":"
FormatTime = FormatTime & Format(Minutes, "00") & ":"
FormatTime = FormatTime & Format(Seconds, "00")
End Function

Monday, August 1, 2011

cmd As Administrator -> cd C:\Windows\Microsoft.NET\Framework64\v4.0.30319 -> aspnet_regiis -i

If you’re new to IIS 7 (you probably are) you might receive this nice little gem when you first start working with it:

HTTP Error 500.19 – Internal Server Error
Description: The requested page cannot be accessed because the related configuration data for the page is invalid.
Error Code: 0×80070021
Notification: BeginRequest
Module: IIS Web Core
Requested URL: http://localhost:80/ExampleApplication/
Physical Path: C:\inetpub\wwwroot\ExampleApplication\
Logon User: Not yet determined
Logon Method: Not yet determined
Handler: Not yet determined
Config Error: This configuration section cannot be used at this path. This happens when the section is locked at a parent level. Locking is either by default (overrideModeDefault=”Deny”), or set explicitly by a location tag with overrideMode=”Deny” or the legacy allowOverride=”false”.
FONT color=#a52a2a>
Config File: \\?\C:\inetpub\wwwroot\ExampleApplication\web.config
Config Source:
  184:      185:      186:     

IIS 7 implements “Configuration Locking“. This is to help with IIS administration. The IIS Administrator can lock down Configuration Sections, Section Elements and Attributes at the IIS level. This allows the administrator to have a more granular level of control on the system. Read this link to see more about it.

Important Note: In order make these changes, you must be an administrator on the machine where the config file resides. If its on your local machine, you must be an administrator on your machine.

Since I’m on my own development machine, and since this is a development machine, I have decided to change the global setting (the config section itselft). To fix this error I had to go to the applicaitonHost.config file and set the overrideModeDefault to “Allow”.

Here’s how:

Open the applicationHost.config file, located here: %windir%\system32\inetsrv\config\applicationHost.config

In my instance, I need to edit the “handlers” section.

Change this line:

Deny” />

To:

Allow” />

Thats it. :)


You might receive more errors after you enable this, such as the same error for modules, but just follow the same steps above, and you should be good.

Note: You can accomplish this same thing through the command line by using the appcmd.exe application (%windir%\system32\inetsrv\appcmd.exe). Like this:

%windir%\system32\inetsrv\appcmd unlock config -section:system.webServer/handlers

One more note…

This is not something you’d want to do on a production server unless you’re sure you want to enable all appliations to override the section contents. Be sure to read up on some of the docs (explanation of the configuration system) before you make this change on production.

Thursday, July 14, 2011

Last week one of my team members was supposed to create a SQL Authenticated ID on a SQL Server 2005 instance. This was as per the request of the Application team who would be using it for an Application.

Since this is a routine task, the DBA created the ID. After passing on the credentials to the Application team, they started complaining that the application is unable to connect to the database using that ID. When the DBA tried connecting to the instance using that ID he got Reason: The password of the account has expired error. In SSMS the Login Properties looked like this.

Since this is an application id, the requirement is the password should never expire. But the DBA had forgot to uncheck the Enforce password policy and User must change password at next login checkbox while creating the ID (these are by default selected). When the application tried connecting to the instance for the first time, the password had expired and it prompted it to be changed. Now the DBA realized the mistake he had done, he uncheck Enforce password policy option and clicked on Ok in SSMS. It was not supposed to be that easy and he got the following error message.

1
2
The CHECK_POLICY and CHECK_EXPIRATION options cannot be turned OFF when MUST_CHANGE is ON.
(Microsoft SQL Server, Error: 15128)

Since the password had already expired, SQL Server was not allowing to be changed with the existing options. Also you will notice that in the above screenshot the User must change password at next login checkbox is grayed out. The only option to overcome this situation was to change the password after disabling the Login Policy check. Here is the query which was used to fix this issue.

1
2
3
4
ALTER LOGIN [LoginName]
WITH PASSWORD = 'newpassword',
CHECK_POLICY = OFF,
CHECK_EXPIRATION = OFF

With this query, the password was successfully changed and the Policy check was disabled as per the requirement.

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

Sunday, May 22, 2011

One problem with HTML forms is it is hard to style the elements to fit into your design. The tutorial will show you how to style the hardest of them all, the select box.

The Plan

Unfortunately browsers allow limited skinning of select boxes. So the plan is to use jQuery to change a select box into a text box and a unorded list for the dropdown. When a user clicks on the text box it will display the list below the textbox, just like a regular select box, but it’s easier to style

see more and download: http://www.devirtuoso.com/2009/08/styling-drop-down-boxes-with-jquery/

Tuesday, May 17, 2011

Adding a column to a table in SQL Server is done using the ALTER TABLE tablename ADD command. When adding columns you can specify all the same settings available when creating a table.

In the example below, we will create a small sample table, then add columns using the ALTER TABLE command.

Multiple columns can be specificied by using the syntax below. First issue an alter table command then add the column name, data type, nullable, and default value.

CREATE TABLE dbo.Employees
(
EmployeeID int IDENTITY (1,1) NOT NULL PRIMARY KEY NONCLUSTERED
)
GO
ALTER TABLE dbo.Employees
ADD
FirstName varchar(50) NULL
,LastName varchar(50) NULL
,SSN varchar(9) NULL CONSTRAINT ssn_unique UNIQUE
,IsTerminated bit NOT NULL DEFAULT 0
,DateAdded datetime DEFAULT GETDATE()
,Comments varchar(255) SPARSE NULL -- SQL Server 2008 sparse column

The Alter Column statement can modify the data type and the Nullable attribute of a column. The syntax is the same for SQL Server 2005 and SQL Server 2008 except 2008 allows the sparse attribute to be changed.

For the example below, we will begin by creating a sample table, then we will modify the columns.

CREATE TABLE dbo.Employee
(
EmployeeID INT IDENTITY (1,1) NOT NULL
,FirstName VARCHAR(50) NULL
,MiddleName VARCHAR(50) NULL
,LastName VARCHAR(50) NULL
,DateHired datetime NOT NULL
)
-- Change the datatype to support 100 characters and make NOT NULL
ALTER TABLE dbo.Employee
ALTER COLUMN FirstName VARCHAR(100) NOT NULL
-- Change datatype and allow NULLs for DateHired
ALTER TABLE dbo.Employee
ALTER COLUMN DateHired SMALLDATETIME NULL
-- Set SPARSE columns for Middle Name (sql server 2008 only)
ALTER TABLE dbo.Employee
ALTER COLUMN MiddleName VARCHAR(100) SPARSE NULL

Tuesday, May 10, 2011

How to use ASP & MySQL Add/Insert Multiple Rows Record This is tutorial asp developers how to using ASP add insert multiple record to MySQL table.

ShotDev Focus:
- ASP & MySQL add insert multiple record.

Example

see more here

Thursday, May 5, 2011

DECLARE mycur CURSOR FOR select O.type_desc,schema_id,O.name
from
sys
.objects O LEFT OUTER JOIN
sys
.extended_properties E ON O.object_id = E.major_id
WHERE
O
.name IS NOT NULL
AND ISNULL(O.is_ms_shipped, 0) = 0
AND ISNULL(E.name, '') <> 'microsoft_database_tools_support'
AND ( O.type_desc = 'SQL_STORED_PROCEDURE' OR O.type_desc = 'SQL_SCALAR_FUNCTION' )
ORDER BY O.type_desc,O.name;

OPEN mycur;

DECLARE @schema_id int;
DECLARE @fname varchar(256);
DECLARE @sname varchar(256);
DECLARE @ftype varchar(256);

FETCH NEXT FROM mycur INTO @ftype, @schema_id, @fname;

WHILE @@FETCH_STATUS = 0
BEGIN
SET @sname = SCHEMA_NAME( @schema_id );
IF @ftype = 'SQL_STORED_PROCEDURE'
EXEC( 'DROP PROCEDURE "' + @sname + '"."' + @fname + '"' );
IF @ftype = 'SQL_SCALAR_FUNCTION'
EXEC( 'DROP FUNCTION "' + @sname + '"."' + @fname + '"' );

FETCH NEXT FROM mycur INTO @ftype, @schema_id, @fname;
END

CLOSE mycur
DEALLOCATE mycur

GO

DECLARE @Sql NVARCHAR(500) DECLARE @Cursor CURSOR

SET @Cursor = CURSOR FAST_FORWARD FOR

SELECT DISTINCT sql = 'ALTER TABLE [' + tc2.TABLE_NAME + '] DROP [' + rc1.CONSTRAINT_NAME + ']'

FROM INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS rc1

LEFT JOIN INFORMATION_SCHEMA.TABLE_CONSTRAINTS tc2 ON tc2.CONSTRAINT_NAME =rc1.CONSTRAINT_NAME

OPEN @Cursor FETCH NEXT FROM @Cursor INTO @Sql

WHILE (@@FETCH_STATUS = 0)

BEGIN

Exec SP_EXECUTESQL @Sql

FETCH NEXT FROM @Cursor INTO @Sql

END

CLOSE @Cursor DEALLOCATE @Cursor

GO

EXEC sp_MSForEachTable 'DROP TABLE ?'

GO

Monday, May 2, 2011

Get all day in month

--**********************
DECLARE @FirstDay smalldatetime, @NumberOfMonths int
SELECT @FirstDay = '2008-02-01', @NumberOfMonths = 1
;WITH Days AS (
SELECT @FirstDay as CalendarDay
UNION ALL
SELECT DATEADD(d, 1, CalendarDay) as CalendarDay
FROM Days
WHERE DATEADD(d, 1, CalendarDay) < DATEADD(m, @NumberOfMonths, @FirstDay)
)
SELECT CONVERT(char(8), CalendarDay, 112) FROM Days
--**********************

Friday, April 29, 2011

string query = "Insert Into tests (tests) Values (@tests);" +
"Select @@Identity";
using (SqlConnection conn = new SqlConnection(connStr))
{
using (SqlCommand cmd = new SqlCommand(query, conn))
{

cmd.Parameters.AddWithValue("@tests", "tests");
conn.Open();
//cmd.ExecuteScalar();
int Idd;
Idd = Convert.ToInt32(cmd.ExecuteScalar());
lblMessage.Text = "ggggggggg" + Idd;
}
}

Thursday, April 28, 2011

Frustrated with the form elements inconsistency among different browsers? With these jQuery plugins, you can unified the look and feel of all your form elements.

Form Validation

It's always good to have client side form validation. These jQuery plugin will save your times and works by reusing already made form validation.

Masking

Masking can help to avoid human mistake. I found these plugins are very helpful to guide users and decrease the chances of bad data.

File Uploader

These file uploader transform the orginal input file element into a more robust file uploader that able to upload multiple files and having a progress bar to indicate the upload progress.

Checkbox & Radio Button

Spice it up your checkbox and radio button with these jQuery plugins!

Spin Button & Slider

Spin button can be useful sometimes. The other alternative will be a slider.

Auto Complete

You must have seen the auto complete functionality from Apple.com, google.com and all the major websites. With the following plugins, we, too can implement it in our websites easily.

Calendar & Time picker

The old school method to let user select date and time are using drop down lists (day, month and year). Now, we can use a calendar, timepicker to replace the old way. Since it's picked from calendar, it decreases the chances of invalid date. I like them.

Drop Down Menu (Select Element)

Want to do more with drop down menu? These plugins able to add more capabilities to drop down menu.

Color Picker

If you are building some online tools that involves colours, I guess you will like the following plugins. jQuery based colour pickers!

Textarea

Sometimes, we get really annoyed when we have to type in message in such a small space (a textarea), and we have to scroll up and down, left and right (sometimes) to read the entire message. Say no more to scrolling! Add this autogrow/resizer capability to textarea to avoid that.

Conclusion

All the plugins are implemented using jQuery, there are still heaps of them out there. Of course, you might able to find other good stuff which are not made from jQuery. If you wrote jQuery plugin that enhances form, and you think it's really cool. Drop me a comment, I will add it in