/// <summary>
        /// Generates code
        /// </summary>
        /// <param name="source">The dependence object</param>
        /// <param name="classType">Type of the class.</param>
        /// <param name="method">The initialize method.</param>
        /// <param name="generateField"></param>
        /// <returns></returns>
        public override CodeExpression Generate(DependencyObject source, CodeTypeDeclaration classType, CodeMemberMethod method, bool generateField)
        {
            CodeExpression fieldReference = base.Generate(source, classType, method, generateField);

            ItemsControl itemsControl = source as ItemsControl;
            CodeComHelper.GenerateTemplateStyleField(classType, method, fieldReference, source, ItemsControl.ItemsPanelProperty);
            CodeComHelper.GenerateTemplateStyleField(classType, method, fieldReference, source, ItemsControl.ItemTemplateProperty);

            if (itemsControl.Items.Count > 0)
            {
                TypeGenerator typeGenerator = new TypeGenerator();
                ValueGenerator valueGenerator = new ValueGenerator();

                CodeMemberMethod itemsMethod = new CodeMemberMethod();
                itemsMethod.Attributes = MemberAttributes.Static | MemberAttributes.Private;
                itemsMethod.Name = "Get_" + itemsControl.Name + "_Items";
                itemsMethod.ReturnType = new CodeTypeReference(typeof(ObservableCollection<object>));
                classType.Members.Add(itemsMethod);

                CodeVariableDeclarationStatement collection = new CodeVariableDeclarationStatement(
                    typeof(ObservableCollection<object>), "items", new CodeObjectCreateExpression(typeof(ObservableCollection<object>)));
                itemsMethod.Statements.Add(collection);

                CodeVariableReferenceExpression itemsVar = new CodeVariableReferenceExpression("items");
                foreach (var item in itemsControl.Items)
                {
                    Type itemType = item.GetType();
                    CodeExpression itemExpr = null;
                    if (typeGenerator.HasGenerator(itemType))
                    {
                        itemExpr = typeGenerator.ProcessGenerators(item, classType, itemsMethod, false);
                    }
                    else
                    {
                        itemExpr = valueGenerator.ProcessGenerators(classType, itemsMethod, item, itemsControl.Name);
                    }

                    if (itemExpr != null)
                    {
                        CodeMethodInvokeExpression addItem = new CodeMethodInvokeExpression(itemsVar, "Add", itemExpr);
                        itemsMethod.Statements.Add(addItem);
                    }
                    else
                    {
                        CodeComHelper.GenerateError(itemsMethod, string.Format("Type {0} in Items Control collection not supported", itemType.Name));
                    }
                }

                CodeMethodReturnStatement returnStatement = new CodeMethodReturnStatement(itemsVar);
                itemsMethod.Statements.Add(returnStatement);

                method.Statements.Add(new CodeAssignStatement(
                    new CodeFieldReferenceExpression(fieldReference, "ItemsSource"),
                    new CodeMethodInvokeExpression(null, itemsMethod.Name)));
            }

            return fieldReference;
        }
Beispiel #2
0
 private static FakeChainFactory CreateFakeChainFactory(ProxyGenerator proxyGenerator, ValueGenerator valueGenerator)
 {
     return(new FakeChainFactory(
                new CachedReturnValueGeneration(new PerMethodCache <object>()),
                GlobalNestingLimit.Of(5),
                proxyGenerator,
                valueGenerator));
 }
Beispiel #3
0
        private void GenerateBehaviorActions(ActionCollection actionCollection, CodeTypeDeclaration classType, CodeMemberMethod method, CodeVariableReferenceExpression behaviorVarRef, string behaviorName)
        {
            for (int i = 0; i < actionCollection.Count; i++)
            {
                var    action     = actionCollection[i];
                string actionName = behaviorName + "_ACT_" + i;
                Type   type       = action.GetType();

                CodeVariableDeclarationStatement variable = new CodeVariableDeclarationStatement(type.Name, actionName, new CodeObjectCreateExpression(type.Name));
                method.Statements.Add(variable);
                var actionVarRef = new CodeVariableReferenceExpression(actionName);

                method.Statements.Add(new CodeMethodInvokeExpression(
                                          behaviorVarRef, "Actions.Add", actionVarRef));

                ValueGenerator valueGenerator      = new ValueGenerator();
                MethodInfo     generateFieldMethod = typeof(CodeComHelper).GetMethod("GenerateField");

                LocalValueEnumerator enumerator = action.GetLocalValueEnumerator();
                while (enumerator.MoveNext())
                {
                    LocalValueEntry    entry    = enumerator.Current;
                    DependencyProperty property = entry.Property;
                    Type valueType = entry.Value.GetType();
                    if (CodeComHelper.IsValidForFieldGenerator(entry.Value))
                    {
                        if (valueGenerator.Generators.ContainsKey(property.PropertyType) || valueGenerator.Generators.ContainsKey(valueType))
                        {
                            CodeExpression propValue = valueGenerator.ProcessGenerators(classType, method, entry.Value, actionName);
                            if (propValue != null)
                            {
                                method.Statements.Add(new CodeAssignStatement(new CodeFieldReferenceExpression(actionVarRef, property.Name), propValue));
                            }
                        }
                        else if (entry.Value is PropertyPath)
                        {
                            PropertyPath path = entry.Value as PropertyPath;
                            method.Statements.Add(new CodeAssignStatement(
                                                      new CodeFieldReferenceExpression(actionVarRef, property.Name),
                                                      new CodeObjectCreateExpression("PropertyPath", new CodePrimitiveExpression(path.Path))));
                        }
                        else if (entry.Value is SoundSource)
                        {
                            var soundSource = CodeComHelper.GenerateSoundSource(method, entry.Value as SoundSource);
                            method.Statements.Add(new CodeAssignStatement(new CodeFieldReferenceExpression(actionVarRef, property.Name), soundSource));
                        }
                        else
                        {
                            MethodInfo generic = generateFieldMethod.MakeGenericMethod(property.PropertyType);
                            if (generic == null)
                            {
                                throw new NullReferenceException("Generic method not created for type - " + property.PropertyType);
                            }

                            generic.Invoke(null, new object[] { method, actionVarRef, action, property });
                        }
                    }
                }

                CodeComHelper.GenerateBindings(method, actionVarRef, action, actionName, behaviorVarRef);
                //CodeComHelper.GenerateResourceReferences(method, actionVarRef, action);
            }
        }
 public void SetUp()
 {
     _generator = new ValueGenerator();
     _list      = new LinkedListNode <string>();
 }
Beispiel #5
0
        internal static List <MappingInfo> GetMetadata(DbContext context, Type type)
        {
            var metadata   = context.Model;
            var entityType = metadata.GetEntityTypes().Single(x => x.ClrType == type);

            var tableName   = GetTableName(context, type);
            var columnsInfo = NpgsqlBulkUploader.RelationalHelper.GetColumnsInfo(context, tableName);

            if (entityType.BaseType != null)
            {
                var baseTableName = GetTableName(context, entityType.BaseType.ClrType);
                if (baseTableName != tableName)
                {
                    var extraColumnsInfo = NpgsqlBulkUploader.RelationalHelper.GetColumnsInfo(context, baseTableName);
                    columnsInfo.AddRange(extraColumnsInfo);
                }
            }

            int optinalIndex = 0;
            var innerList    = entityType
                               .GetProperties()
                               .Where(x => x.GetColumnName() != "xmin") // For now we don't support xmin
                               .Select(x =>
            {
                var relational = x.DeclaringEntityType;
                ValueGenerator localGenerator = null;
                bool isDbGenerated            = false;

                var generatorFactory = x.GetAnnotations().FirstOrDefault(a => a.Name == "ValueGeneratorFactory");
                if (generatorFactory != null)
                {
                    var valueGeneratorAccessor = generatorFactory.Value as Func <IProperty, IEntityType, ValueGenerator>;
                    localGenerator             = valueGeneratorAccessor(x, x.DeclaringEntityType);
                }
                else if (x.GetAnnotations().Any(y => y.Name == "Relational:ComputedColumnSql"))
                {
                    isDbGenerated = true;
                }
                else if (x.GetAnnotations().Any(y => y.Name == "Npgsql:ValueGenerationStrategy"))
                {
                    isDbGenerated = true;
                }

                var indexes       = ((Microsoft.EntityFrameworkCore.Metadata.Internal.Property)x).PropertyIndexes;
                long optionalFlag = 0;
                if (indexes.StoreGenerationIndex >= 0 && localGenerator == null)
                {
                    optionalFlag = 1 << optinalIndex;
                    optinalIndex++;
                }

                return(new MappingInfo()
                {
                    TableName = relational.GetTableName(),
                    TableNameQualified = NpgsqlHelper.GetQualifiedName(relational.GetTableName(), relational.GetSchema()),
                    Property = x.PropertyInfo,
                    ColumnInfo = columnsInfo.First(c => c.ColumnName == x.GetColumnName()),
                    LocalGenerator = localGenerator,
                    ValueConverter = x.GetValueConverter(),
                    IsKey = x.IsKey(),
                    IsInheritanceUsed = entityType.BaseType != null,
                    DbProperty = x,
                    DoUpdate = !isDbGenerated && x.PropertyInfo != null,        // don't update shadow props
                    DoInsert = !isDbGenerated,                                  // do insert of shadow props
                    ReadBack = indexes.StoreGenerationIndex >= 0,
                    IsSpecifiedFlag = optionalFlag
                });
            }).ToList();

            return(innerList);
        }
Beispiel #6
0
        ValueGenerator CreateValueGenerator(XElement settingElement, SettingLimits settingLimits = null)
        {
            ValueGenerator outValueGenerator        = null;
            bool           hasCreatedValueGenerator = false;

            //Iterate through all elements.
            IEnumerable <XElement> elements = settingElement.Elements();

            foreach (XElement element in elements)
            {
                //Warn about more than one value element.
                if (hasCreatedValueGenerator)
                {
                    _errorCollection.AddInvalidElement(element);
                    continue;
                }

                //Handle value element.
                ValueGeneratorTypes valueGeneratorType;
                if (Enum.TryParse <ValueGeneratorTypes>(element.Name.LocalName, out valueGeneratorType))
                {
                    switch (valueGeneratorType)
                    {
                    case ValueGeneratorTypes.Null:
                        outValueGenerator = null;
                        break;

                    case ValueGeneratorTypes.Constant:
                        outValueGenerator = CreateConstantValueGenerator(element);
                        break;

                    case ValueGeneratorTypes.Range:
                        outValueGenerator = CreateRangeValueGenerator(element);
                        break;

                    case ValueGeneratorTypes.Boolean:
                        outValueGenerator = CreateBooleanValueGenerator(element);
                        break;

                    case ValueGeneratorTypes.CoinFlip:
                        outValueGenerator = CreateCoinFlipValueGenerator(element);
                        break;

                    case ValueGeneratorTypes.WeightedSelector:
                        outValueGenerator = CreateWeightedSelectorValueGenerator(element, settingLimits);
                        break;

                    default:
                        _errorCollection.AddInvalidElement(element);
                        break;
                    }

                    hasCreatedValueGenerator = outValueGenerator != null || valueGeneratorType == ValueGeneratorTypes.Null;

                    if (outValueGenerator != null && settingLimits != null && !outValueGenerator.IsValueRangeWithinLimits(settingLimits))
                    {
                        _errorCollection.AddSettingOutsideLimits(element, settingLimits);
                    }
                }
                //Invalid element.
                else
                {
                    _errorCollection.AddInvalidElement(element);
                }
            }

            return(outValueGenerator);
        }
        /// <summary>
        ///     Initializes a new instance of the <see cref="SaveChangesHelper" /> class.
        /// </summary>
        /// <param name="dbContext"> <see cref="DbContext" /> against which the requested query will be executed. </param>
        /// <param name="request"> The <see cref="SaveChangesRequest" /> object from the client containing the updated entities. </param>
        public SaveChangesHelper(DbContext dbContext, SaveChangesRequest request)
        {
            this.dbContext = dbContext;

            var typeMap                  = this.dbContext.Model.GetEntityTypes().ToDictionary(x => x.DisplayName());
            var stateManager             = this.dbContext.GetService <IStateManager>();
            var entityMaterializerSource = this.dbContext.GetService <IEntityMaterializerSource>();

            // Materialize entities and add entries to dbContext
            EntityEntry MaterializeAndTrackEntity(UpdateEntryDto dto)
            {
                IEntityType entityType = typeMap[dto.EntityTypeName];

                object MaterializeEntity()
                {
                    var valueBuffer            = new ValueBuffer(dto.GetCurrentValues(entityType, request.Mapper));
                    var materializationContext = new MaterializationContext(valueBuffer, this.dbContext);

                    return(entityMaterializerSource.GetMaterializer(entityType).Invoke(materializationContext));
                }

                EntityEntry entry;

                if (entityType.HasDefiningNavigation())
                {
                    IKey     key       = entityType.DefiningEntityType.FindPrimaryKey();
                    object[] keyValues = dto.GetDelegatedIdentityKeys(request.Mapper, key);

                    // Here we assume that the owner entry is already present in the context
                    EntityEntry ownerEntry = stateManager.TryGetEntry(key, keyValues).ToEntityEntry();

                    ReferenceEntry referenceEntry = ownerEntry.Reference(entityType.DefiningNavigationName);
                    if (referenceEntry.CurrentValue == null)
                    {
                        referenceEntry.CurrentValue = MaterializeEntity();
                    }

                    entry = referenceEntry.TargetEntry;
                }
                else
                {
                    entry = stateManager.GetOrCreateEntry(MaterializeEntity()).ToEntityEntry();
                }

                // Correlate properties of DTO and entry
                var props = dto.JoinScalarProperties(entry, request.Mapper);

                // Set Key properties
                foreach (var p in props.Where(x => x.EfProperty.Metadata.IsKey()))
                {
                    p.EfProperty.CurrentValue = p.CurrentValue;
                    if (p.EfProperty.Metadata.GetOriginalValueIndex() >= 0)
                    {
                        p.EfProperty.OriginalValue = p.OriginalValue;
                    }
                }

                // Set EntityState after PK values (temp or perm) are set.
                // This will add entities to identity map.
                entry.State = dto.EntityState;

                // Set non key properties
                foreach (var p in props.Where(x => !x.EfProperty.Metadata.IsKey()))
                {
                    bool canSetCurrentValue =
                        p.EfProperty.Metadata.IsShadowProperty ||
                        p.EfProperty.Metadata.TryGetMemberInfo(forConstruction: false, forSet: true, out _, out _);

                    if (canSetCurrentValue)
                    {
                        p.EfProperty.CurrentValue = p.CurrentValue;
                    }

                    if (p.EfProperty.Metadata.GetOriginalValueIndex() >= 0 &&
                        p.EfProperty.OriginalValue != p.OriginalValue)
                    {
                        p.EfProperty.OriginalValue = p.OriginalValue;
                    }

                    if (canSetCurrentValue)
                    {
                        p.EfProperty.IsModified = p.DtoProperty.IsModified;
                    }
                }

                // Mark temporary property values
                foreach (var p in props.Where(x => x.DtoProperty.IsTemporary))
                {
                    p.EfProperty.IsTemporary = true;
                }

                return(entry);
            }

            request.SharedIdentityDataTransferObjects.ForEach(dto => MaterializeAndTrackEntity(dto));
            var entries = request.DataTransferObjects.Select(MaterializeAndTrackEntity).ToList();

            // Replace temporary PKs coming from client with generated values (e.g. HiLoSequence)
            var valueGeneratorSelector = this.dbContext.GetService <IValueGeneratorSelector>();

            foreach (EntityEntry entry in entries)
            {
                foreach (PropertyEntry tempPk in
                         entry.Properties.Where(p =>
                                                p.IsTemporary &&
                                                p.Metadata.IsKey() &&
                                                p.Metadata.RequiresValueGenerator()).ToList())
                {
                    ValueGenerator valueGenerator = valueGeneratorSelector.Select(tempPk.Metadata, entry.Metadata);
                    if (!valueGenerator.GeneratesTemporaryValues)
                    {
                        tempPk.CurrentValue = valueGenerator.Next(entry);
                        tempPk.IsTemporary  = false;
                    }
                }
            }

            this.Entries = entries.Select(e => e.GetInfrastructure()).ToList();
        }
Beispiel #8
0
 public int Roll(bool isCritical = false)
 {
     return((isCritical && Size > 1)
         ? ValueGenerator.RollDice(this) + ValueGenerator.RollDice(this)
         : ValueGenerator.RollDice(this));
 }
Beispiel #9
0
        public async Task <IActionResult> Login([FromBody] LoginRequest request)
        {
            Response <RegisteredUserResponse> response = new Response <RegisteredUserResponse>();

            try
            {
                if (!ModelState.IsValid)
                {
                    var requestResponse = ApiResponseFormatter.RequestResponse(ModelState);
                    return(BadRequest(requestResponse));
                }

                User     userCredentials;
                DateTime dateRegistered;
                using (var _context = new MiniSurveyContext())
                {
                    userCredentials = await _context.Users.Where(x => x.EmailAddress == request.Email.Trim())
                                      .FirstOrDefaultAsync();
                }

                if (userCredentials == null)
                {
                    response = new Response <RegisteredUserResponse>
                    {
                        ResponseBody = new SuccessResponse <RegisteredUserResponse>
                        {
                            Data            = null,
                            ResponseCode    = "E001",
                            ResponseMessage = "Your email and password combination was incorrect, kindly try again later."
                        }
                    };
                    return(Unauthorized(response.ResponseBody));
                }

                bool isPassword = userCredentials != null && _cryptographyService.ValidateHash(request.Password, userCredentials.PasswordSalt, userCredentials.PasswordHash);
                if (!isPassword)
                {
                    response = new Response <RegisteredUserResponse>
                    {
                        ResponseBody = new SuccessResponse <RegisteredUserResponse>
                        {
                            Data            = null,
                            ResponseCode    = "E001",
                            ResponseMessage = "Your email and password combination was incorrect, kindly try again later."
                        }
                    };
                    return(Unauthorized(response.ResponseBody));
                }

                var identity = _jwtFactory.GenerateClaimsIdentity(userCredentials.EmailAddress, userCredentials.Id.ToString());
                var jwtToken = await ValueGenerator.GenerateJwt(identity, _jwtFactory, userCredentials.EmailAddress, _jwtOptions.Value, new JsonSerializerSettings { Formatting = Formatting.None });

                // deserialize generated auth token to be passed to client application.
                var authToken = JsonConvert.DeserializeObject <Token>(jwtToken);

                response = new Response <RegisteredUserResponse>
                {
                    ResponseBody = new SuccessResponse <RegisteredUserResponse>
                    {
                        Data = new RegisteredUserResponse {
                            User = new Dto.UserResponse {
                                Email = userCredentials.EmailAddress, Name = userCredentials.Name, DateRegistered = userCredentials.DateRegistered
                            }, Role = new DefaultResponse {
                                Id = userCredentials.RoleId, Value = HelperFunctions.GetRole(userCredentials.RoleId)
                            }
                        },
                        ResponseCode    = "00",
                        ResponseMessage = "You have been successfully enrolled to participate in the survey."
                    }
                };


                return(Ok(response.ResponseBody));
            }
            catch (Exception)
            {
                response = new Response <RegisteredUserResponse>
                {
                    ResponseBody = new SuccessResponse <RegisteredUserResponse>
                    {
                        Data            = null,
                        ResponseCode    = "E001",
                        ResponseMessage = "Sorry, we are unable to process your request at the moment, kindly try again later."
                    }
                };
                return(StatusCode(500, response.ResponseBody));
            }
        }
        public string LiteralDataTest(object data)
        {
            var generator = new ValueGenerator();

            return(generator.Generate(data));
        }
        private void GenerateBehaviorActions(ActionCollection actionCollection, CodeTypeDeclaration classType, CodeMemberMethod method, CodeVariableReferenceExpression behaviorVarRef, string behaviorName)
        {
            for (int i = 0; i < actionCollection.Count; i++)
            {
                var action = actionCollection[i];
                string actionName = behaviorName + "_ACT_" + i;
                Type type = action.GetType();

                CodeVariableDeclarationStatement variable = new CodeVariableDeclarationStatement(type.Name, actionName, new CodeObjectCreateExpression(type.Name));
                method.Statements.Add(variable);
                var actionVarRef = new CodeVariableReferenceExpression(actionName);

                method.Statements.Add(new CodeMethodInvokeExpression(
                        behaviorVarRef, "Actions.Add", actionVarRef));

                ValueGenerator valueGenerator = new ValueGenerator();
                MethodInfo generateFieldMethod = typeof(CodeComHelper).GetMethod("GenerateField");

                LocalValueEnumerator enumerator = action.GetLocalValueEnumerator();
                while (enumerator.MoveNext())
                {
                    LocalValueEntry entry = enumerator.Current;
                    DependencyProperty property = entry.Property;
                    Type valueType = entry.Value.GetType();
                    if (CodeComHelper.IsValidForFieldGenerator(entry.Value))
                    {
                        if (valueGenerator.Generators.ContainsKey(property.PropertyType) || valueGenerator.Generators.ContainsKey(valueType))
                        {
                            CodeExpression propValue = valueGenerator.ProcessGenerators(classType, method, entry.Value, actionName);
                            if (propValue != null)
                            {
                                method.Statements.Add(new CodeAssignStatement(new CodeFieldReferenceExpression(actionVarRef, property.Name), propValue));
                            }
                        }
                        else if (entry.Value is PropertyPath)
                        {
                            PropertyPath path = entry.Value as PropertyPath;
                            method.Statements.Add(new CodeAssignStatement(
                                new CodeFieldReferenceExpression(actionVarRef, property.Name), 
                                new CodeObjectCreateExpression("PropertyPath", new CodePrimitiveExpression(path.Path))));
                        }
                        else
                        {
                            MethodInfo generic = generateFieldMethod.MakeGenericMethod(property.PropertyType);
                            if (generic == null)
                            {
                                throw new NullReferenceException("Generic method not created for type - " + property.PropertyType);
                            }

                            generic.Invoke(null, new object[] { method, actionVarRef, action, property });
                        }
                    }
                }

                CodeComHelper.GenerateBindings(method, actionVarRef, action, actionName, behaviorVarRef);
                //CodeComHelper.GenerateResourceReferences(method, actionVarRef, action);
            }
        }
        private void GenerateBehaviors(BehaviorCollection behaviors, CodeTypeDeclaration classType, CodeMemberMethod method, FrameworkElement element, CodeExpression fieldReference)
        {

            for (int i = 0; i < behaviors.Count; i++)
            {
                var behavior = behaviors[i];
                string behaviorName = element.Name + "_BEH_" + i;
                Type type = behavior.GetType();
                CodeVariableDeclarationStatement variable = new CodeVariableDeclarationStatement(type.Name, behaviorName, new CodeObjectCreateExpression(type.Name));
                method.Statements.Add(variable);
                var behaviorVarRef = new CodeVariableReferenceExpression(behaviorName);
                
                method.Statements.Add(new CodeMethodInvokeExpression(
                        new CodeVariableReferenceExpression("Interaction"), "GetBehaviors(" + element.Name + ").Add", behaviorVarRef));

                ValueGenerator valueGenerator = new ValueGenerator();
                MethodInfo generateFieldMethod = typeof(CodeComHelper).GetMethod("GenerateField");

                LocalValueEnumerator enumerator = behavior.GetLocalValueEnumerator();
                while (enumerator.MoveNext())
                {
                    LocalValueEntry entry = enumerator.Current;
                    DependencyProperty property = entry.Property;
                    Type valueType = entry.Value.GetType();
                    if (CodeComHelper.IsValidForFieldGenerator(entry.Value))
                    {
                        if (valueGenerator.Generators.ContainsKey(property.PropertyType) || valueGenerator.Generators.ContainsKey(valueType))
                        {
                            CodeExpression propValue = valueGenerator.ProcessGenerators(classType, method, entry.Value, behaviorName);
                            if (propValue != null)
                            {
                                method.Statements.Add(new CodeAssignStatement(new CodeFieldReferenceExpression(behaviorVarRef, property.Name), propValue));
                            }
                        }
                        else if (entry.Value is ActionCollection)
                        {
                            GenerateBehaviorActions(entry.Value as ActionCollection, classType, method, behaviorVarRef, behaviorName);
                        }
                        else
                        {
                            MethodInfo generic = generateFieldMethod.MakeGenericMethod(property.PropertyType);
                            if (generic == null)
                            {
                                throw new NullReferenceException("Generic method not created for type - " + property.PropertyType);
                            }

                            generic.Invoke(null, new object[] { method, behaviorVarRef, behavior, property });
                        }
                    }
                }

                CodeComHelper.GenerateBindings(method, behaviorVarRef, behavior, behaviorName);
                CodeComHelper.GenerateResourceReferences(method, behaviorVarRef, behavior);
            }
        }
Beispiel #13
0
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes:
//ORIGINAL LINE: @ParameterizedTest @MethodSource("validValueGenerators") void mustProduceValidMinimalSplittersWhenValuesAreEqual(ValueGenerator valueGenerator)
        internal virtual void MustProduceValidMinimalSplittersWhenValuesAreEqual(ValueGenerator valueGenerator)
        {
            AssertValidMinimalSplitterForEqualValues(valueGenerator());
        }
 public ValueGeneratorTests()
 {
     generator = new ValueGenerator();
 }
Beispiel #15
0
 public WeaponsPerFunctionKeyGuarantee(ValueGenerator valueGenerator)
 {
     _valueGenerator = valueGenerator;
 }
Beispiel #16
0
 public void SetUp()
 {
     _valueGenerator = new ValueGenerator();
 }
        /// <summary>
        /// Generates code
        /// </summary>
        /// <param name="source">The dependence object</param>
        /// <param name="classType">Type of the class.</param>
        /// <param name="method">The initialize method.</param>
        /// <param name="generateField"></param>
        /// <returns></returns>
        public override CodeExpression Generate(DependencyObject source, CodeTypeDeclaration classType, CodeMemberMethod method, bool generateField)
        {
            CodeExpression fieldReference = base.Generate(source, classType, method, generateField);

            ItemsControl itemsControl = source as ItemsControl;

            CodeComHelper.GenerateTemplateStyleField(classType, method, fieldReference, source, ItemsControl.ItemsPanelProperty);
            CodeComHelper.GenerateTemplateStyleField(classType, method, fieldReference, source, ItemsControl.ItemTemplateProperty);

            if (itemsControl.Items.Count > 0)
            {
                TypeGenerator  typeGenerator  = new TypeGenerator();
                ValueGenerator valueGenerator = new ValueGenerator();

                CodeMemberMethod itemsMethod = new CodeMemberMethod();
                itemsMethod.Attributes = MemberAttributes.Static | MemberAttributes.Private;
                itemsMethod.Name       = "Get_" + itemsControl.Name + "_Items";
                itemsMethod.ReturnType = new CodeTypeReference(typeof(ObservableCollection <object>));
                classType.Members.Add(itemsMethod);

                CodeVariableDeclarationStatement collection = new CodeVariableDeclarationStatement(
                    typeof(ObservableCollection <object>), "items", new CodeObjectCreateExpression(typeof(ObservableCollection <object>)));
                itemsMethod.Statements.Add(collection);

                CodeVariableReferenceExpression itemsVar = new CodeVariableReferenceExpression("items");
                foreach (var item in itemsControl.Items)
                {
                    Type           itemType = item.GetType();
                    CodeExpression itemExpr = null;
                    if (typeGenerator.HasGenerator(itemType))
                    {
                        itemExpr = typeGenerator.ProcessGenerators(item, classType, itemsMethod, false);
                    }
                    else
                    {
                        itemExpr = valueGenerator.ProcessGenerators(classType, itemsMethod, item, itemsControl.Name + "v" + uniqueId);
                    }

                    if (itemExpr != null)
                    {
                        CodeMethodInvokeExpression addItem = new CodeMethodInvokeExpression(itemsVar, "Add", itemExpr);
                        itemsMethod.Statements.Add(addItem);
                    }
                    else
                    {
                        CodeComHelper.GenerateError(itemsMethod, string.Format("Type {0} in Items Control collection not supported", itemType.Name));
                    }

                    uniqueId++;
                }

                CodeMethodReturnStatement returnStatement = new CodeMethodReturnStatement(itemsVar);
                itemsMethod.Statements.Add(returnStatement);

                method.Statements.Add(new CodeAssignStatement(
                                          new CodeFieldReferenceExpression(fieldReference, "ItemsSource"),
                                          new CodeMethodInvokeExpression(null, itemsMethod.Name)));
            }

            return(fieldReference);
        }