2010/08/30

WPF: Binding a ListView to DataTable

Suppose you have a DataTable filled with data. And want a ListView to present the data. This code sample can help you.

XAML

<ListView Name="lv">
    <ListView.View>
        <GridView>
        </GridView>
    </ListView.View>
</ListView>

C#

string tableName = “some_table_name”;
DataSet ds = Dao.GetData(tableName);  // A class to retrieve dataset.
if (ds.Tables == null || ds.Tables.Count == 0)
    return;

GridView gv = (GridView)lv.View;

DataTable dt = ds.Tables[0];
foreach (DataColumn col in dt.Columns) {
    GridViewColumn gvCol = new GridViewColumn();
    gvCol.Header = col.ColumnName;
    gvCol.DisplayMemberBinding = new Binding(col.ColumnName);
    gvCol.Width = 100;
    gv.Columns.Add(gvCol);
}

lv.ItemsSource = ((IListSource)dt).GetList();

2010/06/11

Use WCF to upload image data within a class

Here is a workable sample of uploading image data by WCF.

Requirement:

I have a data model includes image. I want to upload it from client to server.

History:

It was a case in tabular model days. I serialize dataset to a xml file and zip the image file together.  Then upload the zip file to a FTP server. And server side programs will get the zip file in the ftp folder.

Issues:

When uploading files via FTP, I did not know the transfer result. Some times the zip file was broken, but I won't know until server sent an error report to me. Maybe add a md5 check will be good. But even md5 check solve the issue of the broken file. It still need me to do something manually to make the client upload files again. I want the client know uploading result in the meantime. And client can upload again if there is a problem.

Possible Solution:

First, I considered Web Services. But in the final I turned into WCF. Because it can host a service on any processes without a web server. I am not sure WCF is the best way for me. But it dose help me.

Studies:

I list these articles which help me to achieve the goal.

WCF Streaming: Upload files over HTTP by Kjell-Sverre Jerijærvi (February 07, 2007).
How to: Enable Streaming, MSDN.
XML Serialization in C# - Part II – Images by Prajna Das (March 29, 2007).
"There is an error in XML document (0, 0)." error while XML Deserialization, MSDN Data Developer Center Forum.

My first question is how to upload files with WCF. People will suggest you using “Streamed” transfer mode. But many samples I googled, the service only provide a method to receive Stream. What if I want to pass a class instance? Finally I figured out that serialize my class into stream and transfer to server.

The second question is how to serialize images. The article “XML Serialization in C#” listed above give me a thought that Bitmap is hard to handle. I am lazy and not smart, so I want the code is as simple as possible. Then I remembered a project which I participated around 2005. One program in that project has a function: save image to xml file. Lucky I could find that project beside my hand.

Everything is ready. Let’s look how to implement my solution.

Implement I: XML Serialization

In the first, I want to transfer a image data within a class. The data model is:

public class ImageData {
    public string Id { get; set; }
    [XmlElementAttribute(DataType = "base64Binary")]
    public byte[] ImageContent { get; set; }
}

You may notice that the ImageContent property is byte[]. And I added a attribute above it to tell Serializer how to serialize it. Here is a SerializeHelper class handles serialize and deserialize.

public class SerializeHelper {
    public static void Serialize<T>(out Stream stream, T item){
        stream = new MemoryStream();
        XmlSerializer x = new XmlSerializer(typeof(T));
        x.Serialize(stream, item);
        stream.Position = 0;   
    }

    public static T Deserialize<T>(Stream stream) {
        XmlSerializer x = new XmlSerializer(typeof(T));
        T obj = (T)x.Deserialize(stream);
        return obj;
    }
}

The last line of the method, Serialize, is very important. If you did not set the position to 0, you will encounter a exception when deserialize: “There is an error in XML document (0, 0)”. For more information, you can read the article I listed above to learn what happened.

Implement II: WCF service

The service is very simple.

[ServiceContract]
public interface IImageServer {
    [OperationContract]
    Stream GetStream(string data);

    [OperationContract]
    bool UploadStream(Stream stream);
}

Just as the same as MSDN sample. How do I implement it ? See this:

[ServiceBehavior(InstanceContextMode = InstanceContextMode.Single)]
public class PictureServer : IPictureServer {
    public System.IO.Stream GetStream(string data) {
        try {
            ImageData item = new ImageData();
            item.Id = "001";
            item.ImageContent = File.ReadAllBytes(@"c:\temp\001.tif");

            Stream stream = null;
            SerializeHelper.Serialize<ImageData>(out stream, item);
            return stream;

        } catch (Exception ex) {
            Console.Write(ex.Message);
            return null;
        }
    }
   public bool UploadStream(Stream stream) {
        if (stream == null)
        return false;
    
        try {
            ImageData item = SerializeHelper.Deserialize<ImageData>(stream);
            File.WriteAllBytes(@"c:\temp\001_server.tif", item.ImageContent);
        } catch (Exception) {
            return false;
        }
        return true;
    }
}

I hardcode the behaviors in GetStream and UploadStream just for testing the mechanism. And then the app.config of the service.

<?xml version="1.0" encoding="utf-8" ?>
<configuration> 
  <system.serviceModel> 
    <services> 
      <service name="StreamService.PictureServer" 
               behaviorConfiguration="PicutreServerBehavior"> 
        <host> 
          <baseAddresses> 
            <add baseAddress="http://localhost:8000/PictureServer"/> 
          </baseAddresses> 
        </host> 
        <endpoint address="" 
                  binding="basicHttpBinding" 
                  bindingConfiguration="StreamedHttp" 
                  contract="SteramService.IPictureServer"/> 
        <endpoint address="mex" 
                  binding="mexHttpBinding" 
                  contract="IMetadataExchange"/> 
      </service> 
    </services> 
    <bindings> 
      <basicHttpBinding> 
        <binding name="StreamedHttp" 
                 transferMode="Streamed" 
                 maxReceivedMessageSize="67108864"/> 
        </basicHttpBinding> 
    </bindings> 
    <behaviors> 
      <serviceBehaviors> 
        <behavior name="PicutreServerBehavior"> 
          <serviceMetadata httpGetEnabled="True"/> 
        </behavior> 
      </serviceBehaviors> 
    </behaviors> 
  </system.serviceModel>
</configuration>

The most important is the binding element. You need set transferMode to “Streamed” and set maxReceivedMessageSize appropriately. In my case, it is 64mb.

Implement III: Client

Now we can implement a client application to communicate the service. Upload and Get stream. I hardcode some behaviors, too.

class ClientApp {
    IPictureServer server;

    internal void Run() {
        ConnectServiceViaChannelFactory();
        GetImageData();
        UploadImageData();
    }

    private void UploadImageData() { 
        ImageData item = new ImageData();
        item.Id = "001";
        item.ImageContent = File.ReadAllBytes(@"c:\temp\001.tif");


        Stream stream = null
        SerializeHelper.Serialize<ImageData>(out stream, item);
        
        bool success = server.UploadStream(stream);
        if (success) {
            Console.WriteLine("Upload stream successfully.");
        } else {
            Console.WriteLine("Failed uploading stream.");
        }
        Console.WriteLine("Press <enter> to terminate.");
        Console.ReadLine();
    }
    private void GetImageData() {
        Stream stream = server.GetStream("");
        if (stream == null)
            return;

        ImageData item = SerializeHelper.Deserialize<ImageData>(stream);
        File.WriteAllBytes(@"c:\temp\001_client.tif", item.ImageContent);
    }
    private void ConnectServiceViaChannelFactory() {
        server = CreateServiceProxy<IPictureServer>(
            CreateStreamingBinding(),
            "http://localhost:8000/PictureServer");
    }
    private T CreateServiceProxy<T>(Binding binding, string address) {
        ChannelFactory<T> factory =
            new ChannelFactory<T>(
                binding,
                new EndpointAddress(address)
            );
        return factory.CreateChannel();
    }
    private Binding CreateStreamingBinding() {
        //max MessageSize: 64MB
        BasicHttpBinding binding = new BasicHttpBinding {
            TransferMode = TransferMode.Streamed,
            MaxReceivedMessageSize = 67108864
        };
        return binding;
    }
}

Beware that in CreateStreamingBinding method, we need set MaxReceivedMessageSize, too. After uploaded stream, we can get a result. In real case, if the result is false, we need take some actions. For example, save the item to a queue, and retry while a moment. Because the type of ImageData.ImageContent is byte array, it can be any type of file in the fact.Here is keywords for search engine.
WCF, upload image file, XML, Serialize, Bitmap, Complex type, stream, large data

2009/10/19

SONY VAIO FW27 可以裝 8GB 記憶體

欲望是無窮的,特別是要跑 VM 的機器,4GB 已經不能滿足。上 8GB 才是王道。

2009-10-19 17-17-30

2009/08/27

Google docs makes Firefox javascript engine busy.

After opened a document in Google docs, an alert window popup as the screenshot showed.

Firefox_busy_google_docs

Firefox version is 3.7a1pre.

2009/07/21

MSDN 雜誌線上文章中英對照功能

許久沒有看 MSDN 雜誌的線上文章了,赫然發現現在不但有中英對照本版,還可以逐句對映,並且可以編輯中譯內容。由於中文內容一向是繼器翻譯,所以文句上面總是不通順,微軟這招讓社群成員可以編輯中譯本的功能,也頗不錯,集合大家的力量讓中文化資源越來越豐富。雖然是機器翻譯,有些時候還是可以省去翻字典的時間。

msdn_mag

2009/07/10

Microsoft Expression Blend 2 SP1 安裝問題

在微軟 Expression 網站下載英文版的 Blend 2 試用版安裝完成後,接著下載 Blend 2 SP1,安裝完成後,執行 Blend 2 卻跳出一個警示訊息 "The prereleased version of this product has expired. You must update to a newer release.",關掉訊息後,程式也隨之結束。在 google 上爬文後於這個討論串看到有人(Cary321)發現解決方式。

在下載 Blend 2 SP1 的網頁,按下 download 後,會跳到一頁 “Thank You for Downloading” 的說明頁面。在這個說明頁面有另外一個連結,那種告訴你如果瀏覽器沒有自動下載檔案,可以點這裡下載的說明 : "If your download does not start after 30 seconds, click this link: Start download. " 請點一下 "Start download”,下載這個 Blend 2 SP1 安裝檔。

自動下載的檔案和手動下載的檔案名稱雖然一樣,但是檔案大小不同,請安裝手動下載的那個。現在,你可以安心的使用 Blend 2 了。

2009/07/07

在微軟報表檢視器加入自訂程式碼 實例說明

加入程式碼的 MSDN 說明請參考: Adding Custom Code to a ReportViewer Report

在製作報表的時候,客戶有一個需求,假設資料的內容如下:

班號
(ClassNumber)
學生姓名
(StudentName)
001 王大明
001 陳小華
002 李大丙
002 吳小菁
003 張小英

希望輸出的報表的時候,重複的班號不要顯示,如下:

班號 學生姓名
001 王大明
  陳小華
002 李大丙
  吳小菁
003 張小英

在一般製作報表的時候,班號的這個欄位會填上 Fileds!ClassNumber.Value 的內容,但要怎麼才可以濾掉重複出現的班號呢? 使用自訂程式碼。

展開 Visual Stuio 的命令選單 Rport –> Report Properties,選擇 Code 頁籤,寫一段判斷式的函式。如下:

Dim tempClassNumber as String = ""
Public Function ShowClassNumber(ByVal classNumber as String) as String
    If (classNumber = tempClassNumber)
        Return ""
    End If
    tempClassNumber = classNumber
    Return classNumber
End Function

然後在設計報表的地方使用如下的 expression:

=Code.ShowClassNumber(Fileds!ClassNumber.Value)

客戶期望的報表內容就成功了。

自訂程式碼是動態地將程式碼編譯到報表內建的 Code 類別,以記事本打開報表設計 rdlc 檔案,可以在 <code> 區塊看到上面寫的程式碼。在報表的 expression 編輯器,使用 Code 類別來呼叫。有幾點要注意一下:

1. 必須先編譯一次專案才可以使用自訂的程式碼。
2. 在 expression 編輯器不會自動列舉自訂程式碼裡面的函式名稱。
3. 自訂程式碼必須以 Visual Basic 撰寫。