示例#1
0
 public RestMethodParam(string name, string description, RestType type, RestRefSchema refSchema)
 {
     Name        = name;
     Description = description;
     Type        = type;
     RefSchema   = refSchema;
 }
示例#2
0
        /// <summary>
        /// Serializes the given object to a json body or x-www-formurlencoded StringContent.
        /// StringContent can only contain a json or www-form data.
        /// </summary>
        /// <param name="restType">RestType to determine if a serilization is nesseccary.</param>
        /// <param name="bodyParameter"></param>
        /// <param name="wwwFormData"></param>
        /// <returns></returns>
        private StringContent SerializeToStringContent(RestType restType, object bodyParameter,
                                                       Dictionary <string, string> wwwFormData)
        {
            StringContent content = null;

            //Check if the requested RestType can contain content.
            if (restType == RestType.Post || restType == RestType.Put)
            {
                //Check if a body and wwwFormData is given, a request can only contain a body or wwwForm content.
                if (bodyParameter != null && wwwFormData != null)
                {
                    throw new Exception("Cant send a x-www-form-urlencoed and body parameter at the same time.");
                }

                if (bodyParameter != null)
                {
                    //Serialize the body
                    var json = JsonConvert.SerializeObject(bodyParameter);
                    content = new StringContent(json
                                                , Encoding.UTF8, "application/json");
                }

                if (wwwFormData != null)
                {
                    //Serialize the wwwFormData
                    content = new StringContent(DictionaryToWwwwFormData(wwwFormData), Encoding.UTF8,
                                                "application/x-www-form-urlencoded");
                }
            }

            return(content);
        }
        //добавляет к ячейка форматы
        protected void ApplyStyle(object value, RestType restType, ref Cell cell, ref CellValue cellValue)
        {
            if (restType == RestType.stringType)
            {
                // Формат № 0 по умолчанию общий
                cell.StyleIndex = (UInt32Value)0U;
                cell.DataType   = CellValues.String;
                cellValue.Text  = value.ToString();
            }
            else if (restType == RestType.intType)  //ловим на int что бы потом преобразовать в Excel в число
            {
                cell.DataType   = CellValues.Number;
                cell.StyleIndex = (UInt32Value)5U;

                int resultIinteger;
                var intBool = int.TryParse(value.ToString(), out resultIinteger);

                if (intBool)
                {
                    cellValue.Text = resultIinteger.ToString();
                    return;
                }
            }
            else if (restType == RestType.dateType)
            {
                //формат № 3 для дат * 14.03.2015
                cell.StyleIndex = (UInt32Value)1U;
                cell.DataType   = CellValues.Date;

                DateTime resultDate;
                var      dateBool = DateTime.TryParse(value.ToString(), out resultDate);

                if (dateBool)
                {
                    cellValue.Text = string.Format("{0:yyyy-MM-dd}", resultDate);
                    return;
                }
            }
            else if (restType == RestType.decimalType)
            {
                //формат № 2 для денег FormatCode = "#,##0\"р.\""
                cell.StyleIndex = (UInt32Value)7U;
                cell.DataType   = CellValues.Number;

                decimal resultDecemaly;
                var     decemalBool = decimal.TryParse(value.ToString(), out resultDecemaly);

                if (decemalBool)
                {
                    cellValue.Text = string.Format(CultureInfo.InvariantCulture, "{0}", resultDecemaly);
                    return;
                }
            }

            // Формат № 0 по умолчанию общий
            cell.StyleIndex = (UInt32Value)0U;
            cell.DataType   = CellValues.String;
            cellValue.Text  = value.ToString();
        }
        //добавляет к ячейка форматы
        protected void ApplyStyle(object value, RestType restType, ref Cell cell, ref CellValue cellValue)
        {
            if (restType == RestType.stringType)
            {
                // Формат № 0 по умолчанию общий
                cell.StyleIndex = (UInt32Value)0U;
                cell.DataType = CellValues.String;
                cellValue.Text = value.ToString();
            }
            else if (restType == RestType.intType)  //ловим на int что бы потом преобразовать в Excel в число
            {
                cell.DataType = CellValues.Number;
                cell.StyleIndex = (UInt32Value)5U;

                int resultIinteger;
                var intBool = int.TryParse(value.ToString(), out resultIinteger);

                if (intBool)
                {
                    cellValue.Text = resultIinteger.ToString();
                    return;
                }
            }
            else if (restType == RestType.dateType)
            {
                //формат № 3 для дат * 14.03.2015
                cell.StyleIndex = (UInt32Value)1U;
                cell.DataType = CellValues.Date;

                DateTime resultDate;
                var dateBool = DateTime.TryParse(value.ToString(), out resultDate);

                if (dateBool)
                {
                    cellValue.Text = string.Format("{0:yyyy-MM-dd}", resultDate);
                    return;
                }
            }
            else if (restType == RestType.decimalType)
            {
                //формат № 2 для денег FormatCode = "#,##0\"р.\""
                cell.StyleIndex = (UInt32Value)7U;
                cell.DataType = CellValues.Number;

                decimal resultDecemaly;
                var decemalBool = decimal.TryParse(value.ToString(), out resultDecemaly);

                if (decemalBool)
                {
                    cellValue.Text = string.Format(CultureInfo.InvariantCulture, "{0}", resultDecemaly);
                    return;
                }
            }

            // Формат № 0 по умолчанию общий
            cell.StyleIndex = (UInt32Value)0U;
            cell.DataType = CellValues.String;
            cellValue.Text = value.ToString();
        }
示例#5
0
 public RestProperty(string name, string format, string type, RestRefSchema refSchema, string description)
 {
     Name        = name;
     Format      = format;
     Type        = new RestType(type);
     RefSchema   = refSchema;
     Description = description;
 }
示例#6
0
 public RestParameter(string name, string description, string type, string format, string @default, RestRefSchema schemaRestRef)
 {
     Name          = name;
     Description   = description;
     Type          = new RestType(type);
     Format        = format;
     Default       = @default;
     SchemaRestRef = schemaRestRef;
 }
示例#7
0
 public async Task <Result> SendRequest(string uri, RestType restType, bool cacheData = false,
                                        string urlQuery = "", object bodyParameter = null, Dictionary <string, string> wwwFormData = null,
                                        string token    = null, Endpoint endpoint  = Endpoint.Api, bool httpsEnabled = true)
 {
     /*
      * Calls SendRequest<> with Type as expected deserialized data.
      * Type won't get deserialized by SendRequest<>
      */
     return(await SendRequest <Type>(uri, restType, cacheData, urlQuery, bodyParameter, wwwFormData, token,
                                     endpoint, httpsEnabled));
 }
示例#8
0
        public static int GetStatusCode <T>(this Result <T> result, RestType restType, IStatusCodeHelper statusCodeHelper = null)
        {
            if (result is null)
            {
                throw new ArgumentNullException(nameof(result));
            }

            statusCodeHelper ??= new StatusCodeHelper();

            return(statusCodeHelper.GetStatusCode(restType, result));
        }
示例#9
0
        public int GetStatusCode <T>(RestType restType, Result <T> result)
        {
            if (!result.IsValid)
            {
                return(GetFailStatusCode(result.Error.Type));
            }

            return(restType switch
            {
                RestType.Get or RestType.Delete or RestType.Options => StatusCodes.Status200OK,
                RestType.Post => StatusCodes.Status201Created,
                _ => result.Data is not null
                    ? StatusCodes.Status200OK
                    : StatusCodes.Status204NoContent,
            });
示例#10
0
        /// <summary>
        /// Executes a request with given <see cref="RestType"/>.
        /// </summary>
        /// <param name="uri">Endpoint</param>
        /// <param name="restType">RestType for the request.</param>
        /// <param name="client"><see cref="HttpClient"/> that should execute the request.</param>
        /// <param name="content">Content of the request.</param>
        /// <returns></returns>
        private static async Task <HttpResponseMessage> MakeRequest(string uri, RestType restType, HttpClient client,
                                                                    StringContent content)
        {
            switch (restType)
            {
            case RestType.Post:
                return(await client.PostAsync(uri, content));

            case RestType.Get:
                return(await client.GetAsync(uri));

            case RestType.Put:
                return(await client.PutAsync(uri, content));

            case RestType.Delete:
                return(await client.DeleteAsync(uri));

            default:
                throw new Exception("Unexpected RestType " + restType);
            }
        }
示例#11
0
        public async Task <Result <TExpectedType> > SendRequest <TExpectedType>(string uri, RestType restType,
                                                                                bool cacheData = false, string urlQuery = "", object bodyParameter = null,
                                                                                Dictionary <string, string> wwwFormData = null, string token = null, Endpoint endpoint = Endpoint.Api,
                                                                                bool httpsEnabled = true)
        {
            //Object that will contain the resul
            Result <TExpectedType> result = new Result <TExpectedType>();


            using (var client = GetClient(endpoint))
            {
                try
                {
                    uri = AddQuery(uri, urlQuery);

                    //Timer to check the duration of the call.
                    Stopwatch timer = new Stopwatch();
                    timer.Start();

                    AddTokenToClient(token, client);
                    HttpResponseMessage requestResult;

                    StringContent content = SerializeToStringContent(restType, bodyParameter, wwwFormData);

                    //Execute the request with the proper request type.
                    requestResult = await MakeRequest(uri, restType, client, content);

                    result.StatusCode = (int)requestResult.StatusCode;

                    //The token is not valid anymore!
                    await CheckIfTokenIsValid(requestResult.StatusCode, token);


                    //Check wheter or not the request was successfull.
                    if (requestResult.IsSuccessStatusCode ||
                        requestResult.StatusCode == HttpStatusCode.NotAcceptable)
                    {
                        //Basicly a workaround for a not so well made backend implementation that sends a 406 if a location is not correct while still sending data that are needed for the app.
                        await HandleSuccess(uri, result, timer, requestResult);
                    }
                    else
                    {
                        await HandleFailure(uri, timer, requestResult);
                    }
                }
                catch (Exception e)
                {
                    result.RequestFailedToException = true;
                    DebugHelper.PrintDebug(DebugType.Error, $"Request to {uri} failed due to an exception: \n" + e);
                }
            }

            return(result);
        }
示例#12
0
 public Rest(RestType type)
 {
     Type = type;
 }
 public static T SetRestType <T>(this T entity, RestType value)
     where T : RestActivityDefinition
 {
     entity.SetField("restType", value);
     return(entity);
 }