public void Clear()
 {
     modelClass = null;
     propertyGrid.Rows.Clear();
     propertyGrid.RowCount = 0;
     propertyGrid.Visible = false;
 }
        public ModelProperty NewPrimaryKey(ModelClass cls, Column column)
        {
            ModelProperty property = NewProperty(cls, column);
            property.KeyType = KeyType.PrimaryKey;

            return property;
        }
        public ModelProperty NewCompositeKey(ModelClass cls, Column column, string compositeKeyName)
        {
            ModelProperty property = NewProperty(cls, column);
            property.KeyType = KeyType.CompositeKey;
            property.CompositeKeyName = compositeKeyName;

            return property;
        }
 public void Display(ModelClass modelClassToHandle)
 {
     propertyGrid.CancelEdit();
     propertyGrid.Rows.Clear();
     modelClass = modelClassToHandle;
     if (modelClassToHandle != null && modelClassToHandle.Properties != null)
         propertyGrid.RowCount = modelClassToHandle.Properties.Count + 1;
     propertyGrid.ClearSelection();
     propertyGrid.Visible = true;
 }
        protected override void PerformExtraSetup()
        {
            _model = new ModelClass();

              _model.Sequence.Add(new SampleClass() { Name = "Craig", Description = "silly" });
              _model.Sequence.Add(new SampleClass() { Name = "The sky", Description = "blue" });
              _model.Sequence.Add(new SampleClass() { Name = "ZPT-Sharp model rendering", Description = "working" });

              base.PerformExtraSetup();
        }
        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;
        }
        public List<Column> GetProperties(ModelClass cls)
        {
            List<Column> list = new List<Column>();

            IDbCommand command = GetColumnCommand(cls.Table, cls.Schema);
            using (IDataReader reader = command.ExecuteReader())
            {
                while (reader.Read())
                {
                    Column column;

                    column = list.Find(col => col.Name == reader["COLUMN_NAME"].ToString()
                        );

                    if (column == null)
                    {
                        column = new Column
                                     {
                                         Name = reader["COLUMN_NAME"].ToString(),
                                         Schema = cls.Schema,
                                         Table = cls.Table,
                                         DataType = reader["DATA_TYPE"].ToString()
                                     };

                        if (column.DataType == "NUMBER")
                        {
                            string scale = reader["DATA_SCALE"].ToString();
                            if (scale == "0" || string.IsNullOrEmpty(scale))
                            {
                                column.DataType = "INTEGER";
                                // If field is primary key and "integer" it is reasonably safe to assume that it is has
                                // a sequence behind it. Confirming that would in Oracle require trigger parsing
                                column.Identity = reader["PKEY"] != DBNull.Value ? true : false;
                            }
                        }

                        if (reader["PKEY"] != DBNull.Value)
                        {
                            column.Primary = true;
                            column.PrimaryConstraintName = reader["PKEY"].ToString();
                        }

                        if (reader["FKEY"] != DBNull.Value)
                        {
                            column.ForeignConstraints.Add(reader["FKEY"].ToString());
                        }

                        column.Nullable = reader["NULLABLE"].ToString() == "N" ? false : true;
                        list.Add(column);
                    }
                }
            }
            return list;
        }
        public ModelClass NewClass(string owner, string name)
        {
            ModelClass cls = new ModelClass(_store);
            // TODO: Disabled to test server explorer drag drop bug of DeviceBuffer
            //Log(String.Format("Class: Name={0}, Schema={1}", name, owner));
            cls.Name = ModelHelper.GetSafeName(name, string.Empty);
            cls.Schema = owner;
            cls.Table = name;

            classes.Add(name, cls);
            return cls;
        }
Exemple #9
0
        public static string GetMemberName(string name, ModelClass cls, bool isPlural)
        {
            Func<ModelClass, string, bool> memberExists = (modelClass, membername) => modelClass.NavigationProperties.Exists(p => p.Name == membername) || modelClass.Fields.Exists(field => field.Name == membername);
            Func<ModelClass, string, bool> memberExistsInTree = 
                (modelClass, memberName) => (modelClass.Name == memberName || memberExists(modelClass, memberName)) 
                    ? true : ((modelClass.Baseclass != null) ? memberExists(modelClass.Baseclass, memberName) : false);

            var keyword = isPlural ? AgileFx.AgileModeler.DslPackage.Lib.Pluralizer.ToPlural(name) : name;
            var ctr = 1;
            var tempName = keyword;
            while (memberExistsInTree(cls, tempName))
                tempName = keyword + (++ctr).ToString();
            return tempName;
        }
Exemple #10
0
		public List<Column> GetProperties(ModelClass cls)
		{
			List<Column> list = new List<Column>();

			IDbCommand command = GetColumnCommand(cls.Table, cls.Schema);
			using(IDataReader reader = command.ExecuteReader())
			{
				while(reader.Read())
				{
					Column column;

					column = list.Find(col => col.Name == reader["COLUMN_NAME"].ToString());

					if (column == null)
					{
						column = new Column
						             {
						                 Name = reader["COLUMN_NAME"].ToString(),
						                 Schema = cls.Schema,
						                 Table = cls.Table,
						                 DataType = reader["DATA_TYPE"].ToString()
						             };
					    if (reader["CONSTRAINT_TYPE"] != DBNull.Value)
						{
							switch(reader["CONSTRAINT_TYPE"].ToString())
							{
								case "PRIMARY KEY":
									column.Primary = true;
									column.PrimaryConstraintName = reader["CONSTRAINT_NAME"].ToString();
									break;
								case "FOREIGN KEY":
									column.ForeignConstraints.Add(reader["CONSTRAINT_NAME"].ToString());
									break;
									// Check constraints not supported right now.
							}
						}
						column.Nullable = reader["IS_NULLABLE"].ToString() == "NO" ? false : true;
						column.Identity = reader["IS_IDENTITY"].ToString() == "1" ? true : false;
						column.Computed = reader["IS_COMPUTED"].ToString() == "1" ? true : false;

						list.Add(column);
					}
				}
			}

			return list;
		}
Exemple #11
0
 private void Deletebutton2_Click(object sender, EventArgs e)
 {
     if (isvalid())
     {
         ModelClass obj = new ModelClass()
         {
             namep      = nametextBox4.Text,
             purchasep  = purchasetextBox1.Text,
             salep      = saletextBox2.Text,
             availablep = availableQtytextBox3.Text,
             datap      = dateTimePicker1.Value.ToString()
         };
         BusinessClass.businessMethod(obj, "del");
         MessageBox.Show("Delete Data Successfully", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
         dataGridView1.DataSource = ShowData();
         ClearRfocusKlyeMethod();
     }
 }
Exemple #12
0
        /// <summary>
        /// 通过编码获取信息类
        /// </summary>
        /// <param name="sn">类型编码</param>
        /// <returns></returns>
        public ModelClass GetClassBySN(int sn)
        {
            ModelClass c = null;

            SqlParameter[] array = { new SqlParameter("@sn", sn) };
            DataSet        ds    = DBUtil.ExecuteQuery(SQL_getClassBySN, array);

            if (ds.Tables[0].Rows.Count > 0)
            {
                c            = new ModelClass();
                c.Sn         = Convert.ToInt32(ds.Tables[0].Rows[0]["ClTypeSN"]);
                c.Group      = Convert.ToInt32(ds.Tables[0].Rows[0]["Group"]);
                c.GroupTitle = ds.Tables[0].Rows[0]["GroupTitle"].ToString();
                c.Title      = ds.Tables[0].Rows[0]["Title"].ToString();
                c.Memo       = DBUtil.DBNullReplace(ds.Tables[0].Rows[0]["Memo"], "").ToString();
            }
            return(c);
        }
Exemple #13
0
        public void QueryViewsPasses()
        {
            var model = new ModelClass {
                Name = "apple", Value1 = 111, Value2 = 1.234f
            };
            var empry = new ModelClass {
                Name = "empty"
            };

            //作成のテスト
            var viewInstanceCreator = new DefaultViewInstanceCreator(
                (typeof(IntViewObjClass), new IntViewObjClass.Binder()),
                (typeof(FloatViewObjClass), new FloatViewObjClass.Binder())
                );
            var binder = new ModelViewBinder("apple", viewInstanceCreator,
                                             new ModelViewBinder.BindInfo(typeof(IntViewObjClass)),
                                             new ModelViewBinder.BindInfo(typeof(FloatViewObjClass)),
                                             new ModelViewBinder.BindInfo("Int", typeof(IntViewObjClass))
                                             );
            var binderInstance = binder.CreateBindInstance(model, null);

            {//query => typeof(IntViewObjClass).FullName
                var ID = ModelViewBinder.BindInfo.ToID(typeof(IntViewObjClass));
                var queryViewResult = binderInstance.QueryViews(ID);
                Assert.AreEqual(1, queryViewResult.Count(), $"Failed to Query Views... ID={ID}");
                var intViewObj = binderInstance.ViewObjects.First(_v => _v.UseBindInfo.ID == ID);
                Assert.IsTrue(intViewObj == queryViewResult.First());
            }

            {//query => typeof(FloatViewObjClass).FullName
                var ID = ModelViewBinder.BindInfo.ToID(typeof(FloatViewObjClass));
                var queryViewResult = binderInstance.QueryViews(ID);
                Assert.AreEqual(1, queryViewResult.Count());
                var floatViewObj = binderInstance.ViewObjects.First(_v => _v.UseBindInfo.ID == ID);
                Assert.IsTrue(floatViewObj == queryViewResult.First());
            }

            {//query => Int
                var queryViewResult = binderInstance.QueryViews("Int");
                Assert.AreEqual(1, queryViewResult.Count());
                var intIdViewObj = binderInstance.ViewObjects.First(_v => _v.UseBindInfo.ID.MainID == "Int");
                Assert.IsTrue(intIdViewObj == queryViewResult.First());
            }
        }
Exemple #14
0
        public List <Relation> GetPKRelations(ModelClass cls)
        {
            List <Relation> list = new List <Relation>();

            IDbCommand command = _connection.CreateCommand();

            command.CommandText =
                @"
            SELECT st.column_name, om.owner, om.constraint_name, om.table_name, sr.column_name r_column_name
              FROM all_constraints om INNER JOIN all_constraints rm ON om.r_owner = rm.owner
                                                                  AND om.r_constraint_name = rm.constraint_name
                   INNER JOIN all_cons_columns st ON om.constraint_name = st.constraint_name
                                                AND st.owner = om.owner
                                                AND st.table_name = om.table_name
                   INNER JOIN all_cons_columns sr ON rm.constraint_name = sr.constraint_name
                                                AND sr.owner = rm.owner
                                                AND sr.table_name = rm.table_name
             WHERE om.constraint_type = 'R'
               AND rm.table_name = :tname
               AND om.r_owner = :owner
                ";

            AddSchemaAndTableParams(command, cls.Schema, cls.Table);

            using (IDataReader reader = command.ExecuteReader())
            {
                while (reader.Read())
                {
                    Relation relation = new Relation();
                    relation.RelationType  = RelationType.Unknown;
                    relation.RelationName  = reader["CONSTRAINT_NAME"].ToString();
                    relation.PrimaryOwner  = cls.Schema;
                    relation.PrimaryTable  = cls.Table;
                    relation.PrimaryColumn = reader["R_COLUMN_NAME"].ToString();
                    relation.ForeignOwner  = reader["OWNER"].ToString();
                    relation.ForeignTable  = reader["TABLE_NAME"].ToString();
                    relation.ForeignColumn = reader["COLUMN_NAME"].ToString();

                    list.Add(relation);
                }
            }

            return(list);
        }
Exemple #15
0
        private ModelClass ProcessEntity(string entityFullName, EntityType oSpaceType, EntityType sSpaceType, EntityType cSpaceType)
        {
            Type type = assembly.GetType(entityFullName);

            if (type == null)
            {
                log.Warn($"Could not find type for entity {entityFullName}");

                return(null);
            }

            log.Debug($"Found entity {entityFullName}");
            string customAttributes = GetCustomAttributes(type);

            ModelClass result = new ModelClass
            {
                Name               = oSpaceType.Name
                , Namespace        = oSpaceType.NamespaceName
                , IsAbstract       = oSpaceType.Abstract
                , BaseClass        = oSpaceType.BaseType?.Name
                , CustomInterfaces = type.GetInterfaces().Any()
                                                      ? string.Join(",", type.GetInterfaces().Select(t => t.FullName))
                                                      : null
                , IsDependentType  = false
                , CustomAttributes = customAttributes.Length > 2
                                                      ? customAttributes
                                                      : null
                , Properties = oSpaceType.DeclaredProperties
                               .Select(x => x.Name)
                               .Select(propertyName => ProcessProperty(oSpaceType
                                                                       , oSpaceType.DeclaredProperties.FirstOrDefault(q => q.Name == propertyName)
                                                                       , sSpaceType?.DeclaredProperties?.FirstOrDefault(q => q.Name == propertyName)
                                                                       , cSpaceType?.DeclaredProperties?.FirstOrDefault(q => q.Name == propertyName)))
                               .Where(x => x != null)
                               .ToList()
                , UnidirectionalAssociations = GetUnidirectionalAssociations(cSpaceType ?? oSpaceType)
                , BidirectionalAssociations  = GetBidirectionalAssociations(cSpaceType ?? oSpaceType)
                , TableName = GetTableName(type, dbContext)
            };

            log.Debug("\n   " + JsonConvert.SerializeObject(result));

            return(result);
        }
Exemple #16
0
        /// <summary>
        /// Génération des constantes statiques.
        /// </summary>
        /// <param name="w">Writer.</param>
        /// <param name="item">La classe générée.</param>
        private void GenerateConstProperties(CSharpWriter w, ModelClass item)
        {
            int nbConstValues = item.ConstValues.Count;

            if (nbConstValues != 0)
            {
                int i = 0;
                foreach (string constFieldName in item.ConstValues.Keys.OrderBy(x => x, StringComparer.Ordinal))
                {
                    ++i;
                    var           valueLibelle = item.ConstValues[constFieldName];
                    ModelProperty property     = null;
                    if (item.Stereotype == Stereotype.Reference)
                    {
                        foreach (var prop in item.PropertyList)
                        {
                            if (prop.IsUnique)
                            {
                                property = prop;
                                break;
                            }
                        }
                    }
                    else
                    {
                        property = ((IList <ModelProperty>)item.PrimaryKey)[0];
                    }

                    w.WriteSummary(2, valueLibelle.Libelle);

                    if (_parameters.UseTypeSafeConstValues.Value)
                    {
                        w.WriteLine(2, string.Format("public readonly {2}Code {0} = new {2}Code({1});", constFieldName, valueLibelle.Code, item.Name));
                    }
                    else
                    {
                        w.WriteLine(2, string.Format("public const string {0} = {1};", constFieldName, valueLibelle.Code));
                    }

                    w.WriteLine();
                }
            }
        }
Exemple #17
0
        public static void DataMethod(ModelClass txt, string sp)
        {
            string connectionstring = ConfigurationManager.ConnectionStrings["db"].ConnectionString;

            SqlConnection conn = new SqlConnection(connectionstring);

            SqlCommand cmd = new SqlCommand(sp, conn);

            cmd.CommandType = CommandType.StoredProcedure;
            conn.Open();


            cmd.Parameters.AddWithValue("@name", txt.namep);
            cmd.Parameters.AddWithValue("@sale", txt.salep);
            cmd.Parameters.AddWithValue("@purchase", txt.purchasep);
            cmd.Parameters.AddWithValue("@available", txt.availablep);
            cmd.Parameters.AddWithValue("@stockdate", txt.datap);
            cmd.ExecuteNonQuery();
        }
Exemple #18
0
        public OutputExtensionConnector(XmlTextReader r, ModelClass classEntry)
        {
            _parentClassEntry = classEntry;
            _config           = new NameValueCollection();

            if (r.Name != "ClassOutputConnector")
            {
                throw new Exception(string.Format("Source file does not match NitroCast DTD; " +
                                                  "expected 'ClassOutputConnector', found '{0}'.", r.Name));
            }

            r.MoveToContent();
            string pluginName = r.ReadElementString("ParentPlugin");

            ExtensionManager m = ExtensionManager.GetInstance();

            _parentPlugin = m.OutputExtensions[pluginName];

            if (_parentPlugin == null)
            {
                throw new Exception(string.Format("Cannot connect to OutputPlugin '{0}'.",
                                                  pluginName));
            }

            if (r.Name == "Config")
            {
                if (!r.IsEmptyElement)
                {
                    r.Read();
                    while (r.NodeType != XmlNodeType.EndElement)
                    {
                        _config.Add(r.Name, r.ReadElementString(r.Name));
                    }
                    r.ReadEndElement();
                }
                else
                {
                    r.ReadEndElement();
                }
            }

            r.ReadEndElement();
        }
        internal HttpMessage CreateOperationModelRequest(ModelClass value)
        {
            var message = _pipeline.CreateMessage();
            var request = message.Request;

            request.Method = RequestMethod.Get;
            var uri = new RawRequestUriBuilder();

            uri.Reset(endpoint);
            uri.AppendPath("/op", false);
            request.Uri = uri;
            request.Headers.Add("Accept", "application/json");
            request.Headers.Add("Content-Type", "application/json");
            var content = new Utf8JsonRequestContent();

            content.JsonWriter.WriteObjectValue(value);
            request.Content = content;
            return(message);
        }
         protected override void ConfigureTable(List<string> segments, ModelClass modelClass)
         {
            string tableName = string.IsNullOrEmpty(modelClass.TableName) ? modelClass.Name : modelClass.TableName;
            string schema = string.IsNullOrEmpty(modelClass.DatabaseSchema) || modelClass.DatabaseSchema == modelClass.ModelRoot.DatabaseSchema ? string.Empty : $", \"{modelClass.DatabaseSchema}\"";
            string buildAction = modelClass.ExcludeFromMigrations ? ", t => t.ExcludeFromMigrations()" : string.Empty;

            segments.Add($"ToTable(\"{tableName}\"{schema}{buildAction})");

            if (modelClass.Superclass != null)
               segments.Add($"HasBaseType<{modelClass.Superclass.FullName}>()");

            // primary key code segments must be output last, since HasKey returns a different type
            List<ModelAttribute> identityAttributes = modelClass.IdentityAttributes.ToList();

            if (identityAttributes.Count == 1)
               segments.Add($"HasKey(t => t.{identityAttributes[0].Name})");
            else if (identityAttributes.Count > 1)
               segments.Add($"HasKey(t => new {{ t.{string.Join(", t.", identityAttributes.Select(ia => ia.Name))} }})");
         }
            protected virtual void ConfigureTable(List <string> segments, ModelClass modelClass)
            {
                string tableName = string.IsNullOrEmpty(modelClass.TableName) ? modelClass.Name : modelClass.TableName;
                string schema    = string.IsNullOrEmpty(modelClass.DatabaseSchema) || modelClass.DatabaseSchema == modelClass.ModelRoot.DatabaseSchema ? string.Empty : ", \"{modelClass.DatabaseSchema}\"";

                segments.Add($"ToTable(\"{tableName}\"{schema})");

                // primary key code segments must be output last, since HasKey returns a different type
                List <ModelAttribute> identityAttributes = modelClass.IdentityAttributes.ToList();

                if (identityAttributes.Count == 1)
                {
                    segments.Add($"HasKey(t => t.{identityAttributes[0].Name})");
                }
                else if (identityAttributes.Count > 1)
                {
                    segments.Add($"HasKey(t => new {{ t.{string.Join(", t.", identityAttributes.Select(ia => ia.Name))} }})");
                }
            }
Exemple #22
0
      List<string> GetRequiredParameters(ModelClass modelClass, bool? haveDefaults, bool? publicOnly = null)
      {
         List<string> requiredParameters = new List<string>();

         if (haveDefaults != true)
         {
            requiredParameters.AddRange(modelClass.AllRequiredAttributes
                                                   .Where(x => (!x.IsIdentity || x.IdentityType == IdentityType.Manual)
                                                            && !x.IsConcurrencyToken
                                                            && (x.SetterVisibility == SetterAccessModifier.Public || publicOnly != false)
                                                            && string.IsNullOrEmpty(x.InitialValue))
                                                   .Select(x => $"{x.FQPrimitiveType} {x.Name.ToLower()}"));

            // don't use 1..1 associations in constructor parameters. Becomes a Catch-22 scenario.
            requiredParameters.AddRange(modelClass.AllRequiredNavigationProperties()
                                                   .Where(np => np.AssociationObject.SourceMultiplicity != Sawczyn.EFDesigner.EFModel.Multiplicity.One
                                                            || np.AssociationObject.TargetMultiplicity != Sawczyn.EFDesigner.EFModel.Multiplicity.One)
                                                   .Select(x => $"{x.ClassType.FullName} {x.PropertyName.ToLower()}"));
         }

         if (haveDefaults != false)
         {
            requiredParameters.AddRange(modelClass.AllRequiredAttributes
                                                   .Where(x => (!x.IsIdentity || x.IdentityType == IdentityType.Manual)
                                                            && !x.IsConcurrencyToken
                                                            && (x.SetterVisibility == SetterAccessModifier.Public || publicOnly != false)
                                                            && !string.IsNullOrEmpty(x.InitialValue))
                                                   .Select(x =>
                                                            {
                                                               string quote = x.PrimitiveType == "string"
                                                                           ? "\""
                                                                           : x.PrimitiveType == "char"
                                                                              ? "'"
                                                                              : string.Empty;

                                                               string value = FullyQualified(modelClass.ModelRoot, x.InitialValue.Trim('"', '\''));

                                                               return $"{x.FQPrimitiveType} {x.Name.ToLower()} = {quote}{value}{quote}";
                                                            }));
         }

         return requiredParameters;
      }
Exemple #23
0
        public GameForm()
        {
            InitializeComponent();

            model = new ModelClass(new FileDataAccess());
            model.InformPlayerEvent += refreshLabel;
            model.GameOverEvent     += gameOver;

            setupTable();

            tableLayoutPanel1.Paint += drawLines;

            var items = fileMenuItem.DropDownItems;

            items[0].Click += saveGame;
            items[1].Click += loadGame;

            newGameMenuItem.Click += newGame;
        }
Exemple #24
0
        /// <summary>
        /// Search if a class ancestor of a class has a property with the same name of a given property.
        /// </summary>
        /// <param name="property">Property to check.</param>
        /// <param name="classe">Current class.</param>
        /// <returns>The parent class with the same property, <code>null</code> if not found.</returns>
        private static ModelClass SearchParentClassWithIdenticalPropertyName(ModelProperty property, ModelClass classe)
        {
            if (classe.ParentClass == null)
            {
                return(null);
            }

            ModelClass parent = classe.ParentClass;

            foreach (ModelProperty prop in parent.PropertyList)
            {
                if (prop.Name == property.Name)
                {
                    return(parent);
                }
            }

            return(SearchParentClassWithIdenticalPropertyName(property, parent));
        }
Exemple #25
0
        /// <summary>
        /// Génère le constructeur par recopie.
        /// </summary>
        /// <param name="w">Writer.</param>
        /// <param name="item">Classe générée.</param>
        private void GenerateCopyConstructor(CSharpWriter w, ModelClass item)
        {
            w.WriteLine();
            w.WriteSummary(2, "Constructeur par recopie.");
            w.WriteParam("bean", "Source.");
            if (item.ParentClass != null)
            {
                w.WriteLine(2, "public " + item.Name + "(" + item.Name + " bean)");
                w.WriteLine(3, ": base(bean)");
                w.WriteLine(2, "{");
            }
            else
            {
                w.WriteLine(2, "public " + item.Name + "(" + item.Name + " bean)");
                w.WriteLine(2, "{");
            }

            w.WriteLine(3, "if (bean == null)");
            w.WriteLine(3, "{");
            w.WriteLine(4, "throw new ArgumentNullException(nameof(bean));");
            w.WriteLine(3, "}");
            w.WriteLine();

            foreach (var property in item.PropertyList.Where(p => !p.IsPrimitive && !p.IsCollection))
            {
                w.WriteLine(3, property.Name + " = new " + property.DataType + "(bean." + property.Name + ");");
            }

            foreach (var property in item.PropertyList.Where(p => p.IsCollection))
            {
                w.WriteLine(3, property.Name + " = new List<" + LoadInnerDataType(property.DataType) + ">(bean." + property.Name + ");");
            }

            foreach (var property in item.PropertyList.Where(p => p.IsPrimitive))
            {
                w.WriteLine(3, property.Name + " = bean." + property.Name + ";");
            }

            w.WriteLine();
            w.WriteLine(3, "OnCreated(bean);");
            w.WriteLine(2, "}");
        }
Exemple #26
0
        // ReSharper disable once UnusedParameter.Local
        private ModelClass ProcessComplexType(string entityFullName, EntityType oSpaceType, EntityType sSpaceType, EntityType cSpaceType)
        {
            Type type = assembly.GetType(entityFullName);

            if (type == null)
            {
                log.Warn($"Could not find type for complex type {entityFullName}");

                return(null);
            }

            log.Debug($"Found complex type {entityFullName}");
            string customAttributes = GetCustomAttributes(type);

            ModelClass result = new ModelClass
            {
                Name             = oSpaceType.Name,
                Namespace        = oSpaceType.NamespaceName,
                IsAbstract       = oSpaceType.Abstract,
                BaseClass        = oSpaceType.BaseType?.Name,
                IsDependentType  = true,
                CustomAttributes = customAttributes.Length > 2
                                                      ? customAttributes
                                                      : null,
                CustomInterfaces = type.GetInterfaces().Any()
                                                      ? string.Join(",", type.GetInterfaces().Select(GetTypeFullName))
                                                      : null,
                Properties = oSpaceType.DeclaredProperties
                             .Select(x => x.Name)
                             .Select(propertyName => ProcessProperty(oSpaceType
                                                                     , oSpaceType.DeclaredProperties.FirstOrDefault(q => q.Name == propertyName)
                                                                     , sSpaceType.DeclaredProperties.FirstOrDefault(q => q.Name == propertyName)
                                                                     , true))
                             .Where(x => x != null)
                             .ToList(),
                TableName = null
            };

            log.Debug("\n   " + JsonConvert.SerializeObject(result));

            return(result);
        }
Exemple #27
0
        /// <summary>
        /// Retourne la clé primaire d'une classe.
        /// </summary>
        /// <param name="classe">La classe.</param>
        /// <returns>La propriété clé primaire de la classe.</returns>
        internal static ModelProperty GetPrimaryKeyProperty(ModelClass classe)
        {
            if (!classe.HasPrimaryKey)
            {
                ModelClass parentClass = classe.ParentClass;
                while (parentClass != null)
                {
                    if (parentClass.HasPrimaryKey)
                    {
                        return(((IList <ModelProperty>)parentClass.PrimaryKey)[0]);
                    }

                    parentClass = parentClass.ParentClass;
                }

                return(null);
            }

            return(((IList <ModelProperty>)classe.PrimaryKey)[0]);
        }
Exemple #28
0
        public void AddModel(ModelClass model)
        {
            IModel newModel = (IModel)model;

            if (model is IShipModel)
            {
                gameModels.Add((IShipModel)model);
            }
            if (updating != true)
            {
                newModel.Create();
                models.Add(newModel);
            }
            else
            {
                added = true;
                newModel.Create();
                tempModels.Add(newModel);
            }
        }
Exemple #29
0
        /// <summary>
        /// Prend en charge l'alimentation de la classe pour les valeurs d'initialisation.
        /// </summary>
        /// <param name="classe">Classe concernée.</param>
        /// <param name="item">Bean d'initialisation.</param>
        protected void HandleCorrectInit(ModelClass classe, TableInit item)
        {
            if (!DictionaryItemInit.ContainsKey(classe))
            {
                DictionaryItemInit.Add(classe, item);
            }

            foreach (ItemInit itemInit in item.ItemInitList)
            {
                BeanDefinition         definition         = BeanDescriptor.GetDefinition(itemInit.Bean);
                BeanPropertyDescriptor propertyDescriptor = GetReferenceKeyDescriptor(classe, definition);
                object propertyValue = propertyDescriptor.GetValue(itemInit.Bean);
                if (propertyDescriptor.PrimitiveType == typeof(string))
                {
                    propertyValue = "\"" + propertyValue + "\"";
                }

                classe.ConstValues.Add(itemInit.VarName, propertyValue.ToString());
            }
        }
Exemple #30
0
        public void CloneTest()
        {
            var obj = new ModelClass()
            {
                Property     = 12,
                PropertyLink = "asd"
            };

            var cobj = (ModelClass)obj.Clone();

            cobj.PropertyLink += "aa";
            cobj.Property     += 2;


            Assert.AreEqual(obj.Property, 12, $"cobj.Pv:{cobj.Property}");
            Assert.AreEqual(cobj.Property, 14, $"obj.Pv:{obj.Property}");

            Assert.AreEqual(obj.PropertyLink, "asd", $"cobj.Pl:{cobj.PropertyLink}");
            Assert.AreEqual(cobj.PropertyLink, "asdaa", $"obj.Pl:{obj.PropertyLink}");
        }
        public async Task <Response <ModelClass> > OperationModelAsync(ModelClass value, CancellationToken cancellationToken = default)
        {
            if (value == null)
            {
                throw new ArgumentNullException(nameof(value));
            }

            using var message = CreateOperationModelRequest(value);
            await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false);

            switch (message.Response.Status)
            {
            case 200:
            {
                ModelClass value0 = default;
                using var document = await JsonDocument.ParseAsync(message.Response.ContentStream, default, cancellationToken).ConfigureAwait(false);

                value0 = ModelClass.DeserializeModelClass(document.RootElement);
                return(Response.FromValue(value0, message.Response));
            }
Exemple #32
0
        public void EventNullTest()
        {
            var obj = new ModelClass()
            {
                Property     = 12,
                PropertyLink = "asd"
            };

            try
            {
                obj.Property = 14;
                obj.Initialize();
                obj.FinalizeObject();
                obj.Dispose();
            }
            catch (NullReferenceException)
            {
                throw new Exception("TestFailed.. NullReferenceException");
            }
        }
Exemple #33
0
        private void App_Startup(object sender, StartupEventArgs e)
        {
            var contextOptions = new DbContextOptionsBuilder <GameContext>().UseSqlServer(ConfigurationManager.ConnectionStrings["MalomModelv2"].ConnectionString).Options;

            dataAccess           = new DbDataAcces(contextOptions);
            model                = new ModelClass(dataAccess);
            model.GameOverEvent += Model_GameOverEvent;

            viewModel = new ViewModelGame(model);
            viewModel.ExceptionEvent += ViewModel_ExceptionEvent;
            viewModel.ExitEvent      += ViewModel_ExitEvent;
            viewModel.LoadGameOpen   += ViewModel_LoadGameOpen;
            viewModel.LoadGameClose  += ViewModel_LoadGameClose;
            viewModel.SaveGameOpen   += ViewModel_SaveGameOpen;
            viewModel.SaveGameClose  += ViewModel_SaveGameClose;

            view             = new MainWindow();
            view.DataContext = viewModel;
            view.Show();
        }
Exemple #34
0
        public ViewModelGame(ModelClass model)
        {
            this.model = model;
            model.InformPlayerEvent += RefreshLabel;

            NewGameCommand      = new DelegateCommand(p => NewGame());
            ExitCommand         = new DelegateCommand(p => OnExitGame());
            LoadGameOpenCommand = new DelegateCommand(async param =>
            {
                Games = new ObservableCollection <SaveEntry>(await model.ListGamesAsync());
                OnLoadGameOpen();
            });
            LoadGameCloseCommand = new DelegateCommand(
                param => SelectedGame != null,
                param => { OnLoadGameClose(SelectedGame.Name); });
            SaveGameOpenCommand = new DelegateCommand(async param =>
            {
                Games = new ObservableCollection <SaveEntry>(await model.ListGamesAsync());
                OnSaveGameOpen();
            });
            SaveGameCloseCommand = new DelegateCommand(
                param => NewName.Length > 0,
                param => { OnSaveGameClose(NewName); });

            Fields = new ObservableCollection <FieldViewModel>();
            for (int i = 0; i < 7; i++)
            {
                for (int j = 0; j < 7; j++)
                {
                    Fields.Add(new FieldViewModel
                    {
                        Number      = i * 7 + j,
                        FieldType   = FIELDS.NaF,
                        StepCommand = new DelegateCommand(p => Step(Convert.ToInt32(p))),
                        Row         = i,
                        Col         = j
                    });
                }
            }
            RefreshTable();
        }
Exemple #35
0
        private void addClass(object sender, System.EventArgs e)
        {
            TreeNode    selectedNode;
            ModelFolder folder;

            selectedNode = modelTree.SelectedNode;

            // Find Current Folder
            while (selectedNode.Parent != null &
                   !(selectedNode.Tag is ModelFolder))
            {
                selectedNode = selectedNode.Parent;
            }

            if (selectedNode.Tag is ModelFolder)
            {
                folder = (ModelFolder)selectedNode.Tag;
            }
            else
            {
                return;
            }

            // Instantiate new class object
            ModelClass newClass = new ModelClass();

            newClass.ParentModel = this.model;
            newClass.Namespace   = this.model.DefaultNamespace;
            folder.Items.Add(newClass);

            // Add class object to DataTypeManager
            DataTypeManager.ReferenceTypes.Add(new ReferenceType(newClass, null));

            // Instantiate new class object editor
            ClassEditor newClassEditor = new ClassEditor(newClass);

            newClassEditor.MdiParent = this.MdiParent;
            newClassEditor.Show();

            refreshTree();
        }
Exemple #36
0
        public int UserLogin(ModelClass objModelLogin)
        {
            int result = 0;

            try
            {
                con.Open();
                string     checkuser = "******" + objModelLogin.User_id + "'";
                SqlCommand comm      = new SqlCommand(checkuser, con);
                int        temp      = Convert.ToInt32(comm.ExecuteScalar().ToString());
                con.Close();
                if (temp == 1)
                {
                    con.Open();
                    string     checkPasswordQuery = "select password from User_Reg_Details where User_id='" + objModelLogin.User_id + "'";
                    SqlCommand passComm           = new SqlCommand(checkPasswordQuery, con);
                    string     password           = passComm.ExecuteScalar().ToString().Replace(" ", "");
                    if (password == objModelLogin.password)
                    {
                        result = 1;
                    }
                    else
                    {
                        result = 0;
                    }
                }
                else
                {
                    result = -1;
                }
                con.Close();
            }
            catch (Exception ex)
            {
                objModel.ex_source = this.GetType().Name + MethodBase.GetCurrentMethod().Name;
                objModel.ex_url    = HttpContext.Current.Request.Url.AbsolutePath;
                objModel.ex_msg    = ex.Message;
                log.LogException(objModelLogin.User_id, objModel);
            }
            return(result);
        }
Exemple #37
0
        /// <summary>
        /// Génération de la déclaration de la classe.
        /// </summary>
        /// <param name="w">Writer</param>
        /// <param name="item">Classe à générer.</param>
        private void GenerateClassDeclaration(CSharpWriter w, ModelClass item)
        {
            if (item.Stereotype == Stereotype.Reference)
            {
                w.WriteAttribute(1, "Reference");
            }
            else if (item.Stereotype == Stereotype.Statique)
            {
                w.WriteAttribute(1, "Reference", "true");
            }

            if (!string.IsNullOrEmpty(item.DefaultProperty))
            {
                w.WriteAttribute(1, "DefaultProperty", $@"""{item.DefaultProperty}""");
            }

            if (item.DataContract.IsPersistent && !item.IsView)
            {
                if (_parameters.DbSchema != null)
                {
                    w.WriteAttribute(1, "Table", $@"""{item.DataContract.Name}""", $@"Schema = ""{_parameters.DbSchema}""");
                }
                else
                {
                    w.WriteAttribute(1, "Table", $@"""{item.DataContract.Name}""");
                }
            }

            w.WriteClassDeclaration(item.Name, item.ParentClass?.Name, new List <string>());

            GenerateConstProperties(w, item);
            GenerateConstructors(w, item);
            GenerateProperties(w, item);
            GenerateExtensibilityMethods(w, item);
            w.WriteLine(1, "}");

            if (_parameters.UseTypeSafeConstValues.Value)
            {
                GenerateConstPropertiesClass(w, item);
            }
        }
Exemple #38
0
        /// <summary>
        /// Enregistre un message de type erreur.
        /// </summary>
        /// <param name="objet">L'objet en erreur.</param>
        /// <param name="category">La catégorie de l'erreur.</param>
        /// <param name="error">Le message d'erreur.</param>
        /// <param name="isFatal">Indique si l'erreur est bloquante.</param>
        private static void RegisterError(IModelObject objet, Category category, string error, bool isFatal)
        {
            NVortexMessage message      = new NVortexMessage();
            ModelClass     itemClass    = objet as ModelClass;
            ModelProperty  itemProperty = objet as ModelProperty;

            if (itemClass != null)
            {
                message.FileName = SourceDtoDirectory + itemClass.Namespace.Name + Path.DirectorySeparatorChar + itemClass.Name + ".cs";
            }

            if (itemProperty != null)
            {
                message.FileName = SourceDtoDirectory + itemProperty.Class.Namespace.Name + Path.DirectorySeparatorChar + itemProperty.Class.Name + ".cs";
            }

            message.IsError     = isFatal;
            message.Category    = category;
            message.Description = objet.ModelFile + " " + string.Concat(GetObjectType(objet), objet.Name == null ? string.Empty : " " + objet.Name) + " : " + error;
            NVortexMessageList.Add(message);
        }
Exemple #39
0
        public static IEnumerable <ValidationError> ValidateUniqueMembers(ModelClass modelClass)
        {
            var errors   = new List <ValidationError>();
            var dupeList = new List <string>();
            var members  = getMembers(modelClass, true);

            members.ForEach(member =>
            {
                if (dupeList.Contains(member.Name))
                {
                    return;
                }
                var itemErrors = ValidateUniqueMember(member, modelClass);
                if (itemErrors.Count() > 0)
                {
                    dupeList.Add(member.Name);
                    errors.AddRange(itemErrors);
                }
            });
            return(errors);
        }
Exemple #40
0
 /// <summary>
 /// Construit la propriété contenant la composition.
 /// </summary>
 /// <param name="containedClass">La classe contenu.</param>
 /// <param name="multiplicity">La multiplicité de la composition.</param>
 /// <param name="name">Nom de la composition.</param>
 /// <param name="code">Code de la composition.</param>
 /// <param name="comment">Commentaire de la composition.</param>
 /// <returns>La propriété à ajouter dans la classe conteneur.</returns>
 internal static ModelProperty BuildClassCompositionProperty(ModelClass containedClass, string multiplicity, string name, string code, string comment)
 {
     return(new ModelProperty()
     {
         IsFromComposition = true,
         DataDescription = new ModelDataDescription()
         {
             IsPrimaryKey = false,
             Libelle = name.Trim().Length != 0 ? name.Trim() : containedClass.Name,
             ReferenceClass = containedClass
         },
         DataType = AbstractParser.Multiplicity11.Equals(multiplicity) || AbstractParser.Multiplicity01.Equals(multiplicity) ? containedClass.Name : "ICollection<" + containedClass.Name + ">",
         Name = code,
         Comment = comment,
         IsPersistent = false,
         DataMember = new ModelDataMember()
         {
             IsRequired = AbstractParser.Multiplicity11.Equals(multiplicity)
         }
     });
 }
Exemple #41
0
        private void okButton_Click(object sender, EventArgs e)
        {
            ModelerTransaction.Enter(() =>
                {
                    using (Transaction tx = _Store.TransactionManager.BeginTransaction())
                    {
                        var entity = new ModelClass(_Store)
                        {
                            Name = entityNameTextBox.Text,
                            TableName = entityNameTextBox.Text
                        };
                        _Store.ElementDirectory.FindElements<ModelRoot>().Single().Types.Add(entity);

                        if (baseClassComboBox.Text != "(None)")
                        {
                            var baseClass = _Store.ElementDirectory.FindElements<ModelClass>()
                                .First(m => m.Name == baseClassComboBox.Text);

                            InheritanceUtil.AddInheritance(baseClass, entity);
                        }
                        else if (createKeyCheckBox.Checked)
                        {
                            var propType = (BuiltInTypes)Enum.Parse(typeof(BuiltInTypes), propertyTypeComboBox.Text);
                            entity.Fields.Add(new ModelField(_Store)
                            {
                                IsPrimaryKey = true,
                                Name = propertyNameTextBox.Text,
                                Type = (BuiltInTypes)Enum.Parse(typeof(BuiltInTypes), propertyTypeComboBox.Text),
                                IsIdentity = true,
                                IsDbGenerated = true,
                                ColumnName = propertyNameTextBox.Text
                            });
                        }

                        tx.Commit();
                    }
                });

        }
 public ManyToOneRelation NewManyToOneRelation(ModelClass pkClass, ModelClass fkClass, string fkColumn)
 {
     ManyToOneRelation relation = new ManyToOneRelation(fkClass, pkClass)
                                      {
                                          SourceColumn = fkColumn,
                                          TargetColumnKey = fkColumn,
                                          TargetTable = fkClass.Table,
                                          TargetPropertyName = NamingHelper.GetPlural(fkClass.Name)
                                      };
     return relation;
 }
Exemple #43
0
		public List<Relation> GetPKRelations(ModelClass cls)
		{
			List<Relation> list = new List<Relation>();

			IDbCommand command = GetForeginKeyCommand(cls.Table, cls.Schema, null, null);
			using(IDataReader reader = command.ExecuteReader())
			{
				while(reader.Read())
				{
				    list.Add(new Relation
				                 {
				                     RelationType = RelationType.Unknown,
				                     RelationName = reader["FK_NAME"].ToString(),
				                     PrimaryOwner = cls.Schema,
				                     PrimaryTable = cls.Table,
				                     PrimaryColumn = reader["PKCOLUMN_NAME"].ToString(),
				                     ForeignOwner = reader["FKTABLE_OWNER"].ToString(),
				                     ForeignTable = reader["FKTABLE_NAME"].ToString(),
				                     ForeignColumn = reader["FKCOLUMN_NAME"].ToString()
				                 });
				}
			}
			return list;
		}
Exemple #44
0
        public List<Relation> GetPKRelations(ModelClass cls)
        {
            List<Relation> list = new List<Relation>();

            IDbCommand command = _connection.CreateCommand();
            command.CommandText =
                @"
            SELECT st.column_name, om.owner, om.constraint_name, om.table_name, sr.column_name r_column_name
              FROM all_constraints om INNER JOIN all_constraints rm ON om.r_owner = rm.owner
                                                                  AND om.r_constraint_name = rm.constraint_name
                   INNER JOIN all_cons_columns st ON om.constraint_name = st.constraint_name
                                                AND st.owner = om.owner
                                                AND st.table_name = om.table_name
                   INNER JOIN all_cons_columns sr ON rm.constraint_name = sr.constraint_name
                                                AND sr.owner = rm.owner
                                                AND sr.table_name = rm.table_name
             WHERE om.constraint_type = 'R'
               AND rm.table_name = :tname
               AND om.r_owner = :owner
                ";

            AddSchemaAndTableParams(command, cls.Schema, cls.Table);

            using (IDataReader reader = command.ExecuteReader())
            {
                while (reader.Read())
                {
                    Relation relation = new Relation();
                    relation.RelationType = RelationType.Unknown;
                    relation.RelationName = reader["CONSTRAINT_NAME"].ToString();
                    relation.PrimaryOwner = cls.Schema;
                    relation.PrimaryTable = cls.Table;
                    relation.PrimaryColumn = reader["R_COLUMN_NAME"].ToString();
                    relation.ForeignOwner = reader["OWNER"].ToString();
                    relation.ForeignTable = reader["TABLE_NAME"].ToString();
                    relation.ForeignColumn = reader["COLUMN_NAME"].ToString();

                    list.Add(relation);
                }
            }

            return list;

        }
 private void GenerateCommonPrimaryKey(ModelClass cls, CodeTypeDeclaration classDeclaration)
 {
     // Generate a primary key property from the common primary key information in the model.
     // We only do so if no primary key is already present.
     if (!cls.PrimaryKeySpecifiedByUser)
     {
         if (cls.PrimaryKey != null)
         {
             AddMemberField(classDeclaration, cls.PrimaryKey);
         }
     }
 }
 public void AssignModel(ModelClass cls)
 {
     cls.Model = _model;
 }
        private CodeTypeDeclaration GetClassDeclaration(ModelClass cls, CodeNamespace nameSpace)
        {
            if (cls == null)
                throw new ArgumentException("Class not supplied.", "cls");
            if (String.IsNullOrEmpty(cls.Name))
                throw new ArgumentException("Class name cannot be blank.", "cls");

            string className = cls.Name;
            if (cls.Model.GeneratesDoubleDerived)
                className += cls.Model.DoubleDerivedNameSuffix;

            CodeTypeDeclaration classDeclaration = CreateClass(className);

            if (cls.Model.AutomaticAssociations)
                classDeclaration.CreateEmptyPublicConstructor();

            if (cls.Model.GeneratesDoubleDerived)
                classDeclaration.TypeAttributes |= TypeAttributes.Abstract;

            if (cls.ClassParent != null)
            {
                classDeclaration.BaseTypes.Add(new CodeTypeReference(cls.ClassParent.Name));
            }
            else if (cls.Model.UseBaseClass)
            {
                bool withValidator = cls.Properties.FindAll(delegate(ModelProperty property)
                {
                    return property.IsValidatorSet();
                }).Count > 0;

                CodeTypeReference type;
                // base class for every modelclass. If left empty then baseclass from model if left empty ...etc
                if (!string.IsNullOrEmpty(cls.BaseClassName))
                    type = new CodeTypeReference(cls.BaseClassName);
                else if (!string.IsNullOrEmpty(cls.Model.BaseClassName))
                    type = new CodeTypeReference(cls.Model.BaseClassName);
                else if (withValidator)
                    type = new CodeTypeReference(Common.DefaultValidationBaseClass);
                else
                    type = new CodeTypeReference(Common.DefaultBaseClass);

                if (cls.IsGeneric())
                    type.TypeArguments.Add(cls.Name);
                classDeclaration.BaseTypes.Add(type);
            }

            if (cls.DoesImplementINotifyPropertyChanged() && cls.ClassParent == null && !cls.Model.PropertyChangedDefinedInBaseClass)
            {
                classDeclaration.BaseTypes.Add(new CodeTypeReference(Common.INotifyPropertyChangedType));
                AddINotifyPropertyChangedRegion(classDeclaration, cls.Lazy | Context.Model.UseVirtualProperties);
            }
            if (cls.DoesImplementINotifyPropertyChanging() && cls.ClassParent == null && !cls.Model.PropertyChangingDefinedInBaseClass)
            {
                classDeclaration.BaseTypes.Add(new CodeTypeReference(Common.INotifyPropertyChangingType));
                AddINotifyPropertyChangingRegion(classDeclaration, cls.Lazy | Context.Model.UseVirtualProperties);
            }

            if (!String.IsNullOrEmpty(cls.Description))
                classDeclaration.Comments.AddRange(GetSummaryComment(cls.Description));

            if (!cls.Model.GeneratesDoubleDerived)
                cls.AddActiveRecordAttributes(classDeclaration);
            if (cls.Model.UseGeneratedCodeAttribute)
                classDeclaration.CustomAttributes.Add(AttributeHelper.GetGeneratedCodeAttribute());

            nameSpace.Types.Add(classDeclaration);
            return classDeclaration;
        }
		private static void WriteChildElements(DslModeling::SerializationContext serializationContext, ModelClass element, global::System.Xml.XmlWriter writer)
		{
			// UnidirectionalAssociation
			global::System.Collections.ObjectModel.ReadOnlyCollection<UnidirectionalAssociation> allUnidirectionalAssociationInstances = UnidirectionalAssociation.GetLinksToUnidirectionalTargets(element);
			if (!serializationContext.Result.Failed && allUnidirectionalAssociationInstances.Count > 0)
			{
				writer.WriteStartElement("unidirectionalTargets");
				foreach (UnidirectionalAssociation eachUnidirectionalAssociationInstance in allUnidirectionalAssociationInstances)
				{
					if (serializationContext.Result.Failed)
						break;
	
					DslModeling::DomainClassXmlSerializer relSerializer = serializationContext.Directory.GetSerializer(eachUnidirectionalAssociationInstance.GetDomainClass().Id);
					global::System.Diagnostics.Debug.Assert(relSerializer != null, "Cannot find serializer for " + eachUnidirectionalAssociationInstance.GetDomainClass().Name + "!");
					relSerializer.Write(serializationContext, eachUnidirectionalAssociationInstance, writer);
				}
				writer.WriteEndElement();
			}
	
			// ClassHasAttributes
			global::System.Collections.ObjectModel.ReadOnlyCollection<ClassHasAttributes> allClassHasAttributesInstances = ClassHasAttributes.GetLinksToAttributes(element);
			if (!serializationContext.Result.Failed && allClassHasAttributesInstances.Count > 0)
			{
				writer.WriteStartElement("attributes");
				global::System.Type typeofClassHasAttributes = typeof(ClassHasAttributes);
				foreach (ClassHasAttributes eachClassHasAttributesInstance in allClassHasAttributesInstances)
				{
					if (serializationContext.Result.Failed)
						break;
	
					if (eachClassHasAttributesInstance.GetType() != typeofClassHasAttributes)
					{	// Derived relationships will be serialized in full-form.
						DslModeling::DomainClassXmlSerializer derivedRelSerializer = serializationContext.Directory.GetSerializer(eachClassHasAttributesInstance.GetDomainClass().Id);
						global::System.Diagnostics.Debug.Assert(derivedRelSerializer != null, "Cannot find serializer for " + eachClassHasAttributesInstance.GetDomainClass().Name + "!");			
						derivedRelSerializer.Write(serializationContext, eachClassHasAttributesInstance, writer);
					}
					else
					{	// No need to serialize the relationship itself, just serialize the role-player directly.
						DslModeling::ModelElement targetElement = eachClassHasAttributesInstance.Attribute;
						DslModeling::DomainClassXmlSerializer targetSerializer = serializationContext.Directory.GetSerializer(targetElement.GetDomainClass().Id);
						global::System.Diagnostics.Debug.Assert(targetSerializer != null, "Cannot find serializer for " + targetElement.GetDomainClass().Name + "!");			
						targetSerializer.Write(serializationContext, targetElement, writer);
					}
				}
				writer.WriteEndElement();
			}
	
			// ClassHasOperations
			global::System.Collections.ObjectModel.ReadOnlyCollection<ClassHasOperations> allClassHasOperationsInstances = ClassHasOperations.GetLinksToOperations(element);
			if (!serializationContext.Result.Failed && allClassHasOperationsInstances.Count > 0)
			{
				writer.WriteStartElement("operations");
				global::System.Type typeofClassHasOperations = typeof(ClassHasOperations);
				foreach (ClassHasOperations eachClassHasOperationsInstance in allClassHasOperationsInstances)
				{
					if (serializationContext.Result.Failed)
						break;
	
					if (eachClassHasOperationsInstance.GetType() != typeofClassHasOperations)
					{	// Derived relationships will be serialized in full-form.
						DslModeling::DomainClassXmlSerializer derivedRelSerializer = serializationContext.Directory.GetSerializer(eachClassHasOperationsInstance.GetDomainClass().Id);
						global::System.Diagnostics.Debug.Assert(derivedRelSerializer != null, "Cannot find serializer for " + eachClassHasOperationsInstance.GetDomainClass().Name + "!");			
						derivedRelSerializer.Write(serializationContext, eachClassHasOperationsInstance, writer);
					}
					else
					{	// No need to serialize the relationship itself, just serialize the role-player directly.
						DslModeling::ModelElement targetElement = eachClassHasOperationsInstance.Operation;
						DslModeling::DomainClassXmlSerializer targetSerializer = serializationContext.Directory.GetSerializer(targetElement.GetDomainClass().Id);
						global::System.Diagnostics.Debug.Assert(targetSerializer != null, "Cannot find serializer for " + targetElement.GetDomainClass().Name + "!");			
						targetSerializer.Write(serializationContext, targetElement, writer);
					}
				}
				writer.WriteEndElement();
			}
	
			// Generalization
			global::System.Collections.ObjectModel.ReadOnlyCollection<Generalization> allGeneralizationInstances = Generalization.GetLinksToSubclasses(element);
			if (!serializationContext.Result.Failed && allGeneralizationInstances.Count > 0)
			{
				writer.WriteStartElement("subclasses");
				foreach (Generalization eachGeneralizationInstance in allGeneralizationInstances)
				{
					if (serializationContext.Result.Failed)
						break;
	
					DslModeling::DomainClassXmlSerializer relSerializer = serializationContext.Directory.GetSerializer(eachGeneralizationInstance.GetDomainClass().Id);
					global::System.Diagnostics.Debug.Assert(relSerializer != null, "Cannot find serializer for " + eachGeneralizationInstance.GetDomainClass().Name + "!");
					relSerializer.Write(serializationContext, eachGeneralizationInstance, writer);
				}
				writer.WriteEndElement();
			}
	
			// BidirectionalAssociation
			global::System.Collections.ObjectModel.ReadOnlyCollection<BidirectionalAssociation> allBidirectionalAssociationInstances = BidirectionalAssociation.GetLinksToBidirectionalTargets(element);
			if (!serializationContext.Result.Failed && allBidirectionalAssociationInstances.Count > 0)
			{
				writer.WriteStartElement("bidirectionalTargets");
				foreach (BidirectionalAssociation eachBidirectionalAssociationInstance in allBidirectionalAssociationInstances)
				{
					if (serializationContext.Result.Failed)
						break;
	
					DslModeling::DomainClassXmlSerializer relSerializer = serializationContext.Directory.GetSerializer(eachBidirectionalAssociationInstance.GetDomainClass().Id);
					global::System.Diagnostics.Debug.Assert(relSerializer != null, "Cannot find serializer for " + eachBidirectionalAssociationInstance.GetDomainClass().Name + "!");
					relSerializer.Write(serializationContext, eachBidirectionalAssociationInstance, writer);
				}
				writer.WriteEndElement();
			}
	
			// Aggregation
			global::System.Collections.ObjectModel.ReadOnlyCollection<Aggregation> allAggregationInstances = Aggregation.GetLinksToAggregationTargets(element);
			if (!serializationContext.Result.Failed && allAggregationInstances.Count > 0)
			{
				writer.WriteStartElement("aggregationTargets");
				foreach (Aggregation eachAggregationInstance in allAggregationInstances)
				{
					if (serializationContext.Result.Failed)
						break;
	
					DslModeling::DomainClassXmlSerializer relSerializer = serializationContext.Directory.GetSerializer(eachAggregationInstance.GetDomainClass().Id);
					global::System.Diagnostics.Debug.Assert(relSerializer != null, "Cannot find serializer for " + eachAggregationInstance.GetDomainClass().Name + "!");
					relSerializer.Write(serializationContext, eachAggregationInstance, writer);
				}
				writer.WriteEndElement();
			}
	
			// Composition
			global::System.Collections.ObjectModel.ReadOnlyCollection<Composition> allCompositionInstances = Composition.GetLinksToCompositionTargets(element);
			if (!serializationContext.Result.Failed && allCompositionInstances.Count > 0)
			{
				writer.WriteStartElement("compositionTargets");
				foreach (Composition eachCompositionInstance in allCompositionInstances)
				{
					if (serializationContext.Result.Failed)
						break;
	
					DslModeling::DomainClassXmlSerializer relSerializer = serializationContext.Directory.GetSerializer(eachCompositionInstance.GetDomainClass().Id);
					global::System.Diagnostics.Debug.Assert(relSerializer != null, "Cannot find serializer for " + eachCompositionInstance.GetDomainClass().Name + "!");
					relSerializer.Write(serializationContext, eachCompositionInstance, writer);
				}
				writer.WriteEndElement();
			}
	
		}
        public ManyToOneRelation NewManyToOneRelation(ModelClass pkClass, ModelClass fkClass, string fkColumn)
        {
            ManyToOneRelation relation = new ManyToOneRelation(fkClass, pkClass);
            // TODO: Disabled to test server explorer drag drop bug of DeviceBuffer
            /*Log(
                String.Format("Relation: Type=ManyToOne, PKClass={0}, FKClass={1}, Column={2}", pkClass.Name,
                              fkClass.Name, fkColumn));*/
            relation.SourceColumn = fkColumn;
            relation.TargetColumnKey = fkColumn;
            relation.TargetTable = fkClass.Table;
            relation.TargetPropertyName = NamingHelper.GetPlural(fkClass.Name);

            return relation;
        }
        /* The following are the parts of the CodeDOM class hierarchy that may not have have type replacement methods written.
              o System.CodeDom.CodeAttributeArgument (CodeExpression)
              o System.CodeDom.CodeAttributeDeclaration
              o System.CodeDom.CodeNamespaceImportCollection --- System.Collections.IList, System.Collections.ICollection, System.Collections.IEnumerable
              o System.CodeDom.CodeObject
                    + System.CodeDom.CodeComment
                    + System.CodeDom.CodeCompileUnit
                          # System.CodeDom.CodeSnippetCompileUnit
                    + System.CodeDom.CodeNamespace
                    + System.CodeDom.CodeNamespaceImport
                    + System.CodeDom.CodeTypeMember
                          # System.CodeDom.CodeMemberEvent
                          # System.CodeDom.CodeMemberField
                          # System.CodeDom.CodeMemberMethod
                                * System.CodeDom.CodeConstructor
                                * System.CodeDom.CodeEntryPointMethod
                                * System.CodeDom.CodeTypeConstructor
                          # System.CodeDom.CodeMemberProperty
                          # System.CodeDom.CodeSnippetTypeMember
                          # System.CodeDom.CodeTypeDeclaration
                                * System.CodeDom.CodeTypeDelegate
                    + System.CodeDom.CodeTypeReference
              o System.Collections.CollectionBase
                    + System.CodeDom.CodeAttributeArgumentCollection
                    + System.CodeDom.CodeAttributeDeclarationCollection
                    + System.CodeDom.CodeCommentStatementCollection
                    + System.CodeDom.CodeNamespaceCollection
                    + System.CodeDom.CodeParameterDeclarationExpressionCollection
                    + System.CodeDom.CodeTypeDeclarationCollection
                    + System.CodeDom.CodeTypeMemberCollection
        */

        public void AddTemplateMembers(ModelClass modelClass, CodeTypeDeclaration classDeclaration)
        {
            if (TemplateCompileUnit != null)
            {
                CodeTypeMemberCollection methods = new CodeTypeMemberCollection();
                CodeTypeMemberCollection properties = new CodeTypeMemberCollection();

                foreach (CodeTypeMember member in TemplateCompileUnit.Namespaces[0].Types[0].Members)
                {
                    if (member is CodeMemberMethod)
                    {
                        CodeMemberMethod method = ((CodeMemberMethod)member).Clone();


                        // If type is generic, replace all type parameters with the generated class name.
                        if (TemplateCompileUnit.Namespaces[0].Types[0].TypeParameters.Count > 0)
                        {
                            string typeParameter = TemplateCompileUnit.Namespaces[0].Types[0].TypeParameters[0].Name;

                            // If there's a generic parameter, we only need to add new if the parameter signature is the same.
                            if (modelClass.IsSubclass && !method.Parameters.ContainsType(typeParameter))
                                method.Attributes |= MemberAttributes.New;

                            method.ReplaceType(typeParameter, modelClass.Name);
                        }
                        else
                        {
                            // If there's no type argument, the signature will surely match and we need to add new or something similar.
                            if (modelClass.IsSubclass)
                                method.Attributes |= MemberAttributes.New;
                        }

                        methods.Add(method);
                    }
                    else if (member is CodeMemberProperty)
                    {
                        CodeMemberProperty property = ((CodeMemberProperty)member).Clone();

                        if (modelClass.IsSubclass)
                            property.Attributes |= MemberAttributes.New;

                        // If type is generic, replace all type parameters with the generated class name.
                        if (TemplateCompileUnit.Namespaces[0].Types[0].TypeParameters.Count > 0)
                        {
                            string typeParameter = TemplateCompileUnit.Namespaces[0].Types[0].TypeParameters[0].Name;

                            property.ReplaceType(typeParameter, modelClass.Name);
                        }

                        properties.Add(property);
                    }
                }

                AddRegionMarkers(methods, "Methods imported from Member Template File");
                classDeclaration.Members.AddRange(methods);

                AddRegionMarkers(properties, "Properties imported from Member Template File");
                classDeclaration.Members.AddRange(properties);
            }
        }
        private CodeTypeDeclaration GenerateClass(ModelClass cls, CodeNamespace nameSpace)
        {
            if (cls == null)
                throw new ArgumentNullException("Class not supplied", "cls");
            if (nameSpace == null)
                throw new ArgumentNullException("Namespace not supplied", "namespace");
            if (String.IsNullOrEmpty(cls.Name))
                throw new ArgumentException("Class name cannot be blank", "cls");

            if (!CodeGenerationContext.IsClassGenerated(cls))
            {
                if (CodeGenerationContext.IsClassWithSameNameGenerated(cls.Name))
                    throw new ArgumentException(
                        "Ambiguous class name. Code for a class with the same name already generated. Please use a different name.",
                        cls.Name);

                CodeTypeDeclaration classDeclaration = GetClassDeclaration(cls, nameSpace);

                List<ModelProperty> compositeKeys = new List<ModelProperty>();

                // Properties and Fields
                foreach (ModelProperty property in cls.Properties)
                {
                    if (property.KeyType != KeyType.CompositeKey)
                    {
                        CodeMemberField memberField = GetMemberField(classDeclaration, property);

                        classDeclaration.Members.Add(memberField);

                        if (property.DebuggerDisplay)
                            classDeclaration.CustomAttributes.Add(property.GetDebuggerDisplayAttribute());
                        if (property.DefaultMember)
                            classDeclaration.CustomAttributes.Add(property.GetDefaultMemberAttribute());
                    }
                    else
                        compositeKeys.Add(property);
                }

                if (compositeKeys.Count > 0)
                {
                    CodeTypeDeclaration compositeClass =
                        GetCompositeClassDeclaration(nameSpace, classDeclaration, compositeKeys, cls.DoesImplementINotifyPropertyChanged());

                    // TODO: All access fields in a composite group assumed to be the same.
                    // We have a model validator for this case but the user may save anyway.
                    // Check if all access fields are the same.
                    CodeMemberField memberField = GetPrivateMemberFieldOfCompositeClass(compositeClass, PropertyAccess.Property);
                    classDeclaration.Members.Add(memberField);

                    classDeclaration.Members.Add(GetActiveRecordMemberCompositeKeyProperty(compositeClass, memberField, cls.DoesImplementINotifyPropertyChanged()));
                }

                //ManyToOne links where this class is the target (1-n)
                ReadOnlyCollection<ManyToOneRelation> manyToOneSources = ManyToOneRelation.GetLinksToSources(cls);
                foreach (ManyToOneRelation relationship in manyToOneSources)
                {
                    GenerateHasManyRelation(classDeclaration, nameSpace, relationship);
                }

                //ManyToOne links where this class is the source (n-1)
                ReadOnlyCollection<ManyToOneRelation> manyToOneTargets = ManyToOneRelation.GetLinksToTargets(cls);
                foreach (ManyToOneRelation relationship in manyToOneTargets)
                {
                    GenerateBelongsToRelation(classDeclaration, nameSpace, relationship);
                }

                //ManyToMany links where this class is the source
                ReadOnlyCollection<ManyToManyRelation> manyToManyTargets = ManyToManyRelation.GetLinksToManyToManyTargets(cls);
                foreach (ManyToManyRelation relationship in manyToManyTargets)
                {
                    GenerateHasAndBelongsToRelationFromTargets(classDeclaration, nameSpace, relationship);
                }

                //ManyToMany links where this class is the target
                ReadOnlyCollection<ManyToManyRelation> manyToManySources = ManyToManyRelation.GetLinksToManyToManySources(cls);
                foreach (ManyToManyRelation relationship in manyToManySources)
                {
                    GenerateHasAndBelongsToRelationFromSources(classDeclaration, nameSpace, relationship);
                }

                //OneToOne link where this class is the source
                OneToOneRelation oneToOneTarget = OneToOneRelation.GetLinkToOneToOneTarget(cls);
                if (oneToOneTarget != null)
                {
                    GenerateOneToOneRelationFromTarget(classDeclaration, nameSpace, oneToOneTarget);
                }

                //OneToOne links where this class is the target
                ReadOnlyCollection<OneToOneRelation> oneToOneSources = OneToOneRelation.GetLinksToOneToOneSources(cls);
                foreach (OneToOneRelation relationship in oneToOneSources)
                {
                    GenerateOneToOneRelationFromSources(classDeclaration, nameSpace, relationship);
                }

                //Nested links
                ReadOnlyCollection<NestedClassReferencesModelClasses> nestingTargets =
                    NestedClassReferencesModelClasses.GetLinksToNestedClasses(cls);
                foreach (NestedClassReferencesModelClasses relationship in nestingTargets)
                {
                    GenerateNestingRelationFromRelationship(classDeclaration, nameSpace, relationship);
                }

                // TODO: Other relation types (any etc)

                return classDeclaration;
            }
            else
                return CodeGenerationContext.GetTypeDeclaration(cls);
        }
Exemple #52
0
		public List<Relation> GetPKRelations(ModelClass cls)
		{
			List<Relation> list = new List<Relation>();

			IDbCommand command = _connection.CreateCommand();
			command.CommandText =
				@"select 
                    kcu.CONSTRAINT_NAME,
                    kcu.TABLE_SCHEMA,
                    kcu.TABLE_NAME,
                    kcu.COLUMN_NAME,
                    kcu.REFERENCED_TABLE_SCHEMA,
                    kcu.REFERENCED_TABLE_NAME,
                    kcu.REFERENCED_COLUMN_NAME
                from
                    INFORMATION_SCHEMA.KEY_COLUMN_USAGE kcu
                where
                    kcu.CONSTRAINT_SCHEMA is not null
                    and kcu.TABLE_NAME is not null
                    and kcu.COLUMN_NAME is not NULL
                    and kcu.REFERENCED_TABLE_SCHEMA = ?schema
                    and kcu.REFERENCED_TABLE_NAME = ?table";

			AddSchemaAndTableParams(command, cls.Schema, cls.Table);

			using(IDataReader reader = command.ExecuteReader())
			{
				while(reader.Read())
				{
					Relation relation = new Relation();
					relation.RelationType = RelationType.Unknown;
					relation.RelationName = reader["CONSTRAINT_NAME"].ToString();
					relation.PrimaryOwner = cls.Schema;
					relation.PrimaryTable = cls.Table;
					relation.PrimaryColumn = reader["REFERENCED_COLUMN_NAME"].ToString();
					relation.ForeignOwner = reader["TABLE_SCHEMA"].ToString();
					relation.ForeignTable = reader["TABLE_NAME"].ToString();
					relation.ForeignColumn = reader["COLUMN_NAME"].ToString();

					list.Add(relation);
				}
			}

			return list;
		}
		private static void ReadCompositionInstances(DslModeling::SerializationContext serializationContext, ModelClass element, global::System.Xml.XmlReader reader)
		{
			while (!serializationContext.Result.Failed && !reader.EOF && reader.NodeType == global::System.Xml.XmlNodeType.Element)
			{
				DslModeling::DomainClassXmlSerializer newCompositionSerializer = serializationContext.Directory.GetSerializer(Composition.DomainClassId);
				global::System.Diagnostics.Debug.Assert(newCompositionSerializer != null, "Cannot find serializer for Composition!");
				Composition newComposition = newCompositionSerializer.TryCreateInstance (serializationContext, reader, element.Partition) as Composition;
				if (newComposition != null)
				{
					DslModeling::DomainRoleInfo.SetRolePlayer (newComposition, Composition.CompositionSourceDomainRoleId, element);
					DslModeling::DomainClassXmlSerializer targetSerializer = serializationContext.Directory.GetSerializer (newComposition.GetDomainClass().Id);	
					global::System.Diagnostics.Debug.Assert (targetSerializer != null, "Cannot find serializer for " + newComposition.GetDomainClass().Name + "!");
					targetSerializer.Read(serializationContext, newComposition, reader);
				}
				else
				{	// Maybe the relationship is serialized in short-form by mistake.
					DslModeling::DomainClassXmlSerializer newModelClassMonikerOfCompositionSerializer = serializationContext.Directory.GetSerializer(ModelClass.DomainClassId);
					global::System.Diagnostics.Debug.Assert(newModelClassMonikerOfCompositionSerializer != null, "Cannot find serializer for ModelClass!");
					DslModeling::Moniker newModelClassMonikerOfComposition = newModelClassMonikerOfCompositionSerializer.TryCreateMonikerInstance(serializationContext, reader, element, Composition.DomainClassId, element.Partition);
					if (newModelClassMonikerOfComposition != null)
					{
						LinqToRdfSerializationBehaviorSerializationMessages.ExpectingFullFormRelationship(serializationContext, reader, typeof(Composition));
						new Composition(element.Partition, new DslModeling::RoleAssignment(Composition.CompositionSourceDomainRoleId, element), new DslModeling::RoleAssignment(Composition.CompositionTargetDomainRoleId, newModelClassMonikerOfComposition));
						DslModeling::SerializationUtilities.Skip(reader);	// Moniker contains no child XML elements, so just skip.
					}
					else
					{	// Unknown element, skip.
						DslModeling::SerializationUtilities.Skip(reader);
					}
				}
			}
		}
Exemple #54
0
 public PropertyData(string name, ModelClass modelClass)
     : this(name)
 {
     ModelClass = modelClass;
 }
        private void GenerateDerivedClass(ModelClass cls, CodeNamespace nameSpace)
        {
            if (cls.Model.GeneratesDoubleDerived)
            {
                CodeTypeDeclaration derivedClass = new CodeTypeDeclaration(cls.Name);
                derivedClass.IsPartial = true;
                derivedClass.TypeAttributes = TypeAttributes.Public;
                derivedClass.BaseTypes.Add(new CodeTypeReference(cls.Name + cls.Model.DoubleDerivedNameSuffix));
                cls.AddActiveRecordAttributes(derivedClass);

                nameSpace.Types.Add(derivedClass);
            }
        }
		/// <summary>
		/// This method deserializes all child model elements.
		/// </summary>
		/// <remarks>
		/// The caller will position the reader at the open tag of the first child XML element to deserialized.
		/// This method will read as many child elements as it can. It returns under three circumstances:
		/// 1) When an unknown child XML element is encountered. In this case, this method will position the reader at the 
		///    open tag of the unknown element. This implies the if the first child XML element is unknown, this method 
		///    should return immediately and do nothing.
		/// 2) When all child XML elemnets are read. In this case, the reader will be positioned at the end tag of the parent element.
		/// 3) EOF.
		/// </remarks>
		/// <param name="serializationContext">Serialization context.</param>
		/// <param name="reader">XmlReader to read serialized data from.</param>
		/// <param name="element">In-memory ModelClass instance that will get the deserialized data.</param>
		private static void ReadChildElements(DslModeling::SerializationContext serializationContext, ModelClass element, global::System.Xml.XmlReader reader)
		{
			while (!serializationContext.Result.Failed && !reader.EOF && reader.NodeType == global::System.Xml.XmlNodeType.Element)
			{
				switch (reader.LocalName)
				{
					case "unidirectionalTargets":	// Relationship "UnidirectionalAssociation"
						if (reader.IsEmptyElement)
						{	// No instance of this relationship, just skip
							DslModeling::SerializationUtilities.Skip(reader);
						}
						else
						{
							DslModeling::SerializationUtilities.SkipToFirstChild(reader);  // Skip the open tag of <unidirectionalTargets>
							ReadUnidirectionalAssociationInstances(serializationContext, element, reader);
							DslModeling::SerializationUtilities.Skip(reader);  // Skip the close tag of </unidirectionalTargets>
						}
						break;
					case "attributes":	// Relationship "ClassHasAttributes"
						if (reader.IsEmptyElement)
						{	// No instance of this relationship, just skip
							DslModeling::SerializationUtilities.Skip(reader);
						}
						else
						{
							DslModeling::SerializationUtilities.SkipToFirstChild(reader);  // Skip the open tag of <attributes>
							ReadClassHasAttributesInstances(serializationContext, element, reader);
							DslModeling::SerializationUtilities.Skip(reader);  // Skip the close tag of </attributes>
						}
						break;
					case "operations":	// Relationship "ClassHasOperations"
						if (reader.IsEmptyElement)
						{	// No instance of this relationship, just skip
							DslModeling::SerializationUtilities.Skip(reader);
						}
						else
						{
							DslModeling::SerializationUtilities.SkipToFirstChild(reader);  // Skip the open tag of <operations>
							ReadClassHasOperationsInstances(serializationContext, element, reader);
							DslModeling::SerializationUtilities.Skip(reader);  // Skip the close tag of </operations>
						}
						break;
					case "subclasses":	// Relationship "Generalization"
						if (reader.IsEmptyElement)
						{	// No instance of this relationship, just skip
							DslModeling::SerializationUtilities.Skip(reader);
						}
						else
						{
							DslModeling::SerializationUtilities.SkipToFirstChild(reader);  // Skip the open tag of <subclasses>
							ReadGeneralizationInstances(serializationContext, element, reader);
							DslModeling::SerializationUtilities.Skip(reader);  // Skip the close tag of </subclasses>
						}
						break;
					case "bidirectionalTargets":	// Relationship "BidirectionalAssociation"
						if (reader.IsEmptyElement)
						{	// No instance of this relationship, just skip
							DslModeling::SerializationUtilities.Skip(reader);
						}
						else
						{
							DslModeling::SerializationUtilities.SkipToFirstChild(reader);  // Skip the open tag of <bidirectionalTargets>
							ReadBidirectionalAssociationInstances(serializationContext, element, reader);
							DslModeling::SerializationUtilities.Skip(reader);  // Skip the close tag of </bidirectionalTargets>
						}
						break;
					case "aggregationTargets":	// Relationship "Aggregation"
						if (reader.IsEmptyElement)
						{	// No instance of this relationship, just skip
							DslModeling::SerializationUtilities.Skip(reader);
						}
						else
						{
							DslModeling::SerializationUtilities.SkipToFirstChild(reader);  // Skip the open tag of <aggregationTargets>
							ReadAggregationInstances(serializationContext, element, reader);
							DslModeling::SerializationUtilities.Skip(reader);  // Skip the close tag of </aggregationTargets>
						}
						break;
					case "compositionTargets":	// Relationship "Composition"
						if (reader.IsEmptyElement)
						{	// No instance of this relationship, just skip
							DslModeling::SerializationUtilities.Skip(reader);
						}
						else
						{
							DslModeling::SerializationUtilities.SkipToFirstChild(reader);  // Skip the open tag of <compositionTargets>
							ReadCompositionInstances(serializationContext, element, reader);
							DslModeling::SerializationUtilities.Skip(reader);  // Skip the close tag of </compositionTargets>
						}
						break;
					default:
						return;  // Don't know this element.
				}
			}
		}
Exemple #57
0
		public List<Relation> GetFKRelations(ModelClass cls)
		{
			List<Relation> list = new List<Relation>();

			IDbCommand command = GetForeginKeyCommand(null, null, cls.Table, cls.Schema);
			using(IDataReader reader = command.ExecuteReader())
			{
				while(reader.Read())
				{
					Relation relation = new Relation();
					relation.RelationType = RelationType.Unknown; // Caller will decide 
					relation.RelationName = reader["FK_NAME"].ToString();
					relation.PrimaryOwner = reader["PKTABLE_OWNER"].ToString();
					relation.PrimaryTable = reader["PKTABLE_NAME"].ToString();
					relation.PrimaryColumn = reader["PKCOLUMN_NAME"].ToString();
					relation.ForeignOwner = cls.Schema;
					relation.ForeignTable = cls.Table;
					relation.ForeignColumn = reader["FKCOLUMN_NAME"].ToString();

					list.Add(relation);
				}
			}

			return list;
		}
        private CodeTypeDeclaration GetClassDeclaration(ModelClass cls, CodeNamespace nameSpace)
        {
            if (cls == null)
                throw new ArgumentException("Class not supplied.", "cls");
            if (String.IsNullOrEmpty(cls.Name))
                throw new ArgumentException("Class name cannot be blank.", "cls");

            CodeTypeDeclaration classDeclaration = CreateClass(cls.Name);

            if (cls.Model.UseBaseClass)
            {
                bool withValidator = cls.Properties.FindAll(delegate(ModelProperty property)
                {
                    return property.IsValidatorSet();
                }).Count > 0;

                CodeTypeReference type;
                // base class for every modelclass. If left empty then baseclass from model if left empty ...etc
                if (!string.IsNullOrEmpty(cls.BaseClassName))
                    type = new CodeTypeReference(cls.BaseClassName);
                else if (!string.IsNullOrEmpty(cls.Model.BaseClassName))
                    type = new CodeTypeReference(cls.Model.BaseClassName);
                else if (withValidator)
                    type = new CodeTypeReference(Common.DefaultValidationBaseClass);
                else
                    type = new CodeTypeReference(Common.DefaultBaseClass);

                if (cls.IsGeneric())
                    type.TypeArguments.Add(classDeclaration.Name);
                classDeclaration.BaseTypes.Add(type);
            }

            if (cls.DoesImplementINotifyPropertyChanged())
            {
                classDeclaration.BaseTypes.Add(new CodeTypeReference(Common.INotifyPropertyChangedType));
                AddINotifyPropertyChangedRegion(classDeclaration);
            }


            if (!String.IsNullOrEmpty(cls.Description))
                classDeclaration.Comments.AddRange(GetSummaryComment(cls.Description));

            classDeclaration.CustomAttributes.Add(cls.GetActiveRecordAttribute());
            if (cls.Model.UseGeneratedCodeAttribute)
                classDeclaration.CustomAttributes.Add(AttributeHelper.GetGeneratedCodeAttribute());
            // Make a note as "generated" to prevent recursive generation attempts
            CodeGenerationContext.AddClass(cls, classDeclaration);

            nameSpace.Types.Add(classDeclaration);
            return classDeclaration;
        }
		/// <summary>
		/// Reads all instances of relationship ClassHasOperations.
		/// </summary>
		/// <remarks>
		/// The caller will position the reader at the open tag of the first XML element inside the relationship tag, so it can be
		/// either the first instance, or a bogus tag. This method will deserialize all instances and ignore all bogus tags. When the
		/// method returns, the reader will be positioned at the end tag of the relationship (or EOF if somehow that happens).
		/// </remarks>
		/// <param name="serializationContext">Serialization context.</param>
		/// <param name="element">In-memory ModelClass instance that will get the deserialized data.</param>
		/// <param name="reader">XmlReader to read serialized data from.</param>
		private static void ReadClassHasOperationsInstances(DslModeling::SerializationContext serializationContext, ModelClass element, global::System.Xml.XmlReader reader)
		{
			while (!serializationContext.Result.Failed && !reader.EOF && reader.NodeType == global::System.Xml.XmlNodeType.Element)
			{
				DslModeling::DomainClassXmlSerializer newClassOperationOfClassHasOperationsSerializer = serializationContext.Directory.GetSerializer(ClassOperation.DomainClassId);
				global::System.Diagnostics.Debug.Assert(newClassOperationOfClassHasOperationsSerializer != null, "Cannot find serializer for ClassOperation!");
				ClassOperation newClassOperationOfClassHasOperations = newClassOperationOfClassHasOperationsSerializer.TryCreateInstance(serializationContext, reader, element.Partition) as ClassOperation;
				if (newClassOperationOfClassHasOperations != null)
				{
					element.Operations.Add(newClassOperationOfClassHasOperations);
					DslModeling::DomainClassXmlSerializer targetSerializer = serializationContext.Directory.GetSerializer (newClassOperationOfClassHasOperations.GetDomainClass().Id);	
					global::System.Diagnostics.Debug.Assert (targetSerializer != null, "Cannot find serializer for " + newClassOperationOfClassHasOperations.GetDomainClass().Name + "!");
					targetSerializer.Read(serializationContext, newClassOperationOfClassHasOperations, reader);
				}
				else
				{
					global::System.Type typeofClassHasOperations = typeof(ClassHasOperations);
					DslModeling::DomainRelationshipXmlSerializer newClassHasOperationsSerializer = serializationContext.Directory.GetSerializer(ClassHasOperations.DomainClassId) as DslModeling::DomainRelationshipXmlSerializer;
					global::System.Diagnostics.Debug.Assert(newClassHasOperationsSerializer != null, "Cannot find serializer for ClassHasOperations!");
					ClassHasOperations newClassHasOperations = newClassHasOperationsSerializer.TryCreateInstance (serializationContext, reader, element.Partition) as ClassHasOperations;
					if (newClassHasOperations != null)
					{
						if (newClassHasOperations.GetType() == typeofClassHasOperations)
						{	// The relationship should be serialized in short-form.
							LinqToRdfSerializationBehaviorSerializationMessages.ExpectingShortFormRelationship(serializationContext, reader, typeof(ClassHasOperations));
						}
						DslModeling::DomainRoleInfo.SetRolePlayer (newClassHasOperations, ClassHasOperations.ModelClassDomainRoleId, element);
						DslModeling::DomainClassXmlSerializer targetSerializer = serializationContext.Directory.GetSerializer (newClassHasOperations.GetDomainClass().Id);	
						global::System.Diagnostics.Debug.Assert (targetSerializer != null, "Cannot find serializer for " + newClassHasOperations.GetDomainClass().Name + "!");
						targetSerializer.Read(serializationContext, newClassHasOperations, reader);
					}
					else
					{	// Unknown element, skip
						DslModeling::SerializationUtilities.Skip(reader);
					}
				}
			}
		}