.Net Serialization

 Trong phần này sẽ đề cập đến Serialization trong .Net. Chúng ta sẽ tìm hiểu

  • Serialization là gì, tại sao phải Serialize một Object
  • Cách sử dụng Binary và Soap Fomartter để serialize Object


1. Giới thiệu

 
Chúng ta biết rằng trong lập trình hướng đối tượng, Object có thể bao gồm nhiều trạng thái khác nhau. Tại một thời điểm Object có một trạng thái xác định, trạng thái này được lưu trong memory. Khi chương trình kết thúc, trạng thái của Object sẽ bị xóa khỏi memory. 
Serialization là một cách để lưu trạng thái của Object ra một “định dạng” (format) mà có thể lưu được trên đĩa cứng hoặc vận chuyển qua mạng.
Người ta cũng sử dụng Serialization để lưu các bản ghi (structure) ra file nhị phân có cấu trúc (giống như trong C), vì các stream của .Net không hỗ trợ việc này. 
Các class dùng trong Serialization nằm trong namespace: System.Runtime.Serialization

 
1.2. Các loại Formatters trong .Net Serialization

 
Các Object được serialize ra một “định dạng” hay stream (luồng). Việc này sẽ được các Formatter class trong .Net kiểm soát.
Có 2 loại Formatter ta sẽ dùng:

  • BinaryFormatter: class này sẽ serialize Object ra một file nhị phân. Được implement từ IremotingFormatter. Có 2 phương thức chính Serialize() và Deserialize().
  • SoapFormatter: class sẽ serialize Object ra một file .xml theo đúng chuẩn của giao thức SOAP. Được implement từ Iformatter. Có 2 phương thức chính Serialize() và Deserialize().


2. Binary Formatter

 
Để serialize một Object cần có 3 yếu tố sau

  • Object được chỉ định [Serializable]
  • Stream để lưu Object sau khi được serialize
  • Formatter class để serialize Object


2.1. Tạo Class đơn giản sẽ dùng cho các ví dụ

 

[Serializable]
    public class Person
    {
        private string name = null;
        private int age = 0;
        private string address = null;
        private string mobile = null;

        public Person() { }

        public Person(string name, int age, string address, string mobile)
        {
            this.name = name;
            this.age = age;
            this.address = address;
            this.mobile = mobile;
        }

        public override string ToString()
        {
            StringBuilder sb = new StringBuilder();
            sb.AppendLine("Name=" + name);
            sb.AppendLine("Age=" + age);
            sb.AppendLine("Address=" + address);
            sb.AppendLine("Mobie=" + mobile);

            return sb.ToString();
        }
}

Tạo một class Person, để class có thể được serialize cần phải chỉ định [Serializable]

 
2.2. Serialize một Object

using System;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;

class TestSerialization
{
    static void Main(string[] args)
    {
        // Create an Object 
        Person person = new Person("HaPN2", 27, "Ha Noi", "0914348307");

        // Create a stream to store a serialized object
        string fileName = @"C:\BinarySerialization.ex";
        FileStream myStream = new FileStream(fileName, FileMode.Create, FileAccess.Write);

        // Create a binary formatter object
        BinaryFormatter formatter = new BinaryFormatter();

        // Serialize object to stream
        formatter.Serialize(myStream, person);

        // Close stream
        myStream.Close();
    }
}

2.3. Deserialize một Object

using System;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;

class TestSerialization
{
    static void Main(string[] args)
    {
        // Stream that store the serialized object
        string fileName = @"C:\BinarySerialization.ex";
        FileStream myStream = new FileStream(fileName, FileMode.Open);

        // Create a binary formatter object
        BinaryFormatter formatter = new BinaryFormatter();

        // Deserialize
        Person person = (Person)formatter.Deserialize(myStream);

        // Close stream
        myStream.Close();

        // Show object
        Console.WriteLine(person.ToString());
    }
}

3. Soap Formatter
3.1. Serialize một Object

using System;
using System.IO;
using System.Runtime.Serialization.Formatters.Soap;

class TestSerialization
{
    static void Main(string[] args)
    {
        // Create an Object 
        Person person = new Person("HaPN2", 27, "Ha Noi", "0914348307");

        // Stream to serialize object
        string fileName = @"C:\SoapSerialization.xml";
        FileStream myStream = new FileStream(fileName, FileMode.Create, FileAccess.Write);
        // Create a soap formatter object
        SoapFormatter formatter = new SoapFormatter();

        // Serialize object to stream
        formatter.Serialize(myStream , person);

        // Close stream
        myStream .Close();
    }
}

3.2. Deserialize một Object

using System;
using System.IO;
using System.Runtime.Serialization.Formatters.Soap;

class TestSerialization
{
    static void Main(string[] args)
    {
        // Stream that store the serialized object
        string fileName = @"C:\SoapSerialization.xml";
        FileStream myStream = new FileStream(fileName, FileMode.Open);

        // Create a binary formatter object
        SoapFormatter formatter = new SoapFormatter();

        // Deserialize
        Person person = (Person)formatter.Deserialize(myStream);

        // Close stream
        myStream.Close();

        // Show object
        Console.WriteLine(person.ToString());
    }
}

 

4. Chú ý

 
1. Chỉ định một thành phần của Class không bị Serialize.
Mặc định tất cả các thành phần trong Class: thuộc tính và phương thức sẽ đều được serialize khi thực hiện. Tuy nhiên ta có thể dùng chỉ định [NonSerialized] để thiết lập không serialize thành phần này
Vd: 
 

[NonSerialized]
public string GetName()
{
    return name;
}

2. Reference đến Soap formatter
Đôi khi ta sẽ phải thiết lập reference đến SoapFormatter trong VS 2005.
Từ menu: Project > Add Reference… > .Net > 
System.Runtime.Serialization.Formatters.Soap

3. Nếu trong Class được chỉ định [Serializable] có gọi đến các Class khác. Thì tất cả các Class tham chiếu này cũng đều phải được chỉ định [Serializable]

Nguồn: http://my.opera.com/hapn2/blog/net-serialization

Large file download in asp.net CSharp

There are different methods to download files.
But in different scenario there are different method, I have some research on it.

WriteFile method


This is perfect method to download but if you trying to download large file then it is not a perfect method because it stream a file and load into Server

RAM. That makes a failure if Client is trying to download multiple files from different system. So for Large file it make a server memory problems. If client

from different system trying to download a large file on same time it fails.

TransmitFile method

TransmitFile Method reads Transmit the file into smaller memory buffer .So you don’t have control over the response. You don’t know that download is

completed. If download fails it start download from start. And if  a file is large it will not tell you when the file is downloaded.
If anyone has any good idea pleases post here for knowledge.

How can we Multiple download same  Large file (greater 500mb) from different systems over the internet
Example

protected void DownloadFile(string filename)
   {


       string filepath = Server.MapPath(filename);
       FileStream fStream = null;
       try
       {
           fStream = new FileStream(filepath, FileMode.Open, FileAccess.Read);
           byte[] byteBuffer = new byte[(int)fStream.Length];
           fStream.Read(byteBuffer, 0, (int)fStream.Length);

           fStream.Close();
           Response.Clear();
           Response.ContentType = "application/octet-stream";
           Response.AddHeader("Content-Length", byteBuffer.Length.ToString());
           Response.AddHeader("Content-Disposition", "attachment; filename=" + file_name);
           Response.BinaryWrite(byteBuffer);
           Response.End();
       }
       catch (Exception ee)
       {
           if (fStream != null)
           {
               fStream.Close();
               fStream.Dispose();
           }
       }
   }

 

FIX: You cannot download large files from an ASP.NET application on a computer that is running IIS 6.0

FIX: You may receive an error message when you use a client application to connect to a server that is running IIS 6.0 or when you try to download files from the server

PRB: Response.WriteFile cannot download a large file

You cannot download files that are 2 GB or larger

ASP.NET postbacks and URL rewriting

ASP.NET Web Forms extensively use postback mechanism in order to maintain the state of the server-side controls on the web page. This makes it somewhat tricky to perform URL rewriting for ASP.NET pages. When a server side form control is added to the web page, ASP.NET will render the response with HTML <form> tag that contains an action attribute pointing back to the page where the form control is. This means that if URL rewriting was used for that page, the action attribute will point back to the rewritten URL, not to the URL that was requested from the browser. This will cause the browser to show rewritten URL any time a postback occurs.

Let me demonstrate this on an example. Assume you have a very simple web form in a file called default.aspx. When you request http://localhost/default.aspx in a browser and then view the HTML source for the response, you will see that the response contains the <form> element, which looks similar to this:

<form name="form1" method="post" action="Default.aspx" id="form1">

The action attribute contains the URL where the form data will be posted to when you click on the button in the web page.Khác...

DateDiff() function in C#

using System;


namespace ReflectionIT.System {

    public enum DateInterval {
        Year,
        Month,
        Weekday,
        Day,
        Hour,
        Minute,
        Second
    }

    public class DateTimeUtil {

        public static long DateDiff(DateInterval interval, DateTime date1, DateTime date2) {

            TimeSpan ts = date2 - date1;

            switch (interval) {
                case DateInterval.Year:
                    return date2.Year - date1.Year;
                case DateInterval.Month:
                    return (date2.Month - date1.Month) + (12 * (date2.Year - date1.Year));
                case DateInterval.Weekday:
                    return Fix(ts.TotalDays) / 7;
                case DateInterval.Day:
                    return Fix(ts.TotalDays);
                case DateInterval.Hour:
                    return Fix(ts.TotalHours);
                case DateInterval.Minute:
                    return Fix(ts.TotalMinutes);
                default:
                    return Fix(ts.TotalSeconds);
            }
        }

        private static long Fix(double Number) {
            if (Number >= 0) {
                return (long)Math.Floor(Number);
            }
            return (long)Math.Ceiling(Number);
        }
    }
}

JSON in .Net

Bài viết hướng dẫn chuyển đổi(convert) một chuỗi(string) định dạng JSON sang đối tượng (object) của .Net và ngược lại, sử dụng JavaScriptSerializer trong thư viện System.Web.Extensions.

Chúng ta đều biết đối tượng kiểu JSON cực kỳ thuận tiện trong tương tác javascript.
Nhưng khi tương tác với server thông qua Ajax, nó có một hạn chế. Ta ko thể truy xuất sâu hơn các thuộc tính trực tiếp của đối tượng.

Chẳng hạn, ta có đối tượng JSON như sau:

var person = {
     name    : "svincoll",
     address : {
          street : "Le Lai"
          city   : "hcm"
     }
 }

 

sau đó, ta dùng ajax đưa dữ liệu này về server thông qua POST.

 

$.post("jsonDemo.aspx", person);

Hãy xem, ta lấy được gì ở server nhé:



Như vậy, với thuộc tính name ta lấy được giá trị, còn address thì không.
Bởi vì giá trị của address là đối tượng JSON, và browser đã sử dụng hàm toString() trong trường hợp này.

Có lẽ vì điều đó mà bạn nên đọc bài viết này bigsmile

1. Javascript Serialize

Trong Ajax Extensions, có hỗ trợ cho chúng ta một lớp đối tượng JavaScriptSerializer, lớp đối tượng này cho phép ta chuyển đổi một đối tượng C# thành một chuỗi theo định dạng JSON và ngược lại.

Để minh họa điều này, ta sẽ xây dựng hai đối tượng PersonPersonAddress như sau:


Tiếp theo, ta sẽ khởi tạo đối tượng Person, và serialize nó thành chuỗi JSON:



kiểm tra giá trị của biến json, ta được chuỗi JSON như sau:

 

{"Name":"svincoll","Address":{"Street":"Le Lai","City":"hcm"}}

Với chuỗi JSON trên, ta hoàn toàn có thể deserialize để nhận về đối tượng Person ban đầu



Tới đây, việc xử lý dữ liệu phía codebehind (code server) đã xong. Vấn đề mấu chốt là chúng ta cần 1 chuỗi JSON, để từ đó convert qua object.

2. Ajax

Từ browser, chúng ta cần gửi đi một chuỗi JSON, ko phải đối tượng JSON, để server nhận được và chuyển đổi thành object tương ứng.

Việc này không quá khó. Chúng ta có thể viết một hàm riêng, chuyển đổi đối tượng JSON thành chuỗi, hoặc sử dụng các thư viện có sẵn như jQuery JSON

Nguồn: http://my.opera.com/svincoll4/blog/2009/10/18/json-in-net