ASP.NET – Serialize đối tượng .NET thành JSON và ngược lại

Các dữ liệu JSON được sử dụng rất thường xuyên trong ứng dụng web, đặc biệt khi cần truyền dữ liệu thông qua ajax. Trong ASP.NET, bạn có thể sử dụng classJavaScriptSerializer để chuyển đối một đối tượng .NET (hay CLR) bất kì thành một chuỗi JSON và ngược lại. Đồng thời, bạn có thể tạo ra các JavaScriptConverter để quy định cách thức chuyển đổi của JavaScriptSerializer.

Cơ bản

Trong bài viết này, tôi sử dụng một ứng dụng kiểu Console vì vậy cần phải thêm tham chiếu đến assembly System.Web.Script.Serialization. Class  JavaScriptSerializer chứa hai phương thức là  Serialize() và  Deserialize() dùng để chuyển đối tượng thành chuỗi JSON và ngược lại. Với một collection, phương thức Serialize() sẽ trả về một chuỗi JSON dạng mảng.

class Foo
{
    public int Id { get; set; }
    public string Name { get; set; }
    public DateTime Birthday { get; set; }
}
class Program
{
    static void Main(string[] args)
    {
        var js = new JavaScriptSerializer();
        var foo=new Foo(){
            Id = 1,
            Name = "Bar",
            Birthday = DateTime.Today
        };
        var json = js.Serialize(foo);
        Console.WriteLine("+ Serialize:\n"+json+"\n");
        var obj = (Foo) js.Deserialize(json, typeof(Foo));
        Console.WriteLine("+ Deserialize:\nId = {0} \nName = {1} \nBirthday = {2}",obj.Id,obj.Name,obj.Birthday);
        Console.Read();
    }
}
Ouput:

+ Serialize:
{"Id":1,"Name":"Bar","Birthday":"\/Date(1329670800000)\/"}
+ Deserialize:
Id = 1
Name = Bar
Birthday = 2/19/2012 5:00:00 PM

Sử dụng JavaScriptConverter

Trong ví dụ trên, kiểu dữ liệu DateTime được serialize thành một chuỗi rất khó để đọc và định dạng khi cần thiết. Vì thế tôi sẽ tạo một tạo một converter sau đó đăng kí cho đối tượng  JavaScriptSerializer. Converter tôi cần tạo phải được thừa kế từ JavaScriptConverter. Class này có 3 thành viên cần được override trong subclass:
-        SupportedTypes: property này sẽ trả về một danh sách các kiểu dữ liệu được hỗ trợ bởi converter này.
-        Serialize: Phương thức này sẽ tạo một đối tượng Dictionary chứa các cặp name/value dùng để chuyển đổi một đối tượng thành JSON.
-        Deserialize: Phương thức này nhận các dữ liệu cần thiết từ một Dictionary để tạo ra đối tượng .NET.
Như vậy Dictionary chính là đối tượng trung gian của quá trình chuyển đổi giữa đối tượng .NET và JSON. Mọi công việc mà bạn cần thực hiện chỉ đơn giản là thao tác trên dữ liệu của đối tượng Dictionary.
Tôi sẽ viết một class  MyFooConverter và sau đó đăng kí một instance của nó vào  JavaScriptSerializer bằng phương thức  RegisterConverters():

public class MyFooConverter : JavaScriptConverter
{
    public override IEnumerable SupportedTypes
    {
        get { return new List() { typeof(Foo) }; }
    }
    public override IDictionary Serialize(object obj, JavaScriptSerializer serializer)
    {
        var result = new Dictionary();
        var foo = obj as Foo;
        if (foo == null)
            return result;
        result["Id"] = foo.Id;
        result["Name"] = foo.Name;
        result["Birthday"] = foo.Birthday.ToShortDateString();
        return result;
    }
    public override object Deserialize(IDictionary dictionary, Type type, JavaScriptSerializer serializer)
    {
        if (dictionary == null)
            throw new ArgumentNullException("dictionary");
        return new Foo()
        {
            Id = (int) dictionary["Id"],
            Name = (string) dictionary["Name"],
            Birthday = DateTime.Parse(dictionary["Birthday"].ToString())
        };
    }
}
// Main method:
// …
 var js = new JavaScriptSerializer();
        js.RegisterConverters(new []{ new MyFooConverter() });
// ...
Output:


{"Id":1,"Name":"Bar","Birthday":"2/20/2012"}

Một Converter linh hoạt hơn

Sẽ rất bất tiện nếu như đối tượng bạn cần chuyển đối có quá nhiều property, việc override hai phương thức Serialize() và Deserialize() sẽ chiếm một số lượng code kha khá. Vì vậy, để giải quyết vấn đề này, tôi sẽ sử dụng reflection để tự động xây dựng một Dictionary từ đối tượng:

public class MyFooConverter : JavaScriptConverter
{
    public override IEnumerable SupportedTypes
    {
        get { return new List() { typeof(Foo) }; }
    }
    public override IDictionary<string, object> Serialize(object obj, JavaScriptSerializer serializer)
    {
        if (obj == null)
            return new Dictionary<string, object>();
        var result = obj.GetType()
             .GetProperties()
             .ToDictionary(p => p.Name, p => p.GetValue(obj, null));
        result["Birthday"] = ((DateTime)result["Birthday"]).ToShortDateString();
        return result;
    }
    public override object Deserialize(IDictionary<string, object> dictionary, Type type, JavaScriptSerializer serializer)
    {
        if (dictionary == null)
            throw new ArgumentNullException("dictionary");
        return new Foo()
        {
            Id = (int) dictionary["Id"],
            Name = (string) dictionary["Name"],
            Birthday = DateTime.Parse(dictionary["Birthday"].ToString())
        };
    }
}

Đoạn mã trên chỉ là một ví dụ đơn giản về cách làm và nó cần phải cải tiến để có thể được cho mọi class. Bạn có thể gọi đây là một JsDateTimeConverter, nhưng dĩ nhiên bạn có thể thay đổi nó để chuyển đối cả các kiểu dữ liệu khác về định dạng JSON cần thiết. Đây mới thực sự là đoạn mã tôi muốn giới thiệu:

Một Generic Javascript Converter

Kết hợp generic, LINQ và reflection để giải quyết, tôi được đoạn mã sau:

public class MyJsConverter : JavaScriptConverter
{
    public override IEnumerable SupportedTypes
    {
        get { return new List() { typeof(T) }; }
    }
    public override IDictionary<string, object> Serialize(object obj, JavaScriptSerializer serializer)
    {
        if (obj == null)
            return new Dictionary<string, object>();
        var result = obj.GetType()
             .GetProperties()
             .ToDictionary(p => p.Name,
                p => {
                 var value = p.GetValue(obj, null);
                 if (value.GetType() == typeof(DateTime))
                     value = ((DateTime)value).ToShortDateString();
                 return value;
                });
        return result;
    }
    public override object Deserialize(IDictionary<string, object> dictionary, Type type, JavaScriptSerializer serializer)
    {
        if (dictionary == null)
            throw new ArgumentNullException("dictionary");
        var foo = Activator.CreateInstance();
        foreach (var property in type.GetProperties())
        {
            var value = dictionary[property.Name];
            if (property.PropertyType == typeof(DateTime))
                value = DateTime.Parse(value.ToString());
            property.SetValue(foo,value,null);
        }
        return foo;
    }
}
Khi đăng kí, bạn cần xác định rõ kiểu dữ liệu cần chuyển đổi, hoặc bạn cũng có thể tạo một class converter sử dụng kiểu object:

var js = new JavaScriptSerializer();
js.RegisterConverters(new []{new MyJsConverter()});

Chọn và upload nhiều file giống như Gmail sử dụng Jquery và ASP.NET

Có 1 vài người hỏi làm thế nào upload nhiều file kiểu AJAX với progress bar tương tự như Google Gmail.Câu trả lời đó là Uploadify , 1 plugin cho Jquery có thể làm điều đó trong vài phút.Bài này tôi sẽ nói về vấn đề này.
Bước 1

Download Uploadify JQuery plugin và JQuery Library dùng link bên dưới.
Download JQuery

Download Uploadify


Bạn sẽ cần 4 file như bên dưới :


1. jquery-1.3.2.min.js
2. jquery.uploadify.js
3. uploader.fla
4. uploader.swf
trong thư mục scripts trong thư mục gốc của ứng dụng ASP.NET của bạn.
Bước 2
Mở Visual Studio và hoàn thành như bên dưới

Chèn các file CSS và JS trong thẻ head của trang aspx hoặc trang master

<link rel="Stylesheet" type="text/css" href="CSS/uploadify.css" />
<script type="text/javascript" src="scripts/jquery-1.3.2.min.js"></script>
<script type="text/javascript" src="scripts/jquery.uploadify.js"></script>
Add 1 control FileUpload ASP.Net

<form id="form1" runat="server">
    <div style = "padding:40px">
        <asp:FileUpload ID="FileUpload1" runat="server" />
    </div>
</form>
Đặt đoạn script sau trong thẻ head hoặc trong ContentPlaceHolder trong trường hợp bạn sử dụng Master Pages

<script type = "text/javascript">
$(window).load(
    function() {
    $("#<%=FileUpload1.ClientID %>").fileUpload({
        'uploader': 'scripts/uploader.swf',
        'cancelImg': 'images/cancel.png',
        'buttonText': 'Browse Files',
        'script': 'Upload.ashx',
        'folder': 'uploads',
        'fileDesc': 'Image Files',
        'fileExt': '*.jpg;*.jpeg;*.gif;*.png',
        'multi': true,
        'auto': true
    });
   }
);
</script>

Như các bạn thấy chúng ta cần 1 số cài đặt cho FileUpload control. Điểm quan trọng nhất trong đó là 'script': 'Upload.ashx'  cái này sẽ handle FileUpload và lưu file uploaded vào đĩa.
Bên dưới là code của file Upload.ashx


<%@ WebHandler Language="C#" Class="Upload" %>
  
using System;
using System.Web;
using System.IO;
  
public class Upload : IHttpHandler {
    
    public void ProcessRequest (HttpContext context) {
        context.Response.ContentType = "text/plain";
        context.Response.Expires = -1;
        try
        {
            HttpPostedFile postedFile = context.Request.Files["Filedata"];
            
            string savepath = "";
            string tempPath = "";
            tempPath = System.Configuration.ConfigurationManager.AppSettings["FolderPath"];
            savepath = context.Server.MapPath(tempPath);
            string filename = postedFile.FileName;
            if (!Directory.Exists(savepath))
                Directory.CreateDirectory(savepath);
  
            postedFile.SaveAs(savepath + @"\" + filename);
            context.Response.Write(tempPath + "/" + filename);
            context.Response.StatusCode = 200;
        }
        catch (Exception ex)
        {
            context.Response.Write("Error: " + ex.Message);
        }
    }
  
    public bool IsReusable {
        get {
            return false;
        }
    }
}
Như bạn thấy handle này đơn giản chỉ chấp nhận posted files và lưu file vào thư mục là uploads trong thư mục root của website , đường dẫn này đặt trong AppSettings của Web.Config
?
1
2
3
<appSettings>
    <add key ="FolderPath" value ="uploads"/>
</appSettings >

Đó là tất cả những gì chúng ta cần và sau cùng là chạy website chúng ta





 Chọn File để Upload

Bắt đầu upload file

Thật là dễ phải không nào. Chúc các bạn thành công

Cách tạo crystal report thật đơn giản

Nhiều bạn có mail cho mình hỏi cách làm crystal report. hôm nay, mình làm một tut hướng dẫn các bạn cách làm với bộ thư viện mình mới viết. Hi vọng sẽ giúp ích cho các bạn.

Video Download: http://www.mediafire.com/?yug89zd2heqbd48
Library download:http://www.mediafire.com/?w63ta25yycpd6mc

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

Import và Export Excel trong .NET

Trong bài viết hôm này, mình sẽ hướng dẫn các bạn cách Import excel từ một file có sẵn vào csdl và export dữ liệu từ csdl ra 1 file excel.
Đây là thư viện đã xây dựng sẵn, các bạn cứ thế mà dùng. Chỉ cần Add Reference đến thư viện này là được.
Trong thư viện có 2 phương thức đó là:
public DataTable ImportExcel(string strFileName,string strQuery)
Có tác dụng Import file Excel theo đường dẫn strFilename với câu truy vấn sql strQuery vào 1 DataTable.
Ví dụ:
DataTable dt=ImportExcel("D:\\123.xls","Select * from Sheet1");
Tiếp theo là
public void ExportToExcel(DataSet source,string filename)
Có tác dụng là Export dữ liệu từ DataSet source ra file Excel và lưu trữ ở đường dẫn filename
Ví dụ:
ExportToExcel(ds,"C:\\123.xls");

Đơn giản vậy thôi. Chúc các bạn thành công.

Phần mềm tự động sinh code C# và Store Procedure

Đây là phần mềm tự động sinh mã thực thi chức năng của ứng dụng (tầng thứ 2 trong mô hình 3 lớp) và các thủ tục (Store procedure) cần thiết. Nó có thể giúp các bạn giảm thời gian viết code xuống rất nhiều.
Capture
Clink here to start download
Cách sử dụng
- Đăng nhập vào hệ thống như khi đăng nhập vào Sql Server
- Chọn database name
- Chọn table name
- Ấn vào các nút để sinh mã tương ứng.
- Clink phải vào vùng chữ chọn Copy All
- Paste vào ứng dụng của mình
Hi vọng tool nhỏ này sẽ giúp ích nhiều cho các bạn khi viết ứng dụng với Csharp.NET

Các bạn có thể xem hướng dẫn tạo chương trình sinh code tại đây: