internal static Uri GenerateActionLink(EntityInstanceContext entityContext, ActionConfiguration action)
        {
            // the entity type the action is bound to.
            EntityTypeConfiguration actionEntityType = action.BindingParameter.TypeConfiguration as EntityTypeConfiguration;
            Contract.Assert(actionEntityType != null, "we have already verified that binding paramter type is entity");

            Dictionary<string, object> routeValues = new Dictionary<string, object>(StringComparer.OrdinalIgnoreCase);
            routeValues.Add(LinkGenerationConstants.Controller, entityContext.EntitySet.Name);
            routeValues.Add(LinkGenerationConstants.BoundId, ConventionsHelpers.GetEntityKeyValue(entityContext, actionEntityType));
            routeValues.Add(LinkGenerationConstants.ODataAction, action.Name);

            string routeName;

            // generate link without cast if the entityset type matches the entity type the action is bound to.
            if (entityContext.EntitySet.ElementType.IsOrInheritsFrom(entityContext.EdmModel.FindDeclaredType(actionEntityType.FullName)))
            {
                routeName = ODataRouteNames.InvokeBoundAction;
            }
            else
            {
                routeName = ODataRouteNames.InvokeBoundActionWithCast;
                routeValues.Add(LinkGenerationConstants.Entitytype, entityContext.EntityType.FullName());
            }

            string actionLink = entityContext.UrlHelper.Link(routeName, routeValues);

            if (actionLink == null)
            {
                return null;
            }
            else
            {
                return new Uri(actionLink);
            }
        }
        internal static Uri GenerateActionLink(EntityInstanceContext entityContext, ActionConfiguration action)
        {
            // the entity type the action is bound to.
            EntityTypeConfiguration actionEntityType = action.BindingParameter.TypeConfiguration as EntityTypeConfiguration;
            Contract.Assert(actionEntityType != null, "we have already verified that binding paramter type is entity");

            List<ODataPathSegment> actionPathSegments = new List<ODataPathSegment>();
            actionPathSegments.Add(new EntitySetPathSegment(entityContext.EntitySet));
            actionPathSegments.Add(new KeyValuePathSegment(ConventionsHelpers.GetEntityKeyValue(entityContext)));

            // generate link with cast if the entityset type doesn't match the entity type the action is bound to.
            if (!entityContext.EntitySet.ElementType.IsOrInheritsFrom(entityContext.EdmModel.FindDeclaredType(actionEntityType.FullName)))
            {
                actionPathSegments.Add(new CastPathSegment(entityContext.EntityType));
            }

            actionPathSegments.Add(new ActionPathSegment(action.Name));

            string actionLink = entityContext.Url.ODataLink(actionPathSegments);

            if (actionLink == null)
            {
                return null;
            }

            return new Uri(actionLink);
        }
Exemplo n.º 3
0
 internal bool Override( IActivityMonitor monitor, IReadOnlyList<string> fullPath, ActionConfiguration a )
 {
     var e = fullPath.GetEnumerator();
     if( !e.MoveNext() ) throw new ArgumentException( "Must not be empty.", "fullPath" );
     if( e.Current != _action.Name ) throw new ArgumentException( "Must start with the action name.", "fullPath" );
     if( !e.MoveNext() )
     {
         _action = a;
         _isCloned = false;
         monitor.SendLine( LogLevel.Info, string.Format( "Action '{0}' has been overridden.", a.Name ), null );
         return true;
     }
     ActionCompositeConfiguration parent;
     int idx = FindInComposite( e, out parent );
     if( idx >= 0 )
     {
         Debug.Assert( _action is ActionCompositeConfiguration, "It is a composite." );
         Debug.Assert( _action.IsCloneable, "A composite is cloneable." );
         if( !_isCloned )
         {
             _action = ((ActionCompositeConfiguration)_action).CloneComposite( true );
             monitor.SendLine( LogLevel.Info, string.Format( "Action '{0}' has been cloned in order to override an inner action.", string.Join( "/", fullPath ) ), null );
             _isCloned = true;
             idx = FindInComposite( e, out parent );
         }
         Debug.Assert( parent.Children[idx].Name == fullPath.Last() );
         parent.Override( idx, a );
         monitor.SendLine( LogLevel.Info, string.Format( "Inner action '{0}' has been overridden.", string.Join( "/", fullPath ) ), null );
         return true;
     }
     monitor.SendLine( LogLevel.Error, string.Format( "Action '{0}' not found. Unable to override it.", string.Join( "/", fullPath ) ), null );
     return false;
 }
        public FileEventListener Create(ISolutionProject project, ActionConfiguration actionConfiguration)
        {
            var fileChangeSubscriber = new FileChangeSubscriber(this.fileChangeService);
            var fileMonitor = new FileMonitor(this.solutionFilesService, this.globMatcher, fileChangeSubscriber, this.outputService);

            var eventListener = new FileEventListener(fileMonitor, this.onChangeTaskDispatcher, this.actionFactory, fileChangeSubscriber);
            eventListener.Initialize(project, actionConfiguration);
            return eventListener;
        }
        public void CanRemoveProcedureByName()
        {
            // Arrange
            // Act
            ODataModelBuilder builder = new ODataModelBuilder();
            ActionConfiguration action = new ActionConfiguration(builder, "Format");
            bool removed = builder.RemoveProcedure("Format");

            // Assert      
            Assert.Equal(0, builder.Procedures.Count());
        }
        public void CanCreateActionWithPrimitiveCollectionReturnType()
        {
            // Arrange
            // Act
            ODataModelBuilder builder = new ODataModelBuilder();
            ActionConfiguration action = new ActionConfiguration(builder, "CreateMessages");
            action.ReturnsCollection<string>();

            // Assert
            Assert.NotNull(action.ReturnType);
            Assert.Equal("Collection(Edm.String)", action.ReturnType.FullName);
        }
        public void CanBuildBoundProcedureCacheForIEdmModel()
        {
            // Arrange            
            ODataModelBuilder builder = new ODataModelBuilder();
            EntityTypeConfiguration<Customer> customer = builder.EntitySet<Customer>("Customers").EntityType;
            customer.HasKey(c => c.ID);
            customer.Property(c => c.Name);
            customer.ComplexProperty(c => c.Address);

            EntityTypeConfiguration<Movie> movie = builder.EntitySet<Movie>("Movies").EntityType;
            movie.HasKey(m => m.ID);
            movie.HasKey(m => m.Name);
            EntityTypeConfiguration<Blockbuster> blockBuster = builder.Entity<Blockbuster>().DerivesFrom<Movie>();
            IEntityTypeConfiguration movieConfiguration = builder.StructuralTypes.OfType<IEntityTypeConfiguration>().Single(t => t.Name == "Movie");

            // build actions that are bindable to a single entity
            customer.Action("InCache1_CustomerAction");
            customer.Action("InCache2_CustomerAction");
            movie.Action("InCache3_MovieAction");
            ActionConfiguration incache4_MovieAction = new ActionConfiguration(builder, "InCache4_MovieAction");
            incache4_MovieAction.SetBindingParameter("bindingParameter", movieConfiguration, true);
            blockBuster.Action("InCache5_BlockbusterAction");

            // build actions that are either: bindable to a collection of entities, have no parameter, have only complex parameter 
            customer.Collection.Action("NotInCache1_CustomersAction");
            movie.Collection.Action("NotInCache2_MoviesAction");
            ActionConfiguration notInCache3_NoParameters = new ActionConfiguration(builder, "NotInCache3_NoParameters");
            ActionConfiguration notInCache4_AddressParameter = new ActionConfiguration(builder, "NotInCache4_AddressParameter");
            notInCache4_AddressParameter.Parameter<Address>("address");

            IEdmModel model = builder.GetEdmModel();
            IEdmEntityType customerType = model.SchemaElements.OfType<IEdmEntityType>().Single(e => e.Name == "Customer");
            IEdmEntityType movieType = model.SchemaElements.OfType<IEdmEntityType>().Single(e => e.Name == "Movie");
            IEdmEntityType blockBusterType = model.SchemaElements.OfType<IEdmEntityType>().Single(e => e.Name == "Blockbuster");

            // Act 
            BindableProcedureFinder annotation = new BindableProcedureFinder(model);
            IEdmFunctionImport[] movieActions = annotation.FindProcedures(movieType).ToArray();
            IEdmFunctionImport[] customerActions = annotation.FindProcedures(customerType).ToArray();
            IEdmFunctionImport[] blockBusterActions = annotation.FindProcedures(blockBusterType).ToArray();

            // Assert
            Assert.Equal(2, customerActions.Length);
            Assert.NotNull(customerActions.SingleOrDefault(a => a.Name == "InCache1_CustomerAction"));
            Assert.NotNull(customerActions.SingleOrDefault(a => a.Name == "InCache2_CustomerAction"));
            Assert.Equal(2, movieActions.Length);
            Assert.NotNull(movieActions.SingleOrDefault(a => a.Name == "InCache3_MovieAction"));
            Assert.NotNull(movieActions.SingleOrDefault(a => a.Name == "InCache4_MovieAction"));
            Assert.Equal(3, blockBusterActions.Length);
            Assert.NotNull(blockBusterActions.SingleOrDefault(a => a.Name == "InCache3_MovieAction"));
            Assert.NotNull(blockBusterActions.SingleOrDefault(a => a.Name == "InCache4_MovieAction"));
            Assert.NotNull(blockBusterActions.SingleOrDefault(a => a.Name == "InCache5_BlockbusterAction"));
        }
        public void CanRemoveProcedure()
        {
            // Arrange
            // Act
            ODataModelBuilder builder = new ODataModelBuilder();
            ActionConfiguration action = new ActionConfiguration(builder, "Format");
            ProcedureConfiguration procedure = builder.Procedures.SingleOrDefault();
            bool removed = builder.RemoveProcedure(procedure);

            // Assert
            Assert.True(removed);
            Assert.Equal(0, builder.Procedures.Count());
        }
        public void RemoveProcedureByNameThrowsWhenAmbiguous()
        {
            // Arrange
            // Act
            ODataModelBuilder builder = new ODataModelBuilder();

            ActionConfiguration action1 = new ActionConfiguration(builder, "Format");
            ActionConfiguration action2 = new ActionConfiguration(builder, "Format");
            action2.Parameter<int>("SegmentSize");

            Assert.Throws<InvalidOperationException>(() =>
            {
                builder.RemoveProcedure("Format");
            });
        }
        public void AttemptToRemoveNonExistantEntityReturnsFalse()
        {
            // Arrange
            ODataModelBuilder builder = new ODataModelBuilder();
            ODataModelBuilder builder2 = new ODataModelBuilder();
            ProcedureConfiguration toRemove = new ActionConfiguration(builder2, "ToRemove");
            
            // Act
            bool removedByName = builder.RemoveProcedure("ToRemove");
            bool removed = builder.RemoveProcedure(toRemove);

            //Assert
            Assert.False(removedByName);
            Assert.False(removed);
        }
        public void Apply_FollowsConventions()
        {
            // Arrange
            ODataModelBuilder builder = new ODataModelBuilder();
            ActionConfiguration action = new ActionConfiguration(builder, "IgnoreAction");
            Mock<IEdmTypeConfiguration> mockBindingParameterType = new Mock<IEdmTypeConfiguration>();
            mockBindingParameterType.Setup(o => o.Kind).Returns(EdmTypeKind.Entity);
            action.SetBindingParameter("IgnoreParameter", mockBindingParameterType.Object, alwaysBindable: false);
            ActionLinkGenerationConvention convention = new ActionLinkGenerationConvention();

            // Act
            convention.Apply(action, builder);

            // Assert
            Assert.True(action.FollowsConventions);
        }
        public void CanCreateActionWithNoArguments()
        {
            // Arrange
            // Act
            ODataModelBuilder builder = new ODataModelBuilder();
            builder.Namespace = "MyNamespace";
            builder.ContainerName = "MyContainer";
            ActionConfiguration action = new ActionConfiguration(builder, "Format");

            // Assert
            Assert.Equal("Format", action.Name);
            Assert.Equal(ProcedureKind.Action, action.Kind);
            Assert.NotNull(action.Parameters);
            Assert.Empty(action.Parameters);
            Assert.Null(action.ReturnType);
            Assert.True(action.IsSideEffecting);
            Assert.False(action.IsComposable);
            Assert.False(action.IsBindable);
            Assert.Equal("MyContainer.Format", action.ContainerQualifiedName);
            Assert.Equal("MyContainer.Format", action.FullName);
            Assert.Equal("MyNamespace.MyContainer.Format", action.FullyQualifiedName);
            Assert.NotNull(builder.Procedures);
            Assert.Equal(1, builder.Procedures.Count());
        }
 private static IEdmExpression GetEdmEntitySetExpression(Dictionary<string, EdmEntitySet> entitySets, ActionConfiguration action)
 {
     if (action.EntitySet != null)
     {
         if (entitySets.ContainsKey(action.EntitySet.Name))
         {
             EdmEntitySet entitySet = entitySets[action.EntitySet.Name];
             return new EdmEntitySetReferenceExpression(entitySet);
         }
         else
         {
             throw Error.InvalidOperation(SRResources.EntitySetNotFoundForName, action.EntitySet.Name);
         }
     }
     return null;
 }
        public void ActionLink_PreservesFollowsConventions(bool value)
        {
            // Arrange
            ODataModelBuilder builder = ODataModelBuilderMocks.GetModelBuilderMock<ODataModelBuilder>();
            ActionConfiguration configuration = new ActionConfiguration(builder, "IgnoreAction");
            Mock<IEdmTypeConfiguration> bindingParameterTypeMock = new Mock<IEdmTypeConfiguration>();
            bindingParameterTypeMock.Setup(o => o.Kind).Returns(EdmTypeKind.Entity);
            Type entityType = typeof(object);
            bindingParameterTypeMock.Setup(o => o.ClrType).Returns(entityType);
            configuration.SetBindingParameter("IgnoreParameter", bindingParameterTypeMock.Object,
                alwaysBindable: false);
            configuration.HasActionLink((a) => { throw new NotImplementedException(); }, followsConventions: value);
            builder.AddProcedure(configuration);
            builder.AddEntityType(entityType);

            // Act
            IEdmModel model = builder.GetEdmModel();

            // Assert
            var action = Assert.Single(model.SchemaElements.OfType<IEdmAction>());
            ActionLinkBuilder actionLinkBuilder = model.GetActionLinkBuilder(action);
            Assert.NotNull(actionLinkBuilder);
            Assert.Equal(value, actionLinkBuilder.FollowsConventions);
        }
Exemplo n.º 15
0
        protected void RegisterProduct(ODataConventionModelBuilder builder)
        {
            builder.EntitySet <ProductDto>("Product");
            var product = builder.EntityType <ProductDto>();

            product.Count().Filter().OrderBy().Page();
            builder.ComplexType <ProductCategoryDto>();
            builder.ComplexType <ProductManufacturerDto>();
            builder.ComplexType <ProductPictureDto>();
            builder.ComplexType <ProductSpecificationAttributeDto>();
            builder.ComplexType <ProductTierPriceDto>();
            builder.ComplexType <ProductWarehouseInventoryDto>();
            builder.ComplexType <ProductAttributeMappingDto>();
            builder.ComplexType <ProductAttributeValueDto>();
            builder.ComplexType <ProductAttributeCombinationDto>();

            //update stock for product
            ActionConfiguration updateStock = product.Action("UpdateStock");

            updateStock.Parameter <string>("WarehouseId");
            updateStock.Parameter <int>("Stock").Required();
            updateStock.Returns <bool>();

            //insert/update/delete category
            #region Product category
            ActionConfiguration createCategory = product.Action("CreateProductCategory");
            createCategory.Parameter <string>(nameof(ProductCategoryDto.CategoryId)).Required();
            createCategory.Parameter <bool>(nameof(ProductCategoryDto.IsFeaturedProduct));
            createCategory.Returns <bool>();

            ActionConfiguration updateCategory = product.Action("UpdateProductCategory");
            updateCategory.Parameter <string>(nameof(ProductCategoryDto.CategoryId)).Required();
            updateCategory.Parameter <bool>(nameof(ProductCategoryDto.IsFeaturedProduct));
            updateCategory.Returns <bool>();

            ActionConfiguration deleteCategory = product.Action("DeleteProductCategory");
            deleteCategory.Parameter <string>(nameof(ProductCategoryDto.CategoryId)).Required();
            deleteCategory.Returns <bool>();
            #endregion

            //insert/update/delete manufacturer
            #region Product manufacturer
            ActionConfiguration createManufacturer = product.Action("CreateProductManufacturer");
            createManufacturer.Parameter <string>(nameof(ProductManufacturerDto.ManufacturerId)).Required();
            createManufacturer.Parameter <bool>(nameof(ProductManufacturerDto.IsFeaturedProduct));
            createManufacturer.Returns <bool>();

            ActionConfiguration updateManufacturer = product.Action("UpdateProductManufacturer");
            updateManufacturer.Parameter <string>(nameof(ProductManufacturerDto.ManufacturerId)).Required();
            updateManufacturer.Parameter <bool>(nameof(ProductManufacturerDto.IsFeaturedProduct));
            updateManufacturer.Returns <bool>();

            ActionConfiguration deleteManufacturer = product.Action("DeleteProductManufacturer");
            deleteManufacturer.Parameter <string>(nameof(ProductManufacturerDto.ManufacturerId)).Required();
            deleteManufacturer.Returns <bool>();
            #endregion

            //insert/update/delete picture
            #region Product picture
            ActionConfiguration createPicture = product.Action("CreateProductPicture");
            createPicture.Parameter <string>(nameof(ProductPictureDto.PictureId)).Required();
            createPicture.Parameter <string>(nameof(ProductPictureDto.MimeType)).Required();
            createPicture.Parameter <string>(nameof(ProductPictureDto.SeoFilename)).Required();
            createPicture.Parameter <string>(nameof(ProductPictureDto.AltAttribute)).Required();
            createPicture.Parameter <int>(nameof(ProductPictureDto.DisplayOrder)).Required();
            createPicture.Parameter <string>(nameof(ProductPictureDto.TitleAttribute)).Required();
            createPicture.Returns <bool>();

            ActionConfiguration updatePicture = product.Action("UpdateProductPicture");
            updatePicture.Parameter <string>(nameof(ProductPictureDto.PictureId)).Required();
            updatePicture.Parameter <string>(nameof(ProductPictureDto.MimeType)).Required();
            updatePicture.Parameter <string>(nameof(ProductPictureDto.SeoFilename)).Required();
            updatePicture.Parameter <string>(nameof(ProductPictureDto.AltAttribute)).Required();
            updatePicture.Parameter <int>(nameof(ProductPictureDto.DisplayOrder)).Required();
            updatePicture.Parameter <string>(nameof(ProductPictureDto.TitleAttribute)).Required();
            updatePicture.Returns <bool>();

            ActionConfiguration deletePicture = product.Action("DeleteProductPicture");
            deletePicture.Parameter <string>(nameof(ProductPictureDto.PictureId)).Required();
            deletePicture.Returns <bool>();
            #endregion

            #region Product specification
            ActionConfiguration createSpecification = product.Action("CreateProductSpecification");
            createSpecification.Parameter <string>(nameof(ProductSpecificationAttributeDto.Id));
            createSpecification.Parameter <int>(nameof(ProductSpecificationAttributeDto.DisplayOrder));
            createSpecification.Parameter <string>(nameof(ProductSpecificationAttributeDto.CustomValue));
            createSpecification.Parameter <SpecificationAttributeType>(nameof(ProductSpecificationAttributeDto.AttributeType)).Required();
            createSpecification.Parameter <bool>(nameof(ProductSpecificationAttributeDto.AllowFiltering));
            createSpecification.Parameter <string>(nameof(ProductSpecificationAttributeDto.SpecificationAttributeId));
            createSpecification.Parameter <bool>(nameof(ProductSpecificationAttributeDto.ShowOnProductPage));
            createSpecification.Parameter <string>(nameof(ProductSpecificationAttributeDto.SpecificationAttributeOptionId));

            createSpecification.Returns <bool>();

            ActionConfiguration updateSpecification = product.Action("UpdateProductSpecification");
            updateSpecification.Parameter <string>(nameof(ProductSpecificationAttributeDto.Id)).Required();
            updateSpecification.Parameter <int>(nameof(ProductSpecificationAttributeDto.DisplayOrder));
            updateSpecification.Parameter <string>(nameof(ProductSpecificationAttributeDto.CustomValue));
            updateSpecification.Parameter <SpecificationAttributeType>(nameof(ProductSpecificationAttributeDto.AttributeType)).Required();
            updateSpecification.Parameter <bool>(nameof(ProductSpecificationAttributeDto.AllowFiltering));
            updateSpecification.Parameter <string>(nameof(ProductSpecificationAttributeDto.SpecificationAttributeId)).Required();
            updateSpecification.Parameter <bool>(nameof(ProductSpecificationAttributeDto.ShowOnProductPage));
            updateSpecification.Parameter <string>(nameof(ProductSpecificationAttributeDto.SpecificationAttributeOptionId));
            updateSpecification.Returns <bool>();

            ActionConfiguration deleteSpecification = product.Action("DeleteProductSpecification");
            deleteSpecification.Parameter <string>(nameof(ProductSpecificationAttributeDto.Id)).Required();
            deleteSpecification.Returns <bool>();
            #endregion

            #region Product attribute mapping

            ActionConfiguration createProductAttributeMapping = product.Action("CreateProductAttributeMapping");
            createProductAttributeMapping.Parameter <string>(nameof(ProductAttributeMappingDto.Id));
            createProductAttributeMapping.Parameter <int>(nameof(ProductAttributeMappingDto.DisplayOrder));
            createProductAttributeMapping.Parameter <string>(nameof(ProductAttributeMappingDto.ConditionAttributeXml));
            createProductAttributeMapping.Parameter <AttributeControlType>(nameof(ProductAttributeMappingDto.AttributeControlType)).Required();
            createProductAttributeMapping.Parameter <string>(nameof(ProductAttributeMappingDto.DefaultValue));
            createProductAttributeMapping.Parameter <bool>(nameof(ProductAttributeMappingDto.IsRequired));
            createProductAttributeMapping.Parameter <string>(nameof(ProductAttributeMappingDto.TextPrompt));
            createProductAttributeMapping.Parameter <string>(nameof(ProductAttributeMappingDto.ValidationFileAllowedExtensions));
            createProductAttributeMapping.Parameter <int?>(nameof(ProductAttributeMappingDto.ValidationFileMaximumSize));
            createProductAttributeMapping.Parameter <int?>(nameof(ProductAttributeMappingDto.ValidationMaxLength));
            createProductAttributeMapping.Parameter <int?>(nameof(ProductAttributeMappingDto.ValidationMinLength));
            createProductAttributeMapping.Parameter <List <ProductAttributeValueDto> >(nameof(ProductAttributeMappingDto.ProductAttributeValues));
            createProductAttributeMapping.Returns <ProductAttributeMappingDto>();

            ActionConfiguration updateProductAttributeMapping = product.Action("UpdateProductAttributeMapping");
            updateProductAttributeMapping.Parameter <string>(nameof(ProductAttributeMappingDto.Id)).Required();
            updateProductAttributeMapping.Parameter <int>(nameof(ProductAttributeMappingDto.DisplayOrder));
            updateProductAttributeMapping.Parameter <string>(nameof(ProductAttributeMappingDto.ConditionAttributeXml));
            updateProductAttributeMapping.Parameter <AttributeControlType>(nameof(ProductAttributeMappingDto.AttributeControlType)).Required();
            updateProductAttributeMapping.Parameter <string>(nameof(ProductAttributeMappingDto.DefaultValue));
            updateProductAttributeMapping.Parameter <bool>(nameof(ProductAttributeMappingDto.IsRequired));
            updateProductAttributeMapping.Parameter <string>(nameof(ProductAttributeMappingDto.TextPrompt));
            updateProductAttributeMapping.Parameter <string>(nameof(ProductAttributeMappingDto.ValidationFileAllowedExtensions));
            updateProductAttributeMapping.Parameter <int?>(nameof(ProductAttributeMappingDto.ValidationFileMaximumSize));
            updateProductAttributeMapping.Parameter <int?>(nameof(ProductAttributeMappingDto.ValidationMaxLength));
            updateProductAttributeMapping.Parameter <int?>(nameof(ProductAttributeMappingDto.ValidationMinLength));
            updateProductAttributeMapping.Parameter <List <ProductAttributeValueDto> >(nameof(ProductAttributeMappingDto.ProductAttributeValues));
            updateProductAttributeMapping.Returns <ProductAttributeMappingDto>();

            ActionConfiguration deleteProductAttributeMapping = product.Action("DeleteProductAttributeMapping");
            deleteProductAttributeMapping.Parameter <string>(nameof(ProductSpecificationAttributeDto.Id)).Required();
            deleteProductAttributeMapping.Returns <bool>();

            #endregion

            //insert/update/delete tier price
            #region Product tierprice

            ActionConfiguration createTierPrice = product.Action("CreateProductTierPrice");
            createTierPrice.Parameter <int>(nameof(ProductTierPriceDto.Quantity));
            createTierPrice.Parameter <decimal>(nameof(ProductTierPriceDto.Price));
            createTierPrice.Parameter <string>(nameof(ProductTierPriceDto.StoreId));
            createTierPrice.Parameter <string>(nameof(ProductTierPriceDto.CustomerRoleId));
            createTierPrice.Parameter <DateTime?>(nameof(ProductTierPriceDto.StartDateTimeUtc));
            createTierPrice.Parameter <DateTime?>(nameof(ProductTierPriceDto.EndDateTimeUtc));
            createTierPrice.Returns <bool>();

            ActionConfiguration updateTierPrice = product.Action("UpdateProductTierPrice");
            updateTierPrice.Parameter <string>(nameof(ProductTierPriceDto.Id)).Required();
            updateTierPrice.Parameter <int>(nameof(ProductTierPriceDto.Quantity));
            updateTierPrice.Parameter <decimal>(nameof(ProductTierPriceDto.Price));
            updateTierPrice.Parameter <string>(nameof(ProductTierPriceDto.StoreId));
            updateTierPrice.Parameter <string>(nameof(ProductTierPriceDto.CustomerRoleId));
            updateTierPrice.Parameter <DateTime?>(nameof(ProductTierPriceDto.StartDateTimeUtc));
            updateTierPrice.Parameter <DateTime?>(nameof(ProductTierPriceDto.EndDateTimeUtc));
            updateTierPrice.Returns <bool>();

            ActionConfiguration deleteTierPrice = product.Action("DeleteProductTierPrice");
            deleteTierPrice.Parameter <string>(nameof(ProductTierPriceDto.Id)).Required();
            deleteTierPrice.Returns <bool>();

            #endregion
        }
Exemplo n.º 16
0
 bool IProtoRouteConfigurationContext.DeclareAction( ActionConfiguration a, bool overridden )
 {
     if( a == null ) throw new ArgumentNullException();
     ProtoDeclaredAction existsHere;
     if( _declaredActions.TryGetValue( a.Name, out existsHere ) )
     {
         if( overridden )
         {
             _declaredActions[a.Name] = new ProtoDeclaredAction( a );
             Monitor.SendLine( LogLevel.Info, string.Format( "Action '{0}' is overridden", a.Name ), null );
             return true;
         }
         Monitor.SendLine( LogLevel.Error, string.Format( "Action '{0}' is already declared. Use Override to alter it or use another name.", a.Name ), null );
         return false;
     }
     _declaredActions.Add( a.Name, new ProtoDeclaredAction( a ) );
     return true;
 }
Exemplo n.º 17
0
        public static string GetStringReplacedQuery(HttpRequest request, RouteConfiguration route, ActionConfiguration action, object id, string json = null)
        {
            string sqlQuery = GetStringReplacedQuery(request, route, action, json);

            sqlQuery = sqlQuery.Replace(ID_SYMBOL, id.ToString());

            return(sqlQuery);
        }
Exemplo n.º 18
0
        public static string GetStringReplacedQuery(HttpRequest request, RouteConfiguration route, ActionConfiguration action, string json = null)
        {
            if (String.IsNullOrEmpty(action.Query))
            {
                throw new Exception("The action query is required.");
            }

            string sqlQuery = action.Query;

            sqlQuery = sqlQuery.Replace(SCHEMA_SYMBOL, route.Schema);
            sqlQuery = sqlQuery.Replace(TABLE_SYMBOL, route.Table);
            sqlQuery = sqlQuery.Replace(SCHEMA_TABLE_SYMBOL, GetSchemaTableName(route));

            // extract OData query information
            List <string> odataSelectColumns = new List <string>();

            //string odataTopValue = null;
            foreach (KeyValuePair <String, StringValues> query in request.Query)
            {
                if (query.Key.ToLower() == "$select")
                {
                    odataSelectColumns = query.Value.ToString().Split(',').ToList();
                }
                //else if (query.Key.ToLower() == "$top")
                //{
                //    odataTopValue = query.Value.ToString();
                //}
            }


            List <string> selectString = new List <string>();

            if (route.Columns.Any())
            {
                if (odataSelectColumns.Count > 0)
                {
                    foreach (string odataSelectColumn in odataSelectColumns)
                    {
                        if (route.Columns.Find(cc => cc.ColumnName == odataSelectColumn) != null)
                        {
                            selectString.Add(odataSelectColumn);
                        }
                        else
                        {
                            throw new Exception("The OData $SELECT column '" + odataSelectColumn + "' is not a configured property for route '" + route.Name + "'.");
                        }
                    }
                }
                else
                {
                    foreach (ColumnConfiguration column in route.Columns)
                    {
                        selectString.Add(column.ColumnName);
                    }
                }
            }
            else
            {
                if (odataSelectColumns.Count > 0)
                {
                    selectString = odataSelectColumns;
                }
                else
                {
                    selectString.Add("*");
                }
            }

            sqlQuery = sqlQuery.Replace(COLUMN_NAMES_SYMBOL, String.Join(",", selectString));

            //if (odataTopValue != null)
            //{
            //    int indexOfFirstSelect = sqlQuery.ToLower().IndexOf("select");
            //    sqlQuery = sqlQuery.Insert(indexOfFirstSelect + 6, " TOP " + odataTopValue);
            //}

            sqlQuery = sqlQuery.Replace(PRIMARY_KEY_COLUMN_SYMBOL, route.PrimaryKeyColumn);

            if (!String.IsNullOrEmpty(json))
            {
                sqlQuery = ReplaceBodyColumnNamesAndValues(sqlQuery, json);
            }

            return(sqlQuery);
        }
Exemplo n.º 19
0
        public static ActionConfiguration ActionReturnsCollectionFromEntitySet <TElementEntityType>(ODataModelBuilder builder, ActionConfiguration action, string entitySetName) where TElementEntityType : class
        {
            Type clrCollectionType = typeof(IEnumerable <TElementEntityType>);

            action.NavigationSource = CreateOrReuseEntitySet <TElementEntityType>(builder, entitySetName);
            IEdmTypeConfiguration elementType = builder.GetTypeConfigurationOrNull(typeof(TElementEntityType));

            action.ReturnType = new CollectionTypeConfiguration(elementType, clrCollectionType);
            return(action);
        }
Exemplo n.º 20
0
        protected void RegisterCustomers(ODataConventionModelBuilder builder)
        {
            #region Customer

            builder.EntitySet <CustomerDto>("Customer");
            var customer = builder.EntityType <CustomerDto>();
            builder.ComplexType <AddressDto>();

            ActionConfiguration addAddress = customer.Action("AddAddress");
            addAddress.Parameter <string>(nameof(AddressDto.Id)).Required();
            addAddress.Parameter <string>(nameof(AddressDto.City));
            addAddress.Parameter <string>(nameof(AddressDto.Email));
            addAddress.Parameter <string>(nameof(AddressDto.Company));
            addAddress.Parameter <string>(nameof(AddressDto.Address1));
            addAddress.Parameter <string>(nameof(AddressDto.Address2));
            addAddress.Parameter <string>(nameof(AddressDto.LastName));
            addAddress.Parameter <string>(nameof(AddressDto.CountryId));
            addAddress.Parameter <string>(nameof(AddressDto.FaxNumber));
            addAddress.Parameter <string>(nameof(AddressDto.FirstName));
            addAddress.Parameter <string>(nameof(AddressDto.VatNumber));
            addAddress.Parameter <string>(nameof(AddressDto.PhoneNumber));
            addAddress.Parameter <string>(nameof(AddressDto.CustomAttributes));
            addAddress.Parameter <DateTimeOffset>(nameof(AddressDto.CreatedOnUtc));
            addAddress.Parameter <string>(nameof(AddressDto.ZipPostalCode));
            addAddress.Parameter <string>(nameof(AddressDto.StateProvinceId));
            addAddress.Returns <AddressDto>();

            ActionConfiguration updateAddress = customer.Action("UpdateAddress");
            updateAddress.Parameter <string>(nameof(AddressDto.Id)).Required();
            updateAddress.Parameter <string>(nameof(AddressDto.City));
            updateAddress.Parameter <string>(nameof(AddressDto.Email));
            updateAddress.Parameter <string>(nameof(AddressDto.Company));
            updateAddress.Parameter <string>(nameof(AddressDto.Address1));
            updateAddress.Parameter <string>(nameof(AddressDto.Address2));
            updateAddress.Parameter <string>(nameof(AddressDto.LastName));
            updateAddress.Parameter <string>(nameof(AddressDto.CountryId));
            updateAddress.Parameter <string>(nameof(AddressDto.FaxNumber));
            updateAddress.Parameter <string>(nameof(AddressDto.FirstName));
            updateAddress.Parameter <string>(nameof(AddressDto.VatNumber));
            updateAddress.Parameter <string>(nameof(AddressDto.PhoneNumber));
            updateAddress.Parameter <string>(nameof(AddressDto.CustomAttributes));
            updateAddress.Parameter <DateTimeOffset>(nameof(AddressDto.CreatedOnUtc));
            updateAddress.Parameter <string>(nameof(AddressDto.ZipPostalCode));
            updateAddress.Parameter <string>(nameof(AddressDto.StateProvinceId));
            updateAddress.Returns <AddressDto>();

            ActionConfiguration deleteAddress = customer.Action("DeleteAddress");
            deleteAddress.Parameter <string>("addressId");
            deleteAddress.Returns <bool>();

            ActionConfiguration changePassword = customer.Action("SetPassword");
            changePassword.Parameter <string>("password");
            changePassword.Returns <bool>();

            #endregion

            #region Customer Role model

            builder.EntitySet <CustomerRoleDto>("CustomerRole");
            builder.EntityType <CustomerRoleDto>().Count().Filter().OrderBy().Page();

            #endregion

            #region Vendors

            builder.EntitySet <VendorDto>("Vendor");
            builder.EntityType <VendorDto>().Count().Filter().OrderBy().Page();

            #endregion
        }
Exemplo n.º 21
0
        public static IEdmModel GetModel(IAssemblyProvider assemblyProvider)
        {
            if (_model != null)
            {
                return(_model);
            }

            ODataConventionModelBuilder builder = new ODataConventionModelBuilder(assemblyProvider);

            builder.EntitySet <RoutingCustomer>("RoutingCustomers");
            builder.EntitySet <Product>("Products");
            builder.EntitySet <SalesPerson>("SalesPeople");
            builder.EntitySet <EmailAddress>("EmailAddresses");
            builder.EntitySet <üCategory>("üCategories");
            builder.EntitySet <EnumCustomer>("EnumCustomers");
            builder.Singleton <RoutingCustomer>("VipCustomer");
            builder.Singleton <Product>("MyProduct");
            builder.EntitySet <DateTimeOffsetKeyCustomer>("DateTimeOffsetKeyCustomers");
            builder.EntitySet <Destination>("Destinations");
            builder.ComplexType <Dog>();
            builder.ComplexType <Cat>();
            builder.EntityType <SpecialProduct>();
            builder.ComplexType <UsAddress>();

            ActionConfiguration getRoutingCustomerById = builder.Action("GetRoutingCustomerById");

            getRoutingCustomerById.Parameter <int>("RoutingCustomerId");
            getRoutingCustomerById.ReturnsFromEntitySet <RoutingCustomer>("RoutingCustomers");

            ActionConfiguration getSalesPersonById = builder.Action("GetSalesPersonById");

            getSalesPersonById.Parameter <int>("salesPersonId");
            getSalesPersonById.ReturnsFromEntitySet <SalesPerson>("SalesPeople");

            ActionConfiguration getAllVIPs = builder.Action("GetAllVIPs");

            ActionReturnsCollectionFromEntitySet <VIP>(builder, getAllVIPs, "RoutingCustomers");

            builder.EntityType <RoutingCustomer>().ComplexProperty <Address>(c => c.Address);
            builder.EntityType <RoutingCustomer>().Action("GetRelatedRoutingCustomers").ReturnsCollectionFromEntitySet <RoutingCustomer>("RoutingCustomers");

            ActionConfiguration getBestRelatedRoutingCustomer = builder.EntityType <RoutingCustomer>().Action("GetBestRelatedRoutingCustomer");

            ActionReturnsFromEntitySet <VIP>(builder, getBestRelatedRoutingCustomer, "RoutingCustomers");

            ActionConfiguration getVIPS = builder.EntityType <RoutingCustomer>().Collection.Action("GetVIPs");

            ActionReturnsCollectionFromEntitySet <VIP>(builder, getVIPS, "RoutingCustomers");

            builder.EntityType <RoutingCustomer>().Collection.Action("GetProducts").ReturnsCollectionFromEntitySet <Product>("Products");
            builder.EntityType <VIP>().Action("GetSalesPerson").ReturnsFromEntitySet <SalesPerson>("SalesPeople");
            builder.EntityType <VIP>().Collection.Action("GetSalesPeople").ReturnsCollectionFromEntitySet <SalesPerson>("SalesPeople");

            ActionConfiguration getMostProfitable = builder.EntityType <VIP>().Collection.Action("GetMostProfitable");

            ActionReturnsFromEntitySet <VIP>(builder, getMostProfitable, "RoutingCustomers");

            ActionConfiguration getVIPRoutingCustomers = builder.EntityType <SalesPerson>().Action("GetVIPRoutingCustomers");

            ActionReturnsCollectionFromEntitySet <VIP>(builder, getVIPRoutingCustomers, "RoutingCustomers");

            ActionConfiguration getVIPRoutingCustomersOnCollection = builder.EntityType <SalesPerson>().Collection.Action("GetVIPRoutingCustomers");

            ActionReturnsCollectionFromEntitySet <VIP>(builder, getVIPRoutingCustomersOnCollection, "RoutingCustomers");

            builder.EntityType <VIP>().HasRequired(v => v.RelationshipManager);
            builder.EntityType <ImportantProduct>().HasRequired(ip => ip.LeadSalesPerson);

            // function bound to an entity
            FunctionConfiguration topProductId = builder.EntityType <Product>().Function("TopProductId");

            topProductId.Returns <int>();

            FunctionConfiguration topProductIdByCity = builder.EntityType <Product>().Function("TopProductIdByCity");

            topProductIdByCity.Parameter <string>("city");
            topProductIdByCity.Returns <string>();

            FunctionConfiguration topProductIdByCityAndModel = builder.EntityType <Product>().Function("TopProductIdByCityAndModel");

            topProductIdByCityAndModel.Parameter <string>("city");
            topProductIdByCityAndModel.Parameter <int>("model");
            topProductIdByCityAndModel.Returns <string>();

            // function bound to a collection of entities
            FunctionConfiguration topProductOfAll = builder.EntityType <Product>().Collection.Function("TopProductOfAll");

            topProductOfAll.Returns <string>();

            FunctionConfiguration topProductOfAllByCity = builder.EntityType <Product>().Collection.Function("TopProductOfAllByCity");

            topProductOfAllByCity.Parameter <string>("city");
            topProductOfAllByCity.Returns <string>();

            FunctionConfiguration copyProductByCity = builder.EntityType <Product>().Function("CopyProductByCity");

            copyProductByCity.Parameter <string>("city");
            copyProductByCity.Returns <string>();

            FunctionConfiguration topProductOfAllByCityAndModel = builder.EntityType <Product>().Collection.Function("TopProductOfAllByCityAndModel");

            topProductOfAllByCityAndModel.Parameter <string>("city");
            topProductOfAllByCityAndModel.Parameter <int>("model");
            topProductOfAllByCityAndModel.Returns <string>();

            // Function bound to the base entity type and derived entity type
            builder.EntityType <RoutingCustomer>().Function("GetOrdersCount").Returns <string>();
            builder.EntityType <VIP>().Function("GetOrdersCount").Returns <string>();

            // Overloaded function only bound to the base entity type with one paramter
            var getOrderCount = builder.EntityType <RoutingCustomer>().Function("GetOrdersCount");

            getOrderCount.Parameter <int>("factor");
            getOrderCount.Returns <string>();

            // Function only bound to the derived entity type
            builder.EntityType <SpecialVIP>().Function("GetSpecialGuid").Returns <string>();

            // Function bound to the collection of the base and the derived entity type
            builder.EntityType <RoutingCustomer>().Collection.Function("GetAllEmployees").Returns <string>();
            builder.EntityType <VIP>().Collection.Function("GetAllEmployees").Returns <string>();

            // Bound function with enum type parameters
            var boundFunction = builder.EntityType <RoutingCustomer>().Collection.Function("BoundFuncWithEnumParameters");

            boundFunction.Parameter <SimpleEnum>("SimpleEnum");
            boundFunction.Parameter <FlagsEnum>("FlagsEnum");
            boundFunction.Returns <string>();

            // Bound function with enum type parameter for attribute routing
            var boundFunctionForAttributeRouting = builder.EntityType <RoutingCustomer>().Collection
                                                   .Function("BoundFuncWithEnumParameterForAttributeRouting");

            boundFunctionForAttributeRouting.Parameter <SimpleEnum>("SimpleEnum");
            boundFunctionForAttributeRouting.Returns <string>();

            // Unbound function with enum type parameters
            var function = builder.Function("UnboundFuncWithEnumParameters");

            function.Parameter <LongEnum>("LongEnum");
            function.Parameter <FlagsEnum>("FlagsEnum");
            function.Returns <string>();

            // Unbound function
            builder.Function("UnboundFunction").ReturnsCollection <int>().IsComposable = true;

            // Action only bound to the derived entity type
            builder.EntityType <SpecialVIP>().Action("ActionBoundToSpecialVIP");

            // Action only bound to the derived entity type
            builder.EntityType <SpecialVIP>().Collection.Action("ActionBoundToSpecialVIPs");

            // Function only bound to the base entity collection type
            builder.EntityType <RoutingCustomer>().Collection.Function("FunctionBoundToRoutingCustomers").Returns <int>();

            // Function only bound to the derived entity collection type
            builder.EntityType <VIP>().Collection.Function("FunctionBoundToVIPs").Returns <int>();

            // Bound function with multiple parameters
            var functionBoundToProductWithMultipleParamters = builder.EntityType <Product>().Function("FunctionBoundToProductWithMultipleParamters");

            functionBoundToProductWithMultipleParamters.Parameter <int>("P1");
            functionBoundToProductWithMultipleParamters.Parameter <int>("P2");
            functionBoundToProductWithMultipleParamters.Parameter <string>("P3");
            functionBoundToProductWithMultipleParamters.Returns <int>();

            // Overloaded bound function with no parameter
            builder.EntityType <Product>().Function("FunctionBoundToProduct").Returns <int>();

            // Overloaded bound function with one parameter
            builder.EntityType <Product>().Function("FunctionBoundToProduct").Returns <int>().Parameter <int>("P1");

            // Overloaded bound function with multiple parameters
            var functionBoundToProduct = builder.EntityType <Product>().Function("FunctionBoundToProduct").Returns <int>();

            functionBoundToProduct.Parameter <int>("P1");
            functionBoundToProduct.Parameter <int>("P2");
            functionBoundToProduct.Parameter <string>("P3");

            // Unbound function with one parameter
            var unboundFunctionWithOneParamters = builder.Function("UnboundFunctionWithOneParamters");

            unboundFunctionWithOneParamters.Parameter <int>("P1");
            unboundFunctionWithOneParamters.ReturnsFromEntitySet <RoutingCustomer>("RoutingCustomers");
            unboundFunctionWithOneParamters.IsComposable = true;

            // Unbound function with multiple parameters
            var functionWithMultipleParamters = builder.Function("UnboundFunctionWithMultipleParamters");

            functionWithMultipleParamters.Parameter <int>("P1");
            functionWithMultipleParamters.Parameter <int>("P2");
            functionWithMultipleParamters.Parameter <string>("P3");
            functionWithMultipleParamters.Returns <int>();

            // Overloaded unbound function with no parameter
            builder.Function("OverloadUnboundFunction").Returns <int>();

            // Overloaded unbound function with one parameter
            builder.Function("OverloadUnboundFunction").Returns <int>().Parameter <int>("P1");

            // Overloaded unbound function with multiple parameters
            var overloadUnboundFunction = builder.Function("OverloadUnboundFunction").Returns <int>();

            overloadUnboundFunction.Parameter <int>("P1");
            overloadUnboundFunction.Parameter <int>("P2");
            overloadUnboundFunction.Parameter <string>("P3");

            var functionWithComplexTypeParameter =
                builder.EntityType <RoutingCustomer>().Function("CanMoveToAddress").Returns <bool>();

            functionWithComplexTypeParameter.Parameter <Address>("address");

            var functionWithCollectionOfComplexTypeParameter =
                builder.EntityType <RoutingCustomer>().Function("MoveToAddresses").Returns <bool>();

            functionWithCollectionOfComplexTypeParameter.CollectionParameter <Address>("addresses");

            var functionWithCollectionOfPrimitiveTypeParameter =
                builder.EntityType <RoutingCustomer>().Function("CollectionOfPrimitiveTypeFunction").Returns <bool>();

            functionWithCollectionOfPrimitiveTypeParameter.CollectionParameter <int>("intValues");

            var functionWithEntityTypeParameter =
                builder.EntityType <RoutingCustomer>().Function("EntityTypeFunction").Returns <bool>();

            functionWithEntityTypeParameter.EntityParameter <Product>("product");

            var functionWithCollectionEntityTypeParameter =
                builder.EntityType <RoutingCustomer>().Function("CollectionEntityTypeFunction").Returns <bool>();

            functionWithCollectionEntityTypeParameter.CollectionEntityParameter <Product>("products");

            return(_model = builder.GetEdmModel());
        }
        public void CanCreateActionWithNonBindingParameters()
        {
            // Arrange
            // Act
            ODataModelBuilder builder = new ODataModelBuilder();
            ActionConfiguration action = new ActionConfiguration(builder, "MyAction");
            action.Parameter<string>("p0");
            action.Parameter<int>("p1");
            action.Parameter<Address>("p2");
            action.CollectionParameter<string>("p3");
            action.CollectionParameter<int>("p4");
            action.CollectionParameter<ZipCode>("p5");
            ParameterConfiguration[] parameters = action.Parameters.ToArray();
            ComplexTypeConfiguration[] complexTypes = builder.StructuralTypes.OfType<ComplexTypeConfiguration>().ToArray();

            // Assert
            Assert.Equal(2, complexTypes.Length);
            Assert.Equal(typeof(Address).FullName, complexTypes[0].FullName);
            Assert.Equal(typeof(ZipCode).FullName, complexTypes[1].FullName);
            Assert.Equal(6, parameters.Length);
            Assert.Equal("p0", parameters[0].Name);
            Assert.Equal("Edm.String", parameters[0].TypeConfiguration.FullName);
            Assert.Equal("p1", parameters[1].Name);
            Assert.Equal("Edm.Int32", parameters[1].TypeConfiguration.FullName);
            Assert.Equal("p2", parameters[2].Name);
            Assert.Equal(typeof(Address).FullName, parameters[2].TypeConfiguration.FullName);
            Assert.Equal("p3", parameters[3].Name);
            Assert.Equal("Collection(Edm.String)", parameters[3].TypeConfiguration.FullName);
            Assert.Equal("p4", parameters[4].Name);
            Assert.Equal("Collection(Edm.Int32)", parameters[4].TypeConfiguration.FullName);
            Assert.Equal("p5", parameters[5].Name);
            Assert.Equal(string.Format("Collection({0})", typeof(ZipCode).FullName), parameters[5].TypeConfiguration.FullName);
        }
        public void CanCreateActionWithComplexReturnType()
        {
            // Arrange
            // Act
            ODataModelBuilder builder = new ODataModelBuilder();
            
            ActionConfiguration createAddress = new ActionConfiguration(builder, "CreateAddress");
            createAddress.Returns<Address>();
            
            ActionConfiguration createAddresses = new ActionConfiguration(builder, "CreateAddresses");
            createAddresses.ReturnsCollection<Address>();

            // Assert
            IComplexTypeConfiguration address = createAddress.ReturnType as IComplexTypeConfiguration;
            Assert.NotNull(address);
            Assert.Equal(typeof(Address).FullName, address.FullName);
            Assert.Null(createAddress.EntitySet);

            ICollectionTypeConfiguration addresses = createAddresses.ReturnType as ICollectionTypeConfiguration;
            Assert.NotNull(addresses);
            Assert.Equal(string.Format("Collection({0})", typeof(Address).FullName), addresses.FullName);
            address = addresses.ElementType as IComplexTypeConfiguration;
            Assert.NotNull(address);
            Assert.Equal(typeof(Address).FullName, address.FullName);
            Assert.Null(createAddresses.EntitySet);
        }
Exemplo n.º 24
0
 public ProtoDeclaredAction( ActionConfiguration a )
 {
     _action = a;
 }
        public void Apply_SetsActionLinkBuilder_OnlyIfActionIsBindable()
        {
            ODataConventionModelBuilder builder = new ODataConventionModelBuilder();
            var vehicles = builder.EntitySet<Vehicle>("vehicles");
            var paintAction = new ActionConfiguration(builder, "Paint");

            _convention.Apply(paintAction, builder);

            IEdmModel model = builder.GetEdmModel();
            var paintEdmAction = model.EntityContainers().Single().Elements.OfType<IEdmFunctionImport>().Single();

            ActionLinkBuilder actionLinkBuilder = model.GetActionLinkBuilder(paintEdmAction);

            Assert.Null(actionLinkBuilder);
        }
Exemplo n.º 26
0
        private static void SetupExtendSupportDateActionLink(ActionConfiguration extendSupportDateAction)
        {
            extendSupportDateAction.HasActionLink(eic =>
            {
                Product pd = (Product)eic.EntityInstance;

                return new Uri(eic.UrlHelper.Link(ODataRouteNames.InvokeBoundAction, new
                {
                    controller = eic.EntitySet.Name,
                    boundId = pd.ID,
                    odataAction = "ExtendSupportDate"
                }));
            });

            //extendSupportDateAction.HasActionLink(ActionLinkBuilder.CreateActionLinkFactory(
            //baseFactory: eic =>
            //{
            //    Product pd = (Product)eic.EntityInstance;

            //    return new Uri(eic.UrlHelper.Link(ODataRouteNames.InvokeBoundAction, new
            //    {
            //        controller = eic.EntitySet.Name,
            //        boundId = pd.ID,
            //        odataAction = "ExtendSupportDate"
            //    }));
            //},
            //expensiveAvailabilityCheck: eic =>
            //{
            //    //do some check here and return true or false
            //    return true;
            //}));
        }
        public void CanCreateActionWithEntityReturnType()
        {
            // Arrange
            // Act
            ODataModelBuilder builder = new ODataModelBuilder();

            ActionConfiguration createGoodCustomer = new ActionConfiguration(builder, "CreateGoodCustomer");
            createGoodCustomer.ReturnsFromEntitySet<Customer>("GoodCustomers");

            ActionConfiguration createBadCustomers = new ActionConfiguration(builder, "CreateBadCustomers");
            createBadCustomers.ReturnsCollectionFromEntitySet<Customer>("BadCustomers");

            // Assert
            IEntityTypeConfiguration customer = createGoodCustomer.ReturnType as IEntityTypeConfiguration;
            Assert.NotNull(customer);
            Assert.Equal(typeof(Customer).FullName, customer.FullName);
            IEntitySetConfiguration goodCustomers = builder.EntitySets.SingleOrDefault(s => s.Name == "GoodCustomers");
            Assert.NotNull(goodCustomers);
            Assert.Same(createGoodCustomer.EntitySet, goodCustomers);

            ICollectionTypeConfiguration customers = createBadCustomers.ReturnType as ICollectionTypeConfiguration;
            Assert.NotNull(customers);
            customer = customers.ElementType as IEntityTypeConfiguration;
            Assert.NotNull(customer);
            IEntitySetConfiguration badCustomers = builder.EntitySets.SingleOrDefault(s => s.Name == "BadCustomers");
            Assert.NotNull(badCustomers);
            Assert.Same(createBadCustomers.EntitySet, badCustomers);
        }
Exemplo n.º 28
0
            protected override ITestIt DoCreate(IActivityMonitor monitor, IRouteConfigurationLock configLock, ActionConfiguration c)
            {
                ActionTypeAttribute a = c.GetType().GetTypeInfo().GetCustomAttribute <ActionTypeAttribute>();

                return((ITestIt)Activator.CreateInstance(a.ActionType, monitor, c));
            }
Exemplo n.º 29
0
 public static ActionConfiguration ActionReturnsFromEntitySet <TEntityType>(ODataModelBuilder builder, ActionConfiguration action, string entitySetName) where TEntityType : class
 {
     action.NavigationSource = CreateOrReuseEntitySet <TEntityType>(builder, entitySetName);
     action.ReturnType       = builder.GetTypeConfigurationOrNull(typeof(TEntityType));
     return(action);
 }
        public void CanCreateEdmModel_WithNonBindableAction()
        {
            // Arrange
            ODataModelBuilder builder = new ODataModelBuilder();

            // Act
            ActionConfiguration actionConfiguration = new ActionConfiguration(builder, "ActionName");
            actionConfiguration.ReturnsFromEntitySet<Customer>("Customers");

            IEdmModel model = builder.GetEdmModel();

            // Assert
            IEdmEntityContainer container = model.EntityContainers().SingleOrDefault();
            Assert.NotNull(container);
            Assert.Equal(1, container.Elements.OfType<IEdmFunctionImport>().Count());
            Assert.Equal(1, container.Elements.OfType<IEdmEntitySet>().Count());
            IEdmFunctionImport action = container.Elements.OfType<IEdmFunctionImport>().Single();
            Assert.False(action.IsComposable);
            Assert.True(action.IsSideEffecting);
            Assert.False(action.IsBindable);
            Assert.Equal("ActionName", action.Name);
            Assert.NotNull(action.ReturnType);
            Assert.NotNull(action.EntitySet);
            Assert.Equal("Customers", (action.EntitySet as IEdmEntitySetReferenceExpression).ReferencedEntitySet.Name);
            Assert.Equal(typeof(Customer).FullName, (action.EntitySet as IEdmEntitySetReferenceExpression).ReferencedEntitySet.ElementType.FullName());
            Assert.Empty(action.Parameters);
        }
Exemplo n.º 31
0
        public async Task Setup_ActionRule_Sample_OnceEveryHour_And_between9and11_SendPictureToEmail()
        {
            //Create the hourly recurrence first and add to device
            ScheduledEvent  myHourlyRecurrence = new ScheduledEvent("HourlyRecurrence", new ICalendar(PulseInterval.HOURLY, 1));
            ServiceResponse deviceResponse     = await eventService.Add_ScheduledEventAsync(VALID_IP, VALID_USER, VALID_PASS, myHourlyRecurrence);

            if (deviceResponse.IsSuccess) //Recurrence added
            {
                //Create the Weekdays evening schedule annd add to device
                ScheduledEvent myWeeklyEveningSchedule = new ScheduledEvent("WorkingDays", new ICalendar(new ScheduleTime(17, 30), new ScheduleTime(21), new ScheduleDay[] { ScheduleDay.MO, ScheduleDay.TU, ScheduleDay.WE, ScheduleDay.TH, ScheduleDay.FR }));
                deviceResponse = await eventService.Add_ScheduledEventAsync(VALID_IP, VALID_USER, VALID_PASS, myWeeklyEveningSchedule);

                if (deviceResponse.IsSuccess) //Schedule added
                {
                    //First get the possible templates for the device
                    GetActionTemplatesResponse aTemplates = await actionService.GetActionTemplatesAsync(VALID_IP, VALID_USER, VALID_PASS);

                    if (aTemplates.IsSuccess)
                    {
                        //Now create the action template based on template instance- Send SMTP with picture attached
                        ActionConfiguration SendSMTP = new ActionConfiguration(aTemplates.Templates["com.axis.action.fixed.notification.smtp"]);
                        //Set the action config paramters
                        SendSMTP.Parameters["subject"]    = "Week evenings timeLapse";
                        SendSMTP.Parameters["message"]    = "Photo %d";
                        SendSMTP.Parameters["email_to"]   = "*****@*****.**";
                        SendSMTP.Parameters["email_from"] = "*****@*****.**";
                        SendSMTP.Parameters["host"]       = "smtp-relay.gmail.com";
                        SendSMTP.Parameters["port"]       = "587";
                        SendSMTP.Parameters["login"]      = "";
                        SendSMTP.Parameters["password"]   = "";

                        //Add the action config to the device
                        deviceResponse = await actionService.AddActionConfigurationAsync(VALID_IP, VALID_USER, VALID_PASS, SendSMTP);

                        if (deviceResponse.IsSuccess)
                        {
                            //Get the event instances suppported by the device, the collection will also contain our previously created schedule and recurrence event this way
                            GetEventInstancesResponse eInstances = await eventService.GetEventsInstancesAsync(VALID_IP, VALID_USER, VALID_PASS);

                            ActionRule OnEveryWeekDayEveningHourSendPicture = new ActionRule()
                            {
                                Name          = "OnEveryWeekDayEveningHourSendPicture",
                                Enabled       = true,
                                Trigger       = eInstances.EventInstances.Find(x => x.TopicExpression == "tns1:UserAlarm/tnsaxis:Recurring/Pulse"), //See GetEventInstances output for the correct event name
                                Configuration = SendSMTP,
                            };

                            OnEveryWeekDayEveningHourSendPicture.Trigger.Parameters["id"].Value = myHourlyRecurrence.EventID;
                            //Create and add extra condition to Action Rule
                            EventTrigger OnWeekDayEveningSchedule = eInstances.EventInstances.Find(x => x.TopicExpression == "tns1:UserAlarm/tnsaxis:Recurring/Interval");
                            OnWeekDayEveningSchedule.Parameters["id"].Value     = myWeeklyEveningSchedule.EventID;
                            OnWeekDayEveningSchedule.Parameters["active"].Value = "1";
                            OnEveryWeekDayEveningHourSendPicture.AddExtraCondition(OnWeekDayEveningSchedule);

                            //Create action rule on device
                            deviceResponse = await actionService.AddActionRuleAsync(VALID_IP, VALID_USER, VALID_PASS, OnEveryWeekDayEveningHourSendPicture);

                            Assert.IsTrue(deviceResponse.IsSuccess);
                        }
                    }
                }
            }
        }
Exemplo n.º 32
0
        private static IEdmModel GetModel()
        {
            var config = RoutingConfigurationFactory.CreateWithTypes(typeof(Customer));
            ODataModelBuilder builder = ODataConventionModelBuilderFactory.Create(config);

            builder.ContainerName = "C";
            builder.Namespace     = "A.B";
            EntityTypeConfiguration <Customer> customer = builder.EntitySet <Customer>("Customers").EntityType;

            // bound actions
            ActionConfiguration primitive = customer.Action("Primitive");

            primitive.Parameter <int>("Quantity");
            primitive.Parameter <string>("ProductCode");
            primitive.Parameter <Date>("Birthday");
            primitive.Parameter <AColor>("BkgColor");
            primitive.Parameter <AColor?>("InnerColor");

            ActionConfiguration complex = customer.Action("Complex");

            complex.Parameter <int>("Quantity");
            complex.Parameter <MyAddress>("Address");

            ActionConfiguration enumType = customer.Action("Enum");

            enumType.Parameter <AColor>("Color");

            ActionConfiguration primitiveCollection = customer.Action("PrimitiveCollection");

            primitiveCollection.Parameter <string>("Name");
            primitiveCollection.CollectionParameter <int>("Ratings");
            primitiveCollection.CollectionParameter <TimeOfDay>("Time");
            primitiveCollection.CollectionParameter <AColor?>("Colors");

            ActionConfiguration complexCollection = customer.Action("ComplexCollection");

            complexCollection.Parameter <string>("Name");
            complexCollection.CollectionParameter <MyAddress>("Addresses");

            ActionConfiguration enumCollection = customer.Action("EnumCollection");

            enumCollection.CollectionParameter <AColor>("Colors");

            ActionConfiguration entity = customer.Action("Entity");

            entity.Parameter <int>("Id");
            entity.EntityParameter <Customer>("Customer");
            entity.EntityParameter <Customer>("NullableCustomer");

            ActionConfiguration entityCollection = customer.Action("EntityCollection");

            entityCollection.Parameter <int>("Id");
            entityCollection.CollectionEntityParameter <Customer>("Customers");

            // unbound actions
            ActionConfiguration unboundPrimitive = builder.Action("UnboundPrimitive");

            unboundPrimitive.Parameter <int>("Quantity");
            unboundPrimitive.Parameter <string>("ProductCode");
            unboundPrimitive.Parameter <Date>("Birthday");
            unboundPrimitive.Parameter <AColor>("BkgColor");
            unboundPrimitive.Parameter <AColor?>("InnerColor");

            ActionConfiguration unboundComplex = builder.Action("UnboundComplex");

            unboundComplex.Parameter <int>("Quantity");
            unboundComplex.Parameter <MyAddress>("Address");

            ActionConfiguration unboundEnum = builder.Action("UnboundEnum");

            unboundEnum.Parameter <AColor>("Color");

            ActionConfiguration unboundPrimitiveCollection = builder.Action("UnboundPrimitiveCollection");

            unboundPrimitiveCollection.Parameter <string>("Name");
            unboundPrimitiveCollection.CollectionParameter <int>("Ratings");
            unboundPrimitiveCollection.CollectionParameter <TimeOfDay>("Time");
            unboundPrimitiveCollection.CollectionParameter <AColor?>("Colors");

            ActionConfiguration unboundComplexCollection = builder.Action("UnboundComplexCollection");

            unboundComplexCollection.Parameter <string>("Name");
            unboundComplexCollection.CollectionParameter <MyAddress>("Addresses");

            ActionConfiguration unboundEnumCollection = builder.Action("UnboundEnumCollection");

            unboundEnumCollection.CollectionParameter <AColor>("Colors");

            ActionConfiguration unboundEntity = builder.Action("UnboundEntity");

            unboundEntity.Parameter <int>("Id");
            unboundEntity.EntityParameter <Customer>("Customer").Nullable = false;
            unboundEntity.EntityParameter <Customer>("NullableCustomer");

            ActionConfiguration unboundEntityCollection = builder.Action("UnboundEntityCollection");

            unboundEntityCollection.Parameter <int>("Id");
            unboundEntityCollection.CollectionEntityParameter <Customer>("Customers");

            return(builder.GetEdmModel());
        }
Exemplo n.º 33
0
 public IActionExecutor GetActionExecutor(ActionConfiguration actionConfiguration)
 {
     return(actionConfiguration switch
     {
         { Type : ActionType.AnswerToMessage } => new AnswerMessageActionExecutor(_slackClient, actionConfiguration.Value),
 /// <summary>
 /// Overrides (replaces) an <see cref="ActionConfiguration"/> at a specified index.
 /// </summary>
 /// <param name="idx">Index to replace.</param>
 /// <param name="action">The new action to inject.</param>
 internal void Override( int idx, ActionConfiguration action )
 {
     if( action == null ) throw new ArgumentNullException( "action" );
     _children[idx] = action;
 }
 /// <summary>
 /// Adds an <see cref="ActionConfiguration"/> to this composite.
 /// </summary>
 /// <param name="action">The action to add.</param>
 protected void Add( ActionConfiguration action )
 {
     if( action == null ) throw new ArgumentNullException( "action" );
     _children.Add( action );
 }
        public void HasActionLink_SetsFollowsConventions(bool value)
        {
            // Arrange
            ODataModelBuilder builder = new ODataModelBuilder();
            ActionConfiguration action = new ActionConfiguration(builder, "IgnoreAction");
            Mock<IEdmTypeConfiguration> bindingParameterTypeMock = new Mock<IEdmTypeConfiguration>();
            bindingParameterTypeMock.Setup(o => o.Kind).Returns(EdmTypeKind.Entity);
            IEdmTypeConfiguration bindingParameterType = bindingParameterTypeMock.Object;
            action.SetBindingParameter("IgnoreParameter", bindingParameterType, alwaysBindable: false);

            // Act
            action.HasActionLink((a) => { throw new NotImplementedException(); }, followsConventions: value);

            // Assert
            Assert.Equal(value, action.FollowsConventions);
        }
Exemplo n.º 37
0
        public static void Register(HttpConfiguration config)
        {
            // Cross-Origin Resource Sharing
            var cors = new EnableCorsAttribute("*", "*", "*");

            config.EnableCors(cors);

            // Web API routes
            config.MapHttpAttributeRoutes();

            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional }
                );

            // Set timezone
            config.SetTimeZoneInfo(TimeZoneInfo.Utc);

            // Custom authentication
            config.Filters.Add(new BrizbeeAuthorizeAttribute());

            // Custom exception handling
            config.Filters.Add(new CustomExceptionFilterAttribute());

            // Web API configuration and services
            ODataModelBuilder builder = new ODataConventionModelBuilder();

            config.Count().Filter().OrderBy().Expand().Select().MaxTop(null);
            builder.EntitySet <Customer>("Customers");
            builder.EntitySet <Commit>("Commits");
            builder.EntitySet <Job>("Jobs");
            builder.EntitySet <Organization>("Organizations");
            builder.EntitySet <Punch>("Punches");
            builder.EntitySet <Rate>("Rates");
            builder.EntitySet <QuickBooksDesktopExport>("QuickBooksDesktopExports");
            builder.EntitySet <Task>("Tasks");
            builder.EntitySet <TaskTemplate>("TaskTemplates");
            builder.EntitySet <TimesheetEntry>("TimesheetEntries");
            builder.EntitySet <User>("Users");

            // Collection Function - Jobs/Open
            builder.EntityType <Job>()
            .Collection
            .Function("Open")
            .ReturnsCollectionFromEntitySet <Job>("Jobs");

            // Collection Function - Punches/Current
            builder.EntityType <Punch>()
            .Collection
            .Function("Current")
            .ReturnsFromEntitySet <Punch>("Punches");

            // Member Function - Commit/Export
            var export = builder.EntityType <Commit>()
                         .Function("Export")
                         .Returns <string>();

            export.Parameter <string>("Delimiter");

            // Collection Action - Users/Authenticate
            var authenticate = builder.EntityType <User>()
                               .Collection
                               .Action("Authenticate");

            authenticate.Parameter <Session>("Session");
            authenticate.Returns <Credential>();

            // Collection Action - Customers/NextNumber
            builder.EntityType <Customer>()
            .Collection
            .Action("NextNumber");

            // Collection Action - Jobs/NextNumber
            builder.EntityType <Job>()
            .Collection
            .Action("NextNumber");

            // Collection Action - Tasks/NextNumber
            builder.EntityType <Task>()
            .Collection
            .Action("NextNumber");

            // Collection Function - Organizations/Countries
            var countries = builder.EntityType <Organization>()
                            .Collection
                            .Function("Countries");

            countries.ReturnsCollection <Country>();

            // Collection Function - Organizations/TimeZones
            var timeZones = builder.EntityType <Organization>()
                            .Collection
                            .Function("TimeZones");

            timeZones.ReturnsCollection <IanaTimeZone>();

            // Collection Action - Users/Register
            var register = builder.EntityType <User>()
                           .Collection
                           .Action("Register");

            register.Parameter <Organization>("Organization");
            register.Parameter <User>("User");
            register.ReturnsFromEntitySet <User>("Users");

            // Collection Action - Punches/PunchIn
            var punchIn = builder.EntityType <Punch>()
                          .Collection
                          .Action("PunchIn")
                          .ReturnsFromEntitySet <Punch>("Punches");

            punchIn.Parameter <int>("TaskId");
            punchIn.Parameter <string>("InAtTimeZone");
            punchIn.Parameter <string>("LatitudeForInAt");
            punchIn.Parameter <string>("LongitudeForInAt");
            punchIn.Parameter <string>("SourceHardware");
            punchIn.Parameter <string>("SourceOperatingSystem");
            punchIn.Parameter <string>("SourceOperatingSystemVersion");
            punchIn.Parameter <string>("SourceBrowser");
            punchIn.Parameter <string>("SourceBrowserVersion");

            // Collection Action - Punches/PunchOut
            var punchOut = builder.EntityType <Punch>()
                           .Collection
                           .Action("PunchOut")
                           .ReturnsFromEntitySet <Punch>("Punches");

            punchOut.Parameter <string>("OutAtTimeZone");
            punchOut.Parameter <string>("LatitudeForOutAt");
            punchOut.Parameter <string>("LongitudeForOutAt");
            punchOut.Parameter <string>("SourceHardware");
            punchOut.Parameter <string>("SourceOperatingSystem");
            punchOut.Parameter <string>("SourceOperatingSystemVersion");
            punchOut.Parameter <string>("SourceBrowser");
            punchOut.Parameter <string>("SourceBrowserVersion");

            // Collection Function - Punches/Download
            var download = builder.EntityType <Punch>()
                           .Collection
                           .Function("Download")
                           .Returns <string>();

            download.Parameter <int>("CommitId");

            // Collection Function - Tasks/Search
            var tasksSearch = builder.EntityType <Task>()
                              .Collection
                              .Function("Search")
                              .Returns <string>();

            tasksSearch.Parameter <string>("Number");

            // Collection Function - Tasks/ForPunches
            var tasksForPunches = builder.EntityType <Task>()
                                  .Collection
                                  .Function("ForPunches");

            tasksForPunches.Parameter <string>("InAt");
            tasksForPunches.Parameter <string>("OutAt");
            tasksForPunches.ReturnsCollectionFromEntitySet <Task>("Tasks");

            // Collection Action - TimesheetEntries/Add
            var add = builder.EntityType <TimesheetEntry>()
                      .Collection
                      .Action("Add")
                      .ReturnsFromEntitySet <TimesheetEntry>("TimesheetEntries");

            add.Parameter <int>("TaskId");
            add.Parameter <int>("Minutes");
            add.Parameter <string>("EnteredAt");
            add.Parameter <string>("Notes");

            // Collection Function - Rates/BasePayrollRatesForPunches
            var basePayrollRates = builder.EntityType <Rate>()
                                   .Collection
                                   .Function("BasePayrollRatesForPunches");

            basePayrollRates.Parameter <string>("InAt");
            basePayrollRates.Parameter <string>("OutAt");
            basePayrollRates.ReturnsCollectionFromEntitySet <Rate>("Rates");

            // Collection Function - Rates/BaseServiceRatesForPunches
            var baseServiceRates = builder.EntityType <Rate>()
                                   .Collection
                                   .Function("BaseServiceRatesForPunches");

            baseServiceRates.Parameter <string>("InAt");
            baseServiceRates.Parameter <string>("OutAt");
            baseServiceRates.ReturnsCollectionFromEntitySet <Rate>("Rates");

            // Collection Function - Rates/AlternatePayrollRatesForPunches
            var alternatePayrollRates = builder.EntityType <Rate>()
                                        .Collection
                                        .Function("AlternatePayrollRatesForPunches");

            alternatePayrollRates.Parameter <string>("InAt");
            alternatePayrollRates.Parameter <string>("OutAt");
            alternatePayrollRates.ReturnsCollectionFromEntitySet <Rate>("Rates");

            // Collection Function - Rates/AlternateServiceRatesForPunches
            var alternateServiceRates = builder.EntityType <Rate>()
                                        .Collection
                                        .Function("AlternateServiceRatesForPunches");

            alternateServiceRates.Parameter <string>("InAt");
            alternateServiceRates.Parameter <string>("OutAt");
            alternateServiceRates.ReturnsCollectionFromEntitySet <Rate>("Rates");

            // Collection Action - Punches/Split
            var split = builder.EntityType <Punch>()
                        .Collection
                        .Action("Split");

            split.Parameter <string>("InAt");
            split.Parameter <string>("Minutes");
            split.Parameter <string>("OutAt");
            split.Parameter <string>("Time");
            split.Parameter <string>("Type");

            // Collection Action - Punches/SplitAtMidnight
            var splitMidnight = builder.EntityType <Punch>()
                                .Collection
                                .Action("SplitAtMidnight");

            splitMidnight.Parameter <string>("InAt");
            splitMidnight.Parameter <string>("OutAt");

            // Collection Action - Punches/PopulateRates
            var populate = builder.EntityType <Punch>()
                           .Collection
                           .Action("PopulateRates");

            populate.Parameter <PopulateRateOptions>("Options");
            populate.Returns <string>();

            // Member Action - User/ChangePassword
            ActionConfiguration changePassword = builder.EntityType <User>()
                                                 .Action("ChangePassword");

            changePassword.Parameter <string>("Password");

            // Member Action - Commit/Undo
            ActionConfiguration undo = builder.EntityType <Commit>()
                                       .Action("Undo");

            config.MapODataServiceRoute("odata", "odata", builder.GetEdmModel());

            config.EnableDependencyInjection();

            config.EnsureInitialized();
        }