Ejemplo n.º 1
0
        /// <summary>
        /// 执行方法
        /// </summary>
        /// <typeparam name="TResponse"></typeparam>
        /// <param name="request"></param>
        /// <param name="callback"></param>
        /// <returns></returns>
        public ServiceResult Execute <TResponse>(ITopRequest <TResponse> request, Func <TResponse, ServiceResult> callback) where TResponse : TopResponse
        {
            var client = new DefaultTopClient(this.Url, _apiConfig.AppKey, _apiConfig.AppSecret);
            var result = client.Execute(request, _apiConfig.SessionKey) as TResponse;

            return(callback.Invoke(result));
        }
Ejemplo n.º 2
0
 /// <summary>
 /// 根据指定的API请求获取相应的API响应结果。
 /// </summary>
 public T GetResponse <T>(ITopRequest <T> request) where T : TopResponse
 {
     if (this.ResponseList == null || this.ResponseList.Count == 0)
     {
         return(null);
     }
     return(this.ResponseList[request.GetBatchApiOrder()] as T);
 }
Ejemplo n.º 3
0
 public TopBatchRequest AddRequest <T>(ITopRequest <T> request) where T : TopResponse
 {
     if (this.RequestList == null)
     {
         this.RequestList = new List <ITopRequest <TopResponse> >();
     }
     this.RequestList.Add(request);
     return(this);
 }
Ejemplo n.º 4
0
        public new T Execute <T>(ITopRequest <T> request, string session, DateTime timestamp) where T : TopResponse
        {
            T            rsp = null;
            TopException exp = null;

            for (int i = 0; i < maxRetryCount; i++)
            {
                if (i > 0)
                {
                    if ((rsp != null && ((rsp.SubErrCode != null && rsp.SubErrCode.StartsWith("isp.")) ||
                                         (retryErrorCodes != null && retryErrorCodes.ContainsKey(rsp.SubErrCode)))) || exp != null)
                    {
                        Thread.Sleep(retryWaitTime);
                        topLogger.Warn(BuildRetryLog(request.GetApiName(), request.GetParameters(), i));
                    }
                    else
                    {
                        break;
                    }
                }

                try
                {
                    rsp = base.Execute(request, session);
                    if (rsp.IsError)
                    {
                        if (i == maxRetryCount && throwIfOverMaxRetry)
                        {
                            throw RETRY_FAIL;
                        }
                    }
                    else
                    {
                        return(rsp);
                    }
                }
                catch (TopException e)
                {
                    if (exp == null)
                    {
                        exp = e;
                    }
                }
            }

            if (exp != null)
            {
                throw exp;
            }
            else
            {
                return(rsp);
            }
        }
Ejemplo n.º 5
0
        private static T InvokeOpenApi <T>(Domain.Shop shop, ITopRequest <T> request) where T : TopResponse
        {
            var topClient = GetTopClient(shop.AppKey, shop.AppSecret);
            var ret       = topClient.Execute <T>(request, shop.AppAccessToken, DateTime.Now);

            if (ret.IsError)
            {
                throw new Exception("执行淘宝请求出错:" + ret.ErrCode + "," + ret.ErrMsg + ret.SubErrMsg);
            }
            return(ret);
        }
Ejemplo n.º 6
0
 public override T Execute <T>(ITopRequest <T> request, string session, DateTime timestamp)
 {
     if (typeof(TopBatchRequest) == request.GetType())
     {
         return(DoExecute <T>(request, session, timestamp));
     }
     else
     {
         return(base.Execute <T>(request, session, timestamp));
     }
 }
Ejemplo n.º 7
0
        /// <summary>
        /// 获取请求响应对象
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="request"></param>
        /// <param name="serverUrl"></param>
        /// <param name="appKey"></param>
        /// <param name="appSecret"></param>
        /// <returns></returns>
        public static T GetResponse <T>(ITopRequest <T> request, string serverUrl = "", string appKey = "", string appSecret = "") where T : TopResponse
        {
            serverUrl = string.IsNullOrWhiteSpace(serverUrl) ? "http://gw.api.taobao.com/router/rest" : serverUrl;
            appKey    = string.IsNullOrWhiteSpace(appKey) ? "12011627" : appKey;
            appSecret = string.IsNullOrWhiteSpace(appSecret) ? "d63fc6135b1f956116d01969d6295bd0" : appSecret;
            ITopClient client   = new DefaultTopClient(serverUrl, appKey, appSecret);
            var        response = client.Execute(request);

            if (response != null && !response.IsError)
            {
                return(response);
            }
            return(null);
        }
Ejemplo n.º 8
0
        public T Execute <T>(ITopRequest <T> request, string session) where T : TopResponse
        {
            // 添加协议级请求参数
            TopDictionary txtParams = new TopDictionary(request.GetParameters());

            txtParams.Add(METHOD, request.GetApiName());
            txtParams.Add(VERSION, "2.0");
            txtParams.Add(APP_KEY, appKey);
            txtParams.Add(FORMAT, format);
            txtParams.Add(PARTNER_ID, "top-sdk-net-20110512");
            txtParams.Add(TIMESTAMP, DateTime.Now);
            txtParams.Add(SESSION, session);

            // 添加签名参数
            txtParams.Add(SIGN, TopUtils.SignTopRequest(txtParams, appSecret));

            // 是否需要上传文件
            string body;

            if (request is ITopUploadRequest <T> )
            {
                ITopUploadRequest <T>          uRequest   = (ITopUploadRequest <T>)request;
                IDictionary <string, FileItem> fileParams = TopUtils.CleanupDictionary(uRequest.GetFileParameters());
                body = webUtils.DoPost(this.serverUrl, txtParams, fileParams);
            }
            else
            {
                body = webUtils.DoPost(this.serverUrl, txtParams);
            }

            T rsp;

            if (FORMAT_XML.Equals(format))
            {
                ITopParser <T> tp = new TopXmlParser <T>();
                rsp = tp.Parse(body);
            }
            else
            {
                ITopParser <T> tp = new TopJsonParser <T>();
                rsp = tp.Parse(body);
            }

            return(rsp);
        }
Ejemplo n.º 9
0
 public T Execute <T>(ITopRequest <T> request, string session, DateTime timestamp) where T : TopResponse
 {
     if (disableTrace)
     {
         return(DoExecute <T>(request, session, timestamp));
     }
     else
     {
         try
         {
             return(DoExecute <T>(request, session, timestamp));
         }
         catch (Exception e)
         {
             topLogger.Error(this.serverUrl + "\r\n" + e.StackTrace);
             throw e;
         }
     }
 }
Ejemplo n.º 10
0
        public new T Execute <T>(ITopRequest <T> request, string session, DateTime timestamp) where T : TopResponse
        {
            T rsp = null;

            try
            {
                retryCounter++;
                rsp = base.Execute(request, session, timestamp);
                if (rsp.IsError)
                {
                    if (retryCounter < maxRetryCount)
                    {
                        if (rsp.SubErrCode != null && rsp.SubErrCode.StartsWith("isp."))
                        {
                            Thread.Sleep(retryWaitTime);
                            return(Execute(request, session, timestamp));
                        }
                    }
                    else
                    {
                        if (throwIfOverMaxRetry)
                        {
                            throw RETRY_FAIL;
                        }
                    }
                }
            }
            catch (Exception e)
            {
                if (e != RETRY_FAIL && retryCounter < maxRetryCount)
                {
                    Thread.Sleep(retryWaitTime);
                    return(Execute(request, session, timestamp));
                }
            }
            finally
            {
                retryWaitTime = -1;
            }
            return(rsp);
        }
Ejemplo n.º 11
0
        private T DoExecute <T>(ITopRequest <T> request, string session, DateTime timestamp) where T : TopResponse
        {
            // 提前检查业务参数
            try
            {
                request.Validate();
            }
            catch (TopException e)
            {
                return(CreateErrorResponse <T>(e.ErrorCode, e.ErrorMsg));
            }

            // 添加协议级请求参数
            TopDictionary txtParams = new TopDictionary(request.GetParameters());

            txtParams.Add(METHOD, request.GetApiName());
            txtParams.Add(VERSION, "2.0");
            txtParams.Add(SIGN_METHOD, Constants.SIGN_METHOD_MD5);
            txtParams.Add(APP_KEY, appKey);
            txtParams.Add(FORMAT, format);
            txtParams.Add(PARTNER_ID, GetSdkVersion());
            txtParams.Add(TIMESTAMP, timestamp);
            txtParams.Add(TARGET_APP_KEY, request.GetTargetAppKey());
            txtParams.Add(SESSION, session);
            txtParams.AddAll(this.systemParameters);

            if (this.useSimplifyJson)
            {
                txtParams.Add(SIMPLIFY, "true");
            }

            // 添加签名参数
            txtParams.Add(SIGN, TopUtils.SignTopRequest(txtParams, appSecret, true));

            // 添加头部参数
            if (this.useGzipEncoding)
            {
                request.GetHeaderParameters()[Constants.ACCEPT_ENCODING] = Constants.CONTENT_ENCODING_GZIP;
            }

            string realServerUrl = GetServerUrl(this.serverUrl, request.GetApiName(), session);
            string reqUrl        = webUtils.BuildGetUrl(realServerUrl, txtParams);

            try
            {
                string body;
                if (request is ITopUploadRequest <T> ) // 是否需要上传文件
                {
                    ITopUploadRequest <T>          uRequest   = (ITopUploadRequest <T>)request;
                    IDictionary <string, FileItem> fileParams = TopUtils.CleanupDictionary(uRequest.GetFileParameters());
                    body = webUtils.DoPost(realServerUrl, txtParams, fileParams, request.GetHeaderParameters());
                }
                else
                {
                    body = webUtils.DoPost(realServerUrl, txtParams, request.GetHeaderParameters());
                }

                // 解释响应结果
                T rsp;
                if (disableParser)
                {
                    rsp      = Activator.CreateInstance <T>();
                    rsp.Body = body;
                }
                else
                {
                    if (FORMAT_XML.Equals(format))
                    {
                        ITopParser tp = new TopXmlParser();
                        rsp = tp.Parse <T>(body);
                    }
                    else
                    {
                        ITopParser tp;
                        if (useSimplifyJson)
                        {
                            tp = new TopJsonSimplifyParser();
                        }
                        else
                        {
                            tp = new TopJsonParser();
                        }
                        rsp = tp.Parse <T>(body);
                    }
                }

                // 追踪错误的请求
                if (!disableTrace && rsp.IsError)
                {
                    StringBuilder sb = new StringBuilder(reqUrl).Append(" response error!\r\n").Append(rsp.Body);
                    topLogger.Warn(sb.ToString());
                }
                return(rsp);
            }
            catch (Exception e)
            {
                if (!disableTrace)
                {
                    StringBuilder sb = new StringBuilder(reqUrl).Append(" request error!\r\n").Append(e.StackTrace);
                    topLogger.Error(sb.ToString());
                }
                throw e;
            }
        }
Ejemplo n.º 12
0
        private T DoExecute <T>(ITopRequest <T> request, string session, DateTime timestamp) where T : TopResponse
        {
            // 提前检查业务参数

            try
            {
                request.Validate();
            }
            catch (TopException e)
            {
                return(createErrorResponse <T>(e.ErrorCode, e.ErrorMsg));
            }
            string sip_timestamp = timestamp.ToString("yyyy-MM-dd HH:mm:ss.000");
            // 添加协议级请求参数
            TopDictionary     txtParams         = new TopDictionary();
            PortalRestRequest portalRestRequest = request.GetParameters();

            //Jayrock.Json.JsonTextWriter writer = new Jayrock.Json.JsonTextWriter();
            //Jayrock.Json.Conversion.JsonConvert.Export(paramDict, writer);
            //txtParams.Add(PORTALTRANSACTION, "[" + Jayrock.Json.Conversion.JsonConvert.ExportToString(portalRestRequest) + "]");
            txtParams.Add(PORTALTRANSACTION, "[" + Newtonsoft.Json.JsonConvert.SerializeObject(portalRestRequest) + "]");
            txtParams.Add(APP_KEY, appKey);
            txtParams.Add(TIMESTAMP, sip_timestamp);
            txtParams.AddAll(this.systemParameters);

            // 添加签名参数
            txtParams.Add(SIGN, TopUtils.SignBurgeonPortalRequest(appKey, appSecret, sip_timestamp));

            // 是否需要上传文件
            string body;

            if (request is ITopUploadRequest <T> )
            {
                ITopUploadRequest <T>          uRequest   = (ITopUploadRequest <T>)request;
                IDictionary <string, FileItem> fileParams = TopUtils.CleanupDictionary(uRequest.GetFileParameters());
                body = webUtils.DoPost(this.serverUrl, txtParams, fileParams);
            }
            else
            {
                body = webUtils.DoPost(this.serverUrl, txtParams);
            }

            // 解释响应结果
            T rsp;

            if (disableParser)
            {
                rsp      = Activator.CreateInstance <T>();
                rsp.Body = body;
            }
            else
            {
                ITopParser tp = new TopJsonParser();
                //去掉body[]
                body = body.Substring(1, body.LastIndexOf(']') - 1);

                rsp = tp.Parse <T>(body);
            }

            // 追踪错误的请求
            if (!disableTrace)
            {
                rsp.Body   = body;
                rsp.ReqUrl = webUtils.BuildGetUrl(this.serverUrl, txtParams);
                if (rsp.IsError)
                {
                    topLogger.Warn(rsp.ReqUrl + "\r\n" + rsp.Body);
                }
            }

            return(rsp);
        }
Ejemplo n.º 13
0
 public virtual T Execute <T>(ITopRequest <T> request) where T : TopResponse
 {
     return(DoExecute <T>(request, null, DateTime.Now));
 }
Ejemplo n.º 14
0
 public string Execute <T>(ITopRequest <T> request) where T : class
 {
     throw new NotImplementedException();
 }
Ejemplo n.º 15
0
        private T DoExecute <T>(ITopRequest <T> request, string session, DateTime timestamp) where T : TopResponse
        {
            // 提前检查业务参数
            try
            {
                request.Validate();
            }
            catch (TopException e)
            {
                return(createErrorResponse <T>(e.ErrorCode, e.ErrorMsg));
            }

            // 添加协议级请求参数
            TopDictionary txtParams = new TopDictionary(request.GetParameters());

            txtParams.Add(METHOD, request.GetApiName());
            txtParams.Add(VERSION, "2.0");
            txtParams.Add(APP_KEY, appKey);
            txtParams.Add(FORMAT, format);
            txtParams.Add(PARTNER_ID, "top-sdk-net-20130425");
            txtParams.Add(TIMESTAMP, timestamp);
            txtParams.Add(SESSION, session);
            txtParams.AddAll(this.systemParameters);

            // 添加签名参数
            txtParams.Add(SIGN, TopUtils.SignTopRequest(txtParams, appSecret));

            // 是否需要上传文件
            string body;

            if (request is ITopUploadRequest <T> )
            {
                ITopUploadRequest <T>          uRequest   = (ITopUploadRequest <T>)request;
                IDictionary <string, FileItem> fileParams = TopUtils.CleanupDictionary(uRequest.GetFileParameters());
                body = webUtils.DoPost(this.serverUrl, txtParams, fileParams);
            }
            else
            {
                body = webUtils.DoPost(this.serverUrl, txtParams);
            }

            // 解释响应结果
            T rsp;

            if (disableParser)
            {
                rsp      = Activator.CreateInstance <T>();
                rsp.Body = body;
            }
            else
            {
                if (FORMAT_XML.Equals(format))
                {
                    ITopParser tp = new TopXmlParser();
                    rsp = tp.Parse <T>(body);
                }
                else
                {
                    ITopParser tp = new TopJsonParser();
                    rsp = tp.Parse <T>(body);
                }
            }

            // 追踪错误的请求
            if (!disableTrace)
            {
                rsp.ReqUrl = webUtils.BuildGetUrl(this.serverUrl, txtParams);
                if (rsp.IsError)
                {
                    topLogger.Warn(rsp.ReqUrl + "\r\n" + rsp.Body);
                }
            }

            return(rsp);
        }
Ejemplo n.º 16
0
 public virtual T Execute <T>(ITopRequest <T> request, string session) where T : TopResponse
 {
     return(Execute <T>(request, session, DateTime.Now));
 }
 public T Execute <T>(ITopRequest <T> request, string session) where T : YunResponse
 {
     return(Execute <T>(request, session, ToUnix(DateTime.Now)));
 }
Ejemplo n.º 18
0
 public override T Execute <T>(ITopRequest <T> request, string session)
 {
     return(Execute <T>(request, session, DateTime.Now));
 }
Ejemplo n.º 19
0
 public T Execute <T>(ITopRequest <T> request, DateTime timestamp) where T : TopResponse
 {
     return(Execute <T>(request as IParamsRequest, timestamp));
 }
Ejemplo n.º 20
0
        private T DoExecute <T>(ITopRequest <T> request, string session, DateTime timestamp) where T : TopResponse
        {
            long start = DateTime.Now.Ticks;

            TopBatchRequest batchRequest = request as TopBatchRequest;
            List <ITopRequest <TopResponse> > requestList = batchRequest.RequestList;

            if (requestList == null || requestList.Count == 0)
            {
                throw new TopException("40", "client-error:api request list is empty");
            }

            // 本地校验请求参数
            if (batchRequest.PublicParams == null || batchRequest.PublicParams.Count == 0)
            {
                for (int i = 0; i < requestList.Count; i++)
                {
                    try
                    {
                        requestList[i].Validate();
                    }
                    catch (TopException e)
                    {
                        return(CreateErrorResponse <T>(e.ErrorCode, e.ErrorMsg));
                    }
                }
            }

            // 添加协议级请求参数
            TopDictionary parameters = new TopDictionary();

            parameters.Add(Constants.VERSION, "2.0");
            parameters.Add(Constants.APP_KEY, appKey);
            parameters.Add(Constants.TIMESTAMP, timestamp);
            parameters.Add(Constants.FORMAT, format);
            parameters.Add(Constants.SIGN_METHOD, Constants.SIGN_METHOD_HMAC);
            parameters.Add(Constants.PARTNER_ID, GetSdkVersion());
            parameters.Add(Constants.TARGET_APP_KEY, request.GetTargetAppKey());
            parameters.Add(Constants.SESSION, session);
            if (Constants.FORMAT_JSON.Equals(format) && this.useSimplifyJson)
            {
                parameters.Add(Constants.SIMPLIFY, "true");
            }

            // 添加自定义分隔符
            string separator = BATCH_API_DEFAULT_SPLIT;

            if (!string.IsNullOrEmpty(batchApiSeparator))
            {
                batchRequest.AddHeaderParameter(BATCH_API_HEADER_SPLIT, separator = batchApiSeparator);
            }

            // 是否需要压缩响应
            if (this.useGzipEncoding)
            {
                batchRequest.AddHeaderParameter(Constants.ACCEPT_ENCODING, Constants.CONTENT_ENCODING_GZIP);
            }

            try
            {
                // 添加公共请求头
                if (!string.IsNullOrEmpty(batchRequest.PublicMethod))
                {
                    batchRequest.AddPublicParam(Constants.METHOD, batchRequest.PublicMethod);
                }
                else
                {
                    if (IsSameRequest(requestList))
                    {
                        batchRequest.AddPublicParam(Constants.METHOD, requestList[0].GetApiName());
                    }
                }

                // 构建批量请求主体
                StringBuilder requestBody    = new StringBuilder();
                string        publicParamStr = WebUtils.BuildQuery(batchRequest.PublicParams);
                if (!string.IsNullOrEmpty(publicParamStr))
                {
                    requestBody.Append(BATCH_API_PUBLIC_PARAMETER).Append(publicParamStr).Append(separator);
                }

                // 组装每个API的请求参数
                for (int i = 0; i < requestList.Count; i++)
                {
                    ITopRequest <TopResponse> bRequest = requestList[i];
                    bRequest.SetBatchApiOrder(i);
                    IDictionary <string, string> apiParams = bRequest.GetParameters();
                    // 如果单个API的方法和批量API的公共方法不一致,那么需要设置单个API的方法名称
                    if (!string.IsNullOrEmpty(bRequest.GetApiName()) && !bRequest.GetApiName().Equals(batchRequest.PublicMethod))
                    {
                        apiParams.Add(Constants.METHOD, bRequest.GetApiName());
                    }
                    if (!string.IsNullOrEmpty(request.GetBatchApiSession()))
                    {
                        apiParams.Add(Constants.SESSION, bRequest.GetBatchApiSession());
                    }
                    if (!string.IsNullOrEmpty(request.GetTargetAppKey()))
                    {
                        apiParams.Add(Constants.TARGET_APP_KEY, bRequest.GetTargetAppKey());
                    }

                    string apiParamStr = WebUtils.BuildQuery(apiParams);
                    if (string.IsNullOrEmpty(apiParamStr))
                    {
                        apiParamStr = "N";
                    }
                    requestBody.Append(apiParamStr);
                    if (i != requestList.Count - 1)
                    {
                        requestBody.Append(separator);
                    }
                }

                string apiBody = requestBody.ToString();

                // 添加签名参数
                parameters.Add(Constants.SIGN, TopUtils.SignTopRequest(parameters, apiBody, appSecret, Constants.SIGN_METHOD_HMAC));

                // 发起批量请求
                string fullUrl = WebUtils.BuildRequestUrl(this.batchServerUrl, parameters);
                string rsp     = webUtils.DoPost(fullUrl, Encoding.UTF8.GetBytes(apiBody), BATCH_API_CONTENT_TYPE, batchRequest.GetHeaderParameters());

                // 构造响应解释器
                ITopParser <TopResponse> parser = null;
                if (Constants.FORMAT_XML.Equals(format))
                {
                    parser = new TopXmlParser <TopResponse>();
                }
                else
                {
                    if (this.useSimplifyJson)
                    {
                        parser = new TopSimplifyJsonParser <TopResponse>();
                    }
                    else
                    {
                        parser = new TopJsonParser <TopResponse>();
                    }
                }

                // 解释响应结果
                TopBatchResponse batchResponse = new TopBatchResponse();
                batchResponse.Body = rsp;

                string[] responseArray = batchResponse.Body.Split(new string[] { separator }, StringSplitOptions.None);
                // 批量API在走单通道验证时没通过,如前面验证,此时只有一个报错信息
                if (responseArray.Length > 0 && responseArray.Length != requestList.Count)
                {
                    TopResponse tRsp = parser.Parse(responseArray[0], requestList[0].GetType().BaseType.GetGenericArguments()[0]);
                    batchResponse.ErrCode    = tRsp.ErrCode;
                    batchResponse.ErrMsg     = tRsp.ErrMsg;
                    batchResponse.SubErrCode = tRsp.SubErrCode;
                    batchResponse.SubErrMsg  = tRsp.SubErrMsg;
                }
                else
                {
                    for (int i = 0; i < responseArray.Length; i++)
                    {
                        TopResponse tRsp = parser.Parse(responseArray[i], requestList[i].GetType().BaseType.GetGenericArguments()[0]);
                        tRsp.Body = responseArray[i];
                        batchResponse.AddResponse(tRsp);
                    }
                }

                if (batchResponse.IsError)
                {
                    TimeSpan latency = new TimeSpan(DateTime.Now.Ticks - start);
                    TraceApiError(appKey, "BatchApi", batchServerUrl, parameters, latency.TotalMilliseconds, batchResponse.Body);
                }

                return(batchResponse as T);
            }
            catch (Exception e)
            {
                TimeSpan latency = new TimeSpan(DateTime.Now.Ticks - start);
                TraceApiError(appKey, "BatchApi", batchServerUrl, parameters, latency.TotalMilliseconds, e.GetType() + ": " + e.Message);
                throw e;
            }
        }
Ejemplo n.º 21
0
 public override T Execute <T>(ITopRequest <T> request)
 {
     return(Execute <T>(request, null));
 }
Ejemplo n.º 22
0
        private void BindCurrentSource()
        {
            #region 关键字
            string query = Request["query"];
            txtQuery.Text = query;
            #endregion

            #region 参与打折
            bool?discount = null;
            if (!string.IsNullOrEmpty(Request["discount"]))
            {
                discount = bool.Parse(Request["discount"]);
            }
            cbDiscount.Checked = discount.HasValue && discount.Value;
            #endregion

            #region 橱窗推荐
            bool?showCase = null;
            if (!string.IsNullOrEmpty(Request["showCase"]))
            {
                showCase = bool.Parse(Request["showCase"]);
            }
            cbShowCase.Checked = showCase.HasValue && showCase.Value;
            #endregion

            #region 类型
            string type = "onsale";
            if (!string.IsNullOrEmpty(Request["type"]))
            {
                type = Request["type"];
            }
            if (type.Equals("onsale", StringComparison.OrdinalIgnoreCase))
            {
                cbDiscount.Enabled = true;
                cbShowCase.Enabled = true;
            }
            else
            {
                cbDiscount.Enabled = false;
                cbShowCase.Enabled = false;
            }
            #endregion

            #region 过滤子类
            string filter = "all";
            if (!string.IsNullOrEmpty(Request["filter"]))
            {
                filter = Request["filter"];
            }
            TreeNode node = tvCategory.FindNode(type + "/" + filter);
            if (node != null)
            {
                node.Selected = true;
            }
            #endregion

            #region 分页
            int pageIndex = ucCtrlPager.PageIndex + 1;
            int pageSize  = ucCtrlPager.PageSize;
            #endregion

            ITopClient  client = GetProductTopClient();
            ITopRequest req    = GetTopRequest(query, discount, showCase, type, filter, pageIndex, pageSize);
            if (req != null)
            {
                ResponseList <Item> rsp = client.Execute(req, new ItemListJsonParser(), CurrentSessionKey);

                ucCtrlPager.TotalCount = (int)rsp.TotalResults;
                rptItemList.DataSource = rsp.Content;
                rptItemList.DataBind();
            }
        }
        private T DoExecute <T>(ITopRequest <T> request, string session, long timestamp) where T : YunResponse
        {
            // 提前检查业务参数
            try
            {
                request.Validate();
            }
            catch (YunException e)
            {
                return(CreateErrorResponse <T>(e.ErrorCode, e.ErrorMsg));
            }

            // 添加协议级请求参数
            var txtParams = new YunDictionary(request.GetParameters())
            {
                { METHOD, request.GetApiName() },
                { VERSION, "1.0" },
                { APP_KEY, appKey },
                { FORMAT, format },
                { TIMESTAMP, timestamp },
                { SESSION, session }
            };

            txtParams.AddAll(this.systemParameters);

            // 添加签名参数
            txtParams.Add(SIGN, TopUtils.SignTopRequest(txtParams, appSecret, "UTF-8"));

            var reqUrl = webUtils.BuildGetUrl(this.serverUrl, txtParams);

            try
            {
                string body;
                if (request is ITopUploadRequest <T> ) // 是否需要上传文件
                {
                    var uRequest   = (ITopUploadRequest <T>)request;
                    var fileParams = TopUtils.CleanupDictionary(uRequest.GetFileParameters());
                    body = webUtils.DoPost(this.serverUrl, txtParams, fileParams);
                }
                else
                {
                    body = webUtils.DoPost(this.serverUrl, txtParams);
                }

                // 解释响应结果
                T rsp;
                if (disableParser)
                {
                    rsp      = Activator.CreateInstance <T>();
                    rsp.Body = body;
                }
                else
                {
                    if (FORMAT_XML.Equals(format))
                    {
                        ITopParser tp = new TopXmlParser();
                        rsp = tp.Parse <T>(body);
                    }
                    else
                    {
                        ITopParser tp = new TopJsonParser();
                        rsp = tp.Parse <T>(body);
                        //rsp = Newtonsoft.Json.JsonConvert.DeserializeObject<T>(body);
                        //rsp = JsonDeserialize<T>(body);
                    }
                }

                rsp.ReqUrl = reqUrl;

                // 追踪错误的请求
                if (!disableTrace && rsp.IsError)
                {
                    var sb = new StringBuilder(reqUrl).Append(" response error!\r\n").Append(rsp.Body);
                    topLogger.Warn(sb.ToString());
                }
                return(rsp);
            }
            catch (Exception e)
            {
                if (!disableTrace)
                {
                    var sb = new StringBuilder(reqUrl).Append(" request error!\r\n").Append(e.StackTrace);
                    topLogger.Error(sb.ToString());
                }
                throw e;
            }
        }
 public T Execute <T>(ITopRequest <T> request, string session, long timestamp) where T : YunResponse
 {
     return(DoExecute <T>(request, session, timestamp));
 }
Ejemplo n.º 25
0
        private T DoExecute <T>(ITopRequest <T> request, string session, DateTime timestamp) where T : TopResponse
        {
            long start = DateTime.Now.Ticks;

            // 提前检查业务参数
            try
            {
                request.Validate();
            }
            catch (TopException e)
            {
                return(CreateErrorResponse <T>(e.ErrorCode, e.ErrorMsg));
            }

            // 添加协议级请求参数
            TopDictionary txtParams = new TopDictionary(request.GetParameters());

            txtParams.Add(Constants.METHOD, request.GetApiName());
            txtParams.Add(Constants.VERSION, "2.0");
            txtParams.Add(Constants.SIGN_METHOD, Constants.SIGN_METHOD_HMAC);
            txtParams.Add(Constants.APP_KEY, appKey);
            txtParams.Add(Constants.FORMAT, format);
            txtParams.Add(Constants.PARTNER_ID, GetSdkVersion());
            txtParams.Add(Constants.TIMESTAMP, timestamp);
            txtParams.Add(Constants.TARGET_APP_KEY, request.GetTargetAppKey());
            txtParams.Add(Constants.SESSION, session);
            txtParams.AddAll(this.systemParameters);

            if (this.useSimplifyJson)
            {
                txtParams.Add(Constants.SIMPLIFY, "true");
            }

            // 添加签名参数
            txtParams.Add(Constants.SIGN, TopUtils.SignTopRequest(txtParams, appSecret, Constants.SIGN_METHOD_HMAC));

            // 添加头部参数
            if (this.useGzipEncoding)
            {
                request.GetHeaderParameters()[Constants.ACCEPT_ENCODING] = Constants.CONTENT_ENCODING_GZIP;
            }

            string realServerUrl = GetServerUrl(this.serverUrl, request.GetApiName(), session);
            string reqUrl        = WebUtils.BuildRequestUrl(realServerUrl, txtParams);

            try
            {
                string body;
                if (request is ITopUploadRequest <T> ) // 是否需要上传文件
                {
                    ITopUploadRequest <T>          uRequest   = (ITopUploadRequest <T>)request;
                    IDictionary <string, FileItem> fileParams = TopUtils.CleanupDictionary(uRequest.GetFileParameters());
                    body = webUtils.DoPost(realServerUrl, txtParams, fileParams, request.GetHeaderParameters());
                }
                else
                {
                    body = webUtils.DoPost(realServerUrl, txtParams, request.GetHeaderParameters());
                }

                // 解释响应结果
                T rsp;
                if (disableParser)
                {
                    rsp      = Activator.CreateInstance <T>();
                    rsp.Body = body;
                }
                else
                {
                    if (Constants.FORMAT_XML.Equals(format))
                    {
                        ITopParser <T> tp = new TopXmlParser <T>();
                        rsp = tp.Parse(body);
                    }
                    else
                    {
                        ITopParser <T> tp;
                        if (useSimplifyJson)
                        {
                            tp = new TopSimplifyJsonParser <T>();
                        }
                        else
                        {
                            tp = new TopJsonParser <T>();
                        }
                        rsp = tp.Parse(body);
                    }
                }

                // 追踪错误的请求
                if (rsp.IsError)
                {
                    TimeSpan latency = new TimeSpan(DateTime.Now.Ticks - start);
                    TraceApiError(appKey, request.GetApiName(), serverUrl, txtParams, latency.TotalMilliseconds, rsp.Body);
                }
                return(rsp);
            }
            catch (Exception e)
            {
                TimeSpan latency = new TimeSpan(DateTime.Now.Ticks - start);
                TraceApiError(appKey, request.GetApiName(), serverUrl, txtParams, latency.TotalMilliseconds, e.GetType() + ": " + e.Message);
                throw e;
            }
        }
Ejemplo n.º 26
0
        /// <summary>
        /// 执行方法
        /// </summary>
        /// <typeparam name="TResponse"></typeparam>
        /// <param name="request"></param>
        /// <returns></returns>
        public TResponse Execute <TResponse>(ITopRequest <TResponse> request) where TResponse : TopResponse
        {
            var client = new DefaultTopClient(this.Url, _apiConfig.AppKey, _apiConfig.AppSecret);

            return(client.Execute(request, _apiConfig.SessionKey) as TResponse);
        }
Ejemplo n.º 27
0
 public virtual T Execute <T>(ITopRequest <T> request) where T : TopResponse
 {
     return(Execute <T>(request, null));
 }
Ejemplo n.º 28
0
 public T Execute <T>(ITopRequest <T> request) where T : TopResponse
 {
     return(Execute <T>(request, DateTime.Now));
 }
Ejemplo n.º 29
0
 public virtual T Execute <T>(ITopRequest <T> request, string session, DateTime timestamp) where T : TopResponse
 {
     return(DoExecute <T>(request, session, timestamp));
 }
 public T Execute <T>(ITopRequest <T> request) where T : YunResponse
 {
     return(Execute <T>(request, null));
 }