Beispiel #1
0
        /// <summary>
        /// Creates the element that describes a foreign constraint.
        /// </summary>
        /// <param name="foreignKeyElement">A description of a foreign constraint.</param>
        /// <returns>An element that can be used in an XML Schema document to describe a foreign constraint.</returns>
        private static XElement CreateForeignKey(ForeignKeyElement foreignKeyElement)
        {
            //    <xs:keyref name="FK_Entity_AccessControl" refer="EntityKey" msprop:rel_Generator_UserRelationName="FK_Entity_AccessControl"
            //        msprop:rel_Generator_RelationVarName="relationFK_Entity_AccessControl" msprop:rel_Generator_UserChildTable="AccessControl"
            //        msprop:rel_Generator_UserParentTable="Entity" msprop:rel_Generator_ParentPropName="EntityRow"
            //        msprop:rel_Generator_ChildPropName="GetAccessControlRows">
            //      <xs:selector xpath=".//mstns:AccessControl" />
            //      <xs:field xpath="mstns:EntityId" />
            //    </xs:keyref>
            XElement foreignElement = new XElement(
                ScrubXsdCommand.xs + "keyref",
                new XAttribute("name", foreignKeyElement.Name),
                new XAttribute("refer", foreignKeyElement.UniqueKey.Name));

            foreignElement.Add(
                new XElement(
                    ScrubXsdCommand.xs + "selector",
                    new XAttribute("xpath", string.Format(".//mstns:{0}", foreignKeyElement.Table.Name))));

            foreach (ColumnReferenceElement columnReferenceElement in foreignKeyElement.Columns.OrderBy(c => c.Name))
            {
                ColumnElement columnElement = columnReferenceElement.Column;
                foreignElement.Add(
                    new XElement(
                        ScrubXsdCommand.xs + "field",
                        new XAttribute("xpath", string.Format("mstns:{0}", columnElement.Name))));
            }

            // This describes a foreign constraint on a table.
            return(foreignElement);
        }
        private ArrayList DiscoverForeignKeyColumns(SqlEntityElement sqlentity, ConstraintElement constraint, SqlConnection connection)
        {
            ArrayList list = new ArrayList();

            String s = "select 1 ORDINAL_POSITION, c.name COLUMN_NAME, rc.name FOREIGN_COLUMN ";

            s += "from syscolumns c ";
            s += "left join sysreferences r on c.id = r.fkeyid and c.colid=r.fkey1 and r.constid=object_id('" + constraint.Name + "') ";
            s += "left join syscolumns rc on rc.id=r.rkeyid and rc.colid=r.rkey1 ";
            s += "where c.id = object_id('" + sqlentity.Name + "') and r.constid is not null ";

            DataTable table = new DataTable();
            String    sql   = s;

            for (int i = 2; i <= 16; i++)
            {
                sql += " union ";
                sql += s.Replace("1", i.ToString());
            }
            SqlDataAdapter adapter = new SqlDataAdapter(sql, connection);

            adapter.Fill(table);

            foreach (DataRow row in table.Rows)
            {
                ColumnElement column = new ColumnElement();
                column.Name          = row["COLUMN_NAME"].ToString();
                column.ForeignColumn = row["FOREIGN_COLUMN"].ToString();
                list.Add(column);
            }

            return(list);
        }
Beispiel #3
0
        /// <summary>
        /// Initializes a new instance of the <see cref="AutoIncrementField"/> class.
        /// </summary>
        /// <param name="columnElement">The table element.</param>
        public AutoIncrementField(ColumnElement columnElement)
        {
            // Validate the parameter
            if (columnElement == null)
            {
                throw new ArgumentNullException(nameof(columnElement));
            }

            // Initialize the object.
            this.Name = columnElement.Name.ToCamelCase();

            //        /// <summary>
            //        /// The autoincremented index.
            //        /// </summary>
            //        private int entityId;
            this.Syntax = SyntaxFactory.FieldDeclaration(
                SyntaxFactory.VariableDeclaration(
                    SyntaxFactory.PredefinedType(
                        SyntaxFactory.Token(SyntaxKind.IntKeyword)))
                .WithVariables(
                    SyntaxFactory.SingletonSeparatedList <VariableDeclaratorSyntax>(
                        SyntaxFactory.VariableDeclarator(
                            SyntaxFactory.Identifier(this.Name)))))
                          .WithModifiers(AutoIncrementField.Modifiers)
                          .WithLeadingTrivia(AutoIncrementField.DocumentationComment);
        }
Beispiel #4
0
        public void BeginColumn(ColumnElement column)
        {
            // Determine grouping function:
            string function = GetFunction(column.Grouping);

            // Apply select:
            if (column.Visible)
            {
                if (select.Length > 0)
                {
                    select.Append(",\r\n   ");
                }
                select.Append(GetUniqueFullNameWithAlias(column, function));
            }

            // Check for condition:
            if (!String.IsNullOrEmpty(column.Condition))
            {
                if (this.where.Length > 0)
                {
                    this.where.Append("\r\n   AND ");
                }
                this.where.AppendFormat("({0} {1})", GetFullName(column), column.Condition);
            }

            // Apply grouping:
            if (column.Grouping == GroupingFunction.Group)
            {
                if (groupBy.Length > 0)
                {
                    groupBy.Append(",\r\n   ");
                }
                groupBy.Append(GetFullName(column));
            }
        }
Beispiel #5
0
        /// <summary>
        /// Creates the element that describes a unique constraint.
        /// </summary>
        /// <param name="uniqueConstraintSchema">A description of a unique constraint.</param>
        /// <returns>An element that can be used in an XML Schema document to describe a unique constraint.</returns>
        private static XElement CreateUniqueKey(UniqueKeyElement uniqueConstraintSchema)
        {
            //    <xs:unique name="AccessControlKey" msdata:PrimaryKey="true">
            //      <xs:selector xpath=".//mstns:AccessControl" />
            //      <xs:field xpath="mstns:UserId" />
            //      <xs:field xpath="mstns:EntityId" />
            //    </xs:unique>
            XElement uniqueElement = new XElement(
                ScrubXsdCommand.xs + "unique",
                new XAttribute("name", uniqueConstraintSchema.Name));

            if (uniqueConstraintSchema.IsPrimaryKey)
            {
                uniqueElement.Add(new XAttribute(XmlSchemaDocument.IsPrimaryKeyName, true));
            }

            uniqueElement.Add(
                new XElement(
                    ScrubXsdCommand.xs + "selector",
                    new XAttribute("xpath", string.Format(".//mstns:{0}", uniqueConstraintSchema.Table.Name))));

            foreach (ColumnReferenceElement columnReferenceElement in uniqueConstraintSchema.Columns.OrderBy(c => c.Name))
            {
                ColumnElement columnElement = columnReferenceElement.Column;
                uniqueElement.Add(
                    new XElement(
                        ScrubXsdCommand.xs + "field",
                        new XAttribute("xpath", string.Format("mstns:{0}", columnElement.Name))));
            }

            // This describes a unique constraint on a table.
            return(uniqueElement);
        }
        private ArrayList DiscoverIndexColumns(SqlEntityElement sqlentity, IndexElement index, SqlConnection connection)
        {
            ArrayList list = new ArrayList();

            DataTable table = new DataTable();

            String sql = "DECLARE @indid smallint, \n";

            sql += "	@indname sysname,  \n";
            sql += "   	@indkey int,  \n";
            sql += "	@name varchar(30) \n";
            sql += " \n";
            sql += "SET NOCOUNT ON \n";
            sql += " \n";
            sql += "set @name='" + sqlentity.Name + "' \n";
            sql += "set @indname='" + index.Name + "' \n";
            sql += " \n";
            sql += "select @indid=indid from sysindexes where id=object_id(@name) and name=@indname \n";
            sql += "   \n";
            sql += "	create table #spindtab \n";
            sql += "	( \n";
            sql += "		TABLE_NAME			sysname	collate database_default NULL, \n";
            sql += "		INDEX_NAME			sysname	collate database_default NULL, \n";
            sql += "		COLUMN_NAME			sysname	collate database_default NULL, \n";
            sql += "		SORT_DIRECTION			varchar(50) NULL, \n";
            sql += "		ORDINAL_POSITION		int \n";
            sql += "	) \n";
            sql += " \n";
            sql += "     SET @indkey = 1 \n";
            sql += "     WHILE @indkey <= 16 and INDEX_COL(@name, @indid, @indkey) is not null \n";
            sql += "      BEGIN \n";
            sql += "	insert into #spindtab(table_name, index_name, column_name, ordinal_position, sort_direction) values(@name, @indname, INDEX_COL(@name, @indid, @indkey), @indkey, case when indexkey_property(object_id(@name), @indid, 1, 'isdescending')=1 then 'DESC' else '' end) \n";
            sql += "        SET @indkey = @indkey + 1 \n";
            sql += "      END \n";
            sql += " \n";
            sql += "select * from #spindtab order by ordinal_position \n";
            sql += " \n";
            sql += "drop table #spindtab \n";
            sql += " \n";
            sql += "SET NOCOUNT OFF \n";

            SqlDataAdapter adapter = new SqlDataAdapter(sql, connection);

            adapter.Fill(table);

            foreach (DataRow row in table.Rows)
            {
                ColumnElement column = new ColumnElement();
                column.Name          = row["COLUMN_NAME"].ToString();
                column.SortDirection = row["SORT_DIRECTION"].ToString();
                list.Add(column);
            }

            return(list);
        }
Beispiel #7
0
 private string GetFullNameOrAlias(ColumnElement item)
 {
     if (String.IsNullOrEmpty(item.Alias))
     {
         return(String.Format("{0}.{1}", GetFullNameOrAlias(item.Table), item.ColumnName));
     }
     else
     {
         return(String.Format("[{0}]", item.Alias));
     }
 }
 private void clearGroupingToolStripMenuItem_Click(object sender, EventArgs e)
 {
     foreach (object item in this.QueryTree.ModelNodes)
     {
         if (item is ColumnElement)
         {
             ColumnElement c = (ColumnElement)item;
             c.Grouping = GroupingFunction.None;
         }
     }
 }
Beispiel #9
0
        private string GetUniqueFullNameWithAlias(ColumnElement item, string function)
        {
            // Build a unique alias if name would not be unique:
            if (String.IsNullOrEmpty(item.Alias))
            {
                // Build a unique column name:
                string ext = String.Empty;
                string columnName;
                while (true)
                {
                    columnName = String.Format("{0}{1}", item.ColumnName, ext);
                    if (!this.uniqueColumnNames.Contains(columnName))
                    {
                        break;
                    }
                    if (ext == String.Empty)
                    {
                        ext = "2";
                    }
                    else
                    {
                        ext = (Int32.Parse(ext) + 1).ToString();
                    }
                }
                this.uniqueColumnNames.Add(columnName);

                // Store alias if one was created:
                if (columnName != item.ColumnName)
                {
                    item.Alias = columnName;
                }
            }

            // Build name with alias:
            if (String.IsNullOrEmpty(item.Alias))
            {
                return(String.Format(
                           (function == null) ? "{0}.[{1}]" : "{2}({0}.[{1}])",
                           GetFullNameOrAlias(item.Table),
                           item.ColumnName,
                           function
                           ));
            }
            else
            {
                return(String.Format(
                           (function == null) ? "{0}.[{1}] AS [{2}]" : "{3}({0}.[{1}]) AS [{2}]",
                           GetFullNameOrAlias(item.Table),
                           item.ColumnName,
                           item.Alias,
                           function
                           ));
            }
        }
 private void clearAllConditionsToolStripMenuItem_Click(object sender, EventArgs e)
 {
     foreach (object item in this.QueryTree.ModelNodes)
     {
         if (item is ColumnElement)
         {
             ColumnElement c = (ColumnElement)item;
             c.Condition = null;
             c.Visible   = true;
         }
     }
 }
Beispiel #11
0
            public override ColumnElement CreateColumnForDefault(DataRow row, string name, DbObjectCollection.DataType type)
            {
                ColumnElement column = column = base.CreateColumnForDefault(row, name, type);

                if (!row.IsNull("PRIMARY_KEY"))
                {
                    if (row.Field <bool>("PRIMARY_KEY"))
                    {
                        column.IsKey       = true;
                        column.ColumnIndex = Convert.ToInt32(row["ORDINAL_POSITION"]);
                    }
                }
                return(column);
            }
 private void fixGroupingToolStripMenuItem_Click(object sender, EventArgs e)
 {
     foreach (object item in this.QueryTree.ModelNodes)
     {
         if (item is ColumnElement)
         {
             ColumnElement c = (ColumnElement)item;
             if (c.Visible && c.Grouping == GroupingFunction.None)
             {
                 c.Grouping = GroupingFunction.Group;
             }
         }
     }
 }
Beispiel #13
0
 public virtual void ProcessColumn(ColumnElement column, DataRow row, DataType type)
 {
     if (!row.IsNull(Names.Nullable))
     {
         var value = row[Names.Nullable];
         if (value is bool)
         {
             column.IsNullable = (bool)value;
         }
         else
         {
             column.IsNullable = value.ToString() == Names.TrueValue;
         }
     }
     column.ClrType = type.ClrType;
 }
Beispiel #14
0
            public ColumnElement CreateColumn(DataRow row, DataType type)
            {
                var           name   = row.Field <string>("COLUMN_NAME");
                ColumnElement column = null;

                if (Methods.TryGetValue(type.ClrType, out Func <DataRow, string, DataType, ColumnElement> method))
                {
                    column = method(row, name, type);
                }
                else
                {
                    column = CreateColumnForDefault(row, name, type);
                }
                ProcessColumn(column, row, type);
                return(column);
            }
 private void clearAllAliassesToolStripMenuItem_Click(object sender, EventArgs e)
 {
     foreach (object item in this.QueryTree.ModelNodes)
     {
         if (item is TableElement)
         {
             TableElement t = (TableElement)item;
             t.Alias = null;
         }
         else if (item is ColumnElement)
         {
             ColumnElement c = (ColumnElement)item;
             c.Alias = null;
         }
     }
 }
Beispiel #16
0
        /// <summary>
        /// Gets the syntax for the creation of an anonymous type.
        /// </summary>
        /// <param name="uniqueKeyElement">The description of a unique key.</param>
        /// <param name="isDecorated">Indicates that the argument name should be prefixed with the index name.</param>
        /// <returns>An expression that builds an anonymous type from a table description.</returns>
        public static SeparatedSyntaxList <ArgumentSyntax> GetSyntax(UniqueKeyElement uniqueKeyElement, bool isDecorated = false)
        {
            // Validate the argument.
            if (uniqueKeyElement == null)
            {
                throw new ArgumentNullException(nameof(uniqueKeyElement));
            }

            //                    country = this.domain.Countries.CountryCountryCodeKey.Find(countryCountryCodeKeyCountryCode);
            //                    region = this.domain.Regions.RegionExternalKey.Find((regionExternalKeyName, regionExternalKeyCountryCode));
            SeparatedSyntaxList <ArgumentSyntax> findParameters;

            if (uniqueKeyElement.Columns.Count == 1)
            {
                ColumnElement columnElement = uniqueKeyElement.Columns[0].Column;
                string        attributeName = isDecorated ? $"{uniqueKeyElement.Name.ToCamelCase()}{columnElement.Name}" : columnElement.Name.ToVariableName();
                findParameters = SyntaxFactory.SingletonSeparatedList <ArgumentSyntax>(
                    SyntaxFactory.Argument(
                        SyntaxFactory.IdentifierName(attributeName)));
            }
            else
            {
                List <SyntaxNodeOrToken> keys = new List <SyntaxNodeOrToken>();
                foreach (ColumnReferenceElement columnReferenceElement in uniqueKeyElement.Columns)
                {
                    if (keys.Count != 0)
                    {
                        keys.Add(SyntaxFactory.Token(SyntaxKind.CommaToken));
                    }

                    ColumnElement columnElement = columnReferenceElement.Column;
                    string        attributeName = isDecorated ? $"{uniqueKeyElement.Name.ToCamelCase()}{columnElement.Name}" : columnElement.Name.ToVariableName();
                    keys.Add(
                        SyntaxFactory.Argument(
                            SyntaxFactory.IdentifierName(attributeName)));
                }

                findParameters = SyntaxFactory.SingletonSeparatedList <ArgumentSyntax>(
                    SyntaxFactory.Argument(
                        SyntaxFactory.TupleExpression(
                            SyntaxFactory.SeparatedList <ArgumentSyntax>(keys))));
            }

            // This is either the parameter or a tuple that can be used as parameters to a 'Find' operation.
            return(findParameters);
        }
Beispiel #17
0
        /// <summary>
        /// Gets the syntax for the creation of an anonymous type.
        /// </summary>
        /// <param name="uniqueKeyElement">The description of a unique key.</param>
        /// <param name="variableName">The name of the variable holding the keys.</param>
        /// <returns>An expression that builds an anonymous type from a table description.</returns>
        public static SeparatedSyntaxList <ArgumentSyntax> GetMemberSyntax(UniqueElement uniqueKeyElement, string variableName)
        {
            SeparatedSyntaxList <ArgumentSyntax> findParameters;

            if (uniqueKeyElement.Columns.Count == 1)
            {
                //                    country = this.dataModel.Countries.CountryCountryCodeKey.Find(countryCountryCodeKeyCountryCode);
                ColumnElement columnElement = uniqueKeyElement.Columns[0].Column;
                string        propertyName  = columnElement.Name;
                findParameters = SyntaxFactory.SingletonSeparatedList <ArgumentSyntax>(
                    SyntaxFactory.Argument(
                        SyntaxFactory.MemberAccessExpression(
                            SyntaxKind.SimpleMemberAccessExpression,
                            SyntaxFactory.IdentifierName(variableName),
                            SyntaxFactory.IdentifierName(propertyName))));
            }
            else
            {
                //                    region = this.dataModel.Regions.RegionExternalKey.Find((regionExternalKeyName, regionExternalKeyCountryCode));
                List <SyntaxNodeOrToken> keys = new List <SyntaxNodeOrToken>();
                foreach (ColumnReferenceElement columnReferenceElement in uniqueKeyElement.Columns)
                {
                    if (keys.Count != 0)
                    {
                        keys.Add(SyntaxFactory.Token(SyntaxKind.CommaToken));
                    }

                    ColumnElement columnElement = columnReferenceElement.Column;
                    string        attributeName = columnElement.Name.ToVariableName();
                    keys.Add(
                        SyntaxFactory.Argument(
                            SyntaxFactory.MemberAccessExpression(
                                SyntaxKind.SimpleMemberAccessExpression,
                                SyntaxFactory.IdentifierName(variableName),
                                SyntaxFactory.IdentifierName(attributeName))));
                }

                findParameters = SyntaxFactory.SingletonSeparatedList <ArgumentSyntax>(
                    SyntaxFactory.Argument(
                        SyntaxFactory.TupleExpression(
                            SyntaxFactory.SeparatedList <ArgumentSyntax>(keys))));
            }

            // This is either the parameter or a tuple that can be used as parameters to a 'Find' operation.
            return(findParameters);
        }
Beispiel #18
0
            public override ColumnElement CreateColumnForDefault(DataRow row, string name, DbObjectCollection.DataType type)
            {
                ColumnElement column = column = base.CreateColumnForDefault(row, name, type);

                if (!row.IsNull("EXTRA") && row.Field <string>("EXTRA") == "auto_increment")
                {
                    column.Identity = new IdentityInfo();
                }
                if (!row.IsNull("COLUMN_KEY"))
                {
                    if (row.Field <string>("COLUMN_KEY") == "PRI")
                    {
                        column.IsKey       = true;
                        column.ColumnIndex = Convert.ToInt32(row["ORDINAL_POSITION"]);
                    }
                }
                return(column);
            }
Beispiel #19
0
        /// <summary>
        /// Initializes a new instance of the <see cref="ColumnProperty"/> class.
        /// </summary>
        /// <param name="columnElement">The column schema.</param>
        public ColumnProperty(ColumnElement columnElement)
        {
            // Initialize the object.
            this.columnElement = columnElement;

            // This is the name of the property.
            this.Name = this.columnElement.Name;

            //        /// <summary>
            //        /// Gets or sets ConfigurationId.
            //        /// </summary>
            //        public string ConfigurationId { get; set; }
            this.Syntax = SyntaxFactory.PropertyDeclaration(
                Conversions.FromType(columnElement.ColumnType),
                SyntaxFactory.Identifier(this.Name))
                          .WithAccessorList(this.AccessorList)
                          .WithModifiers(ColumnProperty.Modifiers)
                          .WithAttributeLists(this.Attributes)
                          .WithLeadingTrivia(this.DocumentationComment);
        }
        private ArrayList DiscoverPrimaryKeyColumns(SqlEntityElement sqlentity, ConstraintElement constraint, SqlConnection connection)
        {
            ArrayList list = new ArrayList();

            DataTable table = new DataTable();
            String    sql   = "SELECT * ";

            sql += "FROM INFORMATION_SCHEMA.KEY_COLUMN_USAGE  ";
            sql += "where table_name='" + sqlentity.Name + "' and constraint_name='" + constraint.Name + "'  ";
            sql += "order by ORDINAL_POSITION  ";
            SqlDataAdapter adapter = new SqlDataAdapter(sql, connection);

            adapter.Fill(table);

            foreach (DataRow row in table.Rows)
            {
                ColumnElement column = new ColumnElement();
                column.Name = row["COLUMN_NAME"].ToString();
                list.Add(column);
            }

            return(list);
        }
Beispiel #21
0
        /// <summary>
        /// Creates the element that describes a column in a table.
        /// </summary>
        /// <param name="columnElement">A description of a column.</param>
        /// <returns>An element that can be used in an XML Schema document to describe a column.</returns>
        private static XElement CreateColumn(ColumnElement columnElement)
        {
            string dataType = string.Empty;
            string xmlType  = string.Empty;

            switch (columnElement.ColumnType.FullName)
            {
            case "System.Object":

                xmlType = "xs:anyType";
                break;

            case "System.Int32":

                xmlType = "xs:int";
                break;

            case "System.Int64":

                xmlType = "xs:long";
                break;

            case "System.Float":

                xmlType = "xs:double";
                break;

            case "System.Double":

                xmlType = "xs:double";
                break;

            case "System.Decimal":

                xmlType = "xs:decimal";
                break;

            case "System.Boolean":

                xmlType = "xs:boolean";
                break;

            case "System.String":

                xmlType = "xs:string";
                break;

            case "System.DateTime":

                xmlType = "xs:dateTime";
                break;

            case "System.Byte[]":

                xmlType = "xs:base64Binary";
                break;

            default:

                dataType = columnElement.ColumnType.FullName;
                xmlType  = "xs:anyType";
                break;
            }

            //                          <xs:element name="UserId" msdata:DataType="System.Guid, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"
            //                            msprop:Generator_UserColumnName="UserId" msprop:Generator_ColumnVarNameInTable="columnUserId" msprop:Generator_ColumnPropNameInRow="UserId"
            //                            msprop:Generator_ColumnPropNameInTable="UserIdColumn" type="xs:string" minOccurs="0" />
            XElement xElement = new XElement(ScrubXsdCommand.xs + "element", new XAttribute("name", columnElement.Name));

            // Microsoft uses a custom decoration to describe data types that are not part of the cannon XML Schema datatypes.
            if (dataType != string.Empty)
            {
                xElement.Add(new XAttribute(XmlSchemaDocument.DataTypeName, dataType));
            }

            // This attribute controls whether the column is autoincremented by the database server.
            if (columnElement.IsAutoIncrement)
            {
                xElement.Add(new XAttribute(XmlSchemaDocument.AutoIncrementName, true));
            }

            // Emit the column's type.
            if (!columnElement.HasSimpleType)
            {
                xElement.Add(new XAttribute("type", xmlType));
            }
            else
            {
                if (columnElement.ColumnType.FullName == typeof(string).FullName)
                {
                    //                <xs:simpleType>
                    //                  <xs:restriction base="xs:string">
                    //                    <xs:maxLength value="128" />
                    //                  </xs:restriction>
                    //                </xs:simpleType>
                    XElement restrictionElement = new XElement(
                        ScrubXsdCommand.xs + "restriction",
                        new XAttribute("base", xmlType),
                        new XElement(ScrubXsdCommand.xs + "maxLength", new XAttribute("value", columnElement.MaximumLength)));
                    xElement.Add(new XElement(ScrubXsdCommand.xs + "simpleType", restrictionElement));
                }

                if (columnElement.ColumnType.FullName == typeof(decimal).FullName)
                {
                    //                <xs:simpleType>
                    //                  <xs:restriction base="xs:decimal">
                    //                    <xs:fractionDigits value="6" />
                    //                    <xs:totalDigits value="18" />
                    //                  </xs:restriction>
                    //                </xs:simpleType>
                    XElement restrictionElement = new XElement(
                        ScrubXsdCommand.xs + "restriction",
                        new XAttribute("base", xmlType),
                        new XElement(ScrubXsdCommand.xs + "fractionDigits", new XAttribute("value", columnElement.FractionDigits)),
                        new XElement(ScrubXsdCommand.xs + "totalDigits", new XAttribute("value", columnElement.TotalDigits)));
                    xElement.Add(new XElement(ScrubXsdCommand.xs + "simpleType", restrictionElement));
                }
            }

            // An optional column is identified with a 'minOccurs=0' attribute.
            if (columnElement.ColumnType.IsNullable)
            {
                xElement.Add(new XAttribute("minOccurs", 0));
            }

            // Provide an explicit default value for all column elements.
            if (!columnElement.ColumnType.IsNullable && columnElement.DefaultValue != null)
            {
                xElement.Add(new XAttribute("default", columnElement.DefaultValue.ToString().ToLower()));
            }

            // This describes the column of a table.
            return(xElement);
        }
Beispiel #22
0
 private string GetFullName(ColumnElement item)
 {
     return(String.Format("{0}.[{1}]", GetFullNameOrAlias(item.Table), item.ColumnName));
 }
Beispiel #23
0
 public void EndColumn(ColumnElement column)
 {
 }
Beispiel #24
0
 public MemberGenerator(ColumnElement element, string propertyName)
 {
     Element      = element;
     PropertyName = propertyName;
 }
        private ArrayList DiscoverColumns(SqlEntityElement sqlentity, SqlConnection connection)
        {
            ArrayList list = new ArrayList();

            DataTable columns = GetTableColumns(sqlentity, connection);

            foreach (DataRow row in columns.Rows)
            {
                if (row["COLUMN_COMPUTED"].ToString() == "0")
                {
                    ColumnElement column = new ColumnElement();
                    column.Name = row["COLUMN_NAME"].ToString();

                    column.SqlType.Name = row["DATA_TYPE"].ToString();
                    // if the sql type is defined, default to all values defined in it
                    if (sqltypes.ContainsKey(column.SqlType.Name))
                    {
                        column.SqlType = (SqlTypeElement)((SqlTypeElement)sqltypes[column.SqlType.Name]).Clone();
                    }
                    else
                    {
                        WriteToLog("SqlType " + column.SqlType.Name + " was not defined");
                    }

                    column.SqlType.Length = row["CHARACTER_MAXIMUM_LENGTH"].ToString().Length > 0 ? (Int32)row["CHARACTER_MAXIMUM_LENGTH"] : (Int32)(Int16)row["COLUMN_LENGTH"];
                    if (!System.DBNull.Value.Equals(row["NUMERIC_PRECISION"]))
                    {
                        column.SqlType.Precision = (Int32)(Byte)row["NUMERIC_PRECISION"];
                    }
                    if (!System.DBNull.Value.Equals(row["NUMERIC_SCALE"]))
                    {
                        column.SqlType.Scale = (Int32)row["NUMERIC_SCALE"];
                    }
                    column.Identity   = row["IsIdentity"].ToString() == "1";
                    column.RowGuidCol = row["IsRowGuidCol"].ToString() == "1";
                    column.ViewColumn = row["IsViewColumn"].ToString() == "1";
                    column.Required   = row["IS_NULLABLE"].ToString().Trim().ToUpper().Equals("NO");

                    // Check for unicode columns
                    if (column.SqlType.Name.ToLower() == "nchar" || column.SqlType.Name.ToLower() == "nvarchar" || column.SqlType.Name.ToLower() == "ntext")
                    {
                        column.SqlType.Length = column.SqlType.Length / 2;
                    }

                    // Check for text or ntext columns, which require a different length from what SQL Server reports
                    if (column.SqlType.Name.ToLower() == "text")
                    {
                        column.SqlType.Length = 2147483647;
                    }
                    else if (column.SqlType.Name.ToLower() == "ntext")
                    {
                        column.SqlType.Length = 1073741823;
                    }

                    // Append the array to the array list
                    list.Add(column);
                }
            }

            return(list);
        }
Beispiel #26
0
        private void LoadDataFromDBC(string Filename)
        {
            FileInfo DBCInfo = new FileInfo(Filename);

            ConfigFile    DBCLayout     = m_Engine.LoadFile(@"data\dbc_layouts.xml");
            ConfigElement LayoutElement = DBCLayout["layout", DBCInfo.Name];

            if (LayoutElement == null)
            {
                return;
            }

            DataTable DBCTable = m_Data.Tables["data"];

            if (DBCTable == null)
            {
                DBCTable = m_Data.Tables.Add("data");
            }

            DBCTable.BeginLoadData();

            #region Construct Columns

            string          LayoutID       = LayoutElement.GetString("id");
            ConfigElement[] ColumnElements = DBCLayout["column", "id", LayoutID];

            DataColumn PrimaryColumn = null;
            foreach (ConfigElement ColumnElement in ColumnElements)
            {
                Type   ColumnType = typeof(uint);
                string TypeName   = ColumnElement.GetString("type");

                if (TypeName != null)
                {
                    ColumnType = Type.GetType("System." + TypeName, false, true);
                    if (ColumnType == null)
                    {
                        throw new Exception("InvalidTypeException");
                    }
                }

                DataColumn CurrentColumn = DBCTable.Columns.Add(ColumnElement.GetString("name").ToLower(), ColumnType);
                if (ColumnElement.GetBoolean("primarykey"))
                {
                    PrimaryColumn = CurrentColumn;
                }
            }

            if (PrimaryColumn != null)
            {
                DBCTable.PrimaryKey = new DataColumn[1] {
                    PrimaryColumn
                };
            }

            #endregion
            #region Load DBC

            BinaryReader DBCReader = new BinaryReader(File.OpenRead(Filename));
            DBCHeader    Header    = new DBCHeader(DBCReader);

            long   StringTablePos = (Header.RowSize * Header.RowCount) + 20;
            byte[] Buffer         = new byte[Header.RowSize];

            #region Read each Row

            for (int i = 0; i <= Header.RowCount - 1; i++)
            {
                DataRow DBCRow = DBCTable.NewRow();

                DBCReader.Read(Buffer, 0, (int)Header.RowSize);
                long NextRowPosition = DBCReader.BaseStream.Position;

                BinaryReader RowReader = new BinaryReader(new MemoryStream(Buffer));

                foreach (ConfigElement ColumnElement in ColumnElements)
                {
                    string ColumnName = ColumnElement.GetString("name");
                    if (ColumnElement.Exists("position"))
                    {
                        RowReader.BaseStream.Seek((long)ColumnElement.GetUInt64("position"), SeekOrigin.Begin);
                    }

                    Type   ColumnType = typeof(uint);
                    string TypeName   = ColumnElement.GetString("type");

                    if (TypeName != null)
                    {
                        switch (TypeName.ToLower())
                        {
                            #region Type Read Cases
                        case "sbyte":
                            DBCRow[ColumnName] = RowReader.ReadSByte();
                            break;

                        case "byte":
                            DBCRow[ColumnName] = RowReader.ReadByte();
                            break;

                        case "short":
                            DBCRow[ColumnName] = RowReader.ReadInt16();
                            break;

                        case "ushort":
                            DBCRow[ColumnName] = RowReader.ReadUInt16();
                            break;

                        case "int":
                            DBCRow[ColumnName] = RowReader.ReadInt32();
                            break;

                        case "uint":
                            DBCRow[ColumnName] = RowReader.ReadUInt32();
                            break;

                        case "long":
                            DBCRow[ColumnName] = RowReader.ReadInt64();
                            break;

                        case "ulong":
                            DBCRow[ColumnName] = RowReader.ReadUInt64();
                            break;

                        case "float":
                            DBCRow[ColumnName] = RowReader.ReadSingle();
                            break;

                        case "double":
                            DBCRow[ColumnName] = RowReader.ReadDouble();
                            break;

                        case "string":
                            uint StringPos = RowReader.ReadUInt32();
                            DBCReader.BaseStream.Seek(StringTablePos + StringPos, SeekOrigin.Begin);

                            DBCRow[ColumnName] = Utilities.ReadString(DBCReader);

                            DBCReader.BaseStream.Seek(NextRowPosition, SeekOrigin.Begin);
                            break;
                            #endregion
                        }
                    }
                    else
                    {
                        DBCRow[ColumnName] = RowReader.ReadUInt32();
                    }
                }

                RowReader.Close();
                DBCTable.Rows.Add(DBCRow);
            }

            #endregion

            DBCReader.Close();

            #endregion

            DBCTable.EndLoadData();
        }