public string e(Querye querye)
        {
            Dictionary <string, object> metaData = null;
            QueryResult qr        = null;
            Stopwatch   stopWatch = null;

            bool   includeServerMetrics = false;
            bool   returnColumnNames    = false;
            string queryName            = querye.d;

            var inCourseRequest = InCourseRequest.New();
            OrdenesApplication ordenesApplication = OrdenesApplication.Instance;

            inCourseRequest.SecurityTokenId = ordenesApplication.GetSecurityTokenIdFromHeader();
            inCourseRequest.Agencia         = ordenesApplication.GetSecurityAgenciaFromHeader();

            Query query = null;

            try
            {
                SecurityHelper.ensureAuthenticated(inCourseRequest);
                query = JsonConvert.DeserializeObject <Query>(querye.d, new JsonSerializerSettings
                {
                    TypeNameHandling = TypeNameHandling.Objects,
                    TypeNameAssemblyFormatHandling = TypeNameAssemblyFormatHandling.Simple
                });

                var type = (QueryType)Enum.Parse(typeof(QueryType), query.Type);

                //includeServerMetrics = null != opts && opts.ContainsKey("includeServerMetrics");
                //returnColumnNames = null != opts && opts.ContainsKey("returnColumnNames");

                includeServerMetrics = null != query.Options && query.Options.Exists(x => x.Key.Equals("includeServerMetrics", StringComparison.OrdinalIgnoreCase));
                returnColumnNames    = null != query.Options && query.Options.Exists(x => x.Key.Equals("returnColumnNames", StringComparison.OrdinalIgnoreCase));

                if (includeServerMetrics)
                {
                    stopWatch = Stopwatch.StartNew();
                    metaData  = new Dictionary <string, object>(1);
                }

                SecurityHelper.ensureAuthorized(query, inCourseRequest);
                queryName = query.Name;
                //query.ensureAuthorized(inCourseRequest);
                //var queryName = query.getDecriptedQueryName();

                //TODO Encender QueryLog.Start para loguear... hay que adaptarlo a Ordenes
                QueryLog.Start(query, inCourseRequest);

                var requireIdentity = query.Options.Find(x => x.Key.Equals("requireIdentityFilter", StringComparison.OrdinalIgnoreCase));
                // Es comun que varias consultas necesiten el usuario que las activa....
                if (requireIdentity != null && Convert.ToBoolean(requireIdentity.Value))
                {
                    //query.Filters.Add("IdUsuario", session.Identity_rid);
                    query.Filters.Add(new Parameter()
                    {
                        Key = "IdUsuario", Value = MAEUserSession.Instancia.IdUsuario
                    });
                }


                if (query.Options.Exists(x => x.Key == "extendToKnownType"))
                {
                    ExtendQueryFilters(query);
                }
                if (queryName.Contains("_CUSTOM_"))
                {
                    qr = new QueryResult();
                    var    tName  = queryName.Split(new string[] { "_CUSTOM_" }, StringSplitOptions.None)[1] + "CustomQueryById";
                    object result = reflect(query, tName);

                    qr.Data     = new object[] { result };
                    qr.Status   = "EX0000";
                    qr.MetaData = metaData;
                }
                else
                {
                    switch (type)
                    {
                    case QueryType.Grid:
                        var r = new QueryPagingResult();

                        int      totalRows;
                        string[] columnNames;
                        object[] r_grid = null;
                        var      draw   = 0;
                        //query.Filters.Remove("maxrecord"); //TODO: porque remueves este parametro?
                        if (query.Options.Exists(x => x.Key.Equals("gridAdapter", StringComparison.OrdinalIgnoreCase)))
                        {
                            var result = (CustomQueryReturn)reflect(query, queryName);
                            r_grid    = result.Data;
                            totalRows = result.TotalRows;
                        }
                        else
                        {
                            r_grid = SqlServerHelper.RunGrid("orden_owner." + queryName, query.Filters, out columnNames, out totalRows);
                            if (returnColumnNames)
                            {
                                r.ColumnNames = columnNames;
                            }
                        }

                        var pageSize = query.Filters.Find(i => i.Key == "pageSize");
                        draw = (pageSize != null) ? Convert.ToInt32(pageSize.Value) : totalRows;

                        r.Data            = r_grid;
                        r.Status          = "EX0000";
                        r.MetaData        = metaData;
                        r.draw            = (int)draw;
                        r.recordsTotal    = totalRows;
                        r.recordsFiltered = totalRows;    //r_grid.Length;

                        qr = r;
                        break;

                    case QueryType.Combos:
                        qr = new QueryResult();
                        DatabaseQueryResult r_combos = null;
                        if (query.Options.Exists(x => x.Key == "filtersAdapter"))
                        {
                            r_combos = (DatabaseQueryResult)reflect(query, queryName);
                        }
                        else
                        {
                            r_combos = SqlServerHelper.RunCombos("orden_owner." + queryName, query.Filters);
                        }
                        qr.Data     = r_combos.ResultSets.ToArray();
                        qr.Status   = "EX0000";
                        qr.MetaData = metaData;
                        break;

                    case QueryType.Data:
                        qr          = new QueryResult();
                        qr.Data     = new object[1]; // TODO: FIXME: arreglar para tener mas de un data set
                        qr.Data[0]  = SqlServerHelper.RunDictionary("orden_owner." + queryName, query.Filters);
                        qr.Status   = "EX0000";
                        qr.MetaData = metaData;
                        break;

                    case QueryType.FullRecord:
                        if (query.Options.Exists(x => x.Key.Equals("gridAdapter", StringComparison.OrdinalIgnoreCase)))
                        {
                            var rqr    = new QueryPagingResult();
                            var result = (CustomQueryReturn)reflect(query, queryName);
                            r_grid    = result.Data;
                            totalRows = result.TotalRows;
                            draw      = totalRows;

                            rqr.Data            = r_grid;
                            rqr.Status          = "EX0000";
                            rqr.MetaData        = metaData;
                            rqr.draw            = (int)draw;
                            rqr.recordsTotal    = totalRows;
                            rqr.recordsFiltered = totalRows;    //r_grid.Length;
                            qr = rqr;
                        }
                        else
                        {
                            qr = new QueryResult();
                            var r_fullrecord = SqlServerHelper.RunFullRecord("orden_owner." + queryName, query.Filters);
                            qr.Data     = r_fullrecord.ResultSets.ToArray();
                            qr.Status   = "EX0000";
                            qr.MetaData = metaData;
                        }
                        break;

                    case QueryType.FullByEntity:
                        qr = new QueryResult();
                        //TODO ADAPTAR PARA USAR EF...
                        //var r_fullrecord = ReadDatabase.Instance.RunFullRecord("orden_owner." + queryName, query.Filters);
                        //qr.Data = r_fullrecord.ResultSets.ToArray();
                        qr.Status   = "EX0000";
                        qr.MetaData = metaData;
                        break;
                    }
                }

                //TODO Encender QueryLog.FinishOK para loguear... adapatar a Ordenes
                QueryLog.FinishOK(query, qr, inCourseRequest);
            }
            catch (SessionException sex)
            {
                qr = new QueryResult();

                qr.Data = new object[2] {
                    inCourseRequest.Id, "Sessión Expirada"
                };
                qr.Status   = "SE6666";
                qr.MetaData = metaData;

                //TODO: levantar log despues...
                QueryLog.FinishWithError(queryName, qr, sex, inCourseRequest);
            }
            catch (FunctionalException fe)
            {
                qr = new QueryResult();

                qr.Data = new object[2] {
                    inCourseRequest.Id, fe.Message
                };
                qr.Status   = string.Format("FE{0}", fe.Code.ToString("0000"));
                qr.MetaData = metaData;

                //TODO: levantar log despues...
                QueryLog.FinishWithError(queryName, qr, fe, inCourseRequest);
            }
            catch (Exception ex)
            {
                qr = new QueryResult();

                qr.Data = new object[2] {
                    inCourseRequest.Id, ex.Message
                };
                qr.Status   = "TE9999";
                qr.MetaData = metaData;

                //TODO: levantar log despues...
                QueryLog.FinishWithError(queryName, qr, ex, inCourseRequest);
            }
            finally
            {
                if (includeServerMetrics)
                {
                    qr.MetaData.Add("serverMetrics", stopWatch.ElapsedMilliseconds);
                    stopWatch.Reset();
                }
            }

            qr.RequestId = inCourseRequest.Id;
            WebOperationContext.Current.OutgoingResponse.ContentType = "application/json; charset=utf-8";
            return(JsonConvert.SerializeObject(qr));
        }
        public string c(Commande Commnade)
        {
            var     r           = new CommandResult();
            string  commandName = Commnade.d;
            Command command     = null;
            //string desencry = null;

            var inCourseRequest = InCourseRequest.New();
            OrdenesApplication ordenesApplication = OrdenesApplication.Instance;

            //inCourseRequest.SecurityTokenId = ordenesApplication.GetSecurityTokenIdFromHeader();
            try
            {
                //SecurityHelper.ensureAuthenticated(inCourseRequest);
                //AESEncryptor encryptor = new AESEncryptor();
                //desencry = encryptor.DesencriptarQuery(Commnade.d, MAEUserSession.Instancia.Global);
                //desencry = desencry.Replace("@s", "M4Trader.ordenes.server").Replace("@a", "M4Trader.ordenes.mvc");

                Commnade.d = Commnade.d.Replace("@s", "M4Trader.ordenes.server").Replace("@a", "M4Trader.ordenes.mvc");


                command = JsonConvert.DeserializeObject <Command>(Commnade.d, new JsonSerializerSettings
                {
                    TypeNameHandling = TypeNameHandling.Objects,
                    TypeNameAssemblyFormatHandling = TypeNameAssemblyFormatHandling.Simple
                });
                commandName = command.GetType().Name;


                var opts = command.Options;
                inCourseRequest.Agencia = ordenesApplication.GetSecurityAgenciaFromHeader();
                if (!(command is RefrescarCacheCommand) && command.GetIdAccion != (int)IdAccion.Login && !(command is M4Trader.ordenes.server.AppLiteralesCommand) && !(command is M4Trader.ordenes.server.AppThemeCommand))
                {
                    inCourseRequest.SecurityTokenId = ordenesApplication.GetSecurityTokenIdFromHeader();

                    SecurityHelper.ensureAuthorized(command, inCourseRequest);
                    inCourseRequest.Identity_rid = MAEUserSession.Instancia.IdUsuario;
                }

                CommandLog.Start(command, inCourseRequest);

                command.PreProcess();
                command.Validate();

                r.Data      = command.Execute(inCourseRequest).Data;
                r.Status    = "EX0000";
                r.RequestId = inCourseRequest.Id.ToString();

                CommandLog.FinishOK(commandName, r, inCourseRequest);
                try { command.ExecuteAfterSuccess(); }
                catch { }
            }
            catch (JsonSerializationException)
            {
                Commnade.d = Commnade.d.Replace("M4Trader.ordenes.mvc", "M4Trader.ordenes.server");

                command = JsonConvert.DeserializeObject <Command>(Commnade.d, new JsonSerializerSettings
                {
                    TypeNameHandling = TypeNameHandling.Objects,
                    TypeNameAssemblyFormatHandling = TypeNameAssemblyFormatHandling.Simple
                });
                commandName = command.GetType().Name;
                var opts = command.Options;

                if (!(command is RefrescarCacheCommand) && command.GetIdAccion != (int)IdAccion.Login && !(command is M4Trader.ordenes.server.AppLiteralesCommand))
                {
                    inCourseRequest.SecurityTokenId = ordenesApplication.GetSecurityTokenIdFromHeader();
                    SecurityHelper.ensureAuthorized(command, inCourseRequest);
                    inCourseRequest.Identity_rid = MAEUserSession.Instancia.IdUsuario;
                }

                CommandLog.Start(command, inCourseRequest);

                command.PreProcess();
                command.Validate();

                r.Data      = command.Execute(inCourseRequest).Data;
                r.Status    = "EX0000";
                r.RequestId = inCourseRequest.Id.ToString();

                CommandLog.FinishOK(commandName, r, inCourseRequest);
                try { command.ExecuteAfterSuccess(); }
                catch { }
            }
            catch (SessionException sex)
            {
                CommandLog.StartDesencriptado(Commnade.d, inCourseRequest);

                var cr = new CommandResult();
                cr.Data   = ExecutionResult.ReturnWithError("Sessión Expirada", inCourseRequest.Id).Data;
                cr.Status = "SE6666";

                CommandLog.FinishWithError(commandName, sex, inCourseRequest);

                r = cr;
            }
            catch (PreConditionNotEnsuredException ex)
            {
                CommandLog.StartDesencriptado(Commnade.d, inCourseRequest);

                r.Data   = ExecutionResult.ReturnWithError(ex.Message, inCourseRequest.Id).Data;
                r.Status = "FE9999";

                CommandLog.FinishWithError(commandName, ex, inCourseRequest);
            }
            catch (FunctionalException fe)
            {
                CommandLog.StartDesencriptado(Commnade.d, inCourseRequest);

                r.Data   = ExecutionResult.ReturnWithError(fe.Message, inCourseRequest.Id).Data;
                r.Status = string.Format("FE{0}", fe.Code.ToString("0000"));

                CommandLog.FinishWithError(commandName, fe, inCourseRequest);
            }
            catch (M4TraderApplicationException maex)
            {
                CommandLog.StartDesencriptado(Commnade.d, inCourseRequest);

                r.Data   = ExecutionResult.ReturnWithError(maex.Message, inCourseRequest.Id).Data;
                r.Status = string.Format("FE{0}", maex.Codigo);
                CommandLog.FinishWithError(commandName, maex, inCourseRequest);
            }
            catch (MAECommunicationException mce)
            {
                CommandLog.StartDesencriptado(Commnade.d, inCourseRequest);

                r.Data   = ExecutionResult.ReturnWithError(mce.Message, inCourseRequest.Id).Data;
                r.Status = "FE9999";
                CommandLog.FinishWithError(commandName, mce, inCourseRequest);
            }
            catch (MAEConcurrencyException mce)
            {
                CommandLog.StartDesencriptado(Commnade.d, inCourseRequest);

                r.Data   = ExecutionResult.ReturnWithError(mce.Message, inCourseRequest.Id).Data;
                r.Status = "FE00055";
                CommandLog.FinishWithError(commandName, mce, inCourseRequest);
            }
            catch (Exception ex)
            {
                CommandLog.StartDesencriptado(Commnade.d, inCourseRequest);

                r.Data   = ExecutionResult.ReturnWithError(ex.Message, inCourseRequest.Id).Data;
                r.Status = "TE9999";

                CommandLog.FinishWithError(commandName, ex, inCourseRequest);
            }

            finally
            {
                if (command != null)
                {
                    command.Dispose();
                }
            }

            r.RequestId = inCourseRequest.Id.ToString();
            WebOperationContext.Current.OutgoingResponse.ContentType = "application/json; charset=utf-8";
            return(JsonConvert.SerializeObject(r));
        }
Example #3
0
        public string c(Command command)
        {
            var inCourseRequest = InCourseRequest.New();
            OrdenesApplication ordenesApplication = OrdenesApplication.Instance;

            inCourseRequest.SecurityTokenId = ordenesApplication.GetSecurityTokenIdFromHeader();

            Dictionary <string, object> metaData = null;
            var       r                    = new CommandResult();
            Stopwatch stopWatch            = null;
            bool      includeServerMetrics = false;
            string    commandName          = command.GetType().Name;

            try
            {
                var opts = command.Options;
                includeServerMetrics = null != opts && opts.ContainsKey("includeServerMetrics");

                if (includeServerMetrics)
                {
                    stopWatch = Stopwatch.StartNew();
                    metaData  = new Dictionary <string, object>(1);
                }
                Type tipoAConsultar = command.GetType();
                if (tipoAConsultar != typeof(RefrescarCacheCommand) &&
                    command.GetIdAccion != (int)IdAccion.Login)

                {
                    SecurityHelper.ensureAuthorized(command, inCourseRequest);
                    inCourseRequest.Identity_rid = MAEUserSession.Instancia.IdUsuario;//command.ensureAuthorized(inCourseRequest).Identity_rid;
                }
                //TODO: levantar log despues...
                CommandLog.Start(command, inCourseRequest);

                command.PreProcess();
                command.Validate();

                r.MetaData = metaData;

                r.Data      = command.Execute(inCourseRequest).Data;
                r.Status    = "EX0000";
                r.MetaData  = metaData;
                r.RequestId = inCourseRequest.Id.ToString();

                //TODO: levantar log despues...
                CommandLog.FinishOK(commandName, r, inCourseRequest);

                try { command.ExecuteAfterSuccess(); }
                catch { }
            }
            catch (SessionException sex)
            {
                var      cr        = new CommandResult();
                Response resultado = new Response();
                resultado.Resultado       = eResult.Error;
                resultado.MensajeError[0] = "Sessión Expirada";
                cr.Data     = ExecutionResult.ReturnInmediatelyAndQueueOthers(resultado);
                cr.Status   = "SE6666";
                cr.MetaData = metaData;

                CommandLog.FinishWithError(commandName, sex, inCourseRequest);

                r = cr;
            }
            catch (PreConditionNotEnsuredException ex)
            {
                Response resultado = new Response();
                resultado.Resultado       = eResult.Error;
                resultado.MensajeError[0] = ex.Message;
                resultado.Detalle         = inCourseRequest.Id;
                r.Data     = ExecutionResult.ReturnInmediatelyAndQueueOthers(resultado);
                r.Status   = "FE9999";
                r.MetaData = metaData;

                //TODO: levantar log despues...
                CommandLog.FinishWithError(commandName, ex, inCourseRequest);
            }
            catch (FunctionalException fe)
            {
                Response resultado = new Response();
                resultado.Resultado       = eResult.Error;
                resultado.MensajeError[0] = fe.Message;
                resultado.Detalle         = inCourseRequest.Id;
                r.Data     = ExecutionResult.ReturnInmediatelyAndQueueOthers(resultado);
                r.Status   = string.Format("FE{0}", fe.Code.ToString("0000"));
                r.MetaData = metaData;

                //TODO: levantar log despues...
                CommandLog.FinishWithError(commandName, fe, inCourseRequest);
            }
            catch (M4TraderApplicationException maex)
            {
                Response resultado = new Response();
                resultado.Resultado       = eResult.Error;
                resultado.MensajeError[0] = maex.Message;
                resultado.Detalle         = inCourseRequest.Id;
                r.Data     = ExecutionResult.ReturnInmediatelyAndQueueOthers(resultado);
                r.Status   = string.Format("FE{0}", maex.Codigo);
                r.MetaData = metaData;
                CommandLog.FinishWithError(commandName, maex, inCourseRequest);
            }
            catch (MAECommunicationException mce)
            {
                Response resultado = new Response();
                resultado.Resultado       = eResult.Error;
                resultado.MensajeError[0] = mce.Message;
                resultado.Detalle         = inCourseRequest.Id;
                r.Data     = ExecutionResult.ReturnInmediatelyAndQueueOthers(resultado);
                r.Status   = string.Format("FE9999");
                r.MetaData = metaData;
                CommandLog.FinishWithError(commandName, mce, inCourseRequest);
            }
            catch (Exception ex)
            {
                Response resultado = new Response();
                resultado.Resultado       = eResult.Error;
                resultado.MensajeError[0] = ex.Message;
                resultado.Detalle         = inCourseRequest.Id;
                r.Data     = ExecutionResult.ReturnInmediatelyAndQueueOthers(resultado);
                r.Status   = "TE9999";
                r.MetaData = metaData;

                //TODO: levantar log despues...
                CommandLog.FinishWithError(commandName, ex, inCourseRequest);
            }
            finally
            {
                command.Dispose();
                if (includeServerMetrics)
                {
                    r.MetaData.Add("serverMetrics", stopWatch.ElapsedMilliseconds);
                    stopWatch.Reset();
                }
            }


            r.RequestId = inCourseRequest.Id.ToString();
            WebOperationContext.Current.OutgoingResponse.ContentType = "application/json; charset=utf-8";
            return(JsonConvert.SerializeObject(r));
        }