Ejemplo n.º 1
0
        protected Base(string projectName, string assemblyName, string classFullName, string className)
        {
            var byteName = assemblyName.Split('.');
            var serviceName = byteName[byteName.Length - 2];
            byteName[byteName.Length - 1] = serviceName + "Context";
            var contextName = String.Join(".", byteName);

            var projPath = Path.GetDirectoryName(projectName);
            var projRootNamespace = Path.GetFileNameWithoutExtension(projectName);

            Model = new ModelProperty
                        {
                            ServerName = serviceName,
                            ModelTypeNamespace = GetNamespaceByClassname(classFullName),
                            DbContextNamespace = GetNamespaceByClassname(contextName),
                            RepositoryNamespace = projRootNamespace + ".Models",
                            Namespace = projRootNamespace,
                            ModelType = classFullName,
                            ContextType = contextName,//
                            ModelName = classFullName.Split('.').Last(),//User
                            PrimaryKey = "ID",
                            PrimaryKeyProperty = "System.Guid",
                            Name = projRootNamespace.Split('.').Last(),//baseportal
                            ModelTypePluralized = className            //Users
                        };
        }
Ejemplo n.º 2
0
        public ModelPropertyDescriptor(ModelProperty property)
            : base(property.Name, new Attribute[0])
        {
            if (property == null)
                throw new ArgumentNullException("property", "property is null.");

            this.property = property;
            this.property.ChangedEvent += (sender, e) => OnValueChanged(e.Instance, EventArgs.Empty);
        }
Ejemplo n.º 3
0
        public ModelProperty NewProperty(ModelClass cls, Column column)
        {
            ModelProperty property = new ModelProperty(_store);
            property.Name = ModelHelper.GetSafeName(column.Name, _model.PropertyNameFilterExpression);
            property.Column = column.Name;
            property.NotNull = !column.Nullable;
            property.Accessor = Accessor.Public;
            property.ModelClass = cls;

            return property;
        }
Ejemplo n.º 4
0
 public object this[ModelProperty property]
 {
     get
     {
         var value = instanceProperties[property.Index];
         if (value == null && property is ModelReferenceProperty && property.IsList)
             instanceProperties[property.Index] = value = new ObservableCollection<JsonInstance>();
         return value;
     }
     set
     {
         instanceProperties[property.Index] = value;
     }
 }
Ejemplo n.º 5
0
 /// <summary>
 /// Only set the value into the control if it isn't the default.
 /// </summary>
 /// <param name="property">Property Id.</param>
 /// <param name="value">Property value.</param>
 internal static void SparseSetValue(ModelProperty property, object value)
 {
     if (object.Equals(property.DefaultValue, value))
     {
         if (property.IsSet)
         {
             property.ClearValue();
         }
     }
     else
     {
         property.SetValue(value);
     }
 }
Ejemplo n.º 6
0
        ///--------------------------------------------------------------------------------
        /// <summary>This method loads an item of ModelObjectData into the view model.</summary>
        ///
        /// <param name="model">The Model to load.</param>
        /// <param name="modelObject">The ModelObject to load.</param>
        /// <param name="modelProperty">The ModelProperty to load.</param>
        /// <param name="objectInstance">The ObjectInstance to load.</param>
        /// <param name="solution">The Solution to load.</param>
        /// <param name="loadChildren">Flag indicating whether to perform a deeper load.</param>
        ///--------------------------------------------------------------------------------
        public void LoadModelPropertyData(Model model, ModelObject modelObject, ModelProperty modelProperty, ObjectInstance objectInstance, Solution solution, bool loadChildren = true)
        {
            // attach the ModelObject
            Model          = model;
            ModelObject    = modelObject;
            ModelProperty  = modelProperty;
            ObjectInstance = objectInstance;
            Solution       = solution;
            ItemID         = ModelProperty.ModelPropertyID;
            Items.Clear();
            if (loadChildren == true)
            {
                // attach PropertyInstances
                if (PropertyInstances == null)
                {
                    PropertyInstances = new EnterpriseDataObjectList <PropertyInstanceViewModel>();
                    foreach (PropertyInstance item in objectInstance.PropertyInstanceList)
                    {
                        if (item.Solution == null)
                        {
                            // TODO: this is a hack
                            item.Solution = solution;
                        }
                        if (objectInstance == null || item.ModelPropertyID == modelProperty.ModelPropertyID)
                        {
                            PropertyInstanceViewModel itemView = new PropertyInstanceViewModel(item, solution);
                            itemView.Updated += new EventHandler(Children_Updated);
                            PropertyInstances.Add(itemView);
                            Items.Add(itemView);
                        }
                    }
                }
                #region protected
                #endregion protected

                Refresh(false);
            }
        }
Ejemplo n.º 7
0
        private void ChangeValue(object newValue)
        {
            ValueChangingEventArgs changingArgs = new ValueChangingEventArgs()
            {
                RoutedEvent = ValueChangingEvent,
                Source      = this,
                Handled     = false,
                OldValue    = this.Item,
                NewValue    = newValue
            };

            RaiseEvent(changingArgs);

            if (changingArgs.Handled)
            {
                return;
            }

            ModelProperty modelProperty = GetModelProperty();

            if (null == modelProperty)
            {
                return;
            }

            OnChangeValue(newValue, modelProperty);

            RoutedEventArgs changedArgs = new ValueChangedEventArgs()
            {
                RoutedEvent = ValueChangedEvent,
                Source      = this,
                Handled     = false,
                OldValue    = this.Item,
                NewValue    = newValue
            };

            RaiseEvent(changedArgs);
        }
Ejemplo n.º 8
0
 private void AddOppositeProperty(ModelProperty property, bool firstCall)
 {
     if (property == null)
     {
         return;
     }
     if (this.equivalentProperties.Contains(property))
     {
         return;
     }
     if (!this.oppositeProperties.Contains(property))
     {
         this.oppositeProperties.Add(property);
         if (firstCall)
         {
             foreach (var eqProp in this.equivalentProperties)
             {
                 var eqSlot = CreateComplexSlot(map, eqProp);
                 eqSlot.AddOppositeProperty(property, false);
             }
         }
     }
 }
Ejemplo n.º 9
0
        public void DropBoxDeleteViewModel_DeletePath_GivenIsSet_ShouldSetModelItemProperty()
        {
            //------------Setup for test--------------------------
            var agg   = new Mock <IEventAggregator>();
            var model = CreateModelItem();

            //------------Execute Test---------------------------
            // ReSharper disable once UseObjectOrCollectionInitializer
            var dropBoxDeleteViewModel = new DropBoxDeleteViewModel(model, TestResourceCatalog.LazySourceManager.Value);

            dropBoxDeleteViewModel.DeletePath = "A";

            //------------Assert Results-------------------------
            ModelProperty property = model.Properties["DeletePath"];

            if (property == null)
            {
                Assert.Fail("Property Does not exist");
            }
            var modelPropertyValue = property.ComputedValue;

            Assert.AreEqual("A", modelPropertyValue);
        }
Ejemplo n.º 10
0
        /// <summary>
        /// Retourne le code associé au cors de l'implémentation d'un service de type ReferenceAccessor.
        /// </summary>
        /// <param name="className">Nom du type chargé par le ReferenceAccessor.</param>
        /// <param name="defaultProperty">Propriété par defaut de la classe.</param>
        /// <returns>Code généré.</returns>
        protected override string LoadReferenceAccessorBody(string className, ModelProperty defaultProperty)
        {
            string queryParameter = string.Empty;

            if (GeneratorParameters.IsEntityFrameworkUsed)
            {
                if (defaultProperty != null)
                {
                    queryParameter = $".OrderBy(row => row.{defaultProperty.Name})";
                }

                return($"return _dbContext.{Pluralize(className)}{queryParameter}.ToList();");
            }
            else
            {
                if (defaultProperty != null)
                {
                    queryParameter = "new Kinetix.Data.SqlClient.QueryParameter(" + className + ".Cols." + defaultProperty.DataMember.Name + ", Kinetix.Data.SqlClient.SortOrder.Asc)";
                }

                return("return BrokerManager.GetStandardBroker<" + className + ">().GetAll(" + queryParameter + ");");
            }
        }
Ejemplo n.º 11
0
        /// <summary>
        /// Validates a value being assigned to a property.
        /// </summary>
        /// <param name="property">Property being modified.</param>
        /// <param name="value">Value being assigned to the property.</param>
        /// <returns>
        ///   <c>null</c> if the value is valid for the property, or an error message indicating why the value is not valid.
        /// </returns>
        protected override string Validate(ModelProperty property, object value)
        {
            if (property == TextProperty)
            {
                if (String.IsNullOrEmpty((string)value) && IsRequired)
                {
                    if (IsRequired)
                    {
                        return(String.Format("{0} is required", LabelWithoutAccelerators));
                    }

                    Value = null;
                }
                else
                {
                    Int32 iVal;
                    if (!Int32.TryParse((string)value, out iVal))
                    {
                        return(String.Format("{0} is not a valid number", LabelWithoutAccelerators));
                    }

                    if (iVal < MinValue)
                    {
                        return(String.Format("{0} cannot be lower than {1}", LabelWithoutAccelerators, MinValue));
                    }

                    if (iVal > MaxValue)
                    {
                        return(String.Format("{0} cannot be higher than {1}", LabelWithoutAccelerators, MaxValue));
                    }

                    Value = iVal;
                }
            }

            return(base.Validate(property, value));
        }
Ejemplo n.º 12
0
        public bool Update <T>(T model) where T : class
        {
            ModelInfo           mi        = GetModelInfo <T>();
            string              format    = "update {0} set {1} where {2};";
            string              colunms   = "";
            string              condition = "";
            List <SqlParameter> list      = new List <SqlParameter>();

            foreach (PropertyInfo info in mi.ObjType.GetProperties())
            {
                string name       = info.Name;
                object fieldValue = ModelProperty <T> .GetValue(model as T, name);

                list.Add(new SqlParameter("@" + name, fieldValue));

                if (name == mi.IDFieldName)
                {
                    CheckIDField <T>(model, mi, fieldValue);
                    condition = mi.IDFieldName + "=@" + name;
                }
                else if (colunms.Length > 0)
                {
                    string str5 = colunms;
                    colunms = str5 + "," + name + "=@" + name;
                }
                else
                {
                    colunms = colunms + name + "=@" + name;
                }
            }
            format = string.Format(format, mi.TableName, colunms, condition);
            if (SqlHandler.ExecuteSql(mi.Conn, format, list.ToArray()) <= 0)
            {
                return(false);
            }
            return(true);
        }
Ejemplo n.º 13
0
        private TreeNodes CreateUpdatedIntellisense(List <ModelItem> vars)
        {
            TreeNodes result = IntellisenseData;

            lock (_intellisenseLock)
            {
                foreach (var vs in vars)
                {
                    ModelProperty vsProp = vs.Properties["Name"];
                    if (vsProp == null)
                    {
                        continue;
                    }
                    string varName = (string)vsProp.ComputedValue;
                    IEnumerable <TreeNodes> res = result.Nodes.Where(x => x.Name == varName);

                    if (res.FirstOrDefault() == null)
                    {
                        Type          sysType     = null;
                        ModelProperty sysTypeProp = vs.Properties["Type"];
                        if (sysTypeProp != null)
                        {
                            sysType = (Type)sysTypeProp.ComputedValue;
                        }
                        TreeNodes newVar = new TreeNodes
                        {
                            Name        = varName,
                            ItemType    = TreeNodes.NodeTypes.Primitive,
                            SystemType  = sysType,
                            Description = ""
                        };
                        result.Nodes.Add(newVar);
                    }
                }
            }
            return(result);
        }
Ejemplo n.º 14
0
        //Create New TextID
        private void CreateNewIDText(object sender, RoutedEventArgs e)
        {
            Encoding encoding = Encoding.Default;

            //Get the File Path
            string FilePath = Directory.GetCurrentDirectory() + "/StorageTextToolbox/Infos/" + MyIDText + ".txt";

            //Get Encoding
            encoding = DesignUtils.GetEncodingIDText(MyIDText);

            //Clear the Current IDText
            ModelProperty property = this.ModelItem.Properties["IDText"];

            property.SetValue(null);

            //Update IDText
            UpdateIDText();

            //Copy the Arguments, in case there is
            string FilePathPreview = ReturnCurrentFile();

            //File Name
            if (FilePath != null)
            {
                //Update Text File Row Argument
                DesignUtils.CallUpdateTextFileRowArgument(FilePath, "FileName", FilePathPreview, encoding);
            }

            //Encoding
            string MyEncoding = ReturnEncoding();

            if (MyEncoding != null)
            {
                //Update Text File Row Argument
                DesignUtils.CallUpdateTextFileRowArgument(FilePath, "Encoding", MyEncoding, encoding);
            }
        }
Ejemplo n.º 15
0
        public void OnDocumentSelectionChanged(object sender, EventArgs e)
        {
            if (sender != null)
            {
                ModelingDocView view = sender as ModelingDocView;
                if (view != null)
                {
                    ICollection selection = view.GetSelectedComponents();
                    if (selection.Count == 1)
                    {
                        IEnumerator enumerator = selection.GetEnumerator();
                        enumerator.MoveNext();
                        ClassShape shape = enumerator.Current as ClassShape;
                        if (shape != null)
                        {
                            ModelClass modelClass = shape.ModelElement as ModelClass;
                            if (modelClass != null)
                            {
                                control.Display(modelClass);

                                return;
                            }
                        }

                        ModelProperty property = enumerator.Current as ModelProperty;
                        if (property != null)
                        {
                            control.Display(property.ModelClass);

                            return;
                        }
                    }
                }

                control.Clear();
            }
        }
        public void AddFilter(ModelProperty modelProperty, string regSearchValues)
        {
            foreach (var regSearch in regSearchValues.Split('|'))
            {
                var searchType = (SearchType)(regSearch.StartsWith("^") ? 2 : 0) + (regSearch.EndsWith("$") ? 1 : 0);
                var search     = regSearch.TrimStart('^').TrimEnd('$');
                if (search == null || search == ".*")
                {
                    return;
                }

                if (modelProperty.Type.IsString())
                {
                    AddStringFilter(modelProperty, search, searchType);
                }
                if (modelProperty.Type.IsEnum)
                {
                    AddEnumFilter(modelProperty, search, searchType);
                }
                if (modelProperty.Type.IsBool())
                {
                    AddBoolFilter(modelProperty, search, searchType);
                }
                if (modelProperty.Type.IsDateTimeType())
                {
                    AddDateTimeFilter(modelProperty, search, searchType);
                }
                if (modelProperty.Type.IsNumericType())
                {
                    AddNumericFilter(modelProperty, search, searchType);
                }
                if (modelProperty.Type.IsDateTimeOffsetType())
                {
                    AddDateTimeOffsetFilter(modelProperty, search, searchType);
                }
            }
        }
Ejemplo n.º 17
0
        void ValidateRuleCriteria()
        {
            Initialize += (s, e) =>
            {
                // Get the model property from the base class
                ModelProperty p = Property;

                // Verify that the target property is supported by the rule
                if (p is ModelReferenceProperty)
                {
                    if (p.IsList)
                    {
                        throw new ArgumentException("The CompareRule does not support comparing list properties.");
                    }

                    if (CompareOperator != CompareOperator.Equal && CompareOperator != CompareOperator.NotEqual)
                    {
                        throw new ArgumentException("The CompareRule only supports the Equal and NotEqual operators for reference properties.");
                    }
                }
                else
                {
                    var propertyType = ((ModelValueProperty)p).PropertyType;

                    // If Nullable<T> check the underlying type
                    if (propertyType.IsGenericType && propertyType.GetGenericTypeDefinition() == typeof(Nullable <>))
                    {
                        propertyType = Nullable.GetUnderlyingType(propertyType);
                    }

                    if (!typeof(IComparable).IsAssignableFrom(propertyType))
                    {
                        throw new ArgumentException("The CompareRule only supports value properties that implement IComparable.");
                    }
                }
            };
        }
        public override void ShowDialog(PropertyValue propertyValue, IInputElement commandSource)
        {
            ModelPropertyEntryToOwnerActivityConverter propertyEntryConverter =
                new ModelPropertyEntryToOwnerActivityConverter();

            ModelItem activityModelItem =
                (ModelItem)propertyEntryConverter.Convert(propertyValue.ParentProperty, typeof(ModelItem), false, null);

            ModelItem parentModelItem =
                (ModelItem)propertyEntryConverter.Convert(propertyValue.ParentProperty, typeof(ModelItem), true, null);

            EditingContext context = ((IModelTreeItem)activityModelItem).ModelTreeManager.Context;

            ModelItemCollection inputData    = parentModelItem.Properties[propertyValue.ParentProperty.PropertyName].Collection;
            IEnumerable <Type>  rawInputData = inputData.GetCurrentValue() as IEnumerable <Type>;

            Fx.Assert(rawInputData != null, "rawInputData is null or is not IEnumerable<Type>.");

            ModelProperty     editingProperty  = activityModelItem.Properties[propertyValue.ParentProperty.PropertyName];
            bool              allowDuplication = GetOptionValueOrUseDefault(editingProperty.Attributes, TypeCollectionPropertyEditor.AllowDuplicate, true);
            Func <Type, bool> filter           = GetOptionValueOrUseDefault <Func <Type, bool> >(editingProperty.Attributes, TypeCollectionPropertyEditor.Filter, null);
            Type              defaultType      = GetOptionValueOrUseDefault <Type>(editingProperty.Attributes, TypeCollectionPropertyEditor.DefaultType, typeof(Object));
            EditorWindow      editorWindow     = new EditorWindow(activityModelItem, rawInputData, context, activityModelItem.View, allowDuplication, filter, defaultType);

            if (editorWindow.ShowOkCancel())
            {
                using (var commitEditingScope = inputData.BeginEdit(System.Activities.Core.Presentation.SR.ChangeTypeCollectionEditingScopeDesc))
                {
                    inputData.Clear();
                    foreach (Type i in ((TypeCollectionDesigner)editorWindow.Content).UpdatedTypeCollection)
                    {
                        inputData.Add(i);
                    }
                    commitEditingScope.Complete();
                }
            }
        }
Ejemplo n.º 19
0
        void ModelItem_PropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e)
        {
            // If left-hand operand changed, check if it become a feature property having valid values, e.g. Domain Attribute
            if (e.PropertyName == IMConstants.LeftOperandPropertyName)
            {
                IEnumerable <DynamicValue> validValues = ModelItem.Properties[IMConstants.RightOperandPropertyName].Value.GetValidValues();
                ModelProperty rightOperand             = ModelItem.Properties[IMConstants.RightOperandPropertyName];

                // if expression like "1 equals 1" becomes "status equals 1", the right-hand operand should be refresh.
                // if expression like "Status equals new" becomes "1 equals new", the right-hand operand should be refresh, too.
                if (validValues.Any())
                {
                    // TODO: refactor to remove redundant code.
                    DynamicValue dv = validValues.First();
                    rightOperand.SetValue(DynamicLiteral.CreateArgument(dv.Value));
                    _hasValidValues = true;
                }
                else if (_hasValidValues)
                {
                    rightOperand.SetValue(DynamicLiteral.CreateArgument(IMConstants.DefaultNumberValue));
                    _hasValidValues = false;
                }
            }
        }
Ejemplo n.º 20
0
        public PropertyData(ModelProperty p)
        {
            Name = p.Name;

            Access                   = p.Access;
            Accessor                 = p.Accessor;
            Check                    = p.Check;
            Column                   = p.Column;
            ColumnType               = p.ColumnType;
            CustomAccess             = p.CustomAccess;
            CustomColumnType         = p.CustomColumnType;
            CustomMemberType         = p.CustomMemberType;
            DebuggerDisplay          = p.DebuggerDisplay;
            DefaultMember            = p.DefaultMember;
            ColumnDefault            = p.ColumnDefault;
            Description              = p.Description;
            Formula                  = p.Formula;
            Generator                = p.Generator;
            Index                    = p.Index;
            Insert                   = p.Insert;
            KeyType                  = p.KeyType;
            Length                   = p.Length;
            NotNull                  = p.NotNull;
            Params                   = p.Params;
            PropertyType             = p.PropertyType;
            SequenceName             = p.SequenceName;
            SqlType                  = p.SqlType;
            Unique                   = p.Unique;
            UniqueKey                = p.UniqueKey;
            UnsavedValue             = p.UnsavedValue;
            Update                   = p.Update;
            ValidatorPropertyStorage = p.GetValidatorValue();

            ModelClass  = p.ModelClass;
            NestedClass = p.NestedClass;
        }
Ejemplo n.º 21
0
        /// <summary>
        /// Binds a property on a model to the view model.
        /// </summary>
        /// <param name="viewModelProperty">View model property to bind.</param>
        /// <param name="binding">Information about how the view model property is bound.</param>
        public void SetBinding(ModelProperty viewModelProperty, ModelBinding binding)
        {
            ModelBinding oldBinding;

            if (_bindings.TryGetValue(viewModelProperty.Key, out oldBinding))
            {
                _bindings = _bindings.Remove(viewModelProperty.Key);
                if (!IsObserving(oldBinding.Source, oldBinding.SourceProperty))
                {
                    oldBinding.Source.RemovePropertyChangedHandler(oldBinding.SourceProperty, OnSourcePropertyChanged);
                }
            }
            else if (_selfBindings.TryGetValue(viewModelProperty.Key, out oldBinding))
            {
                _selfBindings = _selfBindings.Remove(viewModelProperty.Key);
            }

            if (binding != null)
            {
                if (ReferenceEquals(binding.Source, this))
                {
                    _selfBindings = _selfBindings.Add(viewModelProperty.Key, binding);
                    RefreshBinding(viewModelProperty.Key, binding);
                }
                else
                {
                    if (!IsObserving(binding.Source, binding.SourceProperty))
                    {
                        binding.Source.AddPropertyChangedHandler(binding.SourceProperty, OnSourcePropertyChanged);
                    }

                    _bindings = _bindings.Add(viewModelProperty.Key, binding);
                    RefreshBinding(viewModelProperty.Key, binding);
                }
            }
        }
Ejemplo n.º 22
0
        ///--------------------------------------------------------------------------------
        /// <summary>This method gets the property value for the input property name.</summary>
        ///
        /// <param name="propertyName">The name of the property to get the value of.</param>
        /// <param name="propertyFound">Output flag, indicating whether property was found or not.</param>
        ///--------------------------------------------------------------------------------
        public string GetStringValue(string propertyName, out bool propertyFound)
        {
            StringBuilder value = new StringBuilder();

            propertyFound = false;
            ModelProperty property = ModelObject.ModelPropertyList.Find(p => p.ModelPropertyName == propertyName);

            if (property != null && PropertyInstanceList.Count > 0)
            {
                propertyFound = true;
                foreach (PropertyInstance instance in PropertyInstanceList.FindAll(i => i.ModelPropertyID == property.ModelPropertyID))
                {
                    if (value.ToString() != String.Empty)                     // && property.IsCollection == true)
                    {
                        value.Append(", ").Append(instance.PropertyValue);
                    }
                    else
                    {
                        value.Append(instance.PropertyValue);
                    }
                }
            }
            return(value.ToString());
        }
        public object GenerateValidValue(ModelProperty property)
        {
            if (property.Max.HasValue && property.Max.Value < MIN_LENGTH)
            {
                throw new InvalidOperationException(MAX_LENGTH_ERROR);
            }

            if (property.Min.HasValue && property.Min < MIN_LENGTH)
            {
                property.Min = MIN_LENGTH;
            }

            var generatedCharacterCount = _random.NextDimension(property, MIN_LENGTH, DEFAULT_MAX_LENGTH)
                                          - REQUIRED_EMAIL_CHARACTERS.Length;

            var partLength = generatedCharacterCount / 3;

            var username = _random.NextString(partLength);
            var domain   = _random.NextString(partLength);

            var topLevelDomain = _random.NextString(partLength + (generatedCharacterCount % 3));

            return($"{username}@{domain}.{topLevelDomain}");
        }
        public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
        {
            ModelItem convertedValue = null;

            if (values[1] != null)
            {
                ModelPropertyEntry modelPropertyEntry = values[1] as ModelPropertyEntry;
                if (modelPropertyEntry != null)
                {
                    ModelProperty property = modelPropertyEntry.FirstModelProperty;
                    if (property != null)
                    {
                        ModelItem argumentModelItem = property.Value;
                        if (argumentModelItem != null &&
                            argumentModelItem.Properties["Expression"] != null &&
                            argumentModelItem.Properties["Expression"].Value != null)
                        {
                            convertedValue = argumentModelItem.Properties["Expression"].Value;
                        }
                    }
                }
            }
            return(convertedValue);
        }
        private static ModelItem FindActivityModelItemFromRoot(ModelTreeManager modelTreeManager, Activity errorTarget)
        {
            ModelItem root = modelTreeManager.Root;

            Fx.Assert(root != null && errorTarget != null, "root != null && errorTarget != null");
            ModelProperty property = root.Properties["Properties"];

            ModelItem propertiesModelItem = property == null ? null : property.Value;
            ModelItem foundItem           = null;

            if (propertiesModelItem != null)
            {
                // So,search "Properties" first to delay expanding "Implementation" and other properties.
                foundItem = ModelTreeManager.FindFirst(propertiesModelItem, (modelItem) => (modelItem.GetCurrentValue() == errorTarget));
            }

            // If activity is not in Properties, expand others except Properties.
            foundItem = foundItem ?? ModelTreeManager.FindFirst(
                root,
                (modelItem) => (modelItem.GetCurrentValue() == errorTarget),
                (modelItem) => { return(modelItem != propertiesModelItem); });

            return(foundItem);
        }
 private IEnumerable <ModelItem> GetChildren(ModelItem parent)
 {
     if (!parent.ItemType.IsSubclassOf(typeof(UserControl)))
     {
         ModelProperty content = parent.Content;
         if (!(content == (ModelProperty)null))
         {
             if (content.IsCollection)
             {
                 foreach (ModelItem modelItem in content.Collection)
                 {
                     if (modelItem.View != (ViewItem)null)
                     {
                         yield return(modelItem);
                     }
                 }
             }
             else if (content.Value != null && content.Value.View != (ViewItem)null && content.IsSet)
             {
                 yield return(content.Value);
             }
         }
     }
 }
Ejemplo n.º 27
0
        /// <summary>
        /// Attempts to format the given value as a typed identifier
        /// </summary>
        /// <param name="value"></param>
        /// <param name="systemValue"></param>
        /// <returns></returns>
        internal static bool TryGetSystemValue(ModelProperty property, object value, out string systemValue)
        {
            if (property is ModelReferenceProperty)
                systemValue = value != null ? ((ModelInstance)value).Type.Name + "|" + ((ModelInstance)value).Id : null;
            else if (JsonConverter.GetJsonValueType(((ModelValueProperty)property).PropertyType) == "Boolean")
            {
                if (value is bool)
                    systemValue = (bool)value ? "true" : "false";
                else if (value is bool?)
                    systemValue = ((bool?)value).HasValue ? (((bool?)value).Value ? "true" : "false") : "";
                else
                {
                    systemValue = "";
                    return false;
                }
            }
            else
            {
                systemValue = value != null ? value.ToString() : "";
                return false;
            }

            return true;
        }
Ejemplo n.º 28
0
        public static void ShouldEqual(this ModelProperty actual, ModelProperty expected, string userMessage = null)
        {
            (actual as DataType).ShouldEqual(expected, userMessage);

            actual.Description.ShouldEqual(expected.Description, userMessage.Append("Description"));
        }
Ejemplo n.º 29
0
        private CodeMemberProperty GetActiveRecordMemberProperty(CodeMemberField memberField,
                                                                 ModelProperty property)
        {
            CodeMemberProperty memberProperty =
                GetMemberProperty(memberField, property.Name, property.ColumnType,
								  property.CustomMemberType,
								  property.NotNull,
                                  true,
                                  true,
                                  property.ImplementsINotifyPropertyChanged(),
                                  property.Description);
            CodeAttributeDeclaration attributeDecleration = null;

            switch (property.KeyType)
            {
                // Composite keys must be handled in upper levels
                case KeyType.None:
                    attributeDecleration = property.GetPropertyAttribute();
                    break;
                case KeyType.PrimaryKey:
                    attributeDecleration = property.GetPrimaryKeyAttribute();
                    break;
            }

            memberProperty.CustomAttributes.Add(attributeDecleration);

            return memberProperty;
        }
        /// <summary>
        ///     Translate model Property into view Property (creates a view Property if not yet created)
        /// </summary>
        /// <param name="viewEntityType"></param>
        /// <param name="property"></param>
        /// <returns></returns>
        private ViewModelProperty TranslateProperty(ViewModelEntityType viewEntityType, ModelProperty property)
        {
            var viewProperty =
                ModelToDesignerModelXRef.GetNewOrExisting(EditingContext, property, viewEntityType.Partition) as ViewModelProperty;
            var scalarProperty = viewProperty as ScalarProperty;
            if (scalarProperty != null)
            {
                // flag if we are part of the key
                scalarProperty.EntityKey = property.IsKeyProperty;
            }

            // set the other properties if they aren't null
            if (property.LocalName.Value != null)
            {
                viewProperty.Name = property.LocalName.Value;
            }

            viewProperty.Type = property.TypeName;

            return viewProperty;
        }
Ejemplo n.º 31
0
        public override void Run(ModelLoaderInterface loader)
        {
            Factory.Parallel.SetMode(parallelMode);
            Factory.SysLog.ResetConfiguration();
            this.loader = loader;

            try {
                if (loader.OptimizeOutput == null)
                {
                    Directory.CreateDirectory(Path.GetDirectoryName(FileName));
                    File.Delete(FileName);
                }
            } catch (Exception ex) {
                log.Error("Error while creating directory and deleting '" + FileName + "'.", ex);
                return;
            }

            log.Notice("Beginning Genetic Optimize of: ");
            log.Notice(loader.Name + " model loader. Type: " + loader.GetType().Name);
            loader.QuietMode = true;

            loader.OnInitialize(ProjectProperties);

            optimizeVariables = new List <ModelProperty>();
            for (int i = 0; i < loader.Variables.Count; i++)
            {
                ModelProperty var = loader.Variables[i];
                if (var.Optimize)
                {
                    optimizeVariables.Add(var);
                }
            }

            // Get Total Number of Bits
            int totalBits = 0;

            for (int i = 0; i < optimizeVariables.Count; i++)
            {
                ModelProperty var  = optimizeVariables[i];
                int           bits = Convert.ToString(var.Count - 1, 2).Length;
                totalBits += bits;
            }

            if (optimizeVariables.Count == 1)
            {
                generationCount = 1;
            }

            // Get the highest count.
            populationCount = totalPasses / generationCount;
            tasksRemaining  = totalPasses;

            log.Notice("Assigning genomes.");

            // Create initial set of random chromosomes.
            generation = new List <Chromosome>();
            // This list assures we never retry a previous one twice.
            alreadyTried = new List <Chromosome>();

            // Create a genome holder.
            int[] genome = new int[optimizeVariables.Count];

            // Indexes for going through randomList
            int[] indexes = new int[optimizeVariables.Count];

//			for( int repeat=0; repeat < Math.Min(optimizeVariables.Count,2); repeat++) {
//
            //Get random values for each.
            List <List <int> > randomLists = new List <List <int> >();

            for (int i = 0; i < optimizeVariables.Count; i++)
            {
                randomLists.Add(GetRandomIndexes(optimizeVariables[i]));
            }

            // Create initial population
            for (int loop = 0; loop < populationCount; loop++)
            {
                // Set the genome from the randomLists using the indexes.
                for (int i = 0; i < optimizeVariables.Count; i++)
                {
                    genome[i] = randomLists[i][indexes[i]];
                }

                Chromosome chromosome = new Chromosome(genome);
                log.Debug(chromosome.ToString());
                generation.Add(chromosome);
                alreadyTried.Add(chromosome);
                for (int i = 0; i < indexes.Length; i++)
                {
                    indexes[i]++;
                    ModelProperty var = optimizeVariables[i];
                    if (indexes[i] >= populationCount)
                    {
                        indexes[i] = 0;
                    }
                }
            }
//			}

                        #if CLRPROFILER
            CLRProfilerControl.LogWriteLine("Entering Genetic Loop");
            CLRProfilerControl.AllocationLoggingActive = true;
            CLRProfilerControl.CallLoggingActive       = false;
                        #endif

            int totalEngineCount = Environment.ProcessorCount * generationCount;

            // Pre-setup engines. This causes the progress
            // bar to show a complete set of information for all
            // generations.
            var iteration = 1;

            for (int genCount = 0; genCount < generationCount && !CancelPending; genCount++)
            {
                // Assign fitness values
                var topModels = new List <ModelInterface>();
                for (int i = generation.Count - 1; i >= 0; i--)
                {
                    Chromosome chromosome = generation[i];
                    if (!chromosome.FitnessAssigned)
                    {
                        ModifyVariables(chromosome);
                        var model = ProcessLoader(loader, i);
                        topModels.Add(model);
                    }
                    else
                    {
                        tasksRemaining--;
                        log.Debug("Saves processing on " + chromosome + "!");
                    }
                }

                int tasksPerEngine = CalculateTasksPerEngine(topModels.Count);

                ModelInterface topModel  = new Portfolio();
                int            passCount = 0;
                foreach (var model in topModels)
                {
                    topModel.Chain.Dependencies.Add(model.Chain);
                    passCount++;
                    if (passCount % tasksPerEngine == 0)
                    {
                        var engine = SetupEngine(true, "Iteration" + ++iteration);
                        engine.Model = topModel;
                        engine.QueueTask();
                        engineIterations.Add(engine);
                        topModel = new Portfolio();
                        if (engineIterations.Count >= Environment.ProcessorCount)
                        {
                            ProcessIteration();
                        }
                    }
                }

                if (topModel.Chain.Dependencies.Count > 0)
                {
                    var engine = SetupEngine(true, "Iteration" + ++iteration);
                    engine.Model = topModel;
                    engine.QueueTask();
                    engineIterations.Add(engine);
                }

                if (engineIterations.Count > 0)
                {
                    ProcessIteration();
                }

                generation.Sort();

                log.Notice("After sorting generation...");
                double maxFitness = 0;
                for (int i = 0; i < generation.Count; i++)
                {
                    log.Debug(generation[i].ToString());
                    maxFitness = Math.Max(generation[i].Fitness, maxFitness);
                }
                // If none of the genes in the chromosome
                // had a positive fitness, stop here.
                if (maxFitness <= 0)
                {
                    break;
                }

                List <Chromosome> newGeneration = new List <Chromosome>();
                log.Notice("Crossover starting...");
                while (newGeneration.Count < populationCount - 1)
                {
                    Chromosome chromo1 = Roulette();
                    Chromosome chromo2;
                    do
                    {
                        chromo2 = Roulette();
                    } while(chromo2.Equals(chromo1));

                    log.Debug("Before: " + chromo1 + " - " + chromo2);
                    chromo1.DoubleCrossOver(chromo2);
                    log.Debug("After: " + chromo1 + " - " + chromo2);

                    if (alreadyTried.Contains(chromo1))
                    {
                        chromo1 = alreadyTried[alreadyTried.IndexOf(chromo1)];
                    }
                    else
                    {
                        alreadyTried.Add(chromo1);
                    }
                    if (alreadyTried.Contains(chromo2))
                    {
                        chromo2 = alreadyTried[alreadyTried.IndexOf(chromo2)];
                    }
                    else
                    {
                        alreadyTried.Add(chromo2);
                    }
                    newGeneration.Add(chromo1);
                    newGeneration.Add(chromo2);
                }
                generation = newGeneration;
            }

            GetEngineResults();

            WriteEngineResults(loader, engineIterations);

            engineIterations.Clear();

                        #if CLRPROFILER
            CLRProfilerControl.AllocationLoggingActive = false;
            CLRProfilerControl.CallLoggingActive       = false;
            CLRProfilerControl.LogWriteLine("Exiting Genetic Loop");
                #endif

            log.Notice("Genetic Algorithm Finished.");
        }
Ejemplo n.º 32
0
 /// <summary>
 /// Binds the ViewModel to a source model.
 /// </summary>
 /// <param name="source">Model to bind to.</param>
 /// <param name="property">Property on model to bind to.</param>
 /// <param name="mode">How to bind to the source model.</param>
 public void BindSecretText(ModelBase source, ModelProperty property, ModelBindingMode mode = ModelBindingMode.Committed)
 {
     SetBinding(SecretTextProperty, new ModelBinding(source, property, mode));
 }
Ejemplo n.º 33
0
        ///--------------------------------------------------------------------------------
        /// <summary>Evaluate expression associated with this node.</summary>
        ///
        /// <param name="solutionContext">The associated solution.</param>
        /// <param name="templateContext">The associated template.</param>
        /// <param name="modelContext">The associated model context.</param>
        /// <param name="interpreterType">The type of interpretation to perform.</param>
        ///--------------------------------------------------------------------------------
        public string GetExpressionValue(Solution solutionContext, ITemplate templateContext, IDomainEnterpriseObject modelContext, InterpreterTypeCode interpreterType)
        {
            string expression1Value = String.Empty;

            if (Expression1 != null)
            {
                expression1Value = Expression1.GetExpressionValue(solutionContext, templateContext, modelContext, interpreterType);
            }
            string expression2Value = String.Empty;

            if (Expression2 != null)
            {
                expression2Value = Expression2.GetExpressionValue(solutionContext, templateContext, modelContext, interpreterType);
            }
            if (String.IsNullOrEmpty(expression1Value))
            {
                expression1Value = "null";
            }
            if (String.IsNullOrEmpty(expression2Value))
            {
                expression2Value = "null";
            }
            long   expression1Long;
            long   expression2Long;
            double expression1Double;
            double expression2Double;

            if (Literal != null)
            {
                return(Literal.RawValue);
            }
            if (ModelProperty != null)
            {
                return(ModelProperty.GetPropertyStringValue(solutionContext, templateContext, modelContext, modelContext, interpreterType));
            }
            if (ModelContext != null)
            {
                bool isValidContext;
                IDomainEnterpriseObject nodeContext = ModelContext.GetModelContext(solutionContext, templateContext, modelContext, out isValidContext);
                if (nodeContext == null)
                {
                    return("null");
                }
                else
                {
                    if (nodeContext.ID == Guid.Empty || nodeContext.ID == null)
                    {
                        return("null");
                    }
                    return(nodeContext.ID.ToString());
                }
            }
            else if (CurrentItem != null)
            {
                IDomainEnterpriseObject nodeContext = CurrentItem.GetModelContext(solutionContext, templateContext, modelContext);
                if (nodeContext == null)
                {
                    return("null");
                }
                else
                {
                    return(nodeContext.ID.ToString());
                }
            }
            else if (SpecCurrentItem != null)
            {
                IDomainEnterpriseObject nodeContext = SpecCurrentItem.GetModelContext(solutionContext, templateContext, modelContext);
                if (nodeContext == null)
                {
                    return("null");
                }
                else
                {
                    return(nodeContext.ID.ToString());
                }
            }
            else if (Expression1 != null && Expression2 != null)
            {
                if (BinaryOperator != null)
                {
                    switch (BinaryOperator.Operator)
                    {
                    case "||":
                        if (Expression1.EvaluateExpression(solutionContext, templateContext, modelContext, interpreterType) || Expression2.EvaluateExpression(solutionContext, templateContext, modelContext, interpreterType))
                        {
                            return("true");
                        }
                        return("false");

                    case "&&":
                        if (Expression1.EvaluateExpression(solutionContext, templateContext, modelContext, interpreterType) && Expression2.EvaluateExpression(solutionContext, templateContext, modelContext, interpreterType))
                        {
                            return("true");
                        }
                        return("false");

                    case "==":
                        if (expression1Value == expression2Value)
                        {
                            return("true");
                        }
                        return("false");

                    case "!=":
                        if (expression1Value != expression2Value)
                        {
                            return("true");
                        }
                        return("false");

                    case "<":
                        if (long.TryParse(expression1Value, out expression1Long) == true && long.TryParse(expression2Value, out expression2Long) == true)
                        {
                            if (expression1Long < expression2Long)
                            {
                                return("true");
                            }
                        }
                        else if (double.TryParse(expression1Value, out expression1Double) == true && double.TryParse(expression2Value, out expression2Double) == true)
                        {
                            if (expression1Double < expression2Double)
                            {
                                return("true");
                            }
                        }
                        else
                        {
                            if (expression1Value.Length < expression2Value.Length)
                            {
                                return("true");
                            }
                        }
                        return("false");

                    case ">":
                        if (long.TryParse(expression1Value, out expression1Long) == true && long.TryParse(expression2Value, out expression2Long) == true)
                        {
                            if (expression1Long > expression2Long)
                            {
                                return("true");
                            }
                        }
                        else if (double.TryParse(expression1Value, out expression1Double) == true && double.TryParse(expression2Value, out expression2Double) == true)
                        {
                            if (expression1Double > expression2Double)
                            {
                                return("true");
                            }
                        }
                        else
                        {
                            if (expression1Value.Length > expression2Value.Length)
                            {
                                return("true");
                            }
                        }
                        return("false");

                    case "<=":
                        if (long.TryParse(expression1Value, out expression1Long) == true && long.TryParse(expression2Value, out expression2Long) == true)
                        {
                            if (expression1Long <= expression2Long)
                            {
                                return("true");
                            }
                        }
                        else if (double.TryParse(expression1Value, out expression1Double) == true && double.TryParse(expression2Value, out expression2Double) == true)
                        {
                            if (expression1Double <= expression2Double)
                            {
                                return("true");
                            }
                        }
                        else
                        {
                            if (expression1Value.Length <= expression2Value.Length)
                            {
                                return("true");
                            }
                        }
                        return("false");

                    case ">=":
                        if (long.TryParse(expression1Value, out expression1Long) == true && long.TryParse(expression2Value, out expression2Long) == true)
                        {
                            if (expression1Long >= expression2Long)
                            {
                                return("true");
                            }
                        }
                        else if (double.TryParse(expression1Value, out expression1Double) == true && double.TryParse(expression2Value, out expression2Double) == true)
                        {
                            if (expression1Double >= expression2Double)
                            {
                                return("true");
                            }
                        }
                        else
                        {
                            if (expression1Value.Length >= expression2Value.Length)
                            {
                                return("true");
                            }
                        }
                        return("false");

                    default:
                        return("false");
                    }
                }
                else if (MathOperator != null)
                {
                    switch (MathOperator.Operator)
                    {
                    case "+":
                        if (long.TryParse(expression1Value, out expression1Long) == true && long.TryParse(expression2Value, out expression2Long) == true)
                        {
                            return((expression1Long + expression2Long).ToString());
                        }
                        else if (double.TryParse(expression1Value, out expression1Double) == true && double.TryParse(expression2Value, out expression2Double) == true)
                        {
                            return((expression1Double + expression2Double).ToString());
                        }
                        else
                        {
                            return(expression1Value + expression2Value);
                        }

                    case "-":
                        if (long.TryParse(expression1Value, out expression1Long) == true && long.TryParse(expression2Value, out expression2Long) == true)
                        {
                            return((expression1Long - expression2Long).ToString());
                        }
                        else if (double.TryParse(expression1Value, out expression1Double) == true && double.TryParse(expression2Value, out expression2Double) == true)
                        {
                            return((expression1Double - expression2Double).ToString());
                        }
                        else
                        {
                            return(expression1Value.Replace(expression2Value, ""));
                        }

                    case "*":
                        if (long.TryParse(expression1Value, out expression1Long) == true && long.TryParse(expression2Value, out expression2Long) == true)
                        {
                            return((expression1Long * expression2Long).ToString());
                        }
                        else if (double.TryParse(expression1Value, out expression1Double) == true && double.TryParse(expression2Value, out expression2Double) == true)
                        {
                            return((expression1Double * expression2Double).ToString());
                        }
                        break;

                    case "/":
                        if (long.TryParse(expression1Value, out expression1Long) == true && long.TryParse(expression2Value, out expression2Long) == true && expression2Long != 0)
                        {
                            return((expression1Long / expression2Long).ToString());
                        }
                        else if (double.TryParse(expression1Value, out expression1Double) == true && double.TryParse(expression2Value, out expression2Double) == true && expression2Double != 0.00)
                        {
                            return((expression1Double / expression2Double).ToString());
                        }
                        break;

                    default:
                        break;
                    }
                    return("null");
                }
            }
            else if (Expression1 != null)
            {
                return(Expression1.GetExpressionValue(solutionContext, templateContext, modelContext, interpreterType));
            }
            return("null");
        }
Ejemplo n.º 34
0
 /// <summary>
 /// Binds the ViewModel to a source model.
 /// </summary>
 /// <param name="source">Model to bind to.</param>
 /// <param name="property">Property on model to bind to.</param>
 /// <param name="mode">How to bind to the source model.</param>
 public void BindDate(ModelBase source, ModelProperty property, ModelBindingMode mode = ModelBindingMode.Committed)
 {
     SetBinding(DateProperty, new ModelBinding(source, property, mode));
 }
Ejemplo n.º 35
0
        /// <summary>
        /// Gets the serializable value of a <see cref="ModelProperty"/>.
        /// </summary>
        /// <param name="property"></param>
        /// <param name="source"></param>
        /// <returns></returns>
        internal static object GetPropertyValue(ModelProperty property, IModelPropertySource source)
        {
            ModelReferenceProperty reference = property as ModelReferenceProperty;
            if (reference != null)
            {
                // Serialize lists
                if (reference.IsList)
                    return source.GetList(reference).Select(item => GetReference(reference, item));

                // Serialize references
                else
                    return GetReference(reference, source.GetReference(reference));
            }

            // Serialize values
            else
                return source.GetValue((ModelValueProperty)property);
        }
Ejemplo n.º 36
0
        /// <summary>
        /// Ecrit le SQL pour une colonne.
        /// </summary>
        /// <param name="sb">Flux.</param>
        /// <param name="property">Propriété.</param>
        private static void WriteColumn(StringBuilder sb, ModelProperty property)
        {
            string persistentType = property.DeterminerSqlDataType();

            sb.Append("[").Append(property.GetColumnName()).Append("] ").Append(persistentType).Append(" null");
        }
 public void AddProperty(ModelProperty property)
 {
     this.properties.Add(property);
 }
Ejemplo n.º 38
0
        /// <summary>
        /// Attempts to initialize a <see cref="ModelSource"/> with the specified root type and path.
        /// </summary>
        /// <param name="rootType">The root type name, which is required for instance paths</param>
        /// <param name="path">The source path, which is either an instance path or a static path</param>
        /// <returns>True if the source was created, otherwise false</returns>
        bool InitializeFromTypeAndPath(ModelType rootType, string path, out ModelProperty sourceProperty)
        {
            // Instance Path
            ModelPath instancePath = null;
            sourceProperty = null;

            // clean up any array indices
            string indexFreePath = arraySyntaxRegex.Replace(path, "");
            try
            {
                if (rootType != null)
                    rootType.TryGetPath(indexFreePath, out instancePath);
            }
            catch
            { }
            if (instancePath != null)
            {
                InitializeFromModelPath(instancePath, path, out sourceProperty);
                return true;
            }

            // Static Path
            else if (path.Contains('.'))
            {
                // Store the source path
                var sourceModelType = ModelContext.Current.GetModelType(path.Substring(0, path.LastIndexOf('.')));
                if (sourceModelType != null)
                {
                    sourceProperty = sourceModelType.Properties[path.Substring(path.LastIndexOf('.') + 1)];
                    if (sourceProperty != null && sourceProperty.IsStatic)
                    {
                        this.Path = path;
                        this.IsStatic = true;
                        this.SourceProperty = sourceProperty.Name;
                        this.SourceType = sourceProperty.DeclaringType.Name;
                        return true;
                    }
                }
            }
            return false;
        }
Ejemplo n.º 39
0
        /// <summary>
        /// Initialize the source from a valid <see cref="ModelPath"/>
        /// </summary>
        /// <param name="instancePath"></param>
        void InitializeFromModelPath(ModelPath instancePath, string path, out ModelProperty sourceProperty)
        {
            this.Path = path;
            this.IsStatic = false;
            this.RootType = instancePath.RootType.Name;
            var tokens = tokenizer.Matches(path);
            this.steps = new SourceStep[tokens.Count];
            var rootType = instancePath.RootType;
            int i = 0;
            sourceProperty = null;
            foreach(Match token in tokens)
            {
                sourceProperty = rootType.Properties[token.Groups["Property"].Value];
                if (sourceProperty == null)
                    throw new ArgumentException(String.Format("Property {0} is not valid for type {1} in path {2}.", token.Groups["Property"].Value, rootType.Name, path));
                int index;
                if (!Int32.TryParse(token.Groups["Index"].Value, out index))
                    index = -1;

                steps[i] = new SourceStep() { Property = sourceProperty.Name, Index = index, DeclaringType = sourceProperty.DeclaringType.Name, IsReferenceProperty = sourceProperty is ModelReferenceProperty };
                rootType = sourceProperty is ModelReferenceProperty ? ((ModelReferenceProperty)sourceProperty).PropertyType : null;
                i++;
            }

            this.SourceProperty = sourceProperty.Name;
            this.SourceType = sourceProperty.DeclaringType.Name;
        }
Ejemplo n.º 40
0
 internal CreateAdapterEventArgs(Binding binding, ModelInstance source, ModelProperty property)
 {
     this.binding = binding;
     this.source = source;
     this.property = property;
 }
Ejemplo n.º 41
0
        private CodeMemberField GetMemberFieldOfProperty(ModelProperty property, Accessor accessor)
        {
			if (_model.UseNullables != NullableUsage.No && TypeHelper.IsNullable(property.ColumnType) && !property.NotNull)
            {
                if (_model.UseNullables == NullableUsage.WithHelperLibrary)
                    return GetMemberField(property.Name, TypeHelper.GetNullableTypeReferenceForHelper(property.ColumnType), accessor, property.Access);
                else
                    return GetMemberField(property.Name, TypeHelper.GetNullableTypeReference(property.ColumnType), accessor, property.Access);
            }
            else
                return GetMemberField(property.Name, TypeHelper.GetSystemType(property.ColumnType, property.CustomMemberType), accessor, property.Access);
        }
Ejemplo n.º 42
0
        /// <summary>
        /// Génère la propriété concernée.
        /// </summary>
        /// <param name="w">Writer.</param>
        /// <param name="property">La propriété générée.</param>
        private void GenerateProperty(CSharpWriter w, ModelProperty property)
        {
            w.WriteSummary(2, property.Comment);

            if (!property.Class.IsView && property.IsPersistent && property.DataMember != null && (!_parameters.NoColumnOnAlias.Value || property.Class.Trigram != null))
            {
                if (property.DataDescription.Domain.PersistentDataType.Contains("json"))
                {
                    w.WriteAttribute(2, "Column", $@"""{property.DataMember.Name}""", $@"TypeName = ""{property.DataDescription.Domain.PersistentDataType}""");
                }
                else
                {
                    w.WriteAttribute(2, "Column", $@"""{property.DataMember.Name}""");
                }
            }

            if (property.DataMember.IsRequired && !property.DataDescription.IsPrimaryKey)
            {
                w.WriteAttribute(2, "Required");
            }

            if (property.DataDescription != null)
            {
                if (!string.IsNullOrEmpty(property.DataDescription.ReferenceType) && !property.DataDescription.ReferenceClass.IsExternal)
                {
                    w.WriteAttribute(2, "ReferencedType", $"typeof({property.DataDescription.ReferenceClass.Name})");
                }

                if (property.DataDescription.Domain != null)
                {
                    w.WriteAttribute(2, "Domain", $@"""{property.DataDescription.Domain.Code}""");

                    if (!string.IsNullOrEmpty(property.DataDescription.Domain.CustomAnnotation))
                    {
                        w.WriteLine(2, property.DataDescription.Domain.CustomAnnotation);
                    }
                }
            }

            if (property.DataDescription.IsPrimaryKey)
            {
                w.WriteAttribute(2, "Key");
                if (property.IsIdManuallySet)
                {
                    w.WriteAttribute(2, "DatabaseGenerated", "DatabaseGeneratedOption.None");
                }
            }
            else if (property.DefaultValue != null)
            {
                w.WriteAttribute(2, "DatabaseGenerated", "DatabaseGeneratedOption.Identity");
            }

            if (!property.IsPrimitive)
            {
                w.WriteAttribute(2, "NotMapped");
            }

            string @override = property.IsDerived ? "override " : "";

            w.WriteLine(2, $"public {@override}{LoadShortDataType(property.DataType)} {property.Name} {{ get; set; }}");
        }
Ejemplo n.º 43
0
        public PropertyData(ModelProperty p)
        {
            Name = p.Name;

            Access = p.Access;
            Accessor = p.Accessor;
            Check = p.Check;
            Column = p.Column;
            ColumnType = p.ColumnType;
            CustomAccess = p.CustomAccess;
            CustomColumnType = p.CustomColumnType;
            CustomMemberType = p.CustomMemberType;
            DebuggerDisplay = p.DebuggerDisplay;
            DefaultMember = p.DefaultMember;
            ColumnDefault = p.ColumnDefault;
            Description = p.Description;
            Formula = p.Formula;
            Generator = p.Generator;
            Index = p.Index;
            Insert = p.Insert;
            KeyType = p.KeyType;
            Length = p.Length;
            NotNull = p.NotNull;
            Params = p.Params;
            PropertyType = p.PropertyType;
            SequenceName = p.SequenceName;
            SqlType = p.SqlType;
            Unique = p.Unique;
            UniqueKey = p.UniqueKey;
            UnsavedValue = p.UnsavedValue;
            Update = p.Update;
            ValidatorPropertyStorage = p.GetValidatorValue();
            
            ModelClass = p.ModelClass;
            NestedClass = p.NestedClass;
        }
 /// <summary>
 /// 从类型的属性获取Set属性
 /// </summary>
 /// <param name="type">类型</param>
 /// <returns></returns>
 public static ModelProperty[] GetSetProperties(Type type)
 {
     return(ModelProperty.cached.GetOrAdd(type, ModelProperty.GetSetPropertiesNoCached(type)));
 }
Ejemplo n.º 45
0
        /// <summary>
        /// Gets the set of allowed values for the specified instance and property.
        /// </summary>
        /// <param name="instance"></param>
        /// <param name="property"></param>
        /// <returns></returns>
        public static IEnumerable<object> GetAllowedValues(ModelInstance root, ModelProperty property)
        {
            var rule = Rule.GetRegisteredRules(property.DeclaringType).OfType<AllowedValuesRule>().Where(r => r.Property == property).FirstOrDefault();
            if (rule == null)
                return null;

            return rule.GetAllowedValues(root);
        }
 set => SetValue(ModelProperty, value);
Ejemplo n.º 47
0
 internal static bool IsBoolean(ModelProperty property)
 {
     return property is ModelValueProperty && JsonConverter.GetJsonValueType(((ModelValueProperty) property).PropertyType) == "Boolean";
 }
Ejemplo n.º 48
0
 public static double GetValue(ModelProperty var, int index)
 {
     return(var.Start + (index * var.Increment));
 }
Ejemplo n.º 49
0
        /// <summary>
        /// Attempts to retrieve 
        /// </summary>
        /// <param name="property"></param>
        /// <param name="source"></param>
        /// <param name="allowedValuesTransform"></param>
        /// <param name="rawOptions"></param>
        /// <returns></returns>
        internal static bool TryGetAllowedValues(ModelProperty property, ModelInstance source, Transform allowedValuesTransform, out IEnumerable<object> allowedValues)
        {
            allowedValues = null;

            var allowedInstances = AllowedValuesRule.GetAllowedValues(source, property);

            if (allowedInstances != null)
            {
                if (allowedValuesTransform != null)
                {
                    IEnumerable transformed;
                    if (allowedValuesTransform.TryExecute(Page.Current, allowedInstances, out transformed))
                        allowedValues = transformed.Cast<object>().ToArray();
                }
                else
                    allowedValues = allowedInstances;
            }
            else if (IsBoolean(property))
                allowedValues = new object[] { true, false };

            return allowedValues != null;
        }
Ejemplo n.º 50
0
 internal ModelPropertyGetEvent(ModelInstance instance, ModelProperty property)
     : base(instance)
 {
     this.Property = property;
 }
Ejemplo n.º 51
0
        /// <summary>
        /// Attempts to format the given value using the given format, or the default format for the property.
        /// </summary>
        /// <param name="property"></param>
        /// <param name="format"></param>
        /// <param name="value"></param>
        /// <param name="displayValue"></param>
        /// <returns></returns>
        internal static bool TryGetDisplayValue(ModelProperty property, string format, object value, out string displayValue)
        {
            if (value == null)
                displayValue = "";
            else if (property is ModelValueProperty)
                displayValue = ((ModelValueProperty)property).FormatValue(value, format);
            else if (value is IEnumerable<ModelInstance>)
            {
                StringBuilder builder = new StringBuilder();
                foreach (ModelInstance instance in (IEnumerable<ModelInstance>)value)
                {
                    string instanceValue;
                    if (!instance.TryFormat(format ?? property.Format, out instanceValue))
                    {
                        displayValue = "";
                        return false;
                    }

                    if (builder.Length > 0)
                        builder.Append(", ");

                    builder.Append(instanceValue);
                }

                displayValue = builder.ToString();
            }
            else if (value is ModelInstance)
                return ((ModelInstance)value).TryFormat(format ?? property.Format, out displayValue);
            else
                throw new ArgumentException("Cannot obtain a display value since the given object is invalid for the property.");

            return true;
        }
Ejemplo n.º 52
0
        private CodeMemberProperty GetActiveRecordMemberTimestamp(CodeMemberField memberField,
                                                                  ModelProperty property)
        {
            CodeMemberProperty memberProperty =
                GetMemberProperty(memberField, property.Name, property.ColumnType, null, property.NotNull, true, true, property.ImplementsINotifyPropertyChanged(),
                                  property.Description);
            memberProperty.CustomAttributes.Add(property.GetTimestampAttribute());

            return memberProperty;
        }
Ejemplo n.º 53
0
        private void propertyGrid_CellValuePushed(object sender, DataGridViewCellValueEventArgs e)
        {
            if (modelClass != null)
            {
                if (e.RowIndex > modelClass.Properties.Count - 1)
                {
                    using (Transaction txAdd = modelClass.Model.Store.TransactionManager.BeginTransaction("Add property"))
                    {
                        ModelProperty property = new ModelProperty(modelClass.Model.Store);
                        property.Name = e.Value.ToString();
                        property.ModelClass = modelClass;
                        txAdd.Commit();
                    }
                }
                else
                {
                    ModelProperty property = modelClass.Properties[e.RowIndex];

                    using (Transaction txAdd = property.ModelClass.Model.Store.TransactionManager.BeginTransaction("Add property"))
                    {
                        switch (e.ColumnIndex)
                        {
                            case 0:
                                property.Name = e.Value.ToString();
                                break;
                            case 1:
                                property.ColumnType = (NHibernateType)System.Enum.Parse(typeof(NHibernateType), e.Value.ToString(), true);
                                break;
                            case 2:
                                property.Column = e.Value.ToString();
                                break;
                            case 3:
                                property.KeyType = (KeyType)System.Enum.Parse(typeof(KeyType), e.Value.ToString(), true);
                                break;
                            case 4:
                                property.Description = e.Value.ToString();
                                break;
                            default:
                                e.Value = null;
                                break;
                        }

                        txAdd.Commit();
                    }
                }

                propertyGrid.Invalidate();
            }
        }
Ejemplo n.º 54
0
 private CodeMemberField GetMemberField(CodeTypeDeclaration classDeclaration, ModelProperty property)
 {
     // Soooo ugly.
     CodeMemberField memberField = null;
     switch (property.PropertyType)
     {
         case PropertyType.Property:
             memberField = GetMemberFieldOfProperty(property, Accessor.Private);
             CodeMemberProperty memberProperty = GetActiveRecordMemberProperty(memberField, property);
             classDeclaration.Members.Add(memberProperty);
             if (property.IsValidatorSet())
                 memberProperty.CustomAttributes.AddRange(property.GetValidationAttributes());
             break;
         case PropertyType.Field:
             memberField = GetMemberFieldOfProperty(property, property.Accessor);
             memberField.CustomAttributes.Add(property.GetFieldAttribute());
             break;
         case PropertyType.Version:
             memberField = GetMemberFieldOfProperty(property, Accessor.Private);
             classDeclaration.Members.Add(GetActiveRecordMemberVersion(memberField, property));
             break;
         case PropertyType.Timestamp:
             memberField = GetMemberFieldOfProperty(property, Accessor.Private);
             classDeclaration.Members.Add(GetActiveRecordMemberTimestamp(memberField, property));
             break;
     }
     return memberField;
 }
Ejemplo n.º 55
0
 /// <summary>
 /// Attempts to create a new <see cref="ModelSource"/> for the specified root type and path.
 /// </summary>
 /// <param name="rootType">The root type name, which is required for instance paths</param>
 /// <param name="path">The source path, which is either an instance path or a static path</param>
 /// <returns>True if the source was created, otherwise false</returns>
 public static bool TryGetSource(ModelType rootType, string path, out ModelSource source, out ModelProperty sourceProperty)
 {
     source = new ModelSource();
     if (source.InitializeFromTypeAndPath(rootType, path, out sourceProperty))
         return true;
     else
     {
         source = null;
         return false;
     }
 }