private List <EnumTypeValue> BuildValues()
        {
            var values = new List <EnumTypeValue>();

            foreach (var c in _choices)
            {
                var name          = BuilderHelpers.DisambiguateName(Type, c.CSharpName());
                var memberMapping = _typeMapping?.GetForMember(name);
                values.Add(new EnumTypeValue(
                               BuilderHelpers.CreateMemberDeclaration(name, Type, "public", memberMapping?.ExistingMember, _context.TypeFactory),
                               CreateDescription(c),
                               BuilderHelpers.ParseConstant(c.Value, BaseType)));
            }

            return(values);
        }
Exemple #2
0
        private static void BuildSuppliedPackSizes(Events.IngredientUpdated.Builder builder, List <IngredientSuppliedPackSize> suppliedPackList, List <CategoryType> categoryTypes, List <IngredientPriceBand> priceBands)
        {
            if (suppliedPackList.Count > 0)
            {
                foreach (var suppliedPack in suppliedPackList)
                {
                    var suppliedPackSizeBuilder = Events.IngredientUpdated.Types.SuppliedPackSize.CreateBuilder();

                    suppliedPackSizeBuilder.SetIsDefault(suppliedPack.IsDefault)
                    .SetIsPreferred(suppliedPack.IsPreferred)
                    .SetDistributorName(suppliedPack.DistributorName)
                    .SetDistributorCode(suppliedPack.DistributorCode)
                    .SetDistributorUom(suppliedPack.DistributorUom)
                    .SetSupplyQuantityNumber(suppliedPack.SupplyQuantityNumber)
                    .SetSupplyQuantityQuantity(suppliedPack.SupplyQuantityQuantity)
                    .SetSupplyQuantityUom(suppliedPack.SupplyQuantityUom)
                    .SetSupplyQuantityPackDescription(suppliedPack.SupplyQuantityPackDescription)
                    .SetCostPrice(suppliedPack.CostPrice)
                    .SetCostPricePerItem(suppliedPack.CostPricePerItem)
                    .SetCurrencyIso4217Code(suppliedPack.CurrencyIso4217Code)
                    .SetIsOrderable(suppliedPack.IsOrderable)
                    .SetMaxOrderQuantity(suppliedPack.MaxOrderQuantity)
                    .SetMinOrderQuantity(suppliedPack.MinOrderQuantity)
                    .SetCreatedUserFirstName(suppliedPack.CreatedUserFirstName)
                    .SetCreatedUserLastName(suppliedPack.CreatedUserLastName)
                    .SetCaptureDate(suppliedPack.CaptureDate)
                    .SetModifiedUserFirstName(suppliedPack.ModifiedUserFirstName)
                    .SetModifiedUserLastName(suppliedPack.ModifiedUserLastName)
                    .SetModifiedDate(suppliedPack.ModifiedDate)
                    .SetRetailBarCodeDetails(suppliedPack.RetailBarCodeDetails)
                    .SetRankOrder(suppliedPack.RankOrder)
                    .SetInvoicePrice(Decimal.BuildFromDecimal(suppliedPack.InvoicePrice))
                    .SetInvoiceUnitOfMeasure(suppliedPack.InvoiceUnitOfMeasure)
                    .SetIsVariableWeighted(suppliedPack.IsVariableWeighted)
                    ;

                    var            productCategoryTypes = categoryTypes.Where(ct => ct.ProductId == suppliedPack.ProductId).ToList();
                    Func <dynamic> createCategoryType   = () => Events.IngredientUpdated.Types.CategoryType.CreateBuilder();
                    Func <dynamic> createCategory       = () => Events.IngredientUpdated.Types.CategoryType.Types.Category.CreateBuilder();
                    BuilderHelpers.BuildCategoryTypes(suppliedPackSizeBuilder, createCategoryType, createCategory, productCategoryTypes);

                    BuildPriceBands(suppliedPackSizeBuilder, priceBands.Where(p => p.ProductId == suppliedPack.ProductId).ToList());

                    builder.AddSuppliedPackSizes(suppliedPackSizeBuilder);
                }
            }
        }
Exemple #3
0
        private ReferenceOrConstant?GetPropertyDefaultValue(ObjectTypeProperty property)
        {
            if (property == Discriminator?.Property)
            {
                if (Discriminator.Value != null)
                {
                    return(BuilderHelpers.StringConstant(Discriminator.Value));
                }
            }
            else
            {
                var initializeWithType = property.InitializeWithType;
                return(initializeWithType != null?Constant.NewInstanceOf(initializeWithType) : (ReferenceOrConstant?)null);
            }

            return(null);
        }
Exemple #4
0
        private IEnumerable <ClientMethod> BuildMethods()
        {
            foreach (var operation in _operationGroup.Operations)
            {
                if (operation.IsLongRunning || operation.Language.Default.Paging != null)
                {
                    continue;
                }

                foreach (var request in operation.Requests)
                {
                    var name = operation.CSharpName();
                    RestClientMethod startMethod = RestClient.GetOperationMethod(request);

                    yield return(new ClientMethod(
                                     name,
                                     startMethod,
                                     BuilderHelpers.EscapeXmlDescription(operation.Language.Default.Description),
                                     new Diagnostic($"{Declaration.Name}.{name}", Array.Empty <DiagnosticAttribute>())));
                }
            }
        }
 private static string CreateDescription(RequestParameter requestParameter)
 {
     return(string.IsNullOrWhiteSpace(requestParameter.Language.Default.Description) ?
            $"The {requestParameter.Schema.Name} to use." :
            BuilderHelpers.EscapeXmlDescription(requestParameter.Language.Default.Description));
 }
 protected static string CreateDescription(OperationGroup operationGroup, string clientPrefix)
 {
     return(string.IsNullOrWhiteSpace(operationGroup.Language.Default.Description) ?
            $"The {clientPrefix} service client." :
            BuilderHelpers.EscapeXmlDescription(operationGroup.Language.Default.Description));
 }
 protected Constant ParseConstant(ConstantSchema constant) =>
 BuilderHelpers.ParseConstant(constant.Value.Value, _context.TypeFactory.CreateType(constant.ValueType, constant.Value.Value == null));
Exemple #8
0
        public void BuildCategoryTypes_should_init_builder_with_category_hierarchy()
        {
            var categoryTypes = new List <CategoryType>();

            categoryTypes.AddRange(new[]
            {
                #region CategoryType
                new CategoryType
                {
                    ProductId          = 13768,
                    Id                 = 1,
                    ExternalId         = "83A05879-8C70-4583-A36B-0A31D601F0D9",
                    Name               = "Region",
                    CategoryExportType = 1,
                    MainCategories     = new List <Category>
                    {
                        #region Category
                        new Category
                        {
                            Id               = 51,
                            ProductId        = 13768,
                            ExternalId       = "1AF82BE6-9E9C-4585-8884-CC3B5C775846",
                            Name             = "Scandanavia",
                            ParentExternalId = "83A05879-8C70-4583-A36B-0A31D601F0D9"
                        }
                        #endregion
                    }
                },

                #endregion
                #region CategoryType
                new CategoryType
                {
                    ProductId          = 13768,
                    Id                 = 4,
                    ExternalId         = "AF0FB0B6-34C6-4C9B-BA20-3330FA16A299",
                    Name               = "Course123",
                    CategoryExportType = null,
                    MainCategories     = new List <Category>
                    {
                        #region Category
                        new Category
                        {
                            Id               = 425,
                            ProductId        = 13768,
                            ExternalId       = "232789EA-841E-4FFF-9FD2-F085495E3FAD",
                            Name             = "Starters",
                            ParentExternalId = "AF0FB0B6-34C6-4C9B-BA20-3330FA16A299"
                        },

                        #endregion
                        #region Category
                        new Category
                        {
                            Id               = 425,
                            ProductId        = 13768,
                            ExternalId       = "232789EA-841E-4FFF-9FD2-F085495E3FAD",
                            Name             = "Starters",
                            ParentExternalId = "AF0FB0B6-34C6-4C9B-BA20-3330FA16A299",
                            SubCategories    = new List <Category>
                            {
                                #region Category
                                new Category
                                {
                                    Id               = 442,
                                    ProductId        = 13768,
                                    ExternalId       = "5666E087-E0BC-4902-932A-2DA74A930469",
                                    Name             = "test",
                                    ParentExternalId = "232789EA-841E-4FFF-9FD2-F085495E3FAD"
                                }
                                #endregion
                            }
                        },

                        #endregion
                        #region Category
                        new Category
                        {
                            Id               = 427,
                            ProductId        = 13768,
                            ExternalId       = "353A88C0-C37D-416A-9C66-FE4AAFBE72CE",
                            Name             = "Desserts",
                            ParentExternalId = "AF0FB0B6-34C6-4C9B-BA20-3330FA16A299"
                        },

                        #endregion
                    }
                },

                #endregion
                #region CategoryType
                new CategoryType
                {
                    ProductId          = 13768,
                    Id                 = 5,
                    ExternalId         = "576B4721-5913-439F-8453-FC5AD8B6245E",
                    Name               = "Ingredient Category",
                    CategoryExportType = null,

                    MainCategories = new List <Category>
                    {
                        #region Category
                        new Category
                        {
                            Id               = 382,
                            ProductId        = 13768,
                            ExternalId       = "2D868A36-9108-4389-B355-E8F86135A534",
                            Name             = "Grocery",
                            ParentExternalId = "576B4721-5913-439F-8453-FC5AD8B6245E"
                        },

                        #endregion
                        #region Category
                        new Category
                        {
                            Id               = 63,
                            ProductId        = 13768,
                            ExternalId       = "02C03BD6-1368-4CDB-8D68-105CBE41FDD5",
                            Name             = "Bakery",
                            ParentExternalId = "576B4721-5913-439F-8453-FC5AD8B6245E",
                            SubCategories    = new List <Category>
                            {
                                #region Category
                                new Category
                                {
                                    Id               = 422,
                                    ProductId        = 13768,
                                    ExternalId       = "7C5D42AA-BED0-4ACC-8919-C291DB92E4DB",
                                    Name             = "Italian Breads",
                                    ParentExternalId = "02C03BD6-1368-4CDB-8D68-105CBE41FDD5"
                                }
                                #endregion
                            }
                        },

                        #endregion
                    }
                }
                #endregion
            });

            // act
            var builder = RecipeUpdated.CreateBuilder();
            // mandatory fields -> they are not important now
            builder
            .SetExternalId("")
            .SetCustomerId("")
            .SetCustomerName("")
            .SetSequenceNumber(1)
            .SetSource(SourceSystem.STARCHEF);

            Func <dynamic> createCategoryType = () => RecipeCategoryType.CreateBuilder();
            Func <dynamic> createCategory     = () => RecipeCategory.CreateBuilder();

            BuilderHelpers.BuildCategoryTypes(builder, createCategoryType, createCategory, categoryTypes);

            #region assert
            var suppliedPackSize = builder.Build();
            Assert.Equal(3, suppliedPackSize.CategoryTypesCount);

            var categoryType = suppliedPackSize.CategoryTypesList.Single(ct => ct.CategoryTypeName == "Region");
            Assert.Equal(CategoryExportType.ING, categoryType.ExportType);
            Assert.Equal("83A05879-8C70-4583-A36B-0A31D601F0D9", categoryType.ExternalId);
            Assert.Equal(1, categoryType.MainCategoriesCount);
            Assert.Equal("Scandanavia", categoryType.MainCategoriesList[0].CategoryName);
            Assert.Equal("1AF82BE6-9E9C-4585-8884-CC3B5C775846", categoryType.MainCategoriesList[0].ExternalId);
            Assert.Equal("83A05879-8C70-4583-A36B-0A31D601F0D9", categoryType.MainCategoriesList[0].ParentExternalId);

            categoryType = suppliedPackSize.CategoryTypesList.Single(ct => ct.CategoryTypeName == "Course123");
            Assert.Equal(CategoryExportType.NONE, categoryType.ExportType);
            Assert.Equal("AF0FB0B6-34C6-4C9B-BA20-3330FA16A299", categoryType.ExternalId);
            Assert.Equal(3, categoryType.MainCategoriesCount);
            Assert.Equal("Starters", categoryType.MainCategoriesList[0].CategoryName);
            Assert.Equal("232789EA-841E-4FFF-9FD2-F085495E3FAD", categoryType.MainCategoriesList[0].ExternalId);
            Assert.Equal("AF0FB0B6-34C6-4C9B-BA20-3330FA16A299", categoryType.MainCategoriesList[0].ParentExternalId);
            Assert.Equal("Starters", categoryType.MainCategoriesList[1].CategoryName);
            Assert.Equal("232789EA-841E-4FFF-9FD2-F085495E3FAD", categoryType.MainCategoriesList[1].ExternalId);
            Assert.Equal("AF0FB0B6-34C6-4C9B-BA20-3330FA16A299", categoryType.MainCategoriesList[1].ParentExternalId);
            Assert.Equal(1, categoryType.MainCategoriesList[1].SubCategoriesCount);
            Assert.Equal("test", categoryType.MainCategoriesList[1].SubCategoriesList[0].CategoryName);
            Assert.Equal("5666E087-E0BC-4902-932A-2DA74A930469", categoryType.MainCategoriesList[1].SubCategoriesList[0].ExternalId);
            Assert.Equal("232789EA-841E-4FFF-9FD2-F085495E3FAD", categoryType.MainCategoriesList[1].SubCategoriesList[0].ParentExternalId);
            Assert.Equal("Desserts", categoryType.MainCategoriesList[2].CategoryName);
            Assert.Equal("353A88C0-C37D-416A-9C66-FE4AAFBE72CE", categoryType.MainCategoriesList[2].ExternalId);
            Assert.Equal("AF0FB0B6-34C6-4C9B-BA20-3330FA16A299", categoryType.MainCategoriesList[2].ParentExternalId);

            categoryType = suppliedPackSize.CategoryTypesList.Single(ct => ct.CategoryTypeName == "Ingredient Category");
            Assert.Equal(CategoryExportType.NONE, categoryType.ExportType);
            Assert.Equal("576B4721-5913-439F-8453-FC5AD8B6245E", categoryType.ExternalId);
            Assert.Equal(2, categoryType.MainCategoriesCount);
            Assert.Equal("Grocery", categoryType.MainCategoriesList[0].CategoryName);
            Assert.Equal("2D868A36-9108-4389-B355-E8F86135A534", categoryType.MainCategoriesList[0].ExternalId);
            Assert.Equal("576B4721-5913-439F-8453-FC5AD8B6245E", categoryType.MainCategoriesList[0].ParentExternalId);
            Assert.Equal("Bakery", categoryType.MainCategoriesList[1].CategoryName);
            Assert.Equal("02C03BD6-1368-4CDB-8D68-105CBE41FDD5", categoryType.MainCategoriesList[1].ExternalId);
            Assert.Equal("576B4721-5913-439F-8453-FC5AD8B6245E", categoryType.MainCategoriesList[1].ParentExternalId);
            Assert.Equal(1, categoryType.MainCategoriesList[1].SubCategoriesCount);
            Assert.Equal("Italian Breads", categoryType.MainCategoriesList[1].SubCategoriesList[0].CategoryName);
            Assert.Equal("7C5D42AA-BED0-4ACC-8919-C291DB92E4DB", categoryType.MainCategoriesList[1].SubCategoriesList[0].ExternalId);
            Assert.Equal("02C03BD6-1368-4CDB-8D68-105CBE41FDD5", categoryType.MainCategoriesList[1].SubCategoriesList[0].ParentExternalId);
            #endregion
        }
Exemple #9
0
        public bool SetForUpdate(Events.RecipeUpdated.Builder builder, string connectionString, int entityId, int databaseId)
        {
            if (builder == null)
            {
                return(false);
            }

            var cust   = new Customer(databaseId);
            var reader = ExecuteDbCommand(connectionString, entityId);

            if (reader.Read())
            {
                var changeTypeSc = reader["ChangeType"].ToString();
                var changeType   = Events.ChangeType.UPDATE;
                if (changeTypeSc == "Archive")
                {
                    changeType = Events.ChangeType.ARCHIVE;
                }

                builder.SetCustomerId(cust.ExternalId)
                .SetCustomerName(cust.Name)
                .SetExternalId(reader[0].ToString())
                .SetRecipeName(reader[1].ToString())
                .SetRecipeType(OrchestrateHelper.MapRecipeType(reader[2].ToString()))
                .SetUnitSizeQuantity(reader.GetValueOrDefault <double>(3))
                .SetPortionSizeUnitCode(reader[4].ToString())
                .SetUnitSizePackDescription(reader[5].ToString())
                .SetCost(reader.GetValueOrDefault <double>(8))
                .SetCurrencyIso4217Code(reader[9].ToString())
                .SetVatType(OrchestrateHelper.MapVatType(reader[10].ToString()))
                .SetVatPercentage(reader.GetValueOrDefault <double>(11))
                .SetSellingPrice(reader.GetValueOrDefault <double>(12))
                .SetPricingModel(Events.PricingModel.Margin)
                .SetPricingModelValue(reader.GetValueOrDefault <double>(14))
                .SetSuggestedSellingPrice(reader.GetValueOrDefault <double>(16))
                .SetSuggestedPlu(reader[17].ToString())
                .SetCreatedUserFirstName(reader[18].ToString())
                .SetCreatedUserLastName(reader[19].ToString())
                .SetModifiedUserFirstName(reader[20].ToString())
                .SetModifiedUserLastName(reader[21].ToString())
                .SetCaptureDate(Fourth.Orchestration.Model.UnixDateTime.FromDateTime(reader.GetValueOrDefault <DateTime>(22)))
                .SetModifiedDate(Fourth.Orchestration.Model.UnixDateTime.FromDateTime(reader.GetValueOrDefault <DateTime>(23)))
                .SetPortionSizeQuantity(reader.GetValueOrDefault <double>("PortionSizeQuantity"))
                .SetPortionSizeUom(reader.GetValueOrDefault <string>("PortionSizeUom") ?? string.Empty)
                .SetChangeType(changeType);

                var barcodes = ReadBarcodes(reader);
                if (barcodes.Any())
                {
                    builder.AddRangeBarcode(barcodes);
                }
            }

            //Ingredients
            var ingredientList = new List <RecipeIngredient>();

            if (reader.NextResult())
            {
                ingredientList = ReadIngredients(reader, entityId);
            }

            //Kitchenarea
            var kitchenAreaLookup = new Dictionary <int, List <KitchenArea> >();

            if (reader.NextResult())
            {
                List <KitchenArea> kitchenAreas;
                reader.ReadKitchenAreas(out kitchenAreas);

                kitchenAreaLookup = BuildKitchenAreas(kitchenAreas);
            }

            //Build Ingredients and KitchenArea
            BuildIngredients(builder, ingredientList, kitchenAreaLookup);

            //Groups
            if (reader.NextResult())
            {
                while (reader.Read())
                {
                    var groupBuilder = Events.RecipeUpdated.Types.RecipeGroup.CreateBuilder();
                    var externalId   = reader.GetValueOrDefault <Guid>("group_guid").ToString();
                    var groupName    = reader.GetValueOrDefault <string>("group_name");
                    var groupPrice   = reader.GetValueOrDefault <decimal>("product_price");
                    groupBuilder.SetExternalId(externalId)
                    .SetGroupName(groupName)
                    .SetPrice(Fourth.Orchestration.Model.Common.Decimal.BuildFromDecimal(groupPrice));
                    builder.AddGroups(groupBuilder);
                }
            }

            var             categoryTypes = new List <CategoryType>();
            List <Category> categories;

            //read category types and categories
            if (reader.NextResult())
            {
                reader.ReadCategories(out categoryTypes, out categories);
            }
            if (categoryTypes.Count > 0)
            {
                Func <dynamic> createCategoryType = () => Events.RecipeUpdated.Types.CategoryType.CreateBuilder();
                Func <dynamic> createCategory     = () => Events.RecipeUpdated.Types.CategoryType.Types.Category.CreateBuilder();
                BuilderHelpers.BuildCategoryTypes(builder, createCategoryType, createCategory, categoryTypes);
            }

            //read intolerances
            if (reader.NextResult())
            {
                if (reader.Read())
                {
                    if (!reader.IsDBNull(1))
                    {
                        builder.SetContainsMilkOrMilkProducts(reader.GetBoolean(1));
                    }
                    if (!reader.IsDBNull(2))
                    {
                        builder.SetContainsEggOrEggDerivatives(reader.GetBoolean(2));
                    }
                    if (!reader.IsDBNull(3))
                    {
                        builder.SetContainsCerealsThatContainGluten(reader.GetBoolean(3));
                    }
                    if (!reader.IsDBNull(4))
                    {
                        builder.SetContainsPeanuts(reader.GetBoolean(4));
                    }
                    if (!reader.IsDBNull(5))
                    {
                        builder.SetContainsNutsOrNutTrace(reader.GetBoolean(5));
                    }
                    if (!reader.IsDBNull(6))
                    {
                        builder.SetContainsSesameSeedOrSesameSeedProducts(reader.GetBoolean(6));
                    }
                    if (!reader.IsDBNull(7))
                    {
                        builder.SetContainsSoya(reader.GetBoolean(7));
                    }
                    if (!reader.IsDBNull(8))
                    {
                        builder.SetContainsFishOrFishProducts(reader.GetBoolean(8));
                    }
                    if (!reader.IsDBNull(9))
                    {
                        builder.SetContainsCrustaceans(reader.GetBoolean(9));
                    }
                    if (!reader.IsDBNull(10))
                    {
                        builder.SetContainsMolluscs(reader.GetBoolean(10));
                    }
                    if (!reader.IsDBNull(11))
                    {
                        builder.SetContainsMustardOrMustardProducts(reader.GetBoolean(11));
                    }
                    if (!reader.IsDBNull(12))
                    {
                        builder.SetContainsCeleryOrCeleriacProducts(reader.GetBoolean(12));
                    }
                    if (!reader.IsDBNull(13))
                    {
                        builder.SetContainsSulphurDioxideOrSulphites(reader.GetBoolean(13));
                    }
                    if (!reader.IsDBNull(14))
                    {
                        builder.SetContainsLupinFlourOrLupinProducts(reader.GetBoolean(14));
                    }
                    if (!reader.IsDBNull(15))
                    {
                        builder.SetContainsGlutenOrGlutenProducts(reader.GetBoolean(15));
                    }
                }
            }

            //read nutritions
            if (reader.NextResult())
            {
                if (reader.Read())
                {
                    if (!reader.IsDBNull(1))
                    {
                        builder.SetEnergyKJperServing(reader.GetDouble(1));
                    }
                    if (!reader.IsDBNull(2))
                    {
                        builder.SetEnergyKCalPerServing(reader.GetDouble(2));
                    }
                    if (!reader.IsDBNull(3))
                    {
                        builder.SetFatPerServing(reader.GetDouble(3));
                    }
                    if (!reader.IsDBNull(4))
                    {
                        builder.SetSaturatedFatPerServing(reader.GetDouble(4));
                    }
                    if (!reader.IsDBNull(5))
                    {
                        builder.SetSugarPerServing(reader.GetDouble(5));
                    }
                    if (!reader.IsDBNull(6))
                    {
                        builder.SetSaltPerServing(reader.GetDouble(6));
                    }
                }
            }

            //Recipe sets
            var recipeSets = new List <RecipeSet>();

            if (reader.NextResult())
            {
                recipeSets = GetRecipeSets(reader);
            }

            if (!recipeSets.Any())
            {
                builder.SetChangeType(Events.ChangeType.ARCHIVE);
            }

            BuildRecipeSets(builder, recipeSets);

            return(true);
        }
Exemple #10
0
        private RestClientMethod BuildMethod(Operation operation, HttpRequest httpRequest, ICollection <RequestParameter> requestParameters, ResponseHeaderGroupType?responseHeaderModel)
        {
            HttpWithBodyRequest?httpRequestWithBody         = httpRequest as HttpWithBodyRequest;
            Dictionary <string, PathSegment> uriParameters  = new Dictionary <string, PathSegment>();
            Dictionary <string, PathSegment> pathParameters = new Dictionary <string, PathSegment>();
            List <QueryParameter>            query          = new List <QueryParameter>();
            List <RequestHeader>             headers        = new List <RequestHeader>();
            Dictionary <RequestParameter, ReferenceOrConstant> allParameters    = new Dictionary <RequestParameter, ReferenceOrConstant>();
            Dictionary <RequestParameter, Parameter>           methodParameters = new Dictionary <RequestParameter, Parameter>();

            RequestBody?body = null;

            (RequestParameter, ReferenceOrConstant)? bodyParameter = null;
            RequestParameter[] parameters = operation.Parameters.Concat(requestParameters).ToArray();
            foreach (RequestParameter requestParameter in parameters)
            {
                string defaultName    = requestParameter.Language.Default.Name;
                string serializedName = requestParameter.Language.Default.SerializedName ?? defaultName;
                ReferenceOrConstant constantOrReference;
                Schema valueSchema = requestParameter.Schema;

                if (requestParameter.Implementation == ImplementationLocation.Method)
                {
                    Parameter?parameter = null;
                    // TODO: always generate virtual parameters
                    if (!(requestParameter is VirtualParameter) &&
                        requestParameter.Schema is ConstantSchema constant)
                    {
                        constantOrReference = ParseConstant(constant);
                        valueSchema         = constant.ValueType;
                    }
                    else
                    {
                        parameter = BuildParameter(requestParameter);

                        if (requestParameter.GroupedBy is RequestParameter groupedByParameter)
                        {
                            var groupModel = (ObjectType)_context.TypeFactory.CreateType(groupedByParameter.Schema, false).Implementation;
                            var property   = groupModel.GetPropertyForGroupedParameter(requestParameter);

                            constantOrReference = new Reference($"{groupedByParameter.CSharpName()}.{property.Declaration.Name}", property.Declaration.Type);
                        }
                        else
                        {
                            constantOrReference = parameter;
                        }
                    }

                    allParameters.Add(requestParameter, constantOrReference);

                    if (parameter != null &&
                        requestParameter.Flattened != true &&
                        requestParameter.GroupedBy == null)
                    {
                        methodParameters.Add(requestParameter, parameter);
                    }
                }
                else
                {
                    constantOrReference = _parameters[requestParameter.Language.Default.Name];
                }

                if (requestParameter.Protocol.Http is HttpParameter httpParameter)
                {
                    SerializationFormat serializationFormat = BuilderHelpers.GetSerializationFormat(valueSchema);
                    bool skipEncoding = requestParameter.Extensions !.TryGetValue("x-ms-skip-url-encoding", out var value) && Convert.ToBoolean(value);
                    switch (httpParameter.In)
                    {
                    case ParameterLocation.Header:
                        headers.Add(new RequestHeader(serializedName, constantOrReference, GetSerializationStyle(httpParameter, valueSchema), serializationFormat));
                        break;

                    case ParameterLocation.Query:
                        query.Add(new QueryParameter(serializedName, constantOrReference, GetSerializationStyle(httpParameter, valueSchema), !skipEncoding, serializationFormat));
                        break;

                    case ParameterLocation.Path:
                        pathParameters.Add(serializedName, new PathSegment(constantOrReference, !skipEncoding, serializationFormat));
                        break;

                    case ParameterLocation.Body:
                        bodyParameter = (requestParameter, constantOrReference);
                        break;

                    case ParameterLocation.Uri:
                        uriParameters.Add(serializedName, new PathSegment(constantOrReference, !skipEncoding, serializationFormat, isRaw: true));
                        break;
                    }
                }
            }

            if (bodyParameter is var(bodyRequestParameter, bodyParameterValue))
            {
                Debug.Assert(httpRequestWithBody != null);
                if (httpRequestWithBody.KnownMediaType == KnownMediaType.Binary)
                {
                    body = new BinaryRequestBody(bodyParameterValue);
                }
                else if (httpRequestWithBody.KnownMediaType == KnownMediaType.Text)
                {
                    body = new TextRequestBody(bodyParameterValue);
                }
                else
                {
                    var serialization = _serializationBuilder.Build(
                        httpRequestWithBody.KnownMediaType,
                        bodyRequestParameter.Schema,
                        bodyParameterValue.Type);

                    // This method has a flattened body
                    if (bodyRequestParameter.Flattened == true)
                    {
                        var objectType        = (ObjectType)_context.Library.FindTypeForSchema(bodyRequestParameter.Schema);
                        var virtualParameters = requestParameters.OfType <VirtualParameter>().ToArray();

                        List <ObjectPropertyInitializer> initializationMap = new List <ObjectPropertyInitializer>();
                        foreach (var virtualParameter in virtualParameters)
                        {
                            var actualParameter = allParameters[virtualParameter];

                            initializationMap.Add(new ObjectPropertyInitializer(
                                                      objectType.GetPropertyForSchemaProperty(virtualParameter.TargetProperty, true),
                                                      actualParameter));
                        }

                        body = new FlattenedSchemaRequestBody(objectType, initializationMap.ToArray(), serialization);
                    }
                    else
                    {
                        body = new SchemaRequestBody(bodyParameterValue, serialization);
                    }
                }
            }

            PathSegment[] pathSegments = GetPathSegments(httpRequest.Uri, uriParameters, isRaw: true)
                                         .Concat(GetPathSegments(httpRequest.Path, pathParameters))
                                         .ToArray();
            Request request = new Request(
                httpRequest.Method.ToCoreRequestMethod() ?? RequestMethod.Get,
                pathSegments,
                query.ToArray(),
                headers.ToArray(),
                body
                );

            string operationName = operation.CSharpName();

            List <Response> clientResponse = new List <Response>();

            if (operation.IsLongRunning)
            {
                // Ignore response body and headers for LROs as the ArmOperationHelpers figures out them dynamically
                responseHeaderModel = null;
            }

            foreach (var response in operation.Responses)
            {
                clientResponse.Add(new Response(
                                       operation.IsLongRunning ? null : BuildResponseBody(response),
                                       response.HttpResponse.IntStatusCodes.ToArray()
                                       ));
            }

            var responseType = ReduceResponses(clientResponse);

            return(new RestClientMethod(
                       operationName,
                       BuilderHelpers.EscapeXmlDescription(operation.Language.Default.Description),
                       responseType,
                       request,
                       OrderParameters(methodParameters.Values),
                       clientResponse.ToArray(),
                       responseHeaderModel
                       ));
        }
Exemple #11
0
        private IEnumerable <ObjectTypeProperty> BuildProperties()
        {
            // WORKAROUND: https://github.com/Azure/autorest.modelerfour/issues/261
            var existingProperties = EnumerateHierarchy()
                                     .Skip(1)
                                     .SelectMany(type => type.Properties)
                                     .Select(p => p.SchemaProperty?.Language.Default.Name)
                                     .ToHashSet();

            foreach (var objectSchema in GetCombinedSchemas())
            {
                foreach (Property property in objectSchema.Properties !)
                {
                    if (existingProperties.Contains(property.Language.Default.Name))
                    {
                        // WORKAROUND: https://github.com/Azure/autorest.modelerfour/issues/261
                        continue;
                    }

                    var name = BuilderHelpers.DisambiguateName(Type, property.CSharpName());
                    SourceMemberMapping?memberMapping = _sourceTypeMapping?.GetForMember(name);
                    bool isNotInput = (objectSchema.IsOutput || objectSchema.IsException) && !objectSchema.IsInput;
                    bool isReadOnly = IsStruct ||
                                      isNotInput ||
                                      property.ReadOnly == true ||
                                      // Required properties of input objects should be readonly
                                      (property.Required == true && objectSchema.IsInputOnly);

                    if (property.IsDiscriminator == true)
                    {
                        // Discriminator properties should be writeable
                        isReadOnly = false;
                    }

                    CSharpType type = _typeFactory.CreateType(
                        property.Schema,
                        property.IsNullable());

                    if (!_objectSchema.IsInput)
                    {
                        type = TypeFactory.GetOutputType(type);
                    }

                    var accessibility = property.IsDiscriminator == true ? "internal" : "public";

                    CSharpType?initializeWithType = memberMapping?.Initialize == true?TypeFactory.GetImplementationType(type) : null;

                    yield return(new ObjectTypeProperty(
                                     BuilderHelpers.CreateMemberDeclaration(name, type, accessibility, memberMapping?.ExistingMember, _typeFactory),
                                     BuilderHelpers.EscapeXmlDescription(property.Language.Default.Description),
                                     isReadOnly,
                                     property,
                                     initializeWithType,
                                     memberMapping?.EmptyAsUndefined ?? false));
                }
            }

            if (AdditionalPropertiesProperty is ObjectTypeProperty additionalPropertiesProperty)
            {
                yield return(additionalPropertiesProperty);
            }
        }
Exemple #12
0
        private ObjectTypeConstructor BuildInitializationConstructor()
        {
            List <Parameter> defaultCtorParameters = new List <Parameter>();
            List <ObjectPropertyInitializer> defaultCtorInitializers = new List <ObjectPropertyInitializer>();

            ObjectTypeConstructor?baseCtor = null;

            if (Inherits != null && !Inherits.IsFrameworkType && Inherits.Implementation is ObjectType objectType)
            {
                baseCtor = objectType.Constructors.First();
                defaultCtorParameters.AddRange(baseCtor.Parameters);
            }

            foreach (var property in Properties)
            {
                // Only required properties that are not discriminators go into default ctor
                if (property == Discriminator?.Property)
                {
                    continue;
                }

                ReferenceOrConstant?initializationValue;

                if (property.SchemaProperty?.Schema is ConstantSchema constantSchema)
                {
                    // Turn constants into initializers
                    initializationValue = constantSchema.Value.Value != null?
                                          BuilderHelpers.ParseConstant(constantSchema.Value.Value, property.Declaration.Type) :
                                              Constant.NewInstanceOf(property.Declaration.Type);
                }
                else if (IsStruct || property.SchemaProperty?.Required == true)
                {
                    // For structs all properties become required
                    Constant?defaultParameterValue = null;
                    if (property.SchemaProperty?.ClientDefaultValue is object defaultValueObject)
                    {
                        defaultParameterValue = BuilderHelpers.ParseConstant(defaultValueObject, property.Declaration.Type);
                    }

                    var defaultCtorParameter = new Parameter(
                        property.Declaration.Name.ToVariableName(),
                        property.Description,
                        TypeFactory.GetInputType(property.Declaration.Type),
                        defaultParameterValue,
                        true
                        );

                    defaultCtorParameters.Add(defaultCtorParameter);
                    initializationValue = defaultCtorParameter;
                }
                else
                {
                    initializationValue = GetPropertyDefaultValue(property);
                }

                if (initializationValue != null)
                {
                    defaultCtorInitializers.Add(new ObjectPropertyInitializer(property, initializationValue.Value));
                }
            }

            if (Discriminator != null)
            {
                defaultCtorInitializers.Add(new ObjectPropertyInitializer(Discriminator.Property, BuilderHelpers.StringConstant(Discriminator.Value)));
            }

            return(new ObjectTypeConstructor(
                       BuilderHelpers.CreateMemberDeclaration(
                           Type.Name,
                           Type,
                           // inputs have public ctor by default
                           _objectSchema.IsInput ? "public" : "internal",
                           null,
                           _typeFactory),
                       defaultCtorParameters.ToArray(),
                       defaultCtorInitializers.ToArray(),
                       baseCtor));
        }
Exemple #13
0
        private ObjectTypeConstructor BuildSerializationConstructor()
        {
            bool ownsDiscriminatorProperty = false;

            List <Parameter> serializationConstructorParameters        = new List <Parameter>();
            List <ObjectPropertyInitializer> serializationInitializers = new List <ObjectPropertyInitializer>();
            ObjectTypeConstructor?           baseSerializationCtor     = null;

            if (Inherits != null && !Inherits.IsFrameworkType && Inherits.Implementation is ObjectType objectType)
            {
                baseSerializationCtor = objectType.Constructors.Last();
                serializationConstructorParameters.AddRange(baseSerializationCtor.Parameters);
            }

            foreach (var property in Properties)
            {
                var deserializationParameter = new Parameter(
                    property.Declaration.Name.ToVariableName(),
                    property.Description,
                    property.Declaration.Type,
                    null,
                    false
                    );

                ownsDiscriminatorProperty |= property == Discriminator?.Property;

                serializationConstructorParameters.Add(deserializationParameter);

                serializationInitializers.Add(new ObjectPropertyInitializer(property, deserializationParameter, GetPropertyDefaultValue(property)));
            }

            if (Discriminator != null)
            {
                // Add discriminator initializer to constructor at every level of hierarchy
                if (!ownsDiscriminatorProperty &&
                    baseSerializationCtor != null)
                {
                    var discriminatorParameter = baseSerializationCtor.FindParameterByInitializedProperty(Discriminator.Property);
                    Debug.Assert(discriminatorParameter != null);

                    serializationInitializers.Add(new ObjectPropertyInitializer(Discriminator.Property, discriminatorParameter, BuilderHelpers.StringConstant(Discriminator.Value)));
                }
            }

            return(new ObjectTypeConstructor(
                       BuilderHelpers.CreateMemberDeclaration(Type.Name, Type, "internal", null, _typeFactory),
                       serializationConstructorParameters.ToArray(),
                       serializationInitializers.ToArray(),
                       baseSerializationCtor
                       ));
        }
 private static string CreateDescription(ChoiceValue choiceValue)
 {
     return(string.IsNullOrWhiteSpace(choiceValue.Language.Default.Description) ? choiceValue.Value : BuilderHelpers.EscapeXmlDescription(choiceValue.Language.Default.Description));
 }