Ejemplo n.º 1
0
        /// <summary>
        /// Map RESTful parameters to JsonRpc parameters
        /// </summary>
        /// <param name="restfulParameters"></param>
        /// <returns></returns>
        internal dynamic ReadDataset_MapParameters(dynamic restfulParameters)
        {
            dynamic jsonStatParameters = new ExpandoObject();
            dynamic obj  = new ExpandoObject();
            var     dict = (IDictionary <string, object>)obj;


            dynamic extension = new ExpandoObject();
            dynamic dimension = new ExpandoObject();



            extension.matrix = restfulParameters[1];

            extension.language = restfulParameters.Count >= 5 ? new { code = restfulParameters[4] } : new { code = Configuration_BSO.GetCustomConfig("language.iso.code") };

            if (((string)extension.language.code).Length == 0)
            {
                extension.language = new { code = Configuration_BSO.GetCustomConfig("language.iso.code") }
            }
            ;

            extension.format = new { type = restfulParameters[2], version = restfulParameters[3] };


            jsonStatParameters.extension = extension;
            jsonStatParameters.dimension = dimension;

            dict["class"]     = "query";
            dict["id"]        = new string[] { };
            dict["dimension"] = dimension;
            dict["extension"] = extension;
            dict["version"]   = "2.0";
            dict["m2m"]       = true;


            string suffix;

            using (Format_BSO bso = new Format_BSO(new ADO("defaultConnection")))
            {
                this.MimeType = bso.GetMimetypeForFormat(new Format_DTO_Read()
                {
                    FrmType = restfulParameters[2], FrmVersion = restfulParameters[3]
                });

                suffix = bso.GetFileSuffixForFormat(new Format_DTO_Read()
                {
                    FrmType = restfulParameters[2], FrmVersion = restfulParameters[3]
                });
            };


            if (suffix != null)
            {
                this.FileName = extension.matrix + DateTime.Now.ToString("yyyyMMddHHmmss") + suffix;
            }

            return(Utility.JsonSerialize_IgnoreLoopingReference(dict));
        }
    }
Ejemplo n.º 2
0
        internal static bool FormatForReadDataset(Format_DTO_Read dto)
        {
            if (dto.FrmDirection != Format_DTO_Read.FormatDirection.DOWNLOAD.ToString())
            {
                return(false);
            }
            if (dto.FrmType != EnumInfo.GetEnumDescription(Format_DTO_Read.FormatType.JSONstat) && dto.FrmType != EnumInfo.GetEnumDescription(Format_DTO_Read.FormatType.PX) && dto.FrmType != EnumInfo.GetEnumDescription(Format_DTO_Read.FormatType.CSV) && dto.FrmType != EnumInfo.GetEnumDescription(Format_DTO_Read.FormatType.XLSX) && dto.FrmType != EnumInfo.GetEnumDescription(Format_DTO_Read.FormatType.SDMX))
            {
                return(false);
            }

            bool exists;

            using (Format_BSO bso = new Format_BSO(new ADO("defaultConnection")))
            {
                exists = bso.Exists(dto);
            }
            return(exists);
        }
Ejemplo n.º 3
0
        /// <summary>
        /// Map RESTful parameters to JsonRpc parameters
        /// </summary>
        /// <param name="restfulParameters"></param>
        /// <returns></returns>
        internal dynamic ReadMetadata_MapParameters(dynamic restfulParameters)
        {
            Format_DTO_Read format;

            using (Format_BSO bso = new Format_BSO(new ADO("defaultConnection")))
            {
                format = bso.Read(new Format_DTO_Read()
                {
                    FrmType = Constants.C_SYSTEM_JSON_STAT_NAME, FrmDirection = Format_DTO_Read.FormatDirection.DOWNLOAD.ToString()
                }).FirstOrDefault();
            }

            //Create a null format if one is not found. This will be caught in validation
            if (format == null)
            {
                format = new Format_DTO_Read();
            }

            var prm = JObject.FromObject(new
            {
                matrix   = restfulParameters.Count >= 2 ? restfulParameters[1] : null,
                language = restfulParameters.Count >= 3 ? restfulParameters[2] : null,
                format   = new { type = format.FrmType, version = format.FrmVersion }
            });

            // To make the parameters agnostic of trailing slashes:
            if (restfulParameters.Count >= 2)
            {
                if (restfulParameters[1].ToString().Length == 0)
                {
                    prm["matrix"] = null;
                }
            }
            if (restfulParameters.Count >= 3)
            {
                if (restfulParameters[2].ToString().Length == 0)
                {
                    prm["language"] = null;
                }
            }

            return(prm);
        }
Ejemplo n.º 4
0
        /// <summary>
        ///  Returns a Collection of JsonStat items. RESTful version
        /// </summary>
        /// <param name="restfulRequest"></param>
        /// <returns></returns>
        public static dynamic ReadCollection(RESTful_API restfulRequest)
        {
            //A pre-validation. If a validation problem is found then an output containing the error will be created and returned immediately
            var vldOutput = ValidateRest <Cube_VLD_REST_ReadCollection>(restfulRequest, new Cube_VLD_REST_ReadCollection());

            if (vldOutput != null)
            {
                return(vldOutput);
            }

            //Map the RESTful request to an equivalent Json Rpc request
            JSONRPC_API jsonRpcRequest = Map.RESTful2JSONRPC_API(restfulRequest);

            //Map the parameters - this is specific to the function
            Cube_MAP map = new Cube_MAP();

            jsonRpcRequest.parameters = map.ReadCollection_MapParameters(jsonRpcRequest.parameters);

            //Run the request as a Json Rpc call
            JSONRPC_Output rsp = new Cube_BSO_ReadCollection(jsonRpcRequest, true).Read().Response;

            string mimeType;

            using (Format_BSO fbso = new Format_BSO(new ADO("defaultConnection")))
            {
                mimeType = fbso.GetMimetypeForFormat(new Format_DTO_Read()
                {
                    FrmType = Constants.C_SYSTEM_JSON_STAT_NAME
                });
            };

            //Convert the JsonRpc output to RESTful output
            var response = Map.JSONRPC2RESTful_Output(rsp, mimeType);

            if (rsp.data == null)
            {
                response.statusCode = HttpStatusCode.NoContent;
            }
            response.fileName = map.FileName;
            return(response);
        }
Ejemplo n.º 5
0
        /// <summary>
        /// Get the collection with metadata
        /// </summary>
        /// <param name="theAdo"></param>
        /// <param name="theCubeDTO"></param>
        /// <param name="theResponse"></param>
        /// <returns></returns>
        internal dynamic ExecuteReadCollection(ADO theAdo, Cube_DTO_ReadCollection DTO)
        {
            var ado = new Cube_ADO(theAdo);

            var dbData = ado.ReadCollectionMetadata(DTO.language, DTO.datefrom, DTO.product);


            List <dynamic> jsonStatCollection = new List <dynamic>();

            //Get a list of individual matrix data entities
            List <dynamic> releases = getReleases(dbData);


            var theJsonStatCollection = new JsonStatCollection();

            theJsonStatCollection.Link      = new JsonStatCollectionLink();
            theJsonStatCollection.Link.Item = new List <Item>();

            List <Format_DTO_Read> formats = new List <Format_DTO_Read>();

            using (Format_BSO format = new Format_BSO(new ADO("defaultConnection")))
            {
                formats = format.Read(new Format_DTO_Read()
                {
                    FrmDirection = Utility.GetCustomConfig("APP_FORMAT_DOWNLOAD_NAME")
                });
            };

            //For each of these, get a list of statistics and a list of classifications
            //Then get the JSON-stat for that metadata and add to jsonStatCollection
            foreach (var rls in releases)
            {
                List <dynamic> thisReleaseMetadata = dbData.Where(x => x.RlsCode == rls.RlsCode).Where(x => x.LngIsoCode == rls.LngIsoCode).ToList <dynamic>();

                List <dynamic> stats           = getStatistics(thisReleaseMetadata);
                List <dynamic> classifications = getClassifications(thisReleaseMetadata);
                List <dynamic> periods         = getPeriods(thisReleaseMetadata);
                theJsonStatCollection.Link.Item.Add(GetJsonStatRelease(thisReleaseMetadata, stats, classifications, periods, formats));
            }

            //Get the minimum next release date. The cache can only live until then.
            //If there's no next release date then the cache will live for the maximum configured amount.

            DateTime minDateItem = default;


            dynamic minimum = null;

            if (dbData != null)
            {
                minimum     = dbData.Where(x => x.RlsLiveDatetimeFrom > DateTime.Now).Min(x => x.RlsLiveDatetimeFrom);
                minDateItem = minimum ?? default(DateTime);
            }

            if (minDateItem < DateTime.Now)
            {
                minDateItem = default(DateTime);
            }

            var result = new JRaw(Serialize.ToJson(theJsonStatCollection));

            MemCacheD.Store_BSO <dynamic>("PxStat.Data", "Cube_API", "ReadCollection", DTO, result, minDateItem, Constants.C_CAS_DATA_CUBE_READ_COLLECTION);


            // return the formatted data. This is an array of JSON-stat objects.
            return(result);
        }
Ejemplo n.º 6
0
        public static dynamic ReadDataset(RESTful_API restfulRequest)
        {
            try
            {
                //A pre-validation. If a validation problem is found then an output containing the error will be created and returned immediately
                var vldOutput = ValidateRest <Cube_VLD_REST_ReadDataset>(restfulRequest, new Cube_VLD_REST_ReadDataset());
                if (vldOutput != null)
                {
                    return(vldOutput);
                }

                //Map the RESTful request to an equivalent Json Rpc request
                JSONRPC_API jsonRpcRequest = Map.RESTful2JSONRPC_API(restfulRequest);

                //Map the parameters - this is specific to the function
                Cube_MAP map = new Cube_MAP();
                //jsonRpcRequest.parameters = map.ReadDataset_MapParameters(jsonRpcRequest.parameters);

                JsonStatQuery jq = map.ReadMetadata_MapParametersToQuery(restfulRequest.parameters);

                jq.Extension["codes"] = true;

                jsonRpcRequest.parameters = Utility.JsonSerialize_IgnoreLoopingReference(jq);


                //Run the request as a Json Rpc call
                JSONRPC_Output rsp = new Cube_BSO_ReadDataset(jsonRpcRequest).Read().Response;

                if (rsp.error != null)
                {
                    return(Map.JSONRPC2RESTful_Output(rsp, null, HttpStatusCode.NoContent, HttpStatusCode.InternalServerError));
                }

                Format_DTO_Read format = new Format_DTO_Read()
                {
                    FrmType = restfulRequest.parameters[Constants.C_DATA_RESTFUL_FORMAT_TYPE], FrmVersion = restfulRequest.parameters[Constants.C_DATA_RESTFUL_FORMAT_VERSION]
                };

                string mtype = null;
                using (Format_BSO fbso = new Format_BSO(new ADO("defaultConnection")))
                {
                    mtype = fbso.GetMimetypeForFormat(format);
                };
                //Convert the JsonRpc output to RESTful output
                var response = Map.JSONRPC2RESTful_Output(rsp, mtype, rsp.data == null ? HttpStatusCode.NotFound : HttpStatusCode.NoContent);

                string suffix;
                using (Format_BSO bso = new Format_BSO(new ADO("defaultConnection")))
                {
                    suffix = bso.GetFileSuffixForFormat(format);
                };


                response.fileName = restfulRequest.parameters[Constants.C_DATA_RESTFUL_MATRIX] + "." + DateTime.Now.ToString("yyyyMMddHHmmss") + suffix;
                return(response);
            }
            catch (Exception ex)

            {
                RESTful_Output error = new RESTful_Output
                {
                    statusCode = HttpStatusCode.InternalServerError
                };

                Log.Instance.Debug(ex.Message);
                return(error);
            }
        }
Ejemplo n.º 7
0
        public static dynamic PxAPIv1(RESTful_API restfulRequest)
        {
            try
            {
                var         parameters = ((List <string>)restfulRequest.parameters).Where(x => !string.IsNullOrWhiteSpace(x));
                int         pcount     = parameters.Count() - 1;
                JSONRPC_API rpc        = Map.RESTful2JSONRPC_API(restfulRequest);

                Cube_MAP      map       = new Cube_MAP();
                JObject       rpcParams = new JObject();
                PxApiMetadata meta      = new PxApiMetadata();

                var context = HttpContext.Current.Request;

                switch (pcount)
                {
                case Constants.C_DATA_PXAPIV1_SUBJECT_QUERY:
                    //Get a list of all subjects

                    rpcParams.Add("LngIsoCode", parameters.ElementAt(Constants.C_DATA_PXAPIV1_SUBJECT_QUERY));
                    rpc.parameters = rpcParams;

                    var rspSbj = new Subject_BSO_Read(rpc).Read().Response;

                    if (rspSbj.data == null)
                    {
                        return new RESTful_Output()
                               {
                                   statusCode = HttpStatusCode.NotFound
                               }
                    }
                    ;

                    rspSbj.data = Utility.JsonSerialize_IgnoreLoopingReference(meta.ReadSubjectsAsObjectList(rspSbj));



                    var responseSbj = Map.JSONRPC2RESTful_Output(rspSbj, null, HttpStatusCode.NotFound, HttpStatusCode.InternalServerError);

                    return(responseSbj);

                case Constants.C_DATA_PXAPIV1_PRODUCT_QUERY:
                    //Get a list of products for a subject
                    rpcParams.Add("LngIsoCode", parameters.ElementAt(Constants.C_DATA_PXAPIV1_SUBJECT_QUERY));

                    rpcParams.Add("SbjCode", parameters.ElementAt(Constants.C_DATA_PXAPIV1_PRODUCT_QUERY));
                    rpc.parameters = rpcParams;

                    var rspPrd = new Product_BSO_Read(rpc).Read().Response;

                    if (rspPrd.data == null)
                    {
                        return new RESTful_Output()
                               {
                                   statusCode = HttpStatusCode.NotFound
                               }
                    }
                    ;

                    meta = new PxApiMetadata();

                    if (rspPrd.data.Count == 0)
                    {
                        rspPrd = new JSONRPC_Output();

                        rspPrd.data = null;
                    }
                    else
                    {
                        rspPrd.data = Utility.JsonSerialize_IgnoreLoopingReference(meta.ReadProductsAsObjectList(rspPrd));
                    }

                    var responsePrd = Map.JSONRPC2RESTful_Output(rspPrd, null, HttpStatusCode.NotFound, HttpStatusCode.InternalServerError);

                    return(responsePrd);

                case Constants.C_DATA_PXAPIV1_COLLECTION_QUERY:
                    //Get a list of live tables for a product
                    rpcParams.Add("LngIsoCode", parameters.ElementAt(Constants.C_DATA_PXAPIV1_SUBJECT_QUERY));
                    rpcParams.Add("product", parameters.ElementAt(Constants.C_DATA_PXAPIV1_COLLECTION_QUERY));

                    if (!Int32.TryParse(parameters.ElementAt(Constants.C_DATA_PXAPIV1_PRODUCT_QUERY), out int sbjInt))
                    {
                        rpcParams.Add("SbjCode", "0");
                    }
                    else
                    {
                        rpcParams.Add("SbjCode", sbjInt.ToString());
                    }


                    rpc.parameters = rpcParams;

                    List <dynamic> collection = new List <dynamic>();

                    RESTful_Output output = new RESTful_Output();
                    DateTime       nextReleaseDateForProduct = default;

                    using (Cube_BSO cBso = new Cube_BSO(new ADO("defaultConnection")))
                    {
                        nextReleaseDateForProduct = cBso.GetNextReleaseDate(parameters.ElementAt(Constants.C_DATA_PXAPIV1_COLLECTION_QUERY));
                    }

                    //See if this request has cached data
                    MemCachedD_Value cache = MemCacheD.Get_BSO <dynamic>("PxStat.Data", "Cube_API", "ReadCollectionPxApi", rpcParams);

                    if (cache.hasData && (nextReleaseDateForProduct == default || nextReleaseDateForProduct > DateTime.Now))
                    {
                        output.response   = cache.data;
                        output.statusCode = HttpStatusCode.OK;
                    }

                    else
                    {
                        using (Cube_BSO cBso = new Cube_BSO(new ADO("defaultConnection")))
                        {
                            collection = cBso.ReadCollection(parameters.ElementAt(Constants.C_DATA_PXAPIV1_SUBJECT_QUERY), parameters.ElementAt(Constants.C_DATA_PXAPIV1_PRODUCT_QUERY), parameters.ElementAt(Constants.C_DATA_PXAPIV1_COLLECTION_QUERY));
                        }

                        meta = new PxApiMetadata();

                        if (collection != null)
                        {
                            if (collection.Count > 0)
                            {
                                output.response = Utility.JsonSerialize_IgnoreLoopingReference(meta.ReadCollectionAsObjectList(new JSONRPC_Output()
                                {
                                    data = collection
                                }));
                                output.statusCode = HttpStatusCode.OK;
                            }
                            else
                            {
                                output.statusCode = HttpStatusCode.NotFound;
                            }
                        }
                        else
                        {
                            output.statusCode = HttpStatusCode.NotFound;
                        }
                    }


                    MemCacheD.Store_BSO <dynamic>("PxStat.Data", "Cube_API", "ReadCollectionPxApi", rpcParams, output.response, nextReleaseDateForProduct, Constants.C_CAS_DATA_CUBE_READ_COLLECTION_PXAPI);

                    return(output);

                default:

                    if (pcount < Constants.C_DATA_PXAPIV1_METADATA_QUERY)
                    {
                        throw new Exception(Label.Get("error.validation"));
                    }

                    //Either get the metadata for the table or, if a query has been supplied, get the table data based on the query
                    string request = string.IsNullOrWhiteSpace(restfulRequest.httpPOST) ? restfulRequest.httpGET[Constants.C_JSON_STAT_QUERY_CLASS] : restfulRequest.httpPOST;

                    //For conventional RESTful patterns, don't return metadata unless the requested MtrCode is contained in the collection
                    //for the subject and product parameters
                    List <dynamic> collectionPrdSbjmeta = new List <dynamic>();
                    using (Cube_BSO cBso = new Cube_BSO(new ADO("defaultConnection")))
                    {
                        collectionPrdSbjmeta = cBso.ReadCollection(parameters.ElementAt(Constants.C_DATA_PXAPIV1_SUBJECT_QUERY), parameters.ElementAt(Constants.C_DATA_PXAPIV1_PRODUCT_QUERY), parameters.ElementAt(Constants.C_DATA_PXAPIV1_COLLECTION_QUERY));
                    }

                    if (collectionPrdSbjmeta == null)
                    {
                        var empty = new RESTful_Output();
                        empty.statusCode = HttpStatusCode.NotFound;
                        return(empty);
                    }

                    if (collectionPrdSbjmeta.Where(x => x.MtrCode == parameters.ElementAt(Constants.C_DATA_PXAPIV1_METADATA_QUERY)).ToList().Count == 0)
                    {
                        var empty = new RESTful_Output();
                        empty.statusCode = HttpStatusCode.NotFound;
                        return(empty);
                    }

                    if (request == null)
                    {
                        rpcParams.Add("LngIsoCode", parameters.ElementAt(Constants.C_DATA_PXAPIV1_SUBJECT_QUERY));

                        rpcParams.Add("matrix", parameters.ElementAt(Constants.C_DATA_PXAPIV1_METADATA_QUERY));

                        rpcParams.Add("format", JToken.FromObject(new { type = Constants.C_SYSTEM_JSON_STAT_NAME, version = Constants.C_SYSTEM_JSON_STAT_2X_VERSION }));

                        Matrix theMatrix;
                        using (Cube_BSO cBso = new Cube_BSO(new ADO("defaultConnection")))
                        {
                            theMatrix = cBso.GetMetadataMatrix(parameters.ElementAt(Constants.C_DATA_PXAPIV1_SUBJECT_QUERY), parameters.ElementAt(Constants.C_DATA_PXAPIV1_METADATA_QUERY));
                        }
                        var rspMeta = new RESTful_Output();    // JSONRPC_Output();

                        if (theMatrix != null)
                        {
                            var json = theMatrix.GetApiMetadata(parameters.ElementAt(Constants.C_DATA_PXAPIV1_SUBJECT_QUERY));

                            rpc.parameters = rpcParams;

                            rspMeta.response   = Utility.JsonSerialize_IgnoreLoopingReference(json);
                            rspMeta.statusCode = HttpStatusCode.OK;
                        }
                        else
                        {
                            rspMeta.statusCode = HttpStatusCode.NotFound;
                        }


                        return(rspMeta);
                    }
                    else
                    {
                        //This is a request for data - we need to use the query

                        //For conventional RESTful patterns, don't return metadata unless the requested MtrCode is contained in the collection
                        //for the subject and product parameters
                        List <dynamic> collectionPrdSbjdata = new List <dynamic>();
                        using (Cube_BSO cBso = new Cube_BSO(new ADO("defaultConnection")))
                        {
                            collectionPrdSbjdata = cBso.ReadCollection(parameters.ElementAt(Constants.C_DATA_PXAPIV1_SUBJECT_QUERY), parameters.ElementAt(Constants.C_DATA_PXAPIV1_PRODUCT_QUERY), parameters.ElementAt(Constants.C_DATA_PXAPIV1_COLLECTION_QUERY));
                        }

                        if (collectionPrdSbjmeta == null)
                        {
                            var empty = new RESTful_Output();
                            empty.statusCode = HttpStatusCode.NotFound;
                            return(empty);
                        }

                        if (collectionPrdSbjdata.Where(x => x.MtrCode == parameters.ElementAt(Constants.C_DATA_PXAPIV1_METADATA_QUERY)).ToList().Count == 0)
                        {
                            var empty = new RESTful_Output();
                            empty.statusCode = HttpStatusCode.NotFound;
                            return(empty);
                        }


                        string queryString = string.IsNullOrWhiteSpace(restfulRequest.httpPOST) ? restfulRequest.httpGET[Constants.C_JSON_STAT_QUERY_CLASS] : restfulRequest.httpPOST;

                        PxApiV1Query pxapiQuery = Utility.JsonDeserialize_IgnoreLoopingReference <PxApiV1Query>(queryString);


                        Format_DTO_Read format = new Format_DTO_Read(pxapiQuery.Response.Format);
                        string          pivot  = pxapiQuery.Response.Pivot;


                        JsonStatQuery jsQuery = new JsonStatQuery();
                        jsQuery.Class      = Constants.C_JSON_STAT_QUERY_CLASS;
                        jsQuery.Id         = new List <string>();
                        jsQuery.Dimensions = new Dictionary <string, JsonQuery.Dimension>();
                        foreach (var q in pxapiQuery.Query)
                        {
                            jsQuery.Id.Add(q.Code);
                            jsQuery.Dimensions.Add(q.Code, new JsonQuery.Dimension()
                            {
                                Category = new JsonQuery.Category()
                                {
                                    Index = q.Selection.Values.ToList <string>()
                                }
                            });
                        }
                        jsQuery.Extension = new Dictionary <string, object>();

                        jsQuery.Extension.Add("matrix", parameters.ElementAt(Constants.C_DATA_PXAPIV1_METADATA_QUERY));
                        jsQuery.Extension.Add("language", new Language()
                        {
                            Code = parameters.ElementAt(Constants.C_DATA_PXAPIV1_SUBJECT_QUERY), Culture = null
                        });
                        jsQuery.Extension.Add("codes", false);
                        jsQuery.Extension.Add("format", new JsonQuery.Format()
                        {
                            Type = format.FrmType, Version = format.FrmVersion
                        });
                        if (pivot != null)
                        {
                            jsQuery.Extension.Add("pivot", pivot);
                        }
                        jsQuery.Version = Constants.C_JSON_STAT_QUERY_VERSION;


                        JSONRPC_API jsonRpcRequest = Map.RESTful2JSONRPC_API(restfulRequest);

                        jsonRpcRequest.parameters = Utility.JsonSerialize_IgnoreLoopingReference(jsQuery);

                        //Run the request as a Json Rpc call
                        JSONRPC_Output rsp = new Cube_BSO_ReadDataset(jsonRpcRequest, true).Read().Response;

                        if (rsp.error != null)
                        {
                            return(Map.JSONRPC2RESTful_Output(rsp, null, HttpStatusCode.Forbidden));
                        }
                        // Convert the JsonRpc output to RESTful output
                        var response = Map.JSONRPC2RESTful_Output(rsp, format.FrmMimetype, HttpStatusCode.NotFound, HttpStatusCode.InternalServerError);

                        string suffix;
                        using (Format_BSO bso = new Format_BSO(new ADO("defaultConnection")))
                        {
                            suffix = bso.GetFileSuffixForFormat(format);
                        };


                        response.fileName = parameters.ElementAt(Constants.C_DATA_PXAPIV1_METADATA_QUERY) + "." + DateTime.Now.ToString("yyyyMMddHHmmss") + suffix;
                        return(response);
                    }
                }
            }
            catch (Exception ex)

            {
                RESTful_Output error = new RESTful_Output
                {
                    statusCode = HttpStatusCode.InternalServerError
                };

                Log.Instance.Debug(ex.Message);
                return(error);
            }
        }
Ejemplo n.º 8
0
        public static dynamic PxAPIv1(RESTful_API restfulRequest)
        {
            try
            {
                var         parameters = ((List <string>)restfulRequest.parameters).Where(x => !string.IsNullOrWhiteSpace(x));
                int         pcount     = parameters.Count() - 1;
                JSONRPC_API rpc        = Map.RESTful2JSONRPC_API(restfulRequest);

                Cube_MAP      map       = new Cube_MAP();
                JObject       rpcParams = new JObject();
                PxApiMetadata meta      = new PxApiMetadata();

                var context = HttpContext.Current.Request;

                switch (pcount)
                {
                case Constants.C_DATA_PXAPIV1_SUBJECT_QUERY:
                    //Get a list of all subjects

                    rpcParams.Add("LngIsoCode", parameters.ElementAt(Constants.C_DATA_PXAPIV1_SUBJECT_QUERY));
                    rpc.parameters = rpcParams;

                    var rspSbj = new Subject_BSO_Read(rpc).Read().Response;

                    if (rspSbj.data == null)
                    {
                        return new RESTful_Output()
                               {
                                   statusCode = HttpStatusCode.NotFound
                               }
                    }
                    ;

                    rspSbj.data = Utility.JsonSerialize_IgnoreLoopingReference(meta.ReadSubjectsAsObjectList(rspSbj));



                    var responseSbj = Map.JSONRPC2RESTful_Output(rspSbj, null, rspSbj.data == null ? HttpStatusCode.NotFound : HttpStatusCode.OK);

                    return(responseSbj);

                case Constants.C_DATA_PXAPIV1_PRODUCT_QUERY:
                    //Get a list of products for a subject
                    rpcParams.Add("LngIsoCode", parameters.ElementAt(Constants.C_DATA_PXAPIV1_SUBJECT_QUERY));

                    rpcParams.Add("SbjCode", parameters.ElementAt(Constants.C_DATA_PXAPIV1_PRODUCT_QUERY));
                    rpc.parameters = rpcParams;

                    var rspPrd = new Product_BSO_Read(rpc).Read().Response;

                    if (rspPrd.data == null)
                    {
                        return new RESTful_Output()
                               {
                                   statusCode = HttpStatusCode.NotFound
                               }
                    }
                    ;

                    meta = new PxApiMetadata();

                    if (rspPrd.data.Count == 0)
                    {
                        rspPrd = new JSONRPC_Output();

                        rspPrd.data = null;
                    }
                    else
                    {
                        rspPrd.data = Utility.JsonSerialize_IgnoreLoopingReference(meta.ReadProductsAsObjectList(rspPrd));
                    }

                    var responsePrd = Map.JSONRPC2RESTful_Output(rspPrd, null, rspPrd.data == null ? HttpStatusCode.NotFound : HttpStatusCode.OK);

                    return(responsePrd);

                case Constants.C_DATA_PXAPIV1_COLLECTION_QUERY:
                    //Get a list of live tables for a product
                    rpcParams.Add("LngIsoCode", parameters.ElementAt(Constants.C_DATA_PXAPIV1_SUBJECT_QUERY));

                    rpcParams.Add("product", parameters.ElementAt(Constants.C_DATA_PXAPIV1_COLLECTION_QUERY));
                    rpc.parameters = rpcParams;

                    List <dynamic> collection = new List <dynamic>();

                    RESTful_Output output = new RESTful_Output();
                    DateTime       nextReleaseDateForProduct = default;

                    using (Cube_BSO cBso = new Cube_BSO(new ADO("defaultConnection")))
                    {
                        nextReleaseDateForProduct = cBso.GetNextReleaseDate(parameters.ElementAt(Constants.C_DATA_PXAPIV1_COLLECTION_QUERY));
                    }

                    //See if this request has cached data
                    MemCachedD_Value cache = MemCacheD.Get_BSO <dynamic>("PxStat.Data", "Cube_API", "ReadCollectionPxApi", rpcParams);

                    if (cache.hasData && (nextReleaseDateForProduct == default || nextReleaseDateForProduct > DateTime.Now))
                    {
                        output.response   = cache.data;
                        output.statusCode = HttpStatusCode.OK;
                    }

                    else
                    {
                        using (Cube_BSO cBso = new Cube_BSO(new ADO("defaultConnection")))
                        {
                            collection = cBso.ReadCollection(parameters.ElementAt(Constants.C_DATA_PXAPIV1_SUBJECT_QUERY), parameters.ElementAt(Constants.C_DATA_PXAPIV1_COLLECTION_QUERY));
                        }

                        meta = new PxApiMetadata();

                        if (collection.Count > 0)
                        {
                            output.response = Utility.JsonSerialize_IgnoreLoopingReference(meta.ReadCollectionAsObjectList(new JSONRPC_Output()
                            {
                                data = collection
                            }));
                            output.statusCode = HttpStatusCode.OK;
                        }
                        else
                        {
                            output.statusCode = HttpStatusCode.NotFound;
                        }
                    }



                    MemCacheD.Store_BSO <dynamic>("PxStat.Data", "Cube_API", "ReadCollectionPxApi", rpcParams, output.response, nextReleaseDateForProduct, Constants.C_CAS_DATA_CUBE_READ_COLLECTION_PXAPI + parameters.ElementAt(Constants.C_DATA_PXAPIV1_COLLECTION_QUERY));

                    //MemCacheD.CasRepositoryFlush(Constants.C_CAS_DATA_CUBE_READ_COLLECTION_PXAPI + parameters.ElementAt(Constants.C_DATA_PXAPIV1_COLLECTION_QUERY));
                    return(output);

                case Constants.C_DATA_PXAPIV1_METADATA_QUERY:
                    //Either get the metadata for the table or, if a query has been supplied, get the table data based on the query
                    string request = string.IsNullOrWhiteSpace(Utility.HttpPOST()) ? Utility.HttpGET()["query"] : Utility.HttpPOST();

                    if (request == null)
                    {
                        rpcParams.Add("LngIsoCode", parameters.ElementAt(Constants.C_DATA_PXAPIV1_SUBJECT_QUERY));

                        rpcParams.Add("matrix", parameters.ElementAt(Constants.C_DATA_PXAPIV1_METADATA_QUERY));

                        rpcParams.Add("format", JToken.FromObject(new { type = "JSON-stat", version = "2.0" }));

                        Matrix theMatrix;
                        using (Cube_BSO cBso = new Cube_BSO(new ADO("defaultConnection")))
                        {
                            theMatrix = cBso.GetMetadataMatrix(parameters.ElementAt(Constants.C_DATA_PXAPIV1_SUBJECT_QUERY), parameters.ElementAt(Constants.C_DATA_PXAPIV1_METADATA_QUERY));
                        }
                        var rspMeta = new RESTful_Output();    // JSONRPC_Output();

                        if (theMatrix != null)
                        {
                            var json = theMatrix.GetApiMetadata(parameters.ElementAt(Constants.C_DATA_PXAPIV1_SUBJECT_QUERY));

                            rpc.parameters = rpcParams;

                            rspMeta.response   = Utility.JsonSerialize_IgnoreLoopingReference(json);
                            rspMeta.statusCode = HttpStatusCode.OK;
                        }
                        else
                        {
                            rspMeta.statusCode = HttpStatusCode.NotFound;
                        }


                        return(rspMeta);
                    }
                    else
                    {
                        //This is a request for data - we need to use the query



                        string queryString = string.IsNullOrWhiteSpace(Utility.HttpPOST()) ? Utility.HttpGET()["query"] : Utility.HttpPOST();

                        PxApiV1Query pxapiQuery = Utility.JsonDeserialize_IgnoreLoopingReference <PxApiV1Query>(queryString);

                        Format_DTO_Read format = new Format_DTO_Read(pxapiQuery.Response.Format);

                        Analytic_BSO_Create.Create(HttpContext.Current.Request, "PxStat.Data.PxAPIv1", HttpContext.Current.Request.UserAgent,
                                                   restfulRequest.ipAddress, parameters.ElementAt(Constants.C_DATA_PXAPIV1_METADATA_QUERY), false, format);

                        JsonStatQuery jsQuery = new JsonStatQuery();
                        jsQuery.Class      = "query";
                        jsQuery.Id         = new List <string>();
                        jsQuery.Dimensions = new Dictionary <string, JsonQuery.Dimension>();
                        foreach (var q in pxapiQuery.Query)
                        {
                            jsQuery.Id.Add(q.Code);
                            jsQuery.Dimensions.Add(q.Code, new JsonQuery.Dimension()
                            {
                                Category = new JsonQuery.Category()
                                {
                                    Index = q.Selection.Values.ToList <string>()
                                }
                            });
                        }
                        jsQuery.Extension = new Dictionary <string, object>();
                        jsQuery.Extension.Add("matrix", parameters.ElementAt(Constants.C_DATA_PXAPIV1_METADATA_QUERY));
                        jsQuery.Extension.Add("language", new Language()
                        {
                            Code = parameters.ElementAt(Constants.C_DATA_PXAPIV1_SUBJECT_QUERY)
                        });
                        jsQuery.Extension.Add("format", new JsonQuery.Format()
                        {
                            Type = format.FrmType, Version = format.FrmVersion
                        });
                        jsQuery.Version = Utility.GetCustomConfig("APP_JSON_STAT_QUERY_VERSION");

                        JSONRPC_API jsonRpcRequest = Map.RESTful2JSONRPC_API(restfulRequest);

                        jsonRpcRequest.parameters = Utility.JsonSerialize_IgnoreLoopingReference(jsQuery);
                        //Run the request as a Json Rpc call
                        JSONRPC_Output rsp = new Cube_BSO_ReadDataset(jsonRpcRequest).Read().Response;
                        // Convert the JsonRpc output to RESTful output
                        var response = Map.JSONRPC2RESTful_Output(rsp, format.FrmMimetype, rsp.data == null ? HttpStatusCode.NotFound : HttpStatusCode.OK);

                        string suffix;
                        using (Format_BSO bso = new Format_BSO(new ADO("defaultConnection")))
                        {
                            suffix = bso.GetFileSuffixForFormat(format);
                        };


                        response.fileName = parameters.ElementAt(Constants.C_DATA_PXAPIV1_METADATA_QUERY) + suffix;
                        return(response);
                    }


                default:
                    throw new Exception(Label.Get("error.validation"));
                }
            }
            catch (Exception ex)

            {
                RESTful_Output error = new RESTful_Output
                {
                    statusCode = HttpStatusCode.InternalServerError
                };

                Log.Instance.Error(ex.Message);
                return(error);
            }
        }