Api 呼叫Example

rusli
Site Admin
文章: 212
註冊時間: 週三 7月 07, 2010 9:49 pm

Api 呼叫Example

文章rusli » 週三 2月 29, 2012 6:50 pm

代碼: 選擇全部


        private const string ApiUrl = "http://kwpi-videgree-test.gss.com.tw/iStore/{yourStoreName}/Api.mvc/CustomerImport";
        private const string ApiKey = "df8d5d2285564ca4988fe3dbf0f404d5";


        /// <summary>
        /// 範例程式
        /// </summary>
        private void CustomerImportExample()
        {
            //// 呼較後取得回傳狀態
            string resultString;
            //// 最大傳送筆數
            const int MaxDataCount = 2;
            var contacts = new Contacts[MaxDataCount];

            //// 設定文件
            contacts = new[]
                           {
                               new Contacts
                                   {
                                       CurrentName = "Empty01",
                                       Addrs =
                                           new List<object> {new {ContactMechType = "我的地址", Values = new[] {"Addr1;Addr4;Addr5"}}}
                                       /* ... 後面可以繼續加欄位 ...  */
                                   },
                               new Contacts
                                   {
                                       CurrentName = "Empty02",
                                       Addrs =
                                           new List<object> {new {ContactMechType = "我的地址", Values = new[] {"Addr2"}}}
                                       /* ... 後面可以繼續加欄位 ...  */
                                   },
                               new Contacts
                                   {
                                       CurrentName = "Empty03",
                                       Addrs =
                                           new List<object> {new {ContactMechType = "我的地址", Values = new[] {"Addr3"}}}
                                       /* ... 後面可以繼續加欄位 ...  */
                                   },
                               new Contacts
                                   {
                                       CurrentName = "Empty04",
                                       Mobiles =
                                           new List<object> {new {ContactMechType = "手機", Values = new[] {"0933312346;0933312347"}}},
                                       Fax = new List<object>
                                                       {
                                                           new
                                                               {
                                                                   ContactMechType = "傳真",
                                                                   Values = new[] {"1234567890#1234"}
                                                               },
                                                           new
                                                               {
                                                                   ContactMechType = "公司傳真",
                                                                   Values = new[] {"1234567890#1234"}
                                                               }
                                                       },
                                       Messagers = new List<object>
                                                       {
                                                           new
                                                               {
                                                                   ContactMechType = "GoogleTalk",
                                                                   Values = new[] {"g1@google.com"}
                                                               },
                                                           new
                                                               {
                                                                   ContactMechType = "Messager",
                                                                   Values = new[] {"g1@Messager.com"}
                                                               },
                                                           new
                                                               {
                                                                   ContactMechType = "Yahoo",
                                                                   Values = new[] {"g1@Yahoo.com"}
                                                               }
                                                       },
                                       HomePhones =
                                           new List<object> {new {ContactMechType = "住家電話", Values = new[] {"1", "2"}}},
                                       Urls = new List<object>
                                                  {
                                                      new
                                                          {
                                                              ContactMechType = "網址",
                                                              Values = new[] {"http://www.google.com"}
                                                          },
                                                      new
                                                          {
                                                              ContactMechType = "我的部落格",
                                                              Values = new[] {"http://blog.google.com/第1個;http://blog.google.com/第2個"}
                                                          }
                                                  },
                                       Emails =
                                           new List<object>
                                               {
                                                   new
                                                       {
                                                           ContactMechType = "我的電郵地址",
                                                           Values = new[] {"電郵1@mail.com;電郵2@mail.com"}
                                                       }
                                               },
                                       Addrs = new List<object>
                                                   {
                                                       new {ContactMechType = "住家地址", Values = new[] {"地址1;地址2"}},
                                                       new {ContactMechType = "我的地址", Values = new[] {"地址1;地址2"}}
                                                   }
                                       /* ... 後面可以繼續加欄位 ...  */
                                   }
                           };

            //// 送出資料轉換成JSon 文件
            string postInfo = Util.AnonymousTypeObjectToJson(contacts);
            //// 送出資料 且 使用 ResultString 回傳Json 文件
            resultString = Util.PostUrl(ApiKey, ApiUrl, postInfo, ContentTypeKnd.Xml);
            //// 轉換Json資料成物件
            Result[] result = Util.JsonToObject<Result>(resultString);
            //// result.Length 一定會大於 0
            if (result.Length > 0)
            {
                if (result[0].ErrorCode == 0)
                {
                    ////  成功
                    //// [{"ErrorCode":0,"Message":"SUCCESS","Data":null}]
                }
                if (result[0].ErrorCode == 1)
                {
                    //// result[0].Message; // error msg
                    ////  [{"ErrorCode":1,"Message":"錯誤!","Data":null}]
                }
                if (result[0].ErrorCode == 2)
                {
                    ////  失敗
                    //// [{"ErrorCode":2,"Message":"FAIL","Data":null}]
                }
            }
            else
            {
                //// Server 掛點
            }
        }

附加檔案
Samples20120301.rar
(761.36 KiB) 已下載 12 次

rusli
Site Admin
文章: 212
註冊時間: 週三 7月 07, 2010 9:49 pm

Util

文章rusli » 週三 2月 29, 2012 6:53 pm

代碼: 選擇全部

namespace Library
{
    using System;
    using System.IO;
    using System.Net;
    using System.Runtime.Serialization.Json;
    using System.Text;
    using System.Web.Script.Serialization;
    using System.Xml;
    using System.Xml.Linq;
    using System.Xml.Serialization;
    using System.IO;

    public class Util
    {
        public static string AnonymousTypeObjectToJson<T>(T[] t)
        {
            //// 支援匿名型別
            return (new JavaScriptSerializer()).Serialize(t);
        }

        public static string ObjectToJson<T>(T[] t)
        {
            string result;

            //Create a stream to serialize the object to.
            using (var ms = new MemoryStream())
            {
                //// Serializer the User object to the stream.
                var ser = new DataContractJsonSerializer(typeof (T[]));
                ser.WriteObject(ms, t);
                result = Encoding.UTF8.GetString(ms.ToArray());
            }
            return result;
        }

        public static string ObjectToXML<T>(T[] t)
        {
            string result = string.Empty;
            //// Set the public property values.
            using (var stream = new MemoryStream(500))
            {
                var xmlWriterSettings = new XmlWriterSettings
                                            {
                                                OmitXmlDeclaration = true,
                                                Encoding = Encoding.UTF8,
                                                Indent = true
                                            };
                using (XmlWriter xmlWriter = XmlWriter.Create(stream, xmlWriterSettings))
                {
                    var serializer = new XmlSerializer(typeof (T[]));
                    serializer.Serialize(xmlWriter, t);
                }
                result = Encoding.UTF8.GetString(stream.ToArray());
            }
            return result;
        }

        public static T[] JsonToObject<T>(string json)
        {
            using (var ms = new MemoryStream(Encoding.UTF8.GetBytes(json)))
            {
                return new DataContractJsonSerializer(typeof (T[])).ReadObject(ms) as T[];
            }
        }

        public static T[] XmlToObject<T>(string xmlString)
        {
            XElement xmlRoot = XElement.Parse(xmlString);
            return new XmlSerializer(typeof (T[])).Deserialize(xmlRoot.CreateReader()) as T[];
        }

        /// <summary>
        /// 送出用ApiKey 加密內容
        /// </summary>
        /// <param name="apiKey"></param>
        /// <param name="targetUrl"></param>
        /// <param name="postInfo"></param>
        /// <param name="contentTypeKnd"></param>
        /// <returns></returns>
        public static string PostUrl(string apiKey, string targetUrl, string postInfo, ContentTypeKnd contentTypeKnd)
        {
            byte[] clientKey = Encoding.ASCII.GetBytes(apiKey.Substring(0, 8).ToLowerInvariant());
            postInfo = Base64.Encode(UtilityCrypto.Encrypt(postInfo, clientKey, clientKey));
            return PostUrl(targetUrl, postInfo, contentTypeKnd);
        }

        /// <summary>
        /// 送出
        /// </summary>
        /// <param name="targetUrl"></param>
        /// <param name="postInfo"></param>
        /// <param name="contentTypeKnd"></param>
        /// <returns></returns>
        public static string PostUrl(string targetUrl, string postInfo, ContentTypeKnd contentTypeKnd)
        {
            string responseInfo = string.Empty;

            try
            {
                WebRequest request = WebRequest.Create(targetUrl);
                request.ContentType = contentTypeKnd == ContentTypeKnd.Xml
                                          ? "application/x-www-form-urlencoded"
                                          : "application/json";
                request.Method = "POST";
                byte[] bts = Encoding.UTF8.GetBytes(postInfo);
                request.ContentLength = bts.Length;
                using (Stream st = request.GetRequestStream())
                {
                    st.Write(bts, 0, bts.Length);
                    st.Close();
                }

                WebResponse response = request.GetResponse();
                Stream o = response.GetResponseStream();
                if (o != null)
                {
                    responseInfo = (new StreamReader(o)).ReadToEnd().Trim();
                }
            }
            catch (Exception)
            {
                throw;
            }
            return responseInfo;
        }
    }
}

rusli
Site Admin
文章: 212
註冊時間: 週三 7月 07, 2010 9:49 pm

Contacts

文章rusli » 週三 2月 29, 2012 6:54 pm

代碼: 選擇全部


namespace Library
{
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Reflection;
    using System.Runtime.Serialization;

    [Serializable]
    [DataContract]
    public class Contacts
    {
        public Contacts()
        {
            Init();
        }

        /// <summary>
        /// 測試用
        /// </summary>
        /// <param name="i"></param>
        public Contacts(int i)
        {
            Init();
            Contacts c = this;
            PropertyInfo[] pI = (c).GetType().GetProperties();
            foreach (PropertyInfo o in pI)
            {
                o.SetValue(c, o.Name + i, null);
            }
        }

        [DataMember]
        public string CurrentName { get; set; }

        [DataMember]
        public string FirstName { get; set; }

        [DataMember]
        public string LastName { get; set; }

        //// 英文名
        [DataMember]
        public string EnglishName { get; set; }

        //// 性別
        [DataMember]
        public string Gender { get; set; }

        //// 記事
        [DataMember]
        public string Notes { get; set; }

        [DataMember]
        public string Company { get; set; }

        [DataMember]
        public string JobTitle { get; set; }

        [DataMember]
        public string Nickname { get; set; }

        ////標籤
        [DataMember]
        public string Labels { get; set; }

        ////住家 - 國家/地區
        [DataMember]
        public string HomeCountry { get; set; }

        //// 部門
        [DataMember]
        public string Department { get; set; }

        //// 擴充屬性
        [DataMember]
        public IDictionary<string, string> ExtendedField { get; set; }

        [DataMember]
        public IList<object> Mobiles { get; set; }

        [DataMember]
        public IList<object> Fax { get; set; }

        [DataMember]
        public IList<object> Messagers { get; set; }

        [DataMember]
        public IList<object> HomePhones { get; set; }

        [DataMember]
        public IList<object> Emails { get; set; }

        [DataMember]
        public IList<object> Urls { get; set; }

        [DataMember]
        public IList<object> Addrs { get; set; }

        private void Init()
        {
            Mobiles = new List<object>();
            Fax = new List<object>();
            Messagers = new List<object>();
            HomePhones = new List<object>();
            Emails = new List<object>();
            Urls = new List<object>();
            Addrs = new List<object>();
            ExtendedField = new Dictionary<string, string>();
        }
    }
}


rusli
Site Admin
文章: 212
註冊時間: 週三 7月 07, 2010 9:49 pm

UtilityCrypto

文章rusli » 週三 2月 29, 2012 6:55 pm

代碼: 選擇全部


using System.IO;
using System.Security.Cryptography;

namespace Library
{
    public class UtilityCrypto
    {
        /// <summary>
        /// DES解密 with CBC cipher mode and PKCS7 padding mode
        /// </summary>
        /// <param name="cypherText">A cyphertext byte[]</param>
        /// <param name="key">A Key byte array</param>
        /// <param name="iv">A IV byte array</param>
        /// <returns>The original string</returns>
        public static string Decrypt(byte[] cypherText, byte[] key, byte[] iv)
        {
            DESCryptoServiceProvider desProvider = new DESCryptoServiceProvider();
            desProvider.Mode = CipherMode.ECB;
            desProvider.Padding = PaddingMode.PKCS7;
            desProvider.Key = key;
            desProvider.IV = iv;

            // Create a memory stream to the passed buffer.
            MemoryStream ms = new MemoryStream(cypherText);

            // Create a CryptoStream using the memory stream and the
            // CSP DES key.
            CryptoStream encStream = new CryptoStream(ms, desProvider.CreateDecryptor(), CryptoStreamMode.Read);

            // Create a StreamReader for reading the stream.
            StreamReader sr = new StreamReader(encStream);

            // Read the stream as a string.
            string val = sr.ReadLine();

            // Close the streams.
            sr.Close();
            encStream.Close();
            ms.Close();

            return val;
        }

        /// <summary>
        /// DES加密 with CBC cipher mode and PKCS7 padding mode
        /// </summary>
        /// <param name="plainText">A plaintext string</param>
        /// <param name="key">A key byte array</param>
        /// <param name="iv">A IV byte array</param>
        /// <returns>A byte array</returns>
        public static byte[] Encrypt(string plainText, byte[] key, byte[] iv)
        {
            DESCryptoServiceProvider desProvider = new DESCryptoServiceProvider();
            desProvider.Mode = CipherMode.ECB;
            desProvider.Padding = PaddingMode.PKCS7;
            desProvider.Key = key;
            desProvider.IV = iv;

            // Create a memory stream.
            MemoryStream ms = new MemoryStream();

            // Create a CryptoStream using the memory stream and the
            // CSP DES key. 
            CryptoStream encStream = new CryptoStream(ms, desProvider.CreateEncryptor(), CryptoStreamMode.Write);

            // Create a StreamWriter to write a string
            // to the stream.
            StreamWriter sw = new StreamWriter(encStream);

            // Write the plaintext to the stream.
            sw.WriteLine(plainText);

            // Close the StreamWriter and CryptoStream.
            sw.Close();
            encStream.Close();

            // Get an array of bytes that represents
            // the memory stream.
            byte[] buffer = ms.ToArray();

            // Close the memory stream.
            ms.Close();

            // Return the encrypted byte array.
            return buffer;
        }

        /// <summary>
        /// Convert string to byte array
        /// </summary>
        /// <param name="hex">A hex string</param>
        /// <returns>A byte array</returns>
        public static byte[] StringToByteArray(string hex)
        {
            int numberChars = hex.Length;
            byte[] bytes = new byte[numberChars / 2];
            for (int i = 0; i < numberChars; i += 2)
            {
                bytes[i / 2] = System.Convert.ToByte(hex.Substring(i, 2), 16);
            }

            return bytes;
        }
    }
}


回到「C#」

誰在線上

正在瀏覽這個版面的使用者:沒有註冊會員 和 1 位訪客