Generating EAP to TAP wrapper class

This sample describes about source code generation for an EAP-toTAP wrapper class.

C# (77.3 KB)
 
 
 
 
 
(0)
1,432 times
Add to favorites
5/28/2011
E-mail Twitter del.icio.us Digg Facebook
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace TaskAsyncClient
{
    /// <summary>
    /// Silverlight の WCF クライアント クラスをラッピングして、
    /// Async C# で利用しやすいように、メソッドが Task を返すようにしたものを生成。
    /// </summary>
    public class Generator
    {
        /// <summary>
        /// TaskClient 生成。
        /// </summary>
        /// <param name="definition">クライアント クラスの定義情報</param>
        /// <returns>生成したソースコード</returns>
        public static string Generate(ServiceClient definition)
        {
            var sb = new StringBuilder();

            sb.AppendFormat(@"using System;
using System.Collections.ObjectModel;
using System.Threading.Tasks;

namespace {0}
{{
    public class {1}TaskClient
    {{
        {1}Client client;

        static Task<T> GetAsync<T>(Action<TaskCompletionSource<T>> getAsync)
        {{
            var tcs = new TaskCompletionSource<T>();
            getAsync(tcs);
            return tcs.Task;
        }}

        static void Completed<T>(object sender, dynamic e)
        {{
            var tcs = e.UserState as TaskCompletionSource<T>;

            if (e.Error != null) tcs.TrySetException(e.Error);
            else if (e.Cancelled) tcs.TrySetCanceled();
            else tcs.TrySetResult(e.Result);
        }}

        public {1}TaskClient({1}Client client)
        {{
            this.client = client;

", definition.Namespace, definition.Class);

            foreach (var m in definition.Methods)
            {
                sb.AppendFormat(@"            client.{0}Completed += Completed<{1}>;
", m.Name, m.ReturnType);
            }

            sb.Append(@"}
");

            foreach (var m in definition.Methods)
            {
                var args = m.ArgumentList;
                if (!string.IsNullOrEmpty(args))
                    args += ", ";

                sb.AppendFormat(@"
        public Task<{1}> {0}Async({2})
        {{
            return GetAsync<{1}>(tcs => client.{0}Async({3}tcs));
        }}
", m.Name, m.ReturnType, m.ParameterList, m.ArgumentList);
            }

            sb.Append(@"    }
}
");

            return sb.ToString();
        }
    }
}