예제 #1
0
        /**<summary>If txid is in the mempool, returns all in-mempool ancestors.</summary>**/
        ///<param name="txid">The transaction id (must be in mempool).</param>
        ///<param name="returnFormat">"Json" or "Array of transaction ids".</param>
        public async Task <string> GetMemPoolAncestors(string txid, ReturnFormat returnFormat = ReturnFormat.JSON)
        {
            GetMemPool memPoolAncestors = new GetMemPool {
                ReturnFormat = returnFormat, Txid = txid
            };

            string response = await httpRequest.SendReq(MethodName.getmempoolancestors, memPoolAncestors);

            return(response);
        }
예제 #2
0
        public void FileAsUncPath(string file, ReturnFormat format)
        {
            SimpleUriHandler handler = new SimpleUriHandler();
            string           uri     = $@"\\{Environment.MachineName}\" + Path.Combine(Environment.CurrentDirectory, file).ToLower().Replace("c:", "c$");

            SimpleUriHandlerParameters parms = new SimpleUriHandlerParameters()
            {
                Uri = uri, Format = format
            };
            string result = handler.GetFileUri(parms.ParsedUri.ToString());

            object o = handler.FormatData(result, parms.Format);
        }
예제 #3
0
        public void FileAsUriPath(string file, ReturnFormat format)
        {
            SimpleUriHandler handler = new SimpleUriHandler();
            string           uri     = $"file://" + Path.Combine(Environment.CurrentDirectory, file);

            SimpleUriHandlerParameters parms = new SimpleUriHandlerParameters()
            {
                Uri = uri, Format = format
            };
            string result = handler.GetFileUri(parms.ParsedUri.ToString());

            object o = handler.FormatData(result, parms.Format);
        }
예제 #4
0
파일: Bound.cs 프로젝트: macartur/INACITY
 public string ToString(ReturnFormat format)
 {
     if (format.Equals(ReturnFormat.ClockwiseSouth))
     {
         return(South.ToString(true) + ", " +
                West.ToString(true) + ", " +
                North.ToString(true) + ", " +
                East.ToString(true));
     }
     else
     {
         throw new Exception("ReturnFormat not recognized. Try ReturnFormat.ClockwiseSouth.");
     }
 }
예제 #5
0
 /// <summary>
 /// You can retrieve metadata for a specified time-series database.
 /// <a href="https://docs.quandl.com/docs/in-depth-usage#section-get-metadata-for-a-time-series-database">Reference</a>
 /// </summary>
 /// <param name="databaseCode">Code identifying the database to which the dataset belongs.</param>
 /// <param name="returnFormat">Return format</param>
 /// <param name="token">Cancellation token</param>
 /// <returns>Metadata for a specified time-series database</returns>
 public async Task <Stream> GetDatabaseMetadataAsync(string databaseCode, ReturnFormat returnFormat, CancellationToken token = default(CancellationToken))
 {
     try
     {
         return(await $"{Constant.HostUri}/databases/{databaseCode}.{returnFormat.ToEnumMemberValue()}"
                .SetQueryParam("api_key", _apiKey)
                .GetAsync(token)
                .ReceiveStream()
                .ConfigureAwait(false));
     }
     catch (FlurlHttpException ex)
     {
         throw ex.ToQuandlException();
     }
 }
예제 #6
0
        public static string GetReturnFormat(ReturnFormat returnFormat)
        {
            switch (returnFormat)
            {
            case ReturnFormat.JSON:
                return("json");

            case ReturnFormat.XML:
                return("xml");

            case ReturnFormat.CSV:
                return("csv");

            default:
                return(string.Empty);
            }
        }
        /// <summary>
        /// 测试返回通用格式total/data
        /// </summary>
        /// <returns></returns>
        public HttpResponseMessage TestReturnFormat()
        {
            List <userInfo>         users        = IniUsers();
            ReturnFormat <userInfo> returnFormat = new ReturnFormat <userInfo>
            {
                data = users
            };

            ReturnFormat <userInfo> returnFormat2 = new ReturnFormat <userInfo>();

            returnFormat2.data = users;

            string json = JsonConvert.SerializeObject(returnFormat);

            ReturnFormat <userInfo> users2 = JsonConvert.DeserializeObject <ReturnFormat <userInfo> >(json);

            return(ConvertToHttpResponseMessage(returnFormat));
        }
예제 #8
0
    public void MergeData(ref object data, object merge, ReturnFormat format)
    {
        switch (format)
        {
        case ReturnFormat.Yaml:
        case ReturnFormat.Json:
        {
            Dictionary <object, object> exitData = data as Dictionary <object, object>;
            YamlHelpers.Merge(ref exitData, merge as Dictionary <object, object>);

            data = exitData;
            break;
        }

        case ReturnFormat.Xml:
        {
            XmlDocument exitData = data as XmlDocument;

            if (merge is XmlNode[] && ((XmlNode[])merge).Length > 0)
            {
                foreach (XmlNode node in (XmlNode[])merge)
                {
                    XmlDocument mergeDoc = new XmlDocument();
                    mergeDoc.LoadXml($@"<root>{node.OuterXml}</root>");
                    XmlHelpers.Merge(ref exitData, mergeDoc);
                }
            }
            else
            {
                XmlHelpers.Merge(ref exitData, merge as XmlDocument);
            }

            data = exitData;
            break;
        }
            //default:
            //{
            //    return data;
            //}
        }
    }
        /*-------------------------------------------------------------------------------------------------------
         * // ** MergeDocument **
         * // This method implements the "v1/document/merge" Web API call
         * //
         * // Parameters:
         * //  - MergeBody MergeBody
         * //  - string TemplateName (default = null)
         * //  - ReturnFormat ReturnFormat (default = PDF)
         * //  - bool Append (default = true)
         * //
         * // Return value: A List of byte[]
         *-----------------------------------------------------------------------------------------------------*/
        /// <summary>
        /// This method merges a template with data.
        /// </summary>
        /// <param name="mergeBody">The MergeBody object contains the data, optionally a template and merge settings.</param>
        /// <param name="templateName">The name of the template in the template storage.</param>
        /// <param name="returnFormat">The document format of the resulting document.</param>
        /// <param name="append">Specifies whether the resulting documents should be appended or not.</param>
        /// <param name="test">Specifies whether it is a test run or not. A test run is not counted against the quota and created documents contain a watermark.</param>
        public List <byte[]> MergeDocument(MergeBody mergeBody,
                                           string templateName       = null,
                                           ReturnFormat returnFormat = ReturnFormat.PDF,
                                           bool append = true,
                                           bool test   = false)
        {
            // create a new HttpClient using the Factory method CreateHttpClient
            using (HttpClient client = CreateHttpClient())
            {
                var sMergeBody = JsonConvert.SerializeObject(mergeBody, new JsonSerializerSettings
                {
                    ContractResolver = new CamelCasePropertyNamesContractResolver(),
                });

                // set the endpoint and pass the query paramaters
                // MergeBody is posted as a JSON object
                HttpResponseMessage response = client.PostAsync("v1/document/merge?templateName=" + templateName +
                                                                "&returnFormat=" + returnFormat.ToString() +
                                                                "&append=" + append.ToString() + "&test=" + test.ToString(),
                                                                new StringContent(sMergeBody, Encoding.UTF8, "application/json")).Result;

                // if sucessful, return the image list
                if (response.IsSuccessStatusCode)
                {
                    List <byte[]> bResults = new List <byte[]>();

                    foreach (string sResult in (List <string>)JsonConvert.DeserializeObject(response.Content.ReadAsStringAsync().Result, typeof(List <string>)))
                    {
                        bResults.Add(Convert.FromBase64String(sResult));
                    }

                    return(bResults);
                    //return response.Content.ReadAsAsync<List<string>>().Result;
                }
                else
                {
                    // throw exception with the message from the endpoint
                    throw new ArgumentException(response.Content.ReadAsStringAsync().Result);
                }
            }
        }
예제 #10
0
 /// <summary>
 /// You can filter on both rows and columns by appending both filter types to your API request.
 /// <a href="https://docs.quandl.com/docs/in-depth-usage-1#section-filter-rows-and-columns">Reference</a>
 /// </summary>
 /// <param name="datatableCode">Short code for datatable</param>
 /// <param name="returnFormat">Return format</param>
 /// <param name="rowFilterCriteria">Criteria to filter row, value is ampersand-seperated.</param>
 /// <param name="columnFilterCriteria">Criteria to filter column, value is comma-seperated.</param>
 /// <param name="export">Good for large queries; the data requested will be packaged into a zip file for download.</param>
 /// <param name="perPage">The number of results per page that can be returned, to a maximum of 10,000 rows. (Large tables will be displayed over several pages.)</param>
 /// <param name="cursorId">Each API call returns a unique cursor ID that identifies the next page of the table. Including the cursor ID in your API call will allow you to page through the table. A null cursor ID means that the current page will be the last page of the table. For more on downloading entire tables, click here.</param>
 /// <param name="token">Cancellation token</param>
 /// <returns>Filtered table</returns>
 public async Task <Stream> GetAsync(string datatableCode, ReturnFormat returnFormat, string rowFilterCriteria = null, string columnFilterCriteria = null,
                                     bool?export = null, int?perPage = null, int?cursorId = null, CancellationToken token = default(CancellationToken))
 {
     try
     {
         return(await $"{Constant.HostUri}/datatables/{datatableCode}.{returnFormat.ToEnumMemberValue()}"
                .SetQueryParamForEach(Filter.Parse(rowFilterCriteria))
                .SetQueryParam("qopts.columns", columnFilterCriteria)
                .SetQueryParam("qopts.export", export)
                .SetQueryParam("qopts.per_page", perPage)
                .SetQueryParam("qopts.cursor_id", cursorId)
                .SetQueryParam("api_key", _apiKey)
                .GetAsync(token)
                .ReceiveStream()
                .ConfigureAwait(false));
     }
     catch (FlurlHttpException ex)
     {
         throw ex.ToQuandlException();
     }
 }
        /*-------------------------------------------------------------------------------------------------------
         * // ** ConvertDocument **
         * // This method implements the "v1/document/convert" Web API call
         * //
         * // Parameters:
         * //  - ReturnFormat ReturnFormat
         * //  - string Template
         * //
         * // Return value: void
         *-----------------------------------------------------------------------------------------------------*/
        /// <summary>
        /// This method converts a document to another format.
        /// </summary>
        /// <param name="document">The source document data as a byte array.</param>
        /// <param name="returnFormat">The document format of the resulting document.</param>
        /// <param name="test">Specifies whether it is a test run or not. A test run is not counted against the quota and created documents contain a watermark.</param>
        public byte[] ConvertDocument(byte[] document, ReturnFormat returnFormat, bool test = false)
        {
            // create a new HttpClient using the Factory method CreateHttpClient
            using (HttpClient client = CreateHttpClient())
            {
                // set the endpoint and pass the query paramaters
                // Template is posted as a JSON object
                HttpResponseMessage response = client.PostAsync("v1/document/convert?returnFormat=" + returnFormat + "&test=" + test.ToString(),
                                                                new StringContent(JsonConvert.SerializeObject(document), Encoding.UTF8, "application/json")).Result;

                // if sucessful, return the document list
                if (response.IsSuccessStatusCode)
                {
                    return(Convert.FromBase64String((string)JsonConvert.DeserializeObject(response.Content.ReadAsStringAsync().Result, typeof(string))));
                }
                else
                {
                    // throw exception with the message from the endpoint
                    throw new ArgumentException(response.Content.ReadAsStringAsync().Result);
                }
            }
        }
        /*-------------------------------------------------------------------------------------------------------
         * // ** ConvertDocument **
         * // This method implements the "v1/document/convert" Web API call
         * //
         * // Parameters:
         * //  - ReturnFormat ReturnFormat
         * //  - string Template
         * //
         * // Return value: void
         *-----------------------------------------------------------------------------------------------------*/
        /// <summary>
        /// This method converts a document to another format.
        /// </summary>
        /// <param name="document">The source document data as a byte array.</param>
        /// <param name="returnFormat">The document format of the resulting document.</param>
        /// <param name="test">Specifies whether it is a test run or not. A test run is not counted against the quota and created documents contain a watermark.</param>
        public byte[] ConvertDocument(byte[] document, ReturnFormat returnFormat, bool test = false)
        {
            // create a new HttpClient using the Factory method CreateHttpClient
            using (HttpClient client = CreateHttpClient())
            {
                // set the endpoint and pass the query paramaters
                // Template is posted as a JSON object
                HttpResponseMessage response = client.PostAsync("v1/document/convert?returnFormat=" + returnFormat + "&test=" + test.ToString(),
                                                                Convert.ToBase64String(document), formatter).Result;

                // if sucessful, return the document list
                if (response.IsSuccessStatusCode)
                {
                    return(Convert.FromBase64String(response.Content.ReadAsAsync <string>().Result));
                }
                else
                {
                    // throw exception with the message from the endpoint
                    throw new ArgumentException(response.Content.ReadAsStringAsync().Result);
                }
            }
        }
예제 #13
0
        public virtual Task <HttpContent> GetMetadataAsync(string database_code, ReturnFormat return_format, string api_key, CancellationToken token)
        {
            var arguments = new object[] { database_code, return_format, api_key, token };

            return((Task <HttpContent>)methodImpls["GetMetadataAsync"](Client, arguments));
        }
예제 #14
0
 public async Task <string> ExportMetaDataAsync(string token, Content content = Content.MetaData, ReturnFormat format = ReturnFormat.json, string[] fields = null, string[] forms = null, OnErrorFormat onErrorFormat = OnErrorFormat.json)
 {
     try
     {
         /*
          * Check for presence of token
          */
         this.CheckToken(token);
         var payload = new Dictionary <string, string>
         {
             { "token", token },
             { "content", content.GetDisplayName() },
             { "format", format.GetDisplayName() },
             { "returnFormat", onErrorFormat.GetDisplayName() }
         };
         // Optional
         if (fields?.Length > 0)
         {
             for (var i = 0; i < fields.Length; i++)
             {
                 payload.Add($"fields[{i}]", fields[i].ToString());
             }
         }
         if (forms?.Length > 0)
         {
             for (var i = 0; i < forms.Length; i++)
             {
                 payload.Add($"forms[{i}]", forms[i].ToString());
             }
         }
         return(await this.SendPostRequestAsync(payload, _uri));
     }
     catch (Exception Ex)
     {
         /*
          * We'll just log the error and return the error message.
          */
         Log.Error($"{Ex.Message}");
         return(Ex.Message);
     }
 }
예제 #15
0
 /// <summary>
 /// API Version 1.0.0+
 /// Export Instruments (Data Entry Forms)
 /// This method allows you to export a list of the data collection instruments for a project.
 /// This includes their unique instrument name as seen in the second column of the Data Dictionary, as well as each instrument's corresponding instrument label, which is seen on a project's left-hand menu when entering data. The instruments will be ordered according to their order in the project.
 /// </summary>
 /// <remarks>
 /// To use this method, you must have API Export privileges in the project.
 /// </remarks>
 /// <param name="token">The API token specific to your REDCap project and username (each token is unique to each user for each project). See the section on the left-hand menu for obtaining a token for a given project.</param>
 /// <param name="content">instrument</param>
 /// <param name="format">csv, json [default], xml</param>
 /// <returns>Instruments for the project in the format specified and will be ordered according to their order in the project.</returns>
 public async Task <string> ExportInstrumentsAsync(string token, Content content = Content.Instrument, ReturnFormat format = ReturnFormat.json)
 {
     try
     {
         /*
          * Check for presence of token
          */
         this.CheckToken(token);
         var payload = new Dictionary <string, string>
         {
             { "token", token },
             { "content", content.GetDisplayName() },
             { "format", format.GetDisplayName() }
         };
         // Execute request
         return(await this.SendPostRequestAsync(payload, _uri));
     }
     catch (Exception Ex)
     {
         /*
          * We'll just log the error and return the error message.
          */
         Log.Error($"{Ex.Message}");
         return(Ex.Message);
     }
 }
예제 #16
0
        /// <summary>
        /// API Version 1.0.0++
        /// Export Record
        /// This method allows you to export a single record for a project.
        /// Note about export rights: Please be aware that Data Export user rights will be applied to this API request.For example, if you have 'No Access' data export rights in the project, then the API data export will fail and return an error. And if you have 'De-Identified' or 'Remove all tagged Identifier fields' data export rights, then some data fields *might* be removed and filtered out of the data set returned from the API. To make sure that no data is unnecessarily filtered out of your API request, you should have 'Full Data Set' export rights in the project.
        /// </summary>
        /// <remarks>
        /// To use this method, you must have API Export privileges in the project.
        /// </remarks>
        /// <param name="token">The API token specific to your REDCap project and username (each token is unique to each user for each project). See the section on the left-hand menu for obtaining a token for a given project.</param>
        /// <param name="content">record</param>
        /// <param name="format">csv, json [default], xml, odm ('odm' refers to CDISC ODM XML format, specifically ODM version 1.3.1)</param>
        /// <param name="redcapDataType">flat - output as one record per row [default], eav - output as one data point per row. Non-longitudinal: Will have the fields - record*, field_name, value. Longitudinal: Will have the fields - record*, field_name, value, redcap_event_name</param>
        /// <param name="record">a single record specifying specific records you wish to pull (by default, all records are pulled)</param>
        /// <param name="fields">an array of field names specifying specific fields you wish to pull (by default, all fields are pulled)</param>
        /// <param name="forms">an array of form names you wish to pull records for. If the form name has a space in it, replace the space with an underscore (by default, all records are pulled)</param>
        /// <param name="events">an array of unique event names that you wish to pull records for - only for longitudinal projects</param>
        /// <param name="rawOrLabel">raw [default], label - export the raw coded values or labels for the options of multiple choice fields</param>
        /// <param name="rawOrLabelHeaders">raw [default], label - (for 'csv' format 'flat' type only) for the CSV headers, export the variable/field names (raw) or the field labels (label)</param>
        /// <param name="exportCheckboxLabel">true, false [default] - specifies the format of checkbox field values specifically when exporting the data as labels (i.e., when rawOrLabel=label) in flat format (i.e., when type=flat). When exporting labels, by default (without providing the exportCheckboxLabel flag or if exportCheckboxLabel=false), all checkboxes will either have a value 'Checked' if they are checked or 'Unchecked' if not checked. But if exportCheckboxLabel is set to true, it will instead export the checkbox value as the checkbox option's label (e.g., 'Choice 1') if checked or it will be blank/empty (no value) if not checked. If rawOrLabel=false or if type=eav, then the exportCheckboxLabel flag is ignored. (The exportCheckboxLabel parameter is ignored for type=eav because 'eav' type always exports checkboxes differently anyway, in which checkboxes are exported with their true variable name (whereas the 'flat' type exports them as variable___code format), and another difference is that 'eav' type *always* exports checkbox values as the choice label for labels export, or as 0 or 1 (if unchecked or checked, respectively) for raw export.)</param>
        /// <param name="onErrorFormat">csv, json, xml - specifies the format of error messages. If you do not pass in this flag, it will select the default format for you passed based on the 'format' flag you passed in or if no format flag was passed in, it will default to 'json'.</param>
        /// <param name="exportSurveyFields">true, false [default] - specifies whether or not to export the survey identifier field (e.g., 'redcap_survey_identifier') or survey timestamp fields (e.g., instrument+'_timestamp') when surveys are utilized in the project. If you do not pass in this flag, it will default to 'false'. If set to 'true', it will return the redcap_survey_identifier field and also the survey timestamp field for a particular survey when at least one field from that survey is being exported. NOTE: If the survey identifier field or survey timestamp fields are imported via API data import, they will simply be ignored since they are not real fields in the project but rather are pseudo-fields.</param>
        /// <param name="exportDataAccessGroups">true, false [default] - specifies whether or not to export the 'redcap_data_access_group' field when data access groups are utilized in the project. If you do not pass in this flag, it will default to 'false'. NOTE: This flag is only viable if the user whose token is being used to make the API request is *not* in a data access group. If the user is in a group, then this flag will revert to its default value.</param>
        /// <param name="filterLogic">String of logic text (e.g., [age] > 30) for filtering the data to be returned by this API method, in which the API will only return the records (or record-events, if a longitudinal project) where the logic evaluates as TRUE. This parameter is blank/null by default unless a value is supplied. Please note that if the filter logic contains any incorrect syntax, the API will respond with an error message. </param>
        /// <returns>Data from the project in the format and type specified ordered by the record (primary key of project) and then by event id</returns>
        public async Task <string> ExportRecordAsync(string token, Content content, string record, ReturnFormat format = ReturnFormat.json, RedcapDataType redcapDataType = RedcapDataType.flat, string[] fields = null, string[] forms = null, string[] events = null, RawOrLabel rawOrLabel = RawOrLabel.raw, RawOrLabelHeaders rawOrLabelHeaders = RawOrLabelHeaders.raw, bool exportCheckboxLabel = false, OnErrorFormat onErrorFormat = OnErrorFormat.json, bool exportSurveyFields = false, bool exportDataAccessGroups = false, string filterLogic = null)
        {
            try
            {
                this.CheckToken(token);

                var payload = new Dictionary <string, string>
                {
                    { "token", token },
                    { "records", record },
                    { "content", content.GetDisplayName() },
                    { "format", format.GetDisplayName() },
                    { "returnFormat", onErrorFormat.GetDisplayName() },
                    { "type", redcapDataType.GetDisplayName() }
                };

                // Optional
                if (fields?.Length > 0)
                {
                    payload.Add("fields", await this.ConvertArraytoString(fields));
                }
                if (forms?.Length > 0)
                {
                    payload.Add("forms", await this.ConvertArraytoString(forms));
                }
                if (events?.Length > 0)
                {
                    payload.Add("events", await this.ConvertArraytoString(events));
                }

                /*
                 * Pertains to CSV data only
                 */
                var _rawOrLabelValue = rawOrLabelHeaders.ToString();
                if (!IsNullOrEmpty(_rawOrLabelValue))
                {
                    payload.Add("rawOrLabel", _rawOrLabelValue);
                }
                // Optional (defaults to false)
                if (exportCheckboxLabel)
                {
                    payload.Add("exportCheckboxLabel", exportCheckboxLabel.ToString());
                }
                // Optional (defaults to false)
                if (exportSurveyFields)
                {
                    payload.Add("exportSurveyFields", exportSurveyFields.ToString());
                }
                // Optional (defaults to false)
                if (exportDataAccessGroups)
                {
                    payload.Add("exportDataAccessGroups", exportDataAccessGroups.ToString());
                }
                if (!IsNullOrEmpty(filterLogic))
                {
                    payload.Add("filterLogic", filterLogic);
                }
                return(await this.SendPostRequestAsync(payload, _uri));
            }
            catch (Exception Ex)
            {
                /*
                 * We'll just log the error and return the error message.
                 */
                Log.Error($"{Ex.Message}");
                return(Ex.Message);
            }
        }
예제 #17
0
 /// <summary>
 /// You can slice, transform and otherwise customize your time-series dataset prior to download by appending various optional parameters to your query.
 /// <a href="https://docs.quandl.com/docs/in-depth-usage#section-get-filtered-time-series-data">Reference</a>
 /// </summary>
 /// <param name="databaseCode">Code identifying the database to which the dataset belongs.</param>
 /// <param name="datasetCode">Code identifying the dataset.</param>
 /// <param name="returnFormat">Return format</param>
 /// <param name="limit">Use limit=n to get the first n rows of the dataset. Use limit=1 to get just the latest row.</param>
 /// <param name="columnIndex">Request a specific column. Column 0 is the date column and is always returned. Data begins at column 1.</param>
 /// <param name="startDate">Retrieve data rows on and after the specified start date.</param>
 /// <param name="endDate">Retrieve data rows up to and including the specified end date.</param>
 /// <param name="order">Return data in ascending or descending order of date. Default is desc.</param>
 /// <param name="collapse">Change the sampling frequency of the returned data. Default is none; i.e., data is returned in its original granularity.</param>
 /// <param name="transform">Perform elementary calculations on the data prior to downloading. Default is none. Calculation options are described below.</param>
 /// <param name="token">Cancellation token</param>
 /// <returns>Data from a specified time-series</returns>
 public async Task <Stream> GetDataAsync(string databaseCode, string datasetCode, ReturnFormat returnFormat, int?limit = null, int?columnIndex = null,
                                         DateTime?startDate = null, DateTime?endDate = null, Order?order = null, Collapse?collapse = null, Transform?transform = null, CancellationToken token = default(CancellationToken))
 {
     try
     {
         return(await $"{Constant.HostUri}/datasets/{databaseCode}/{datasetCode}/data.{returnFormat.ToEnumMemberValue()}"
                .SetQueryParam("limit", limit)
                .SetQueryParam("column_index", columnIndex)
                .SetQueryParam("start_date", startDate?.ToString("yyyy-MM-dd"))
                .SetQueryParam("end_date", endDate?.ToString("yyyy-MM-dd"))
                .SetQueryParam("order", order.ToEnumMemberValue())
                .SetQueryParam("collapse", collapse.ToEnumMemberValue())
                .SetQueryParam("transform", transform.ToEnumMemberValue())
                .SetQueryParam("api_key", _apiKey)
                .GetAsync(token)
                .ReceiveStream()
                .ConfigureAwait(false));
     }
     catch (FlurlHttpException ex)
     {
         throw ex.ToQuandlException();
     }
 }
예제 #18
0
 public static async Task <Models.RestResponse> invoke(object content, string url, RestMethod rest_method = RestMethod.Get, bool request_as_query = false, bool is_anonymous = false, ReturnFormat return_format = ReturnFormat.Json, bool should_serialize = true)
 {
     try
     {
         Dictionary <RestParamType, object> request_content = new Dictionary <RestParamType, object>();
         RestParamType request_method = RestParamType.RequestBody;
         if (request_as_query)
         {
             request_method = RestParamType.QueryString;
         }
         request_content.Add(request_method, content);
         return(invoke(request_content, url, rest_method, is_anonymous, return_format, should_serialize).Result);
     }
     catch (Exception ex)
     {
         throw ex;
     }
 }
예제 #19
0
        public static async Task <Models.RestResponse> invoke(Dictionary <RestParamType, object> content, string url, RestMethod rest_method = RestMethod.Get, bool is_anonymous = false, ReturnFormat return_format = ReturnFormat.Json, bool should_serialize = true)
        {
            //var _url = _getBaseUrl(url);

            //INVOKE
            //var client = new RestClient(_url.base_url);
            var client = new RestClient();

            Models.RestResponse _result = new Models.RestResponse();

            Method _method = Method.GET;

            switch (rest_method)
            {
            case RestMethod.Delete:
                _method = Method.DELETE;
                break;

            case RestMethod.Put:
                _method = Method.PUT;
                break;

            case RestMethod.Post:
                _method = Method.POST;
                break;
            }
            //var _request = new RestRequest(_url.method_url, _method); //Each request can have only one method.
            var _request = new RestRequest(url, _method); //Each request can have only one method.

            //ADD HEADERS
            _request.AddHeader("Content-Type", @"application/json; charset=utf-8");
            if (!is_anonymous) //Need authorization to proceed. If authorization is not available, throw error
            {
                if (string.IsNullOrEmpty(jwt))
                {
                    throw new ArgumentException("Authorization String not found");                            //Remember you need to have a jwt value in session for processing.
                }
                string _jwt = token_prefix ?? "";
                _jwt = _jwt + " " + jwt;
                _request.AddHeader("Authorization", _jwt); //If token prefix is null, then send in nothing.
            }

            if (content == null)
            {
                throw new ArgumentNullException("Content cannot be empty");                  //If we don't have anything to post, just move on
            }
            RestParamType request_type = RestParamType.QueryString;

            foreach (var item in content)
            {
                request_type = rest_method == RestMethod.Get ? RestParamType.QueryString : item.Key; //For a Get method, it should only be sent as query because get methods cannot have a body.
                _fillRequestParameters(item.Value, _request, request_type, should_serialize);        //Sometimes, we just send in a dicitionary. sometimes we send in a object.
            }

            DataFormat _rest_return_format = DataFormat.Json;

            switch (return_format)
            {
            case ReturnFormat.Json:
                _rest_return_format = DataFormat.Json;
                break;

            case ReturnFormat.XML:
                _rest_return_format = DataFormat.Xml;
                break;

            case ReturnFormat.None:
                //_rest_return_format = DataFormat.None;
                break;
            }
            _request.RequestFormat = _rest_return_format;
            try
            {
                //Below lines are required because sometimes it results in error during async methods.
                ServicePointManager.Expect100Continue = true;
                ServicePointManager.SecurityProtocol  = SecurityProtocolType.Tls12;
                //var _response = await client.ExecuteAsync(_request);
                var _response = client.Execute(_request);
                _result.content          = _response.Content;
                _result.server_url       = _response.Server;
                _result.is_success       = _response.IsSuccessful;
                _result.status_code      = _response.StatusCode;
                _result.contents_raw     = _response.RawBytes;
                _result.content_encoding = _response.ContentEncoding;
                _result.content_length   = _response.ContentLength;
                _result.error_message    = _response.ErrorMessage;
                _result.exception        = _response.ErrorException;
                _result.response_uri     = _response.ResponseUri;
                return(_result);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
예제 #20
0
        public virtual Task <HttpContent> GetDataAndMetadataAsync(string database_code, string dataset_code, ReturnFormat return_format, int?limit, int?column_index, DateTime?start_date, DateTime?end_date, Order?order, Collapse?collapse, Transform?transform, string api_key, CancellationToken token)
        {
            var arguments = new object[] { database_code, dataset_code, return_format, limit, column_index, start_date, end_date, order, collapse, transform, api_key, token };

            return((Task <HttpContent>)methodImpls["GetDataAndMetadataAsync"](Client, arguments));
        }
예제 #21
0
        public virtual Task <HttpContent> GetListAsync(ReturnFormat return_format, string query, int?per_page, int?page, string api_key, CancellationToken token)
        {
            var arguments = new object[] { return_format, query, per_page, page, api_key, token };

            return((Task <HttpContent>)methodImpls["GetListAsync"](Client, arguments));
        }
예제 #22
0
        public PentahoUrlBuilder(string name, string description, string appendParams = "", ReturnFormat returnFormat = ReturnFormat.Excel)
        {
            Description  = description;
            Name         = name;
            AppendParams = appendParams;
            UserId       = "Admin";
            Password     = "******";

            switch (returnFormat)
            {
            case ReturnFormat.Excel:
                Format    = "table/excel;page-mode=flow";
                Extension = ".xls";
                break;

            default:
            case ReturnFormat.PDF:
                Format    = "pageable/pdf";
                Extension = ".pdf";
                break;
            }
        }