Click here to Skip to main content
15,892,161 members
Articles / Programming Languages / C#

Customize an application with XML fragments

Rate me:
Please Sign up or sign in to vote.
1.44/5 (3 votes)
22 May 20073 min read 28.3K   124   10  
How to customize an application using XML fragments
using System;
using System.Collections.Generic;
using System.Text;
using System.Data.SqlClient;
using System.Data.Common;
using System.Data;

namespace Bulasoft.Common.SchemaGenerators
{
    internal class MSSQLSchemaGenerator : SchemaGeneratorBase
    {
        protected override string GenerateTableCommand(TableDescriptor name, FieldDescriptorList fields)
        {
            StringBuilder commandText;
            if (fields.Count == 0)
            {
                commandText = new StringBuilder("create table ");
                commandText.AppendFormat("[{0}] (", name.Name);
                commandText.Append(Environment.NewLine);
                foreach (FieldDescriptor field in name.Fields)
                    if (field.HasNulls)
                        commandText.AppendFormat(" [{0}] {1}," + Environment.NewLine, field.Name, FieldToSQL(field));
                    else
                    {
                        if (field.IsPK)
                            commandText.AppendFormat(" [{0}] {1} NOT NULL CONSTRAINT {2} PRIMARY KEY," + Environment.NewLine, field.Name, FieldToSQL(field), SchemaGenerator.PKPrefix + name.Name);
                        else
                            commandText.AppendFormat(" [{0}] {1} NOT NULL," + Environment.NewLine, field.Name, FieldToSQL(field));
                    }

                commandText.Remove(commandText.Length - 1 - Environment.NewLine.Length, 1 + Environment.NewLine.Length);
                commandText.Append(")");
            }
            else
            {
                bool someChange = false;
                commandText = new StringBuilder("alter table ");
                commandText.AppendFormat("[{0}] add", name.Name);
                commandText.Append(Environment.NewLine);
                foreach (FieldDescriptor field in name.Fields)
                    if (!fields.Contains(field.Name))
                    {
                        someChange = true;
                        if (field.HasNulls)
                            commandText.AppendFormat("[{0}] {1}," + Environment.NewLine, field.Name, FieldToSQL(field));
                        else
                            commandText.AppendFormat("[{0}] {1} NOT NULL," + Environment.NewLine, field.Name, FieldToSQL(field));
                    }

                if (!someChange)
                    return null;
                commandText.Remove(commandText.Length - 1 - Environment.NewLine.Length, 1 + Environment.NewLine.Length);
                commandText.Append("");
            }
            return commandText.ToString();
        }

        protected override string FieldToSQL(FieldDescriptor field)
        {
            switch (Type.GetTypeCode(field.FieldSystemType))
            {
                case TypeCode.DateTime:
                    return "datetime";
                case TypeCode.Int32:
                    return "int";
                case TypeCode.Int64:
                    return "bigint";
                case TypeCode.Double:
                    return "float";
                case TypeCode.String:
                    if (field.Length.HasValue)
                        return string.Format("nvarchar({0})", field.Length);
                    else
                        return "nvarchar(max)";
                case TypeCode.Boolean:
                    return "bit";
                case TypeCode.Decimal:
                    return "money";
                default:
                    {
                        if (field.FieldSystemType == typeof(Guid))
                            return "uniqueidentifier";

                        if (field.FieldSystemType == typeof(TimeSpan))
                            return "char(11)";

                        if (field.FieldSystemType == typeof(Enum))
                            return "int";

                        throw new ArgumentException(string.Format("Unsupported data type {0}", field.FieldSystemType.GetType().Name));
                    }
            }
        }

        protected override string GenerateFKCommand(TableDescriptor table, FieldDescriptor field)
        {
            return string.Format("ALTER TABLE {0} ADD CONSTRAINT {1} FOREIGN KEY ({2}) REFERENCES {3}",
                table.Name, table.GetFKName(field), field.Name, field.FKTableName);
        }

        protected override FieldDescriptorList GetFieldDescriptorList(string tableName)
        {
            FieldDescriptorList result = new FieldDescriptorList();
            DataColumn tableNameCol = allColumns.Columns["table_name"];
            DataColumn dbTypeCol = allColumns.Columns["data_type"];
            DataColumn columnNameCol = allColumns.Columns["column_name"];

            foreach (DataRow dr in allColumns.Rows)
            {
                if (dr[tableNameCol].ToString() == tableName)
                {
                    string dataType = dr[dbTypeCol].ToString();
                    FieldDescriptor descriptor = result.Add(dr[columnNameCol].ToString(), dataType);
                    descriptor.HasNulls = dr["is_nullable"].ToString().Equals("YES", StringComparison.OrdinalIgnoreCase);
                    if (dataType == "nvarchar")
                        descriptor.Length = (int)dr["character_maximum_length"];
                    if (dataType == "decimal")
                    {
                        descriptor.Precision = (byte)dr["numeric_precision"];
                        descriptor.Scale = (byte)dr["numeric_scale"];
                    }
                }
            }

            return result;
        }

        protected override string GenerateIndexCommand(TableDescriptor table, FieldDescriptor field)
        {
            return string.Format("CREATE INDEX {0} ON {1} ({2})", SchemaGenerator.IndexPrefix + table.Name + '_' + field.Name, table.Name, field.Name);
        }

    }
}

By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here


Written By
Web Developer
Germany Germany
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions