chuyển đổi datetime từ timezone này sang timezone khác trong .net

by Neon Quach 23. May 2010 17:58

Time là 1 vấn đề yêu cầu chung của các ứng dụng hiện nay, chẳng hạn như khi bạn develop ứng dụng cho Netherlands liên quan đến thời gian hiển thị trên website trên mấy với timezone khác (GMT+07:00) Bangkok, Hanoi, Jakarta) chẳng hạn, đó là vấn đề thường xảy ra, may thay .Net hổ trợ chúng ta việc chuyển đổi qua lại dự trên TimeZone ID.

C# Snippet code

DateTime
now = DateTime.Now;
Console
.WriteLine(TimeZoneInfo.ConvertTimeBySystemTimeZoneId(now, "SE Asia Standard Time").ToString("yyyy-MM-dd HH-mm-ss"));
Console
.Read();

 


VB.NET Snippet code

Dim
now As DateTime = DateTime.Now
Console.WriteLine(TimeZoneInfo.ConvertTimeBySystemTimeZoneId(now, "SE Asia Standard Time").ToString("yyyy-MM-dd HH-mm-ss"))
Console
.Read()

Và đây là danh sách các timezone ID được .net support

 

Time Zone ID

Time Zone Display Name

Morocco Standard Time

(GMT) Casablanca

GMT Standard Time

(GMT) Greenwich Mean Time : Dublin, Edinburgh, Lisbon, London

Greenwich Standard Time

(GMT) Monrovia, Reykjavik

W. Europe Standard Time

(GMT+01:00) Amsterdam, Berlin, Bern, Rome, Stockholm, Vienna

Central Europe Standard Time

(GMT+01:00) Belgrade, Bratislava, Budapest, Ljubljana, Prague

Romance Standard Time

(GMT+01:00) Brussels, Copenhagen, Madrid, Paris

Central European Standard Time

(GMT+01:00) Sarajevo, Skopje, Warsaw, Zagreb

W. Central Africa Standard Time

(GMT+01:00) West Central Africa

Jordan Standard Time

(GMT+02:00) Amman

GTB Standard Time

(GMT+02:00) Athens, Bucharest, Istanbul

Middle East Standard Time

(GMT+02:00) Beirut

Egypt Standard Time

(GMT+02:00) Cairo

South Africa Standard Time

(GMT+02:00) Harare, Pretoria

FLE Standard Time

(GMT+02:00) Helsinki, Kyiv, Riga, Sofia, Tallinn, Vilnius

Israel Standard Time

(GMT+02:00) Jerusalem

E. Europe Standard Time

(GMT+02:00) Minsk

Namibia Standard Time

(GMT+02:00) Windhoek

Arabic Standard Time

(GMT+03:00) Baghdad

Arab Standard Time

(GMT+03:00) Kuwait, Riyadh

Russian Standard Time

(GMT+03:00) Moscow, St. Petersburg, Volgograd

E. Africa Standard Time

(GMT+03:00) Nairobi

Georgian Standard Time

(GMT+03:00) Tbilisi

Iran Standard Time

(GMT+03:30) Tehran

Arabian Standard Time

(GMT+04:00) Abu Dhabi, Muscat

Azerbaijan Standard Time

(GMT+04:00) Baku

Mauritius Standard Time

(GMT+04:00) Port Louis

Caucasus Standard Time

(GMT+04:00) Yerevan

Afghanistan Standard Time

(GMT+04:30) Kabul

Ekaterinburg Standard Time

(GMT+05:00) Ekaterinburg

Pakistan Standard Time

(GMT+05:00) Islamabad, Karachi

West Asia Standard Time

(GMT+05:00) Tashkent

India Standard Time

(GMT+05:30) Chennai, Kolkata, Mumbai, New Delhi

Sri Lanka Standard Time

(GMT+05:30) Sri Jayawardenepura

Nepal Standard Time

(GMT+05:45) Kathmandu

N. Central Asia Standard Time

(GMT+06:00) Almaty, Novosibirsk

Central Asia Standard Time

(GMT+06:00) Astana, Dhaka

Myanmar Standard Time

(GMT+06:30) Yangon (Rangoon)

SE Asia Standard Time

(GMT+07:00) Bangkok, Hanoi, Jakarta

North Asia Standard Time

(GMT+07:00) Krasnoyarsk

China Standard Time

(GMT+08:00) Beijing, Chongqing, Hong Kong, Urumqi

North Asia East Standard Time

(GMT+08:00) Irkutsk, Ulaan Bataar

Singapore Standard Time

(GMT+08:00) Kuala Lumpur, Singapore

W. Australia Standard Time

(GMT+08:00) Perth

Taipei Standard Time

(GMT+08:00) Taipei

Tokyo Standard Time

(GMT+09:00) Osaka, Sapporo, Tokyo

Korea Standard Time

(GMT+09:00) Seoul

Yakutsk Standard Time

(GMT+09:00) Yakutsk

Cen. Australia Standard Time

(GMT+09:30) Adelaide

AUS Central Standard Time

(GMT+09:30) Darwin

E. Australia Standard Time

(GMT+10:00) Brisbane

AUS Eastern Standard Time

(GMT+10:00) Canberra, Melbourne, Sydney

West Pacific Standard Time

(GMT+10:00) Guam, Port Moresby

Tasmania Standard Time

(GMT+10:00) Hobart

Vladivostok Standard Time

(GMT+10:00) Vladivostok

Central Pacific Standard Time

(GMT+11:00) Magadan, Solomon Is., New Caledonia

New Zealand Standard Time

(GMT+12:00) Auckland, Wellington

Fiji Standard Time

(GMT+12:00) Fiji, Kamchatka, Marshall Is.

Tonga Standard Time

(GMT+13:00) Nuku'alofa

Azores Standard Time

(GMT-01:00) Azores

Cape Verde Standard Time

(GMT-01:00) Cape Verde Is.

Mid-Atlantic Standard Time

(GMT-02:00) Mid-Atlantic

E. South America Standard Time

(GMT-03:00) Brasilia

Argentina Standard Time

(GMT-03:00) Buenos Aires

SA Eastern Standard Time

(GMT-03:00) Georgetown

Greenland Standard Time

(GMT-03:00) Greenland

Montevideo Standard Time

(GMT-03:00) Montevideo

Newfoundland Standard Time

(GMT-03:30) Newfoundland

Atlantic Standard Time

(GMT-04:00) Atlantic Time (Canada)

SA Western Standard Time

(GMT-04:00) La Paz

Central Brazilian Standard Time

(GMT-04:00) Manaus

Pacific SA Standard Time

(GMT-04:00) Santiago

Venezuela Standard Time

(GMT-04:30) Caracas

SA Pacific Standard Time

(GMT-05:00) Bogota, Lima, Quito, Rio Branco

Eastern Standard Time

(GMT-05:00) Eastern Time (US & Canada)

US Eastern Standard Time

(GMT-05:00) Indiana (East)

Central America Standard Time

(GMT-06:00) Central America

Central Standard Time

(GMT-06:00) Central Time (US & Canada)

Central Standard Time (Mexico)

(GMT-06:00) Guadalajara, Mexico City, Monterrey

Canada Central Standard Time

(GMT-06:00) Saskatchewan

US Mountain Standard Time

(GMT-07:00) Arizona

Mountain Standard Time (Mexico)

(GMT-07:00) Chihuahua, La Paz, Mazatlan

Mountain Standard Time

(GMT-07:00) Mountain Time (US & Canada)

Pacific Standard Time

(GMT-08:00) Pacific Time (US & Canada)

Pacific Standard Time (Mexico)

(GMT-08:00) Tijuana, Baja California

Alaskan Standard Time

(GMT-09:00) Alaska

Hawaiian Standard Time

(GMT-10:00) Hawaii

Samoa Standard Time

(GMT-11:00) Midway Island, Samoa

Dateline Standard Time

(GMT-12:00) International Date Line West

Refereence

Tags: , ,


Categories: net framework | c# | vb.net

var keyword trong c#

by Neon Quach 20. May 2010 22:04

Từ version .net 2.0 thì khi khai báo 1 biến trong c# thì phải đi kèm với kiểu giá trị của nó, ví dụ khai báo 1 biến để lưu giá trị kiểu int thì người ta dùng:

int a = 0;

Thế nhưng sau khi có sự xuất hiện của linq thì từ version .net 3.0 trở đi cho phép chúng ta khai bao 1 biến lưu giá trị ngầm định, "ngầm định" ở đây là chúng ta sẻ chưa biết kiểu giá trị của nó cho đến khi trình biên dịch quyết định kiểu giá trị của nó.

Khi đó kiểu giá trị của nó sẻ phụ thuộc vào giá trị bên vế phải ví dụ:

var helloworld = "Hello world";

Khi đó helloworld sẻ có kiểu giá trị là kiểu int, how to check it

var helloworld = "Hello world";

Console.WriteLine(helloworld.GetType().Name);

Console.Read();

Giới hạn:
Chắc rằng var keyword cũng có mặt giới hạn của nó, thứ nhất nó chỉ cho phép khai báo trong phạm vi cục bộ (local) trong phương thức hoặc thuộc tính, và không hợp lệ nếu như kiểu dữ liêu trả về là var, cũng như là tham số cho phương thức.

Ví dụ: private var myInt = 10;

public var MyMethod(var x, var y) { }


Trình biên dịch sẻ báo lổi không thể biên dịch, tiếp theo là khi khai báo chúng ta phải gián giá trị mặc định cho nó, và giá trị đó không được null

// Error! Must assign a value!

var myData;

// Error! Must assign value at exact time of declaration!

var myInt;

myInt = 0;

// Error! Can't assign null as initial value!

var myObj = null;

Biên dịch không thành công

Kết luân: nếu chúng ta chưa biết giá trị cần lưu là gì thì nên dùng từ khóa var.
History version:
√ 20/05/2010 first release
√ 27/05/2010 add Restrictions of var keyword

Tags:


Categories: c#

asp.net role membership provider phần 3

by Neon Quach 19. May 2010 02:43

Trong phần 3 này chúng ta sẻ tìm hiểu về cách thực thi việc buộc thành viên thay đổi mật khẩu khi mật khẩu đã quá hạn. Đối với người dùng Window thì đây không phải là công việc lạ lẫm gì, việc buộc người dùng phải thay đổi mật khẩu của mình, vì mục đích bảo mật.

Đầu tiên mình sẻ tạo 1 trang ChangePassword.aspx, trang này sẻ cho phép người dùng nhập mật khẩu mới.



Ở trang này mình sẻ dùng
asp:ChangePassword user control và template lại với việc thêm 1 dòng username, như hình bên trên.

v à đây là code markup:

        <asp:ChangePassword ID="ChangePassword1" runat="server">

            <ChangePasswordTemplate>

                <table cellpadding="1" cellspacing="0" style="border-collapse: collapse;">

                    <tr>

                        <td>

                            <table cellpadding="0">

                                <tr>

                                    <td align="center" colspan="2">

                                        Change Your Password

                                    </td>

                                </tr>

                                <tr>

                                  <td align="right">

                                        <asp:Label ID="lblUser" runat="server" AssociatedControlID="txtUsername">User Name:</asp:Label>

                                    </td>

                                    <td>

                                        <asp:TextBox ID="txtUsername" runat="server"></asp:TextBox>

                                    </td>

                                </tr>

                                <tr>

                                    <td align="right">

                                        <asp:Label ID="CurrentPasswordLabel" runat="server" AssociatedControlID="CurrentPassword">Password:</asp:Label>

                                    </td>

                                    <td>

                                        <asp:TextBox ID="CurrentPassword" runat="server" TextMode="Password"></asp:TextBox>

                                        <asp:RequiredFieldValidator ID="CurrentPasswordRequired" runat="server" ControlToValidate="CurrentPassword"

                                            ErrorMessage="Password is required." ToolTip="Password is required." ValidationGroup="ChangePassword1">*</asp:RequiredFieldValidator>

                                    </td>

                                </tr>

                                <tr>

                                    <td align="right">

                                        <asp:Label ID="NewPasswordLabel" runat="server" AssociatedControlID="NewPassword">New Password:</asp:Label>

                                    </td>

                                    <td>

                                        <asp:TextBox ID="NewPassword" runat="server" TextMode="Password"></asp:TextBox>

                                        <asp:RequiredFieldValidator ID="NewPasswordRequired" runat="server" ControlToValidate="NewPassword"

                                            ErrorMessage="New Password is required." ToolTip="New Password is required."

                                            ValidationGroup="ChangePassword1">*</asp:RequiredFieldValidator>

                                    </td>

                                </tr>

                                <tr>

                                    <td align="right">

                                        <asp:Label ID="ConfirmNewPasswordLabel" runat="server" AssociatedControlID="ConfirmNewPassword">Confirm New Password:</asp:Label>

                                    </td>

                                    <td>

                                        <asp:TextBox ID="ConfirmNewPassword" runat="server" TextMode="Password"></asp:TextBox>

                                        <asp:RequiredFieldValidator ID="ConfirmNewPasswordRequired" runat="server" ControlToValidate="ConfirmNewPassword"

                                            ErrorMessage="Confirm New Password is required." ToolTip="Confirm New Password is required."

                                            ValidationGroup="ChangePassword1">*</asp:RequiredFieldValidator>

                                    </td>

                                </tr>

                                <tr>

                                    <td align="center" colspan="2">

                                        <asp:CompareValidator ID="NewPasswordCompare" runat="server" ControlToCompare="NewPassword"

                                            ControlToValidate="ConfirmNewPassword" Display="Dynamic" ErrorMessage="The Confirm New Password must match the New Password entry."

                                            ValidationGroup="ChangePassword1"></asp:CompareValidator>

                                    </td>

                                </tr>

                                <tr>

                                    <td align="center" colspan="2" style="color: Red;">

                                        <asp:Literal ID="FailureText" runat="server" EnableViewState="False"></asp:Literal>

                                    </td>

                                </tr>

                                <tr>

                                    <td align="right">

                                        <asp:Button ID="ChangePasswordPushButton" runat="server" CommandName="ChangePassword"

                                            Text="Change Password" ValidationGroup="ChangePassword1" />

                                    </td>

                                    <td>

                                        <asp:Button ID="CancelPushButton" runat="server" CausesValidation="False" CommandName="Cancel"

                                            Text="Cancel" />

                                    </td>

                                </tr>

                            </table>

                        </td>

                    </tr>

                </table>

            </ChangePasswordTemplate>

        </asp:ChangePassword>


 Việc kiểm tra liệu user đó có hay không việc thay đổi mật khẩu được tiến hành khi SignUp và mình cũng tiến hành thực thi lại việc kiểm tra user đăng nhập:

    protected void Login_OnClick(object sender, EventArgs e)

    {

        string passwordExpired = WebConfigurationManager.AppSettings["expired"];

 

        TextBox txtUsr = (TextBox)LoginView1.FindControl("txtUsr");

        TextBox txtPass = (TextBox)LoginView1.FindControl("txtPass");

        CheckBox RememberMe = (CheckBox)LoginView1.FindControl("RememberMe");

        Label FailureText = (Label)LoginView1.FindControl("FailureText");

        if (Page.IsValid)

        {

            if (Membership.ValidateUser(txtUsr.Text, txtPass.Text))

            {

                MembershipUser mUser = Membership.GetUser(txtUsr.Text);

                int days = Convert.ToInt32(DateTime.Now.Subtract(mUser.LastPasswordChangedDate).TotalDays);

 

                if (days > Convert.ToInt32(passwordExpired))

                {

                    Response.Redirect(String.Format("{0}{1}", "~/ChangePassword.aspx?UserName=", Server.UrlEncode(txtUsr.Text)));

                }

                else

                {

                    FormsAuthentication.RedirectFromLoginPage(txtUsr.Text, RememberMe.Checked);

                }

            }

            else

            {

                FailureText.Visible = true;

            }

        }

    }
 Trước khi thực thi đoạn code trên bạn sẻ phải chắc chắn rằng là bạn đã thêm 1 thiết lập expired mới trong web.config:

  <appSettings>

    <add  key="expired" value="20"/>

  </appSettings>


Đơn giản là sau khi chứng thực thành công, chúng ta sẻ lấy thông tin user thông qua hàm Membership.GetUser  và tham số truyền vào là tên user hiện tại đang login và đem so sánh giá trị của thuộc tính LastPasswordChangedDate với giá trị expired trong phần appSetting, nếu như số ngày lớn hơn số ngày mà bạn config thì tiến hành chuyển user sang trang ChangePassword.aspx.

Hope this help

Tags: , ,


Categories: asp.net | c#

khắc phục lổi potentially dangerous message trong blogengine

by Neon Quach 27. April 2010 03:26

khi approve bài viết trong blogengine nếu bài viết chứa các ký tự đặc biệt hoặc chứa ký tự html giống như:



Chúng ta sẻ gặp lổi sau và không thể approve bài viết được.



Lý do chúng ta submit form mà chứa các ký tự đặc biệt, để khắc phục trường hợp này trước khi submit, chúng ta phải encode các ký tự này trong textarea đi bằng cách thêm dòng

txtArea.Value = HttpUtility.HtmlEncode(_comment.Content);


Trong sự kiện page load của admin\Comments\Editor.aspx.cs thì chúng ta sẻ không thấy lổi này nửa.

Hope this help,

Tags: , ,


Categories: asp.net | blogengine | c#

nên Disposable SmtpClient object khi sử dụng .net 4.0

by Neon Quach 24. April 2010 21:52

Mặc định trình "thu lụm rác" (Garbage Collection) trong Visual studio sẻ tự động hủy object, sau khi nó không còn được reference nửa, nếu muốn tự tay mình disposable object sau khi object đó ra khỏi phạm vi sử lý nửa thì thường chúng ta wrap chúng trong using statement like:

using(object obj = new object())
{
.......
}


Trong version 3.5 trước của Net framework, khi chúng ta sử dụng object SmtpClient thì object này không inherit từ IDisposable nên chúng ta không thể bọc object trong using statement được. Nhưng đối với .net 4.0 thì chúng ta có thể làm được điều đó.

   
public string SendMail(string subject, string body, string to, bool isHtml, bool isSSL)
    {
        try
        {
            using (MailMessage mail = new MailMessage())
            {
                mail.From = new MailAddress(FormAddress, "code2code.info");
                mail.To.Add(to);
                mail.Subject = subject;
                mail.Body = body;
                mail.IsBodyHtml = isHtml;
                using (SmtpClient client = new SmtpClient())
                {
                    client.EnableSsl = isSSL;
                    if (FileUpload1.HasFile)
                    {
                        mail.Attachments.Add(new Attachment(FileUpload1.PostedFile.InputStream, FileUpload1.FileName));
                    }
                    client.Send(mail);
                }
            }
        }
        catch (SmtpException ex)
        {
            return ex.Message;
        }
        return "Send email successful!";
    }


Nếu chúng ta build với StyleCop enable thì sẻ cảnh báo message này:

Warning    20    CA2000 : Microsoft.Reliability : In method 'TestEmail.btnSendTest_Click(object, EventArgs)', call System.IDisposable.Dispose on object 'new SmtpClient()' before all references to it are out of scope.

Note: việc quản lý object bằng cách hủy chúng đi khi không còn reference nửa, rất quan trọng trong vấn đề cải thiện tốc độ cho ứng dụng, chúng ta nên warp tất cả các đối tượng nào kế thừa từ IDisposable.

Hope this help.

Tags: , , ,


Categories: asp.net | visual studio 2010 | visual studio tips | c#

hướng dẫn cài graffiti cms trên localhost

by Neon Quach 24. April 2010 21:01

Graffiti CMS là phần mềm mã nguồn mở viết bằng asp.net C#, được phát triển bởi Telligent, trước đây chúng ta đã biết đến Community Server cũng của cty này, Graffiti giúp chúng ta dễ dàng xuất bản (publish), cũng như dễ dàng quản lý, chỉnh sửa nội dung của bài viết 1 cách dễ dàng và nhanh chóng mà không cần đến kiến thức về lập trình.
Trong bài này mình sẻ huớng dẫn mọi người cách cài đặt Graffiti trên localhost.

Các bước thực hiện:
1. Cài đặt và tải mã nguồn Graffiti.
2. Tạo CSDL, thêm lược đồ (schema) và data cho csdl.
3. Cấu hình chuổi kết nối (connection string).
4. Cài đặt theme cho Graffiti.
5. Thêm mới 1 bài viết và tạo danh mục (catagory)

Let's started!
1. Cài đặt và tải mã nguồn Graffiti.
Trước khi cài đặt Graffiti, máy của chúng ta phải cần có Visual Studio (optinal) và sql server, version mình đang sài là VS2010 và sql2008, nhưng version củ hơn cũng có thể làm được. Download Graffiti tại http://graffiticms.codeplex.com/.

Download the source http://graffiticms.codeplex.com/SourceControl/ListDownloadableCommits.aspx
Download binary: http://graffiticms.com/lib/lib.zip
Giả nén source code, tiếp sau đó giả nén lib.zip và copy toàn bộ *.dll và bỏ vào thư mục \Branches\v1.3\src\Lib.

2. Tạo CSDL, thêm lược đồ (schema) và data cho csdl.
Mặc dù Graffiti support nhiều loại csdl nhưng trong bài này mình sẻ sử dụng csdl sql: Open Sql server và tạo csdl tên là Graffiti, sau đó tiến hành setup schema bằng cách run Branches\v1.3\data\Graffiti_SQL_Schema.sql, tiếp tục cài data Branches\v1.3\data\Graffiti_SQL_Data.sql

Begin inserting data in graffiti_Categories
(1 row(s) affected)
Begin inserting data in graffiti_Comments
Begin inserting data in graffiti_Logs
Begin inserting data in graffiti_ObjectStore
(1 row(s) affected)

3. Cấu hình chuổi kết nối (connection string).
Double click vào Graffiti.sln -> open web.config (có thể dùng notepad...) tìm đến dòng <add name="Graffiti" connectionString="...."
và sửa chúng thành

<add name="Graffiti" connectionString="Data Source=.\sqlexpress;Initial Catalog=Graffiti;Persist Security Info=True;User ID=sa;Password=111111"/>

Run trang default, Graffiti sẻ open màng hình config đầu tiên như hình sau:

graffiti config

Sau khi save xong Graffiti sẻ redirect chúng ta vào phần admin.

graffiti admin section

4. Cài đặt theme cho Graffiti.
Graffiti release với theme mặc định, để thay đổi theme, chúng ta tiến hành download tại http://ooto.info/files/uploads/freshG1.0.zip và giải nén chúng ta có 1 file freshG1.0.xml, đừng quan tâm đến filename, chúng ta sẻ import chúng vào.

Từ admin, chúng ta navigate đến Presentation → Themes
Upload Theme chọn file freshG1.0.xml vừa unrar.

graffiti theme

5. Thêm mới 1 bài viết và tạo danh mục (catagory)
Để tạo 1 bài viết mới chúng ta click chọn Write và nhập tiêu đề, nội dung, và tạo danh  mục mới nếu muốn.

graffiti new article

Tóm lại: Graffiti là phần mềm CMS mã mở, giúp chúng ta xây dựng và publish nội dung động, có thể mở rộng bằng các plug-in,widget, extension... 1 phần mềm tuyệt vời, đơn giản, và dễ sử dụng.

Tags: , , , ,


Categories: asp.net | open source | c# | graffiticms

compress javascript code using .net

by Neon Quach 15. April 2010 02:55

Compress your JavaScript file by removing UN use code, or comment, whitespace, trim… to make it load faster in your web page is one of good work.

My last post which shows you how to compress css code to decrease file size
http://code2code.info/post/Efficient-stylesheet-minification-in-Net.aspx

and now, I will show all of you how to apply this technique for JavaScript.

 For the demo purpose, I will create console application using both C# and VB.NET

here is c# function:

/// <summary>
        /// Strips the whitespace from any .js file.
        /// </summary>
        private static string StripWhitespace(string content)
        {
            string[] lines = content.Split(new string[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries);
            StringBuilder emptyLines = new StringBuilder();
            foreach (string line in lines)
            {
                string s = line.Trim();
                if (s.Length > 0 && !s.StartsWith("//"))
                    emptyLines.AppendLine(s.Trim());
            }
            content = emptyLines.ToString();
            // remove C styles comments
            content = Regex.Replace(content, "/\\*.*?\\*/", String.Empty, RegexOptions.Compiled | RegexOptions.Singleline);
            //// trim left
            content = Regex.Replace(content, "^\\s*", String.Empty, RegexOptions.Compiled | RegexOptions.Multiline);
            //// trim right
            content = Regex.Replace(content, "\\s*[\\r\\n]", "\r\n", RegexOptions.Compiled | RegexOptions.ECMAScript);
            // remove whitespace beside of left curly braced
            content = Regex.Replace(content, "\\s*{\\s*", "{", RegexOptions.Compiled | RegexOptions.ECMAScript);
            // remove whitespace beside of coma
            content = Regex.Replace(content, "\\s*,\\s*", ",", RegexOptions.Compiled | RegexOptions.ECMAScript);
            // remove whitespace beside of semicolon
            content = Regex.Replace(content, "\\s*;\\s*", ";", RegexOptions.Compiled | RegexOptions.ECMAScript);
            // remove newline after keywords
            content = Regex.Replace(content, "\\r\\n(?<=\\b(abstract|boolean|break|byte|case|catch|char|class|const|continue|default|delete|do|double|else|extends|false|
final|finally|float|for|function|goto|if|implements|import|in|instanceof|int|interface|long|native|new|null|package|
private|protected|public|return|short|static|super|switch|synchronized|this|throw|throws|transient|true|try|typeof|
var|void|while|with)\\r\\n)"
, " ", RegexOptions.Compiled | RegexOptions.ECMAScript);
            content = Regex.Replace(content, @"[\n\r]+\s*", string.Empty); // space
            return content;
        }

VB.NET

Public Function StripWhitespace(ByVal content As String) As String
        Dim lines() = content.Split(New String() {Environment.NewLine}, StringSplitOptions.RemoveEmptyEntries)
        Dim emptyLines As New StringBuilder()
        For Each line As String In lines
            Dim s = line.Trim()
            If s.Length > 0 AndAlso Not s.StartsWith("//") Then
                emptyLines.Append(s.Trim())
            End If
        Next
        content = emptyLines.ToString()
        ' remove C styles comments
        content = Regex.Replace(content, "/\*.*?\*/", [String].Empty, RegexOptions.Compiled Or RegexOptions.Singleline)
        content = Regex.Replace(content, "^\s*", [String].Empty, RegexOptions.Compiled Or RegexOptions.Multiline)
        content = Regex.Replace(content, "\s*[\r\n]", vbCr & vbLf, RegexOptions.Compiled Or RegexOptions.ECMAScript)
        ' remove whitespace beside of left curly braced
        content = Regex.Replace(content, "\s*{\s*", "{", RegexOptions.Compiled Or RegexOptions.ECMAScript)
        ' remove whitespace beside of coma
        content = Regex.Replace(content, "\s*,\s*", ",", RegexOptions.Compiled Or RegexOptions.ECMAScript)
        ' remove whitespace beside of semicolon
        content = Regex.Replace(content, "\s*;\s*", ";", RegexOptions.Compiled Or RegexOptions.ECMAScript)
        ' remove newline after keywords
        content = Regex.Replace(content, "\\r\\n(?<=\\b(abstract|boolean|break|byte|case|catch|char|class|const|continue|default|delete|do|double|else|extends|false|final|finally|
float|for|function|goto|if|implements|import|in|instanceof|int|interface|long|native|new|null|package|private|protected|public|
return|short|static|super|switch|synchronized|this|throw|throws|transient|true|try|typeof|var|void|while|with)\\r\\n)"
, " ", RegexOptions.Compiled Or RegexOptions.ECMAScript)
        content = Regex.Replace(content, "[\n\r]+\s*", String.Empty) ' space
        Return content
    End Function

Then I call this function in the Main

C#
static void Main(string[] args)
{
    string content = File.ReadAllText("../../blog.js");
    File.WriteAllText("../../blog-min.js", StripWhitespace(content));
    Console.Write("Press any key to continue!");
    Console.Read();
}

VB.NET

Sub Main()
        Dim content As String = File.ReadAllText("../../blog.js")
        File.WriteAllText("../../blog-min.js", StripWhitespace(content))
        Console.WriteLine("Press any key to continue!`")
        Console.Read()
End Sub


Done, now when you run this code, it will create a new file with compress content.

Tags: ,


Categories: javascript | c# | vb.net

AppDev Visual Studio 2010 Free Training

by Neon Quach 12. April 2010 23:39

AppDev Visual Studio 2010 Free Training


Your free Visual Studio 2010 training includes these courses and topics...

Exploring Visual Studio 2010 Using Visual Basic or Visual C# (full course)

-Investigate new language features and see the benefits of the new WPF-based IDE.
-Learn about many of the new ASP.NET Web Forms features.
-See how the all-new Workflow 4.0 works and get started learning its features.
-Create services using the new features in WCF.
-Drill into new WPF features, focusing on new controls, data binding and more.
-Create Silverlight applications using the new designer built into Visual Studio 2010.
-Incorporate Office 2010 features into .NET applications, focusing on SharePoint 2010.

Exploring Visual Studio 2010 ALM Tools (4 out of 8 modules)

-See the new features of Visual Studio 2010 for Application Lifecycle Management (ALM)
-Understand about Team System and Excel Reports as well as Ad-hoc reporting.
-Then move on to Version Control with Team Foundation Server version control concepts
- Learn about Microsoft Test and Lab Manager for test plans for both manual and automated testing.

P.S: YOU HAVE TO BE REGISTERED.

http://vs2010.appdev.com/default.aspx?src=EB01226

OR

http://vs2010.appdev.com/SN00068

Tags: , , ,


Categories: vs .net | c# | visual studio 2010

send email với attachment

by Neon Quach 9. April 2010 02:42

Ở bài viết trước Gửi Email động trong ASP.NET chúng ta đả được làm quen với đối tượng MailMessage và 1 số thuộc tính quan trong của nó trong việc gửi email.

Giờ chúng ta sẻ làm quen với việc làm thế nào để đính kèm tập tin khi send mail.

Tại source code tại: http://code2code.info/post/send-dynamic-email-in-aspnet.aspx và thêm mới 1 section bao gồm 1 nhãn named là Đính kèm và 1 FileUpload control.

            <tr>

                <td>Đính kèm:</td>

                <td>

                    <asp:FileUpload ID="FileUpload1" runat="server" Width="250px" />

                </td>

            </tr>
Chỉnh sửa 1 tí về cấu hình smtp, mình sẻ send mail dùng stmp của google, vì có rất nhiều bạn send mail và message cho mình nhờ giúp đở về việc send email sử dụng mail server của google.

  <system.net>

    <mailSettings>

      <smtp>

        <network host="smtp.gmail.com" port="587" userName="quachngochoangnguyen@gmail.com" password="your password"/>

      </smtp>

    </mailSettings>

  </system.net>

Ở đây mình cũng sẻ nói thêm luôn là nếu send mail thông qua mail server của google thì chúng ta sẻ phải enable SSL của đối tượng SmtpClient.

Chúng ta sẻ chỉnh sửa hàm SendMail để nhận đính kèm:

C#:
                if (FileUpload1.HasFile)

                {

                    mail.Attachments.Add(new Attachment(FileUpload1.PostedFile.InputStream, FileUpload1.FileName));

                }

                client.Send(mail);
VB:
                client.EnableSsl = isSSL

                If FileUpload1.HasFile Then

                    mail.Attachments.Add(New Attachment(FileUpload1.PostedFile.InputStream, FileUpload1.FileName))

                End If

                client.Send(mail)
Constructor của Attachment nhận vào 2 tham số bao gồm: nội dụng dạng Stream của file, và tên file, Press F5 lên và tiến hành send mail có đính kèm:



và kết quả:


Hope this help
Check out my code:http://code2code.googlecode.com/svn/trunk/SendingDynamicEmailWithAttachment

SendingDynamicEmailWithAttachment.rar (8.38 kb)

Tags: , ,


Categories: asp.net | net framework | c#

Phân biệt HOA thường với StringComparer.OrdinalIgnoreCase

by Neon Quach 1. April 2010 03:24

Nếu bạn so sánh 1 chuổi nào đó có trong mãng các ký tự hay không, nhưng phất lờ việc phân biệt Hoa thường, thì đây sẻ là cách

 

using System;

using System.Linq;

 

namespace CS

{

    class Program

    {

        static void Main(string[] args)

        {

            string[] name = { "NeonQuach", "QuachNguyen" };

            if (name.Contains("neonquach",StringComparer.OrdinalIgnoreCase))

            {

                Console.WriteLine("compare with no case-sensitive, neonquach exits in name array");

            }

            else if (name.Contains("neonquach"))

            {

                Console.WriteLine("compare with case-sensitive");

            }

            Console.Read();

        }

    }

}


VB.NET
Module Module1

 

    Sub Main()

        Dim name As String() = {"NeonQuach", "QuachNguyen"}

        If name.Contains("neonquach", StringComparer.OrdinalIgnoreCase) Then

            Console.WriteLine("compare with no case-sensitive, neonquach exits in name array")

        ElseIf name.Contains("neonquach") Then

            Console.WriteLine("compare with case-sensitive")

        End If

        Console.Read()

    End Sub

 

End Module


Mặc định nếu không có StringComparer.OrdinalIgnoreCase thì chuổi chúng ta đem đi so sánh nó phân biệt Hoa thường

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

Tags: , ,


Categories: net framework | c# | vb.net

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