/// <summary>
 /// Получает refresh_token клиента. Если его нет возвращает пустую строку
 /// </summary>
 /// <param name="token"></param>
 /// <returns></returns>
 public bool ReceiveRefreshTokenForClient(String token)
 {
     try
     {
         var returnValue = new DefaultResponse();
         _cnn.Open();
         SqlCommand cmd = _cnn.CreateCommand();
         cmd.CommandType = CommandType.StoredProcedure;
         cmd.CommandText = "RefreshTokenCheckForClient";
         cmd.Parameters.AddWithValue("@token", token);
         cmd.Parameters.Add("@errormessage", SqlDbType.NVarChar, 100);
         cmd.Parameters["@errormessage"].Direction = ParameterDirection.Output;
         cmd.Parameters.Add("@result", SqlDbType.Int);
         cmd.Parameters["@result"].Direction = ParameterDirection.ReturnValue;
         cmd.ExecuteNonQuery();
         returnValue.ErrorCode = Convert.ToInt32(cmd.Parameters["@result"].Value);
         returnValue.Message   = Convert.ToString(cmd.Parameters["@errormessage"].Value);
         if (returnValue.ErrorCode == 0)
         {
             return(true);
         }
         return(false);
     }
     catch (Exception e)
     {
         Log.Error(e, "LCManagerAPI");
         return(false);
     }
     finally
     {
         _cnn.Close();
     }
 }
示例#2
0
        public DefaultResponse GetUserList()
        {
            DefaultResponse defaultResponse = new DefaultResponse();

            need = "s";
            List <SqlParameter> list = new List <SqlParameter>()
            {
                new SqlParameter(nameof(need), need)
            };

            try
            {
                DataTable dt = SqlQuery.GetDataTableFromProcedure(list, "prc_i_u_s_d_tbl_user", _connectionString);
                if (dt.Rows.Count > 0)
                {
                    List <UserModel> lsusermodel = GetModelList(dt);
                    defaultResponse.payload = lsusermodel;
                    defaultResponse.result  = DefaultResponse.ActionResult.success.ToString();
                    defaultResponse.message = "The data of user list";
                }
            }
            catch (Exception ex)
            {
                defaultResponse.result  = DefaultResponse.ActionResult.failure.ToString();
                defaultResponse.message = "Error while getting user list";
            }
            return(defaultResponse);
        }
示例#3
0
        public override async Task <DefaultResponse> AddFlightRoute(FlightRouteRequestModel request, ServerCallContext context)
        {
            var result = new DefaultResponse();

            try
            {
                var airports = await _airportProxy.GetAllAirports();

                if (!airports.Where(x => x.City == request.Source).Any())
                {
                    result.Message = $"There is no connection with the airport in {request.Source}";
                    return(result);
                }

                if (!airports.Where(x => x.City == request.Target).Any())
                {
                    result.Message = $"There is no connection with the airport in {request.Target}";
                    return(result);
                }

                var fligthRoute = new FlightRouteRaw()
                {
                    Source        = airports.Where(x => x.City == request.Source).FirstOrDefault().Id,
                    Target        = airports.Where(x => x.City == request.Target).FirstOrDefault().Id,
                    EstimatedTime = request.EstimatedTime
                };
                _airlineRepository.AddFligthRoute(fligthRoute);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, $"ERROR: Adding FligthRoute");
            }

            return(result);
        }
示例#4
0
        public override async Task <DefaultResponse> UpdateFligthStatus(ControlTowerRequestModel request, ServerCallContext context)
        {
            var response = new DefaultResponse();

            try
            {
                if (!STATUSACCEPT.Where(x => x == request.Status).Any())
                {
                    response.Message = $"Status {request.Status} is not vaild";
                    return(response);
                }

                _airlineRepository.UpdateFligthStatus(request.FligthId, request.Status);

                var statusString = request.Status switch
                {
                    1 => "CURRENTLY-FLYING",
                    2 => "CANCELED",
                    _ => "SCHEDULED"
                };

                response.Message = $"Fligth status changed to {statusString}";
                return(response);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, $"ERROR: Update fligth status");
            }
            return(response);
        }
示例#5
0
        /// <summary>
        /// Удаляет список товаров из БД
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        public DefaultResponse RemoveOperatorGoodList(OperatorGoodRemoveRequest request)
        {
            var returnValue = new DefaultResponse();

            _cnn.Open();
            SqlCommand cmd = _cnn.CreateCommand();

            cmd.CommandType = CommandType.Text;
            cmd.CommandText = "delete from goodlist where id=@id";
            cmd.Parameters.AddWithValue("@id", request.OperatorGoodList);

            try
            {
                cmd.ExecuteNonQuery();
                returnValue.ErrorCode = 0;
                returnValue.Message   = string.Empty;
            }
            catch (Exception e)
            {
                returnValue.ErrorCode = 10;
                returnValue.Message   = e.Message;
            }
            finally
            {
                _cnn.Close();
            }
            return(returnValue);
        }
示例#6
0
        public IHttpActionResult Login([FromBody] DTOUsuario usuario)
        {
            try
            {
                AutenticacaoService authService = new AutenticacaoService();

                SenhaAcesso usuarioLogado;

                var response = new DefaultResponse <SenhaAcesso>
                {
                    data = new List <SenhaAcesso>()
                };

                if (authService.Autenticar(usuario, out usuarioLogado))
                {
                    FormsAuthentication.SetAuthCookie(usuarioLogado.Usuario, true);
                    response.success = true;
                    response.message = "Conectado(a) com sucesso.";
                    return(Ok(response));
                }
                else
                {
                    response.success = false;
                    response.message = "Usuário ou senha incorretos.";

                    return(Ok(response));
                }
            }
            catch (Exception ex)
            {
                return(BadRequest(ex.Message));
            }
        }
示例#7
0
        private DefaultResponse ClientChangePhone(ClientChangeModel model)
        {
            var response = new DefaultResponse();

            try
            {
                AddPhoneRequest request = new AddPhoneRequest
                {
                    ClientID = model.Id,
                    Phone    = Convert.ToInt64(PhoneService.GetPhoneFromStr(model.Phone))
                };
                HttpResponseMessage changeResponse = HttpClientService.PostAsync("api/client/AddPhone", request).Result;
                if (changeResponse.IsSuccessStatusCode)
                {
                    response = changeResponse.Content.ReadAsAsync <DefaultResponse>().Result;
                    return(response);
                }
            }
            catch (Exception e)
            {
                response.ErrorCode = 500;
                response.Message   = e.Message;
            }
            return(response);
        }
示例#8
0
        public JsonResult OperatorPosListRemove(Int16 id)
        {
            DefaultResponse defaultResponse = new DefaultResponse();

            try
            {
                OperatorPosRemoveRequest operatorPosRemoveRequest = new OperatorPosRemoveRequest
                {
                    OperatorPosList = id
                };
                HttpResponseMessage responseMessage = HttpClientService.PostAsync("api/pos/RemoveOperatorPosList", operatorPosRemoveRequest).Result;
                if (responseMessage.IsSuccessStatusCode)
                {
                    defaultResponse = responseMessage.Content.ReadAsAsync <DefaultResponse>().Result;
                    if (defaultResponse.ErrorCode == 0 && string.IsNullOrEmpty(defaultResponse.Message))
                    {
                        return(Json(new { success = true }));
                    }
                    return(Json(new { success = false, error = JsonConvert.SerializeObject(defaultResponse) }));
                }
                defaultResponse.ErrorCode = 10;
                defaultResponse.Message   = "Ошибка удаления данных";
            }
            catch (Exception ex)
            {
                defaultResponse.ErrorCode = 10;
                defaultResponse.Message   = ex.Message;
            }
            return(Json(new { success = false, error = JsonConvert.SerializeObject(defaultResponse) }));
        }
示例#9
0
        public Response <XDocument> Upload(WebFormDownloadSettings settings)
        {
            AsyncArgs args = new AsyncArgs(null)
            {
                Settings = settings
            };

            if (settings.Account.Crumb == string.Empty)
            {
                Html2XmlDownload html = new Html2XmlDownload();
                html.Settings.Account = settings.Account;
                html.Settings.Url     = settings.Url;
                Response <XDocument> resp = html.Download();
                this.ConvertHtml(resp.Result, args);
            }
            PostDataUpload dl = new PostDataUpload();

            this.PrepareDownloader(dl, args);
            if (dl.Settings.PostStringData != string.Empty)
            {
                DefaultResponse <System.IO.Stream> resp = (DefaultResponse <System.IO.Stream>)dl.Download();
                return(resp.CreateNew(MyHelper.ParseXmlDocument(resp.Result)));
            }
            else
            {
                return(null);
            }
        }
示例#10
0
        public DefaultResponse Active(int userid)
        {
            DefaultResponse defaultResponse = new DefaultResponse();

            need      = "a";
            i_user_id = userid;
            List <SqlParameter> list = new List <SqlParameter>()
            {
                new SqlParameter(nameof(need), need),
                new SqlParameter(nameof(i_user_id), i_user_id)
            };

            try
            {
                DataTable dt = SqlQuery.GetDataTableFromProcedure(list, "prc_i_u_s_d_tbl_user", _connectionString);
                if (dt.Rows.Count > 0)
                {
                    defaultResponse.result  = DefaultResponse.ActionResult.success.ToString();
                    defaultResponse.message = "user deleted successfully";
                }
            }
            catch (Exception ex)
            {
                defaultResponse.result  = DefaultResponse.ActionResult.failure.ToString();
                defaultResponse.message = "Error while deleting user";
            }
            return(defaultResponse);
        }
示例#11
0
        public IHttpActionResult Listar(string nomeCategoria = "")
        {
            try
            {
                CategoriasService service = new CategoriasService();
                var categorias            = service.Listar(nomeCategoria).OrderBy(x => x.Nome).ToList();

                var response = new DefaultResponse <Categoria>
                {
                    message = categorias.Count > 0 ? "Encontramos as seguintes categorias." : "Oops, parece que tem nada por aqui.",
                    data    = categorias.Count > 0 ? categorias : new List <Categoria>(),
                    success = true
                };

                var json = Json(response, new Newtonsoft.Json.JsonSerializerSettings
                {
                });

                if (categorias.Count > 0)
                {
                    return(Ok(response));
                }
                else
                {
                    return(Content(HttpStatusCode.NoContent, response));
                }
            }
            catch (Exception ex)
            {
                return(BadRequest(ex.Message));
            }
        }
示例#12
0
        public IDocument Parse(String str, String type)
        {
            var ctx     = _window?.Document.Context;
            var factory = ctx?.GetService <IDocumentFactory>() ?? throw new DomException(DomError.NotSupported);

            using (var content = new MemoryStream(TextEncoding.Utf8.GetBytes(str)))
            {
                var response = new DefaultResponse
                {
                    Address = new Url(_window.Document.Url),
                    Content = content,
                    Headers = new Dictionary <String, String>
                    {
                        { HeaderNames.ContentType, type },
                    },
                };

                try
                {
                    var task     = factory.CreateAsync(ctx, new CreateDocumentOptions(response), default);
                    var document = task.Result;
                    return(document);
                }
                catch (Exception ex)
                {
                    var message    = ex.InnerException?.Message ?? ex.Message ?? "Something went wrong.";
                    var sourceText = String.Empty;
                    var error      = $"<parsererror xmlns=\"http://www.mozilla.org/newlayout/xml/parsererror.xml\">{message}<sourcetext>{sourceText}</sourcetext></parsererror>";
                    return(Parse(error, MimeTypeNames.Xml));
                }
            }
        }
示例#13
0
        public IHttpActionResult Cadastrar([FromBody] DTOUsuario usuario)
        {
            try
            {
                AutenticacaoService authService = new AutenticacaoService();

                var usuarioCadastrado = authService.Cadastrar(usuario);

                if (usuarioCadastrado != null)
                {
                    var response = new DefaultResponse <SenhaAcesso>
                    {
                        message = "Cadastrado efetuado com sucesso.",
                        data    = new List <SenhaAcesso>(),
                        success = true
                    };

                    response.data.Add(usuarioCadastrado);

                    return(Created(HttpContext.Current.Request.RawUrl, response));
                }
                else
                {
                    return(BadRequest("Houve um erro ao cadastrar."));
                }
            }
            catch (Exception ex)
            {
                return(BadRequest(ex.Message));
            }
        }
示例#14
0
        public DefaultResponse Update()
        {
            DefaultResponse defaultRespose = new DefaultResponse();

            try
            {
                int id = ExecuteProc("u");
                if (id > 0)
                {
                    defaultRespose.result  = DefaultResponse.ActionResult.success.ToString();
                    defaultRespose.payload = id;
                    defaultRespose.message = "The user updated successfully";
                }
                else
                {
                    defaultRespose.result  = DefaultResponse.ActionResult.failure.ToString();
                    defaultRespose.message = "Error while updated user";
                }
            }
            catch (Exception ex)
            {
                defaultRespose.result  = DefaultResponse.ActionResult.failure.ToString();
                defaultRespose.message = "Error while updated user";
            }
            return(defaultRespose);
        }
示例#15
0
        public override async Task <DefaultResponse> AddCustomer(CustomerRequest request, ServerCallContext context)
        {
            var result = new DefaultResponse();

            try
            {
                var costumer = new Model.Customer()
                {
                    Address    = request.Address,
                    BirthDate  = DateTimeOffset.Parse(request.BirthDate),
                    City       = request.City,
                    Country    = request.Country,
                    Email      = request.Email,
                    FirsName   = request.FirsName,
                    IdNumber   = request.IdNumber,
                    LastName   = request.LastName,
                    MiddleName = request.MiddleName,
                    Movil      = request.Movil,
                    Phone      = request.Phone
                };

                costumer.CaesarEncipherObject(_keyCaesarEncipher);
                await _costumerRepository.Add(costumer);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, $"ERROR: Adding Costumer");
                result.Message = $"ERROR: Adding Costumer";
            }
            return(result);
        }
示例#16
0
    void FinishRequest(DefaultResponse response)
    {
        if (response == null)
        {
            textError.text = "Erro de conexão!";
        }
        else
        {
            if (response.code == 1)
            {
                PlayerPrefs.SetString("Login", inputUsuario.text);
                PlayerPrefs.SetString("Password", inputSenha.text);
                UserInstance.Instance.User = JsonUtility.FromJson <DataUser>(response.data);

                string dataAsJson = File.ReadAllText(Application.persistentDataPath + "/staticdatavalidation.json");
                UserInstance.Instance.DataObjects = JsonUtility.FromJson <DataValidation>(dataAsJson);

                UnityEngine.SceneManagement.SceneManager.LoadScene("main");
                Debug.Log(response.data);
            }
            else
            {
                textError.text = response.data;
            }
        }
    }
        /// <summary>
        /// Performs an asynchronous request that can be cancelled.
        /// </summary>
        /// <param name="request">The options to consider.</param>
        /// <param name="cancel">The token for cancelling the task.</param>
        /// <returns>
        /// The task that will eventually give the response data.
        /// </returns>
        protected override async Task <IResponse> PerformRequestAsync(Request request, CancellationToken cancel)
        {
            // create the request message
            var method         = new HttpMethod(request.Method.Stringify());
            var requestMessage = new HttpRequestMessage(method, request.Address);
            var contentHeaders = new List <KeyValuePair <String, String> >();

            foreach (var header in request.Headers)
            {
                // Source:
                // https://github.com/aspnet/Mvc/blob/02c36a1c4824936682b26b6c133d11bebee822a2/src/Microsoft.AspNet.Mvc.WebApiCompatShim/HttpRequestMessage/HttpRequestMessageFeature.cs
                if (!requestMessage.Headers.TryAddWithoutValidation(header.Key, header.Value))
                {
                    contentHeaders.Add(new KeyValuePair <String, String>(header.Key, header.Value));
                }
            }

            // set up the content
            if (request.Content != null && method != HttpMethod.Get && method != HttpMethod.Head)
            {
                requestMessage.Content = new StreamContent(request.Content);

                foreach (var header in contentHeaders)
                {
                    requestMessage.Content.Headers.TryAddWithoutValidation(header.Key, header.Value);
                }
            }

            // execute the request
            var responseMessage = await _client.SendAsync(requestMessage, cancel).ConfigureAwait(false);

            // convert the response
            var response = new DefaultResponse
            {
                Headers    = responseMessage.Headers.ToDictionary(p => p.Key, p => String.Join(", ", p.Value)),
                Address    = Url.Convert(responseMessage.RequestMessage.RequestUri),
                StatusCode = responseMessage.StatusCode
            };

            // get the anticipated content
            var content = responseMessage.Content;

            if (content != null)
            {
                response.Content = await content.ReadAsStreamAsync().ConfigureAwait(false);

                foreach (var pair in content.Headers)
                {
                    response.Headers[pair.Key] = String.Join(", ", pair.Value);
                }
            }

            if (IsRedirected(response) && !response.Headers.ContainsKey(HeaderNames.SetCookie))
            {
                response.Headers[HeaderNames.SetCookie] = String.Empty;
            }

            return(response);
        }
示例#18
0
 private void OnSuccess(DefaultResponse response, object cookie)
 {
     this.isAuthenticating                    = false;
     this.successfullySetUserName             = true;
     Service.Get <CurrentPlayer>().PlayerName = this.inputTextField.Text;
     this.inputBackground.Color               = Color.green;
     this.nextButton.Enabled                  = true;
 }
示例#19
0
 private void OnSyncConflictLoadExistingConfirmSuccess(DefaultResponse response, object cookie)
 {
     if (this.recoverAccountCallback != null)
     {
         this.recoverAccountCallback();
         this.recoverAccountCallback = null;
     }
 }
示例#20
0
        public IActionResult Delete(int id)
        {
            var response = new DefaultResponse
            {
                Success = _orderRepository.OrderReset(id)
            };

            return(Ok(response));
        }
示例#21
0
        /// <summary>
        /// The Default Response
        ///
        /// The default response command is generated when a device receives a unicast       /// command, there is no other relevant response specified for the command, and       /// either an error results or the Disable default response bit of its Frame control field       /// is set to 0.       ///
        /// @param commandIdentifier {@link byte} Command identifier
        /// @param statusCode {@link ZclStatus} Status code
        /// @return the Task<CommandResult> command result Task
        /// </summary>
        public Task <CommandResult> DefaultResponse(byte commandIdentifier, ZclStatus statusCode)
        {
            DefaultResponse command = new DefaultResponse();

            // Set the fields
            command.CommandIdentifier = commandIdentifier;
            command.StatusCode        = statusCode;

            return(Send(command));
        }
        public async Task <HttpResponseMessage> GetRefreshProcess(string cardNo, string adminNo)
        {
            LogWriter._other(TAG, string.Format(@"[>>] Request: [{0}, {1}]", cardNo, adminNo));
            HttpResponseMessage message  = new HttpResponseMessage();
            DefaultResponse     response = new DefaultResponse();
            string ip       = httpUtil.GetClientIPAddress(HttpContext.Current.Request);
            string secToken = string.Empty;

            try
            {
                secToken = HttpContext.Current.Request.Headers["Authorization"].Replace("Basic ", "").Trim();
                if (dbconn.idbStatOK())
                {
                    string insId    = string.Empty;
                    string insPhone = string.Empty;
                    if (dbconn.tabletCheckToken(secToken, out insId, out insPhone))
                    {
                        if (dbconn.refreshService(cardNo, insPhone))
                        {
                            response.isSuccess     = true;
                            response.errorCode     = Convert.ToString((int)HttpStatusCode.OK);
                            response.resultMessage = "success";
                        }
                        else
                        {
                            response.isSuccess     = false;
                            response.errorCode     = Convert.ToString((int)HttpStatusCode.InternalServerError);
                            response.resultMessage = "Internal Error";
                        }
                    }
                    else
                    {
                        response.isSuccess     = false;
                        response.errorCode     = Convert.ToString((int)HttpStatusCode.Unauthorized);
                        response.resultMessage = "Session has expired";
                    }
                }
                else
                {
                    response.isSuccess     = false;
                    response.errorCode     = Convert.ToString((int)HttpStatusCode.InternalServerError);
                    response.resultMessage = "Internal Error";
                }
            }
            catch (Exception ex)
            {
                LogWriter._error(TAG, string.Format(@"Token: [{0}], Exception: [{1}]", secToken, ex.ToString()));
                response.isSuccess     = false;
                response.errorCode     = Convert.ToString((int)HttpStatusCode.InternalServerError);
                response.resultMessage = ex.Message;
            }
            LogWriter._other(TAG, string.Format(@"[<<] ClientIp: [{0}], Response: [{1}]", ip, serializer.Serialize(response)));
            message = Request.CreateResponse(HttpStatusCode.OK, response);
            return(message);
        }
        public DefaultResponse <Item> GetItemByBarcode(string barcode)
        {
            var result = new DefaultResponse <Item>
            {
                HasResult  = true,
                Result     = _itemService.GetItems(x => x.Barcode == barcode).FirstOrDefault(),
                ResultText = "T"
            };

            return(result);
        }
        public DefaultResponse <IEnumerable <Item> > Get()
        {
            var result = new DefaultResponse <IEnumerable <Item> >
            {
                HasResult  = true,
                Result     = _itemService.GetItems(),
                ResultText = "T"
            };

            return(result);
        }
 public async Task <TResponse> Handle(TRequest request, CancellationToken cancellationToken, RequestHandlerDelegate <TResponse> next)
 {
     try
     {
         return(await next());
     }
     catch (Exception e)
     {
         return(DefaultResponse.Failed(request, e) as TResponse);
     }
 }
示例#26
0
        /// <summary>
        /// Anies the specified request.
        /// </summary>
        /// <param name="request">The request.</param>
        /// <returns>System.Object.</returns>
        /// <remarks>聚石塔WebService</remarks>
        public object Any(GetFXTrade request)
        {
            logger.Debug(JsonConvert.SerializeObject(request));
            FXTradeValidator validator = new FXTradeValidator();
            ValidationResult results   = validator.Validate(request);

            if (!results.IsValid)
            {
                logger.Error(JsonConvert.SerializeObject(results));
                return(results);
            }

            using (RDSContext db = new RDSContext())
            {
                IQueryable <jdp_fx_trade> q = db.jdp_fx_trade;

                //0:淘宝推送时间;1:订单修改时间;默认0
                if (request.DateType == 0)
                {
                    q = q.Where(u => u.jdp_modified >= request.StartDateTime && u.jdp_modified <= request.EndDateTime).OrderBy(m => m.jdp_modified);
                }
                else
                {
                    q = q.Where(u => u.modified >= request.StartDateTime && u.modified <= request.EndDateTime).OrderBy(m => m.modified);
                }
                //订单状态
                if (request.Status != 0)
                {
                    q = q.Where(u => u.status == ((FXTradeStatus)request.Status).ToString());
                }

                if (request.FenxiaoID != 0)
                {
                    q = q.Where(u => u.fenxiao_id == request.FenxiaoID);
                }

                if (!string.IsNullOrEmpty(request.SupplierName))
                {
                    q = q.Where(u => u.supplier_username == request.SupplierName);
                }
                if (!string.IsNullOrEmpty(request.DistributorUserName))
                {
                    q = q.Where(u => u.distributor_username == request.DistributorUserName);
                }

                DefaultResponse response = new DefaultResponse();
                response.PageSize    = request.PageSize;
                response.RecordCount = q.Count();
                response.PageCount   = (int)Math.Ceiling(response.RecordCount * 1.00 / response.PageSize);
                response.Result      = q.Skip(request.PageNo * request.PageSize).Take(request.PageSize).Select(u => u.jdp_response).ToList();
                logger.Debug(JsonConvert.SerializeObject(results));
                return(response);
            }
        }
 private AblyRealtime GetRealtime(Action <ClientOptions> optionsAction = null)
 {
     return(GetRealtimeClient(request =>
     {
         if (request.Url == Defaults.InternetCheckUrl)
         {
             return (_internetCheckOK ? Defaults.InternetCheckOkMessage : "Blah").ToAblyResponse();
         }
         return DefaultResponse.ToTask();
     }, optionsAction));
 }
示例#28
0
        public void IsNoAttachmentWhenDispositionIsMissing()
        {
            var response = new DefaultResponse
            {
                Address = Url.Create("http://example.com/foo.png"),
                Headers = new Dictionary <string, string>
                {
                }
            };

            Assert.IsFalse(response.IsAttachment());
        }
示例#29
0
        /// <summary>
        /// Sends a default response to the client
        ///
        /// <param name="transactionId">the transaction ID to use in the response</param>
        /// <param name="commandIdentifier">the command identifier to which this is a response</param>
        /// <param name="status">the ZclStatus to send in the response</param>
        /// </summary>
        public void SendDefaultResponse(byte transactionId, byte commandIdentifier, ZclStatus status)
        {
            DefaultResponse defaultResponse = new DefaultResponse();

            defaultResponse.TransactionId      = transactionId;
            defaultResponse.CommandIdentifier  = commandIdentifier;
            defaultResponse.DestinationAddress = _zigbeeEndpoint.GetEndpointAddress();
            defaultResponse.ClusterId          = _clusterId;
            defaultResponse.StatusCode         = status;

            _zigbeeEndpoint.SendTransaction(defaultResponse);
        }
示例#30
0
        /// <summary>
        /// 获取分销退货数据
        /// </summary>
        /// <param name="request">分销退货请求</param>
        /// <returns>System.Object.</returns>
        /// <remarks>聚石塔WebService</remarks>
        public object Any(GetFXRefund request)
        {
            //记录请求
            logger.Debug(JsonConvert.SerializeObject(request));
            //验证请求数据
            FXRefundValidator validator = new FXRefundValidator();
            ValidationResult  results   = validator.Validate(request);

            if (!results.IsValid)
            {
                logger.Error(JsonConvert.SerializeObject(results));
                return(results);
            }
            //业务数据查询
            using (RDSContext db = new RDSContext())
            {
                IQueryable <jdp_fx_refund> q = db.jdp_fx_refund;

                //0:淘宝推送时间;1:订单修改时间;默认0
                if (request.DateType == 0)
                {
                    q = q.Where(u => u.jdp_modified >= request.StartDateTime && u.jdp_modified <= request.EndDateTime).OrderBy(m => m.jdp_modified);
                }
                else
                {
                    q = q.Where(u => u.modified >= request.StartDateTime && u.modified <= request.EndDateTime).OrderBy(m => m.modified);
                }
                //订单状态
                if (request.RefundStatus != 0)
                {
                    q = q.Where(u => u.refund_status == request.RefundStatus);
                }

                if (!string.IsNullOrEmpty(request.SupplierNick))
                {
                    q = q.Where(u => u.supplier_nick == request.SupplierNick);
                }
                if (!string.IsNullOrEmpty(request.DistributorNick))
                {
                    q = q.Where(u => u.distributor_nick == request.DistributorNick);
                }
                //组装返回对象
                DefaultResponse response = new DefaultResponse();
                response.PageSize    = request.PageSize;
                response.RecordCount = q.Count();
                response.PageCount   = (int)Math.Ceiling(response.RecordCount * 1.00 / response.PageSize);
                response.Result      = q.Skip(request.PageNo * request.PageSize).Take(request.PageSize).Select(u => u.jdp_response).ToList();
                //记录返回对象
                logger.Debug(JsonConvert.SerializeObject(results));
                return(response);
            }
        }
        public static DefaultResponse BuildErrorResponseWithMessage(this Exception exception)
        {
            var errorResponse = new DefaultResponse
            {
                Success = false,
                Message = exception.Message
            };

            if (exception.InnerException != null)
            {
                errorResponse.Message += exception.InnerException.Message;
            }

            return errorResponse;
        }
        public void WriteError(HttpListenerContext httpListenerContext, string errorCode, string errorMessage, string stackTrace)
        {
            var response = new DefaultResponse
              	{
              		Error = new Error
                {
                    Code = errorCode,
                    Message = errorMessage,
                    StackTrace = stackTrace,
                }
              	};

            using (var outputStream = httpListenerContext.Response.OutputStream)
            {
                this.responseSerializer.WriteObject(outputStream, response);
            }
        }
示例#33
0
        DefaultResponse GetResponse()
        {
            var result = new DefaultResponse();
            var headers = _response.Headers.AllKeys.Select(m => new { Key = m, Value = _response.Headers[m] });
            result.Content = _response.GetResponseStream();
            result.StatusCode = _response.StatusCode;

            foreach (var header in headers)
                result.Headers.Add(header.Key, header.Value);

            return result;
        }