/// <summary> /// Execute /// </summary> /// <returns></returns> protected override bool Execute() { if (DTO.Format.FrmDirection != FormatDirection.DOWNLOAD.ToString()) { return(false); } ////See if this request has cached data MemCachedD_Value cache = MemCacheD.Get_BSO <dynamic>("PxStat.Data", "Cube_API", "ReadMetadata", DTO); if (cache.hasData) { Response.data = cache.data; return(true); } if (Throttle_BSO.IsThrottled(Ado, HttpContext.Current.Request, Request, SamAccountName)) { Log.Instance.Debug("Request throttled"); Response.error = Label.Get("error.throttled"); } var items = new Release_ADO(Ado).ReadLiveNow(DTO.matrix, DTO.language); var result = Release_ADO.GetReleaseDTO(items); if (result == null) { Response.data = null; return(true); } //The Language of the received data may be different from the request - so we make sure it corresponds to the language of the metadata DTO.language = items.LngIsoCode; return(ExecuteReadMetadata(Ado, DTO, result, Response)); }
/// <summary> /// Execute /// </summary> /// <returns></returns> protected override bool Execute() { DTO.CcnUsername = SamAccountName; if (!IsUserAuthenticated()) { return(true); } JSONRPC_Output response = new JSONRPC_Output(); //The cache key is created to be unique to a given CcnUsername. MemCachedD_Value cache = MemCacheD.Get_BSO <dynamic>("PxStat.Security", "Account_API", "ReadCurrentAccesss", DTO.CcnUsername); if (cache.hasData) { Response.data = cache.data; return(true); } Account_BSO bso = new Account_BSO(); ADO_readerOutput output = bso.ReadCurrentAccess(Ado, DTO.CcnUsername); if (!output.hasData) { Log.Instance.Debug("No Account data found"); return(false); } Response.data = output.data; return(true); }
/// <summary> /// Execute /// </summary> /// <returns></returns> protected override bool Execute() { //so that caches don't get mixed up.. DTO.meta = _meta; //See if this request has cached data MemCachedD_Value cache = MemCacheD.Get_BSO <dynamic>("PxStat.Data", "Cube_API", "ReadCollection", DTO); if (cache.hasData) { Response.data = cache.data; return(true); } if (Throttle_BSO.IsThrottled(Ado, HttpContext.Current.Request, Request, SamAccountName)) { Log.Instance.Debug("Request throttled"); Response.error = Label.Get("error.throttled"); } Cube_BSO cBso = new Cube_BSO(); // cache store is done in the following function Response.data = cBso.ExecuteReadCollection(Ado, DTO, _meta); return(true); }
/// <summary> /// Execute /// </summary> /// <returns></returns> protected override bool Execute() { //See if this request has cached data MemCachedD_Value cache = MemCacheD.Get_BSO <dynamic>("PxStat.Data", "Cube_API", "ReadCollection", DTO); Navigation_ADO adoNav = new Navigation_ADO(Ado); //If we're cacheing, we only want the cache to live until the next scheduled release goes live //Also, if there is a next release before the scheduled cache expiry time, then we won't trust the cache var nextRelease = adoNav.ReadNextLiveDate(DateTime.Now); DateTime nextReleaseDate = default; if (nextRelease.hasData) { if (!nextRelease.data[0].NextRelease.Equals(DBNull.Value)) { nextReleaseDate = Convert.ToDateTime(nextRelease.data[0].NextRelease); } } if (cache.hasData && nextReleaseDate >= cache.expiresAt) { Response.data = cache.data; return(true); } Cube_BSO cBso = new Cube_BSO(); // cache store is done in the following function Response.data = cBso.ExecuteReadCollection(Ado, DTO); return(true); }
/// <summary> /// Execute /// </summary> /// <returns></returns> protected override bool Execute() { if (DTO.Format.FrmDirection != FormatDirection.DOWNLOAD.ToString()) { return(false); } ////See if this request has cached data MemCachedD_Value cache = MemCacheD.Get_BSO <dynamic>("PxStat.Data", "Cube_API", "ReadPreMetadata", DTO); if (cache.hasData) { Response.data = cache.data; return(true); } var item = new Matrix_ADO(Ado).Read(DTO.release, DTO.language, SamAccountName); var result = Release_ADO.GetReleaseDTO(item); if (result == null) { Response.data = null; return(true); } DTO.language = item.LngIsoCode; return(Cube_BSO_ReadMetadata.ExecuteReadMetadata(Ado, DTO, result, Response, false)); }
/// <summary> /// Execute /// </summary> /// <returns></returns> protected override bool Execute() { Navigation_ADO adoNav = new Navigation_ADO(Ado); //If we're cacheing, we only want the cache to live until the next scheduled release goes live //Also, if there is a next release before the scheduled cache expiry time, then we won't trust the cache var nextRelease = adoNav.ReadNextLiveDate(DateTime.Now); DateTime nextReleaseDate = default; if (nextRelease.hasData) { if (!nextRelease.data[0].NextRelease.Equals(DBNull.Value)) { nextReleaseDate = Convert.ToDateTime(nextRelease.data[0].NextRelease); } } //Read the cached value for this if it's available but only if there isn't a next release before the cache expiry time MemCachedD_Value cache = MemCacheD.Get_BSO <dynamic>("PxStat.System.Navigation", "Navigation_API", "Read", DTO); if (cache.hasData && nextReleaseDate >= cache.expiresAt) { Response.data = cache.data; return(true); } //No cache available, so read from the database and cache that result ADO_readerOutput result = adoNav.Read(DTO); if (result.hasData) { List <dynamic> formattedOutput = formatOutput(result.data); if (nextRelease != null) { if (nextRelease.hasData) { if (!nextRelease.data[0].NextRelease.Equals(DBNull.Value)) { nextReleaseDate = Convert.ToDateTime(nextRelease.data[0].NextRelease); } } } Response.data = formattedOutput; MemCacheD.Store_BSO <dynamic>("PxStat.System.Navigation", "Navigation_API", "Read", DTO, Response.data, nextReleaseDate, Resources.Constants.C_CAS_NAVIGATION_READ); return(true); } return(false); }
/// <summary> /// Execute /// </summary> /// <returns></returns> protected override bool Execute() { Navigation_ADO adoNav = new Navigation_ADO(Ado); Navigation_BSO nBso = new Navigation_BSO(Ado, DTO); bool wordSearch = false; if (!String.IsNullOrEmpty(DTO.Search)) { DTO.SearchTerms = nBso.PrepareSearchData(); wordSearch = true; } //DTO.search has too much variation to use as a cache key - the search terms are formatted in the table so we don't need it any more DTO.Search = ""; MemCachedD_Value cache = MemCacheD.Get_BSO("PxStat.System.Navigation", "Navigation_API", "Search", DTO); // if (cache.hasData) { Response.data = cache.data; return(true); } if (wordSearch) { Response.data = nBso.RunWordSearch(); } else { Response.data = nBso.RunEntitySearch(); } DateTime minDateItem = default; Release_ADO rAdo = new Release_ADO(Ado); dynamic dateQuery = rAdo.ReadNextReleaseDate(); if (dateQuery != null) { minDateItem = dateQuery.RlsDatetimeNext.Equals(DBNull.Value) ? default(DateTime) : dateQuery.RlsDatetimeNext; } else { minDateItem = default; } MemCacheD.Store_BSO("PxStat.System.Navigation", "Navigation_API", "Search", DTO, Response.data, minDateItem, Resources.Constants.C_CAS_NAVIGATION_SEARCH); return(true); }
internal Static_Output Read(Static_API staticRequest) { Static_Output output = new Static_Output() { }; output.mimeType = "application/json"; ////See if this request has cached data MemCachedD_Value cache = MemCacheD.Get_BSO <dynamic>("PxStat.Data", "GeoMap_BSO_Read", "Read", staticRequest.parameters[1]); if (cache.hasData) { output.response = cache.data; output.statusCode = HttpStatusCode.OK; return(output); } using (GeoMap_BSO bso = new GeoMap_BSO(new ADO("defaultConnection"))) { try { var dataRead = bso.Read(staticRequest.parameters[1]); if (dataRead.hasData) { output.statusCode = HttpStatusCode.OK; GeoJson readGeoJson = JsonConvert.DeserializeObject <GeoJson>(dataRead.data[0].GmpGeoJson); MemCacheD.Store_BSO("PxStat.Data", "GeoMap_BSO_Read", "Read", staticRequest.parameters[1], readGeoJson, default(DateTime)); output.response = Utility.JsonSerialize_IgnoreLoopingReference(JsonConvert.DeserializeObject <GeoJson>(dataRead.data[0].GmpGeoJson)); } else { output.statusCode = HttpStatusCode.NotFound; } } catch (Exception ex) { Log.Instance.Error(ex.Message); Log.Instance.Error(ex.StackTrace); output.statusCode = HttpStatusCode.InternalServerError; } }; return(output); }
/// <summary> /// Execute /// </summary> /// <returns></returns> protected override bool Execute() { if (DTO.jStatQueryExtension.extension.Pivot != null) { if (DTO.jStatQueryExtension.extension.Format.Type != "CSV" && DTO.jStatQueryExtension.extension.Format.Type != "XLSX") { DTO.jStatQueryExtension.extension.Pivot = null; } } //if the role details haven't been supplied then look it up from the metadata in the database if (DTO.Role == null) { DTO.Role = new Cube_BSO().UpdateRoleFromMetadata(Ado, DTO); } //The Language of the received data may be different from the request - so we make sure it corresponds to the language of the dataset (???) var items = new Release_ADO(Ado).ReadLiveNow(DTO.jStatQueryExtension.extension.Matrix, DTO.jStatQueryExtension.extension.Language.Code); ////See if this request has cached data MemCachedD_Value cache = MemCacheD.Get_BSO <dynamic>("PxStat.Data", "Cube_API", "ReadDataset", DTO); if (cache.hasData) { Response.data = cache.data; return(true); } if (Throttle_BSO.IsThrottled(Ado, HttpContext.Current.Request, Request, SamAccountName)) { Log.Instance.Debug("Request throttled"); Response.error = Label.Get("error.throttled"); } var result = Release_ADO.GetReleaseDTO(items); if (result == null) { Response.data = null; return(true); } var data = ExecuteReadDataset(Ado, DTO, result, Response, DTO.jStatQueryExtension.extension.Language.Code, DTO.jStatQueryExtension.extension.Language.Culture, defaultPivot); return(data); }
/// <summary> /// Execute /// </summary> /// <returns></returns> protected override bool Execute() { //if the role details haven't been supplied then look it up from the metadata in the database if (DTO.Role == null) { DTO.Role = new Cube_BSO().UpdateRoleFromMetadata(Ado, DTO); } //The Language of the received data may be different from the request - so we make sure it corresponds to the language of the dataset (???) var items = new Release_ADO(Ado).ReadLiveNow(DTO.jStatQueryExtension.extension.Matrix, DTO.jStatQueryExtension.extension.Language.Code); /* string requestLanguage = DTO.language; * DTO.language = items.LngIsoCode; */ ////See if this request has cached data MemCachedD_Value cache = MemCacheD.Get_BSO <dynamic>("PxStat.Data", "Cube_API", "ReadDataset", DTO); if (cache.hasData) { Response.data = cache.data; return(true); } var result = Release_ADO.GetReleaseDTO(items); if (result == null) { Response.data = null; return(true); } var data = ExecuteReadDataset(Ado, DTO, result, Response, DTO.jStatQueryExtension.extension.Language.Code, DTO.jStatQueryExtension.extension.Language.Culture); return(data); }
/// <summary> /// Constructor /// </summary> /// <returns></returns> public BaseTemplate_Read <T, V> Read() { try { // first of all, we check if user has the right to perform this operation! if (HasUserToBeAuthenticated()) { if (!IsUserAuthenticated() || !HasUserPrivilege()) { return(this); } } //Run the parameters through the cleanse process dynamic cleansedParams = Cleanser.Cleanse(Request.parameters); try { DTO = GetDTO(cleansedParams); } catch { throw new InputFormatException(); } DTO = Sanitizer.Sanitize(DTO); DTOValidationResult = Validator.Validate(DTO); if (!DTOValidationResult.IsValid) { OnDTOValidationError(); return(this); } //Create the analytic data if required Security.Analytic_BSO_Create.Create(Ado, DTO, HttpContext.Current.Request, Request); //See if there's a cache in the process if (MethodReader.MethodHasAttribute(Request.method, "CacheRead")) { cDTO = new CacheMetadata("CacheRead", Request.method, DTO); MemCachedD_Value cache = MemCacheD.Get_BSO <dynamic>(cDTO.Namespace, cDTO.ApiName, cDTO.Method, DTO); if (cache.hasData) { Response.data = cache.data; return(this); } } // The Actual Read should happen here by the specific class! if (!Execute()) { OnExecutionError(); return(this); } OnExecutionSuccess(); return(this); } catch (UnmatchedParametersException unmatchException) { Log.Instance.Debug(unmatchException); OnDTOValidationError(); return(this); } catch (FormatException formatException) { //A FormatException error has been caught, log the error and return a message to the caller Log.Instance.Error(formatException); Response.error = Label.Get("error.schema"); return(this); } catch (Exception ex) { //An error has been caught, log the error and return a message to the caller Log.Instance.Error(ex); Response.error = Label.Get("error.exception"); return(this); } finally { Dispose(); } }
/// <summary> /// Constructor /// </summary> /// <returns></returns> public BaseTemplate_Read <T, V> Read() { try { // first of all, we check if user has the right to perform this operation! if (HasUserToBeAuthenticated()) { if (!IsUserAuthenticated() || !HasUserPrivilege()) { OnAuthenticationFailed(); return(this); } } //if we didn't attempt to authenticate and it's an external call then we still need to the the SamAccountName if (SamAccountName == null && Request.sessionCookie != null) { Log.Instance.Debug("Session cookie: " + Request.sessionCookie.Value); //Does the cookie correspond with a live token for a user? ADO_readerOutput user; using (Login_BSO lBso = new Login_BSO()) { user = lBso.ReadBySession(Request.sessionCookie.Value); if (user.hasData) { SamAccountName = user.data[0].CcnUsername; } } } //Run the parameters through the cleanse process dynamic cleansedParams; //If the API has the IndividualCleanseNoHtml attribute then parameters are cleansed individually //Any of these parameters whose corresponding DTO property contains the NoHtmlStrip attribute will not be cleansed of HTML tags if (Resources.MethodReader.MethodHasAttribute(Request.method, "IndividualCleanseNoHtml")) { dynamic dto = GetDTO(Request.parameters); cleansedParams = Cleanser.Cleanse(Request.parameters, dto); } else { cleansedParams = Cleanser.Cleanse(Request.parameters); } try { DTO = GetDTO(cleansedParams); } catch { throw new InputFormatException(); } DTO = Sanitizer.Sanitize(DTO); DTOValidationResult = Validator.Validate(DTO); if (!DTOValidationResult.IsValid) { OnDTOValidationError(); return(this); } ////Has the user hit a limit of how many queries are allowed? //if (Throttle_BSO.IsThrottled(Ado, HttpContext.Current.Request, Request, SamAccountName)) //{ // OnThrottle(); // return this; //} //Create the analytic data if required Security.Analytic_BSO_Create.Create(Ado, DTO, HttpContext.Current.Request, Request); //See if there's a cache in the process if (MethodReader.MethodHasAttribute(Request.method, "CacheRead")) { cDTO = new CacheMetadata("CacheRead", Request.method, DTO); MemCachedD_Value cache = MemCacheD.Get_BSO <dynamic>(cDTO.Namespace, cDTO.ApiName, cDTO.Method, DTO); if (cache.hasData) { Response.data = cache.data; return(this); } } // The Actual Read should happen here by the specific class! if (!Execute()) { OnExecutionError(); } else { OnExecutionSuccess(); } return(this); } catch (UnmatchedParametersException unmatchException) { Log.Instance.Debug(unmatchException); OnDTOValidationError(); return(this); } catch (FormatException formatException) { //A FormatException error has been caught, log the error and return a message to the caller Log.Instance.Error(formatException); Response.error = Label.Get("error.schema"); return(this); } catch (Exception ex) { //An error has been caught, log the error and return a message to the caller Log.Instance.Error(ex); Response.error = Label.Get("error.exception"); return(this); } finally { Dispose(); } }
/// <summary> /// Search method /// </summary> /// <param name="dto"></param> /// <returns></returns> internal dynamic Search(Navigation_DTO_Search dto) { //Get a keyword extractor. The keyword extractor should, if possible, correspond to the supplied LngIsoCode //If an extractor is not found for the supplied LngIsoCode then a basic default extractor is supplied. Keyword_BSO_Extract kbe = new Keyword_BSO_Extract(dto.LngIsoCode); // IKeywordExtractor extractor = kbe.GetExtractor(); //Get a list of keywords based on the supplied search term List <string> searchList = new List <string>(); List <string> searchListInvariant = new List <string>(); int searchTermCount = 0; if (dto.Search != null) { //Get a singularised version of each word searchList = kbe.ExtractSplitSingular(dto.Search); //We need a count of search terms (ignoring duplicates caused by singularisation) searchTermCount = searchList.Count; //Some words will not be searched for in their singular form (flagged on the table), so we need those as well searchListInvariant = kbe.ExtractSplit(dto.Search); //Eliminate duplicates from the list searchList = searchList.Union(searchListInvariant).ToList(); } //The list of keywords must be supplied to the search stored procedure //In order to do this, we pass a datatable as a parameter //First we create the table DataTable dt = new DataTable(); dt.Columns.Add("Key"); dt.Columns.Add("Value"); dt.Columns.Add("Attribute"); //Gather any synonyms and include them in the search, in the synonyms column foreach (string word in searchList) { var hitlist = kbe.extractor.SynonymList.Where(x => x.match == word.ToLower()); if ((kbe.extractor.SynonymList.Where(x => x.match == word.ToLower())).Count() > 0) { foreach (var syn in hitlist) { var row = dt.NewRow(); row["Key"] = syn.lemma; row["Value"] = syn.match; row["Attribute"] = Configuration_BSO.GetCustomConfig("search.synonym-multiplier"); dt.Rows.Add(row); } } else { var row = dt.NewRow(); row["Key"] = word; row["Value"] = word; row["Attribute"] = Configuration_BSO.GetCustomConfig("search.synonym-multiplier"); dt.Rows.Add(row); } //The main search term must be included along with the synonyms, i.e. a word is a synonym of itself //But with a higher search priority, which goes into the Attribute column var keyrow = dt.NewRow(); if (dt.Select("Key = '" + word + "'").Count() == 0) { keyrow["Key"] = word; keyrow["Value"] = word; keyrow["Attribute"] = Configuration_BSO.GetCustomConfig("search.search-word-multiplier"); dt.Rows.Add(keyrow); } } //Sort the search terms to ensure invariant word order in the search dt.DefaultView.Sort = "Key,Value asc"; dt = dt.DefaultView.ToTable(); //The ExecuteReaderProcedure method requires that the parameters be contained in a List<ADO_inputParams> List <ADO_inputParams> paramList = new List <ADO_inputParams>() { new ADO_inputParams() { name = "@LngIsoCode", value = dto.LngIsoCode } }; ADO_inputParams param = new ADO_inputParams() { name = "@Search", value = dt }; param.typeName = "KeyValueVarcharAttribute"; paramList.Add(param); //We need a count of search terms (ignoring duplicates caused by singularisation) paramList.Add(new ADO_inputParams() { name = "@SearchTermCount", value = searchTermCount }); if (dto.MtrCode != null) { paramList.Add(new ADO_inputParams() { name = "@MtrCode", value = dto.MtrCode }); } if (dto.MtrOfficialFlag != null) { paramList.Add(new ADO_inputParams() { name = "@MtrOfficialFlag", value = dto.MtrOfficialFlag }); } if (dto.SbjCode != default(int)) { paramList.Add(new ADO_inputParams() { name = "@SbjCode", value = dto.SbjCode }); } if (dto.PrcCode != null) { paramList.Add(new ADO_inputParams() { name = "@PrcCode", value = dto.PrcCode }); } if (dto.CprCode != null) { paramList.Add(new ADO_inputParams() { name = "@CprCode", value = dto.CprCode }); } if (dto.RlsExceptionalFlag != null) { paramList.Add(new ADO_inputParams() { name = "@RlsExceptionalFlag", value = dto.RlsExceptionalFlag }); } if (dto.RlsReservationFlag != null) { paramList.Add(new ADO_inputParams() { name = "@RlsReservationFlag", value = dto.RlsReservationFlag }); } if (dto.RlsArchiveFlag != null) { paramList.Add(new ADO_inputParams() { name = "@RlsArchiveFlag", value = dto.RlsArchiveFlag }); } if (dto.RlsAnalyticalFlag != null) { paramList.Add(new ADO_inputParams() { name = "@RlsAnalyticalFlag", value = dto.RlsAnalyticalFlag }); } //We store from the ADO because the search terms may have been changed by keyword rules MemCachedD_Value cache = MemCacheD.Get_ADO("PxStat.System.Navigation", "System_Navigation_Search", paramList); // if (cache.hasData) { return(cache.data.ToObject <List <dynamic> >()); } //Call the stored procedure ADO_readerOutput output = ado.ExecuteReaderProcedure("System_Navigation_Search", paramList); MemCacheD.Store_ADO <dynamic>("PxStat.System.Navigation", "System_Navigation_Search", paramList, output.data, new DateTime(), Resources.Constants.C_CAS_NAVIGATION_SEARCH); //return the list of entities that have been found return(output.data); }
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); } }
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); } }