用Silverlight做淘宝应用

 

Silverlight无法直接调用淘宝的API,可以使用WebClient或者自定义WCF来间接调用淘宝接口。

本例中采用的是调用WebClient方式,执行一段ashx,然后将返回的数据用反序列化生成相应对象的实例。

起始页面为Login.aspx,固定调试端口为49441。需要配合自己淘宝开放平台的应用的回调页面URL来调整。

示例代码下载

ashx代码:

(说明:代码中ITopClient为淘宝接口TopSdk.dll中的类,此例子使用的ItemsOnsaleGetRequest是用于获取销售中的商品,response.Body是获取到的数据信息)

public class OnsaleGet : IHttpHandler
    {

        public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "text/plain";
            
            ITopClient client = new DefaultTopClient(Config.ServerURL, Config.Appkey, Config.Secret);

            ItemsOnsaleGetRequest req = new ItemsOnsaleGetRequest();
            req.Fields = "approve_status,num_iid,title,nick,type,cid,pic_url,num,props,valid_thru,list_time,price,has_discount,has_invoice,has_warranty,has_showcase,modified,delist_time,postage_id,seller_cids,outer_id";
            ItemsOnsaleGetResponse response = client.Execute(req, Config.Top_session);


            if (response.IsError)
            {
                context.Response.Write("[错误:查询函数执行失败]");
            }
            else
            {
                context.Response.Write(response.Body);
            }

        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }

 

前端SL获取数据信息的方法

void GetList()
        {
            string absolutePath = HtmlPage.Document.DocumentUri.AbsoluteUri;
            string address = absolutePath.Substring(0, absolutePath.LastIndexOf('/'))
            + "/TaoBaoHandler/OnsaleGet.ashx";

            Uri uri = new Uri(address);

            WebClient client = new WebClient();
            client.DownloadStringCompleted += (sender, e) =>
            {
                if (e.Error == null)
                {
                    System.Xml.Linq.XElement.Parse(e.Result);//字符串转为xml
                    
                    ItemsOnsaleGetResponse list = SerializeHelper.DeserializeFromString<ItemsOnsaleGetResponse>(e.Result);//反序列化
                    if (list != null)
                    {
                        if (list.Items != null && list.Items.Count > 0)
                        {
                            MessageBox.Show(list.Items[0].NumIid.ToString());
                        }
                    }
                    else
                    {
                        
                    }
                }
                else
                {
                    MessageBox.Show(e.Error.Message);
                }
            };
            client.DownloadStringAsync(uri);
        }

 

SerializeHelper

序列化部分是自定义的一个类

public class SerializeHelper
    {
        private SerializeHelper() { }

        #region Serialize

        /// <summary>
        /// 序列化实体
        /// </summary>
        /// <typeparam name="T">实体类型</typeparam>
        /// <param name="data">实体</param>
        /// <returns>xml字体串</returns>
        public static string Serialize<T>(T data)
        {
            try
            {
                var serializer = new XmlSerializer(typeof(T));

                XmlSerializerNamespaces ns = new XmlSerializerNamespaces();
                ns.Add("", "");
                XmlWriterSettings writerSettings = new XmlWriterSettings();
                writerSettings.OmitXmlDeclaration = true;
                StringWriter stringWriter = new StringWriter();
                using (XmlWriter xmlWriter = XmlWriter.Create(stringWriter, writerSettings))
                {
                    serializer.Serialize(xmlWriter, data, ns);
                }
                string xmlText = stringWriter.ToString();

                return xmlText;
            }
            catch (InvalidOperationException ex)
            {
                if (ex.Message != "")
                { }
            }

            return string.Empty;
        }

        public static string SerializeList<T>(List<T> list)
        {
            try
            {
                var serializer = new XmlSerializer(typeof(List<T>));

                XmlSerializerNamespaces ns = new XmlSerializerNamespaces();
                ns.Add("", "");
                XmlWriterSettings writerSettings = new XmlWriterSettings();
                writerSettings.OmitXmlDeclaration = true;
                StringWriter stringWriter = new StringWriter();
                using (XmlWriter xmlWriter = XmlWriter.Create(stringWriter, writerSettings))
                {
                    serializer.Serialize(xmlWriter, list, ns);
                }
                string xmlText = stringWriter.ToString();

                return xmlText;
            }
            catch
            { }

            return string.Empty;
        }

        #endregion

        #region Deserializer

        /// <summary>
        /// 反序列化实体
        /// </summary>
        /// <typeparam name="T">实体类型</typeparam>
        /// <param name="xml">xml字体串</param>
        /// <returns>实体</returns>
        public static T DeserializeFromString<T>(string xml)
        {
            T theObject;
            try
            {
                XmlReader reader = XmlReader.Create(new StringReader(xml));
                var serializer = new XmlSerializer(typeof(T));
                theObject = (T)serializer.Deserialize(reader);
                reader.Close();
                return theObject;
            }
            catch
            { }

            return default(T);
        }

        public static List<T> DeserializeListFromString<T>(string xml)
        {
            try
            {
                var serializer = new XmlSerializer(typeof(List<T>));
                StringReader reader = new StringReader(xml);

                List<T> list = (List<T>)serializer.Deserialize(reader);
                reader.Close();

                return list;
            }
            catch (InvalidOperationException ex)
            {
                if (ex.InnerException.Message != "")
                { }
            }

            return null;
        }

        #endregion
    }

 

淘宝相关的数据类型

TopModels模块中的ItemsOnsaleGetResponse,Item,ItemImg,Location等这些实体是从TopSdk.dll中找到相应的定义粘贴出来供Silverlight下使用的。如图

web.config中的配置

配置沙箱环境和正式环境的选择,以及AppKey和AppSecret

<appSettings>
    
    <!--IsSandBox 1=沙箱开启 0=非沙箱(正式环境)  -->
    <add key="SandBox" value="1"/>
    <!--应用 信息-->
    <add key="AppKey" value="1012596959"/>
    <add key="AppSecret" value="sandboxc5928dd8d1cfa3bb4f7d87e33"/>

  </appSettings>

 

另外,web中的那些Client.cs和Config.cs则是从淘宝示例Demo中来的。

 

最终数据的获取如下:

 

 

 

示例代码下载

转载于:https://www.cnblogs.com/xtechnet/archive/2012/06/26/TopBySilverlight.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值