示例#1
0
        public async Task <GetAccessTokenFromSecretKeyResponse> GetAccessTokenFromSecretKey(string secretKey, string clientId)
        {
            var client = new HttpClient()
            {
                BaseAddress = new Uri(_authUri)
            };

            client.DefaultRequestHeaders.Authorization = BasicAuthHeader.GetHeader(clientId, secretKey);

            var parameters = new Dictionary <string, string>()
            {
                { "grant_type", "client_credentials" },
                { "scope", "api1" }
            };

            var clientResponse = await client.PostAsync("connect/token", HttpClientHelpers.GetPostBody(parameters));

            var response = await QuickResponse <GetAccessTokenFromSecretKeyResponse> .FromMessage(clientResponse);

            if (response.Data?.AccessToken == null)
            {
                throw new Exception($"Could not get access token. Error: {response.ResponseBody}");
            }

            return(response.Data);
        }
示例#2
0
        private async Task <QuickResponse <T> > SendHttp <T>(Func <HttpRequestMessage> requestFunc)
        {
            try
            {
                var request = requestFunc();
                await SetAuthHeader(request, false);

                var response = await _httpClientFactory().SendAsync(request);

                if (response.StatusCode == HttpStatusCode.Unauthorized)
                {
                    request = requestFunc();
                    await SetAuthHeader(request, true);

                    response = await _httpClientFactory().SendAsync(request);
                }

                return(await QuickResponse <T> .FromMessage(response));
            }
            catch (Exception ex)
            {
                return(new QuickResponse <T>()
                {
                    Errors = new List <ApiError>()
                    {
                        new ApiError()
                        {
                            ErrorMessage = GetRecursiveErrorMessage(ex)
                        }
                    }
                });
            }
        }
示例#3
0
        protected async Task <QuickResponse <T> > GetHttp <T>(string url)
        {
            try
            {
                await SetInitialToken();

                var response = await _client.GetAsync(url);

                if (response.StatusCode == HttpStatusCode.Unauthorized)
                {
                    await GetToken();

                    response = await _client.GetAsync(url);
                }

                return(await QuickResponse <T> .FromMessage(response));
            }
            catch (Exception ex)
            {
                return(new QuickResponse <T>()
                {
                    Errors = new List <ApiError>()
                    {
                        new ApiError()
                        {
                            ErrorMessage = GetRecursiveErrorMessage(ex)
                        }
                    }
                });
            }
        }
示例#4
0
        /// <summary>
        /// Returns the quick-info object for json serialization
        /// </summary>
        /// <param name="db">The connection to use</param>
        /// <returns>The user info object</returns>
        public static object LoadQuickInfo(IDbConnection db)
        {
            var uid = Context.UserID;

            // If the user is not logged in, send empty response
            if (string.IsNullOrWhiteSpace(uid))
            {
                return(new QuickResponse());
            }

            // Build a response
            var res = new QuickResponse()
            {
                LoggedIn = true,
                UserID   = uid
            };

            // Add database information
            var user = db.SelectItemById <Database.User>(uid);

            res.Name                = user.Name;
            res.AvatarImage         = Services.Images.CreateLinkForId(user.AvatarImageID);
            res.UnreadNotifications = db.SelectCount <Database.Notification>(x => x.UserID == uid && x.Seen == false);
            res.IsAdmin             = Services.AdminHelper.IsAdmin(db, uid);

            return(res);
        }
示例#5
0
        /// <summary>
        ///  更新快捷回复跟据 AccountId
        /// </summary>
        /// <param name="qr"></param>
        public void UpdateQuickResponseById(QuickResponse model)
        {
            StringBuilder strSql = new StringBuilder();

            strSql.Append("update LiveChat_QuickResponse set ");
            strSql.Append("DomainName=@DomainName,");
            strSql.Append("AccountId=@AccountId,");
            strSql.Append("OperatorId=@OperatorId,");
            strSql.Append("Submenu=@Submenu,");
            strSql.Append("node=@node");
            strSql.Append(" where QuickId=@QuickId ");
            SqlParameter[] parameters =
            {
                new SqlParameter("@QuickId",    SqlDbType.Int,      4),
                new SqlParameter("@DomainName", SqlDbType.VarChar, 50),
                new SqlParameter("@AccountId",  SqlDbType.VarChar, 50),
                new SqlParameter("@OperatorId", SqlDbType.VarChar, 50),
                new SqlParameter("@Submenu",    SqlDbType.VarChar, 50),
                new SqlParameter("@node",       SqlDbType.Text)
            };
            parameters[0].Value = model.QuickId;
            parameters[1].Value = model.DomainName;
            parameters[2].Value = model.AccountId;
            parameters[3].Value = model.OperatorId;
            parameters[4].Value = model.Submenu;
            parameters[5].Value = model.Node;

            DBHelper.ExecuteCommand(strSql.ToString(), parameters);
        }
示例#6
0
    /// <summary>
    /// 跟据域名更新快捷回复
    /// </summary>
    /// <param name="operatorId"></param>
    /// <param name="response"></param>
    public static void SaveQuickResponseByDomainName(string operatorId, string domainName, List <QuickResponseCategory> response)
    {
        string accountId = OperatorService.GetOperatorById(operatorId).AccountId;

        DBProvider.DeleteQuickResponseByDomainName(domainName);
        foreach (var item in response)
        {
            QuickResponse qr = new QuickResponse();
            qr.DomainName = domainName;
            qr.AccountId  = accountId;
            qr.Submenu    = item.Name;
            qr.OperatorId = operatorId;
            string node = string.Empty;
            foreach (var n in item.Responses)
            {
                node += n.ToString() + "|";
            }
            if (node.Length > 0 && node[node.Length - 1] == '|')
            {
                node = node.Substring(0, node.Length - 1);
            }
            qr.Node = node;
            DBProvider.NewQuickResponse(qr);
        }
    }
示例#7
0
    /// <summary>
    /// Processes some returned text from a www. Technically not threadsafe, but in current
    /// usage context is 100 % safe. Works around UNitys limitations on only main thread
    /// accessing Unity stuff, as such error checking on the WWW MUST BE DONE BEFORE CALLING
    /// THIS using PRequest.WWWSuccess.
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="data"></param>
    /// <returns></returns>
    public static QuickResponse <T> FastProcessUnityThread <T>(string data) where T : ResponseBase
    {
        var response = new QuickResponse <T>();

        if (string.IsNullOrEmpty(data))
        {
            response.success   = false;
            response.errorcode = 1;

            return(response);
        }

        var results = LitJson.JsonMapper.ToObject <T>(data);

        response.success   = results.success;
        response.errorcode = results.errorcode;

        response.ResponseObject = results;

        // Lets clean up after ourselves
        data = null;
        GC.Collect();

        return(response);
    }
示例#8
0
    private IEnumerator SendListRequest <T>(Dictionary <string, object> postdata,
                                            Action <List <T>, int, PResponse> callback) where T : PlayerChallenge, new()
    {
        var www = PRequest.Prepare(SECTION, LIST, postdata);

        yield return(www);

        List <T> challenges    = null;
        int      numchallenges = 0;
        var      response      = default(QuickResponse <ListChallengeResponse <T> >);

        if (PRequest.WWWSuccess(www))
        {
            string data = www.text;

            Thread t = new Thread(() =>
            {
                response = PRequest.FastProcessUnityThread <ListChallengeResponse <T> >(data);
            });

            t.Start();

            // wait for thread to finish
            while (t.ThreadState == ThreadState.Running)
            {
                yield return(null);
            }
        }
        else
        {
            response = new QuickResponse <ListChallengeResponse <T> > {
                success = false, errorcode = 1
            };
        }

        if (response.success)
        {
            var challengeArray = response.ResponseObject.challenges;

            challenges = new List <T>();

            for (int i = 0; i < challengeArray.Length; i++)
            {
                challenges.Add(challengeArray[i]);
            }

            numchallenges = challenges.Count;
        }

        var resp = new PResponse {
            errorcode = response.errorcode, success = response.success
        };

        callback(challenges, numchallenges, resp);
    }
示例#9
0
        /// <summary>
        /// Método que hace la facturación del envío
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnFacturar_Click(object sender, EventArgs e)
        {
            IBLLFactura _BLLFactura   = new BLLFactura();
            string      rutaImagen    = @"c:\temp\qr.png";
            string      numeroFactura = "";

            if (pCliente == null)
            {
                MessageBox.Show("Debe Seleccionar un Cliente", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
            if (_EncabezadoFactura == null)
            {
                MessageBox.Show("No hay datos por facturar", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
            if (_EncabezadoFactura._ListDetFactura.Count == 0)
            {
                MessageBox.Show("No hay items en la factura ", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
            _EncabezadoFactura = _BLLFactura.GuardarFactura(_EncabezadoFactura);
            numeroFactura      = _EncabezadoFactura.IDEncFactura.ToString();
            pnumerofactura     = numeroFactura;

            if (_EncabezadoFactura == null)
            {
                MessageBox.Show("Error al crear factura!", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            else
            {
                if (File.Exists(rutaImagen))
                {
                    File.Delete(rutaImagen);
                }

                Image quickResponseImage = QuickResponse.QuickResponseGenerador(numeroFactura.ToString(), 53);
                quickResponseImage.Save(rutaImagen, ImageFormat.Png);

                frmReporteFactura ofrmReporteFactura = new frmReporteFactura(pnumerofactura);
                ofrmReporteFactura.ShowDialog();
                if (ofrmReporteFactura.DialogResult == DialogResult.OK || ofrmReporteFactura.DialogResult == DialogResult.Cancel)
                {
                    this.Close();
                }
                else
                {
                    this.Close();
                }
            }
        }
示例#10
0
        protected async Task <QuickResponse <T> > PostHttp <T>(string url, object data)
        {
            await SetInitialToken();

            var response = await _client.PostAsync(url, HttpClientHelpers.GetJsonBody(data));

            if (response.StatusCode == HttpStatusCode.Unauthorized)
            {
                await GetToken();

                response = await _client.PostAsync(url, HttpClientHelpers.GetJsonBody(data));
            }

            return(await QuickResponse <T> .FromMessage(response));
        }
示例#11
0
        protected async Task <QuickResponse <T> > PostHttp <T>(string url, Dictionary <string, string> parameters)
        {
            await SetInitialToken();

            var response = await _client.PostAsync(url, HttpClientHelpers.GetPostBody(parameters));

            if (response.StatusCode == HttpStatusCode.Unauthorized)
            {
                await GetToken();

                response = await _client.PostAsync(url, HttpClientHelpers.GetPostBody(parameters));
            }

            return(await QuickResponse <T> .FromMessage(response));
        }
示例#12
0
        protected async Task <QuickResponse> DeleteHttp(string url)
        {
            await SetInitialToken();

            var response = await _client.DeleteAsync(url);

            if (response.StatusCode == HttpStatusCode.Unauthorized)
            {
                await GetToken();

                response = await _client.DeleteAsync(url);
            }

            return(await QuickResponse.FromMessage(response));
        }
示例#13
0
    private IEnumerator SendSaveLoadRequest <T>(string action,
                                                Dictionary <string, object> postdata,
                                                Action <T, PResponse> callback) where T : PlayerChallenge
    {
        var www = PRequest.Prepare(SECTION, action, postdata);

        yield return(www);

        var response  = default(QuickResponse <UpdateChallengeResponse <T> >);
        var challenge = default(T);

        if (PRequest.WWWSuccess(www))
        {
            string data = www.text;

            Thread t = new Thread(() =>
            {
                response = PRequest.FastProcessUnityThread <UpdateChallengeResponse <T> >(data);
            });

            t.Start();

            // wait for thread to finish
            while (t.ThreadState == ThreadState.Running)
            {
                yield return(null);
            }
        }
        else
        {
            response = new QuickResponse <UpdateChallengeResponse <T> > {
                success = false, errorcode = 1
            };
        }

        if (response.success)
        {
            challenge = response.ResponseObject.challenge;
        }

        var resp = new PResponse {
            success = response.success, errorcode = response.errorcode
        };

        callback(challenge, resp);
    }
示例#14
0
    private IEnumerator getReplay <T>(string section, string action, Dictionary <string, object> postdata, Action <T, PResponse> callback)
    {
        var www = PRequest.Prepare(section, action, postdata);

        yield return(www);

        var replay   = default(T);
        var response = new QuickResponse <GetReplayResponse <T> >();

        if (PRequest.WWWSuccess(www))
        {
            string data = www.text;

            // spool deserialization off to another thread, allows UI to continue updating in the meantime
            Thread t = new Thread(() =>
            {
                response = PRequest.FastProcessUnityThread <GetReplayResponse <T> >(data);
            });
            t.Start();

            // wait for thread to finish
            while (t.ThreadState == ThreadState.Running)
            {
                yield return(null);
            }

            if (response.success)
            {
                replay = response.ResponseObject.challenge["replay"];
            }
        }
        else
        {
            response = new QuickResponse <GetReplayResponse <T> > {
                success = false, errorcode = 1
            };
        }

        var resp = new PResponse {
            errorcode = response.errorcode, success = response.success
        };

        callback(replay, resp);
    }
示例#15
0
    public static QuickResponse <T> FastProcess <T>(WWW www) where T : ResponseBase
    {
        var response = new QuickResponse <T>();

        if (!PRequest.WWWSuccess(www))
        {
            response.errorcode = 1;
            response.success   = false;
            return(response);
        }

        var results = LitJson.JsonMapper.ToObject <T>(www.text);

        response.success   = results.success;
        response.errorcode = results.errorcode;

        response.ResponseObject = results;
        return(response);
    }
示例#16
0
        public async Task <GetAccessTokenFromSecretKeyResponse> GetAccessToken()
        {
            var client = new HttpClient
            {
                BaseAddress = new Uri(_authUri)
            };

            client.DefaultRequestHeaders.Authorization = BasicAuthHeader.GetHeader(_consumerKey, _consumerSecret);

            var clientResponse = await client.GetAsync("/oauth/v1/generate?grant_type=client_credentials");

            var response = await QuickResponse <GetAccessTokenFromSecretKeyResponse> .FromMessage(clientResponse);

            if (response.Data?.AccessToken == null)
            {
                throw new Exception($"Could not get access token. Error: {response.ResponseBody}");
            }

            return(response.Data);
        }
示例#17
0
    private IEnumerator SendUpdate <T>(string section,
                                       string action,
                                       Dictionary <string, object> postdata,
                                       Action <bool, PResponse> callback) where T : PlayerChallenge, new()
    {
        var www = PRequest.Prepare(section, action, postdata);

        yield return(www);

        var response = default(QuickResponse <ReplaySentResponse>);

        if (PRequest.WWWSuccess(www))
        {
            string data = www.text;
            Thread t    = new Thread(() =>
            {
                response = PRequest.FastProcessUnityThread <ReplaySentResponse>(data);
            });

            t.Start();

            // wait for thread to finish
            while (t.ThreadState == ThreadState.Running)
            {
                yield return(null);
            }
        }
        else
        {
            response = new QuickResponse <ReplaySentResponse> {
                success = false, errorcode = 1
            };
        }

        var resp = new PResponse {
            errorcode = response.errorcode, success = response.success
        };

        callback(response.success, resp);
    }
示例#18
0
        /// <summary>
        ///  添天节点
        /// </summary>
        /// <param name="model"></param>
        public void NewQuickResponse(QuickResponse model)
        {
            StringBuilder strSql = new StringBuilder();

            strSql.Append("insert into LiveChat_QuickResponse(");
            strSql.Append("DomainName,AccountId,OperatorId,Submenu,node)");
            strSql.Append(" values (");
            strSql.Append("@DomainName,@AccountId,@OperatorId,@Submenu,@node)");
            SqlParameter[] parameters =
            {
                new SqlParameter("@DomainName", SqlDbType.VarChar, 50),
                new SqlParameter("@AccountId",  SqlDbType.VarChar, 50),
                new SqlParameter("@OperatorId", SqlDbType.VarChar, 50),
                new SqlParameter("@Submenu",    SqlDbType.VarChar, 50),
                new SqlParameter("@node",       SqlDbType.Text)
            };
            parameters[0].Value = model.DomainName;
            parameters[1].Value = model.AccountId;
            parameters[2].Value = model.OperatorId;
            parameters[3].Value = model.Submenu;
            parameters[4].Value = model.Node;
            DBHelper.ExecuteCommand(strSql.ToString(), parameters);
        }
示例#19
0
        private void toolStripBtnFacturar_Click(object sender, EventArgs e)
        {
            IBLLEncFactura _BLLFactura    = new BLLEncFactura();
            IBLLTarjeta    _BLLTarjeta    = new BLLTarjeta();
            IBLLHuesped    _BLLHuesped    = new BLLHuesped();
            IBLLHabitacion _BLLHabitacion = new BLLHabitacion();

            IBLLImpuesto _BLLImpuesto = new BLLImpuesto();

            DetFactura oFacturaDetalle = new DetFactura();

            this.cmbEstado.SelectedIndex = 1;

            IBLLReservacion _BLLReservacion = new BLLReservacion();


            Tarjeta oTarjeta      = new Tarjeta();
            string  rutaImagen    = @"c:\temp\qr.png";
            double  numeroFactura = 0d;

            try
            {
                _FacturaEncabezado = new EncFactura()
                {
                    IDFactura  = Double.Parse(this.txtNumeroFactura.Text),
                    _Tarjeta   = cmbTarjeta.SelectedItem as Tarjeta,//_BLLTarjeta.GetTarjetaById(Double.Parse(this.txtNumeroTarjeta.Text)),
                    Fecha      = DateTime.Now.Date,
                    EstadoFact = this.cmbEstado.SelectedIndex.ToString(),
                };

                oFacturaDetalle._EncFactura  = _BLLFactura.GetFactura(Double.Parse(this.txtNumeroFactura.Text));
                oFacturaDetalle._Reservacion = _BLLReservacion.GetReserva(Double.Parse(this.mskIDReserva.Text.ToString()));



                oFacturaDetalle.Precio = Double.Parse(this.txtPrecio.Text.ToString());

                // Calcular el Impuesto
                IBLLImpuesto _BLLImpuestotest = new BLLImpuesto();
                oFacturaDetalle._Impuesto = _BLLImpuestotest.GetImpuesto();
                // Enumerar la secuencia
                oFacturaDetalle.Numero = _FacturaEncabezado._ListaFacturaDetalle.Count == 0 ?
                                         1 : _FacturaEncabezado._ListaFacturaDetalle.Max(p => p.Numero) + 1;

                ;
                // Agregar
                _FacturaEncabezado.AddDetalle(oFacturaDetalle);


                if (_FacturaEncabezado == null)
                {
                    MessageBox.Show("No hay datos por facturar", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }
                if (_FacturaEncabezado._ListaFacturaDetalle.Count == 0)
                {
                    MessageBox.Show("No hay items en la factura ", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }



                this.txtSubtotal.Text = _FacturaEncabezado.GetSubTotal().ToString();
                this.txtImpuesto.Text = _FacturaEncabezado.GetImpuesto().ToString();
                this.txtTotal.Text    = (_FacturaEncabezado.GetSubTotal() + (_FacturaEncabezado.GetImpuesto())).ToString();

                _FacturaEncabezado = _BLLFactura.SaveFactura(_FacturaEncabezado);

                numeroFactura = _BLLFactura.GetCurrentNumeroFactura();

                EstadoHabitaciones();

                if (_FacturaEncabezado == null)
                {
                    MessageBox.Show("Error al crear factura!", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
                else
                //toolStripBtnNuevo_Click(null, null);


                // Si existe borrelo
                if (File.Exists(rutaImagen))
                {
                    File.Delete(rutaImagen);
                }


                // Crear imagen quickresponse
                Image quickResponseImage = QuickResponse.QuickResponseGenerador(numeroFactura.ToString(), 53);



                // Salvarla en c:\temp para luego ser leida
                quickResponseImage.Save(rutaImagen, ImageFormat.Png);

                frmFacturaImpresion ofrmFacturaImpresion = new frmFacturaImpresion((int)numeroFactura, _BLLHuesped.GetHuespedById(Double.Parse(this.txtIdHuesped.Text)).Nombre);


                ofrmFacturaImpresion.ShowDialog();


                this.txtNumeroTarjeta.Text    = "";
                this.txtNumHabitacion.Text    = "";
                this.txtNUMDetalle.Text       = "1";
                this.txtImpuesto.Text         = "";
                this.txtIdHuesped.Text        = "";
                this.txtCantDias.Text         = "";
                this.txtPrecio.Text           = "";
                this.txtSubtotal.Text         = "";
                this.txtTotal.Text            = "";
                this.cmbEstado.SelectedIndex  = 0;
                this.cmbTarjeta.SelectedIndex = 0;
                this.Subtotal.Text            = "";
                this.mskIDReserva.Text        = "";
                this.dgvDetalleFactura.Rows.Clear();
                this.dgvDetalleFactura.Refresh();
            }
            catch (Exception er)
            {
                StringBuilder msg = new StringBuilder();
                msg.AppendFormat("Message        {0}\n", er.Message);
                msg.AppendFormat("Source         {0}\n", er.Source);
                msg.AppendFormat("InnerException {0}\n", er.InnerException);
                msg.AppendFormat("StackTrace     {0}\n", er.StackTrace);
                msg.AppendFormat("TargetSite     {0}\n", er.TargetSite);
                // Log error
                _MyLogControlEventos.ErrorFormat("Error {0}", msg.ToString());
                // Mensaje de Error
                MessageBox.Show("Se ha producido el siguiente error " + er.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }