Example #1
0
        public void Create()
        {
            Delete();
            _targetDatabase.Collation = "Latin1_General_CI_AI";
            var fileGroup = new FileGroup(_targetDatabase, "PRIMARY");

            _targetDatabase.FileGroups.Add(fileGroup);


            var dataFile = new DataFile(fileGroup, _targetSettings.DatabaseName, _targetSettings.DataFilePath)
            {
                Growth     = 10,
                GrowthType = FileGrowthType.Percent
            };

            fileGroup.Files.Add(dataFile);

            var logFile = new LogFile(_targetDatabase, string.Format("{0}_log", _targetSettings.DatabaseName),
                                      _targetSettings.LogFilePath)
            {
                Growth     = 10,
                GrowthType = FileGrowthType.Percent
            };

            _targetDatabase.LogFiles.Add(logFile);
            _targetDatabase.Collation = _sourceDatabase.Collation;

            Logger.WriteLine("Creating target database {0}", _targetSettings.DatabaseName);
            _targetDatabase.DatabaseOptions.Trustworthy = true;
            _targetDatabase.Create();
        }
        public async Task <MessageViewModel> UpdateName([FromBody] RenameGroupParams renameGroupParams)
        {
            MessageViewModel msg = RenameGroupParamsValidator.Validate(renameGroupParams);

            if (msg.Code != MessageCode.Success)
            {
                return(msg);
            }

            FileGroup group = await fileGroupBusiness.Get(this.CurrentAuthShopId(), renameGroupParams.GroupId);

            if (group == null)
            {
                return new MessageViewModel {
                           Code = MessageCode.Fail, Message = "分组不存在"
                }
            }
            ;

            group.Name = renameGroupParams.GroupName;
            fileGroupBusiness.Update(group);
            return(new MessageViewModel {
                Code = MessageCode.Success, Message = "重命名成功"
            });
        }
Example #3
0
        /// <summary>
        /// Return a list of file paths from the corresponding group in the target library
        /// </summary>
        public static IEnumerable <PathAndPropertiesTuple> GetFilePathAndProperties(
            this FileGroup fileGroup, LockFileTargetLibrary package)
        {
            switch (fileGroup)
            {
            case FileGroup.CompileTimeAssembly:
                return(SelectPath(package.CompileTimeAssemblies));

            case FileGroup.RuntimeAssembly:
                return(SelectPath(package.RuntimeAssemblies));

            case FileGroup.ContentFile:
                return(SelectPath(package.ContentFiles));

            case FileGroup.NativeLibrary:
                return(SelectPath(package.NativeLibraries));

            case FileGroup.ResourceAssembly:
                return(SelectPath(package.ResourceAssemblies));

            case FileGroup.RuntimeTarget:
                return(SelectPath(package.RuntimeTargets));

            case FileGroup.FrameworkAssembly:
                return(package.FrameworkAssemblies.Select(c => Tuple.Create(c, _emptyProperties)));

            default:
                throw new ArgumentOutOfRangeException(nameof(fileGroup));
            }
        }
 private static string replacePlaceholders(string text, FileGroup fileGroup)
 {
     return(text
            .Replace(PlaceholderFileGroupName, makeFolderNameCompatible(fileGroup.Name))
            .Replace(PlaceholderFileGroupNumber,
                     Math.Abs(fileGroup.UniqueID.GetHashCode()).ToString(CultureInfo.InvariantCulture)));
 }
Example #5
0
        static void Main(string[] args)
        {
            //Program Start
            //string choice;
            //Console.WriteLine("Choose Your Option:\n1:Company To Removeable Disk\n2:Home To Removeable Disk");
            //Console.WriteLine("3:Removeable Disk To Company\n4:Removeable Disk To Home\n");
            //choice = Console.ReadKey().KeyChar.ToString();
            //switch (choice)
            //{
            //    case "1":
            //        Console.WriteLine("Now Start Company To Removeable Disk\n");
            //        break;
            //        //case "2":
            //        //    Console.WriteLine("Press 2");
            //        //    break;
            //        //case "3":
            //        //    Console.WriteLine("Press 3");
            //        //    break;
            //        //case "4":
            //        //    Console.WriteLine("Press 4");
            //        //    break;
            //        //default:
            //        //    Console.WriteLine("You Should Make Right Choice!");
            //        //    return;
            //}

            //Start Logic
            FileGroup home = new FileGroup(EStations.Home.ToString());

            home.ReadFromXML(EStations.Home);
            home.Show();
            Console.ReadKey();
        }
Example #6
0
        public IOutput Create()
        {
            var group = new FileGroup("Ids");

            var sb = new StringBuilder();

            sb.Al($"namespace {_module.Namespace}.Core.Ids");
            sb.Al("{");
            sb.I(1).Al("public interface IIdGenerator");
            sb.I(1).Al("{");
            sb.I(2).Al("Guid New();");
            sb.I(1).Al("}");
            sb.Al("}");
            group.AddFile(new File("IIdGenerator.cs", sb.ToString(), canOverwrite: true));

            sb.Clear();
            sb.Al($"namespace {_module.Namespace}.Core.Ids");
            sb.Al("{");
            sb.I(1).Al("public class NulloIdGenerator : IIdGenerator");
            sb.I(1).Al("{");
            sb.I(2).Al("public Guid New() => Guid.NewGuid();");
            sb.I(1).Al("}");
            sb.Al("}");
            group.AddFile(new File("NulloIdGenerator.cs", sb.ToString(), canOverwrite: true));

            return(group);
        }
Example #7
0
 public Filetypevaliator(FileGroup filetype)
 {
     if (filetype == FileGroup.Image)
     {
         validtypes = new string[] { "image/jpeg", "image/png", "image/gif" };
     }
 }
 public void Fill(Database database, string connectionString)
 {
     try
     {
         if (database.Options.Ignore.FilterTableFileGroup)
         {
             using (SqlConnection conn = new SqlConnection(connectionString))
             {
                 using (SqlCommand command = new SqlCommand(GetSQL(), conn))
                 {
                     conn.Open();
                     using (SqlDataReader reader = command.ExecuteReader())
                     {
                         while (reader.Read())
                         {
                             FileGroup item = new FileGroup(database);
                             item.Id    = (int)reader["ID"];
                             item.Name  = reader["name"].ToString();
                             item.Owner = "";
                             item.IsDefaultFileGroup = (bool)reader["is_default"];
                             item.IsReadOnly         = (bool)reader["is_read_only"];
                             item.IsFileStream       = reader["type"].Equals("FD");
                             FillFiles(item, connectionString);
                             database.FileGroups.Add(item);
                         }
                     }
                 }
             }
         }
     }
     catch
     {
         throw;
     }
 }
Example #9
0
        private List <MeterDataSet> LoadMeterDataSets(AdoDataConnection connection, FileGroup fileGroup)
        {
            List <MeterDataSet> meterDataSets = new List <MeterDataSet>();
            IEnumerable <Event> eventTable    = (new TableOperations <Event>(connection)).QueryRecordsWhere("FileGroupID = {0}", fileGroup.ID);

            MeterDataSet meterDataSet;
            DataGroup    dataGroup;

            foreach (IGrouping <int, Event> eventGroup in eventTable.GroupBy(evt => evt.MeterID))
            {
                meterDataSet       = new MeterDataSet();
                meterDataSet.Meter = (new TableOperations <Meter>(connection)).QueryRecordWhere("ID = {0}", eventGroup.Key);
                meterDataSet.Meter.ConnectionFactory = () => new AdoDataConnection(connection.Connection, typeof(SqlDataAdapter), false);

                foreach (Event evt in eventGroup)
                {
                    dataGroup = new DataGroup();
                    dataGroup.FromData(meterDataSet.Meter, (new TableOperations <EventData>(connection)).QueryRecordWhere("ID = {0}", evt.EventDataID).TimeDomainData);

                    foreach (DataSeries dataSeries in dataGroup.DataSeries)
                    {
                        meterDataSet.DataSeries.Add(dataSeries);
                    }
                }

                meterDataSets.Add(meterDataSet);
            }

            return(meterDataSets);
        }
Example #10
0
        public static void NewPrimaryFile(ref FileGroup fileGroup, string dataFolderPath, double?initialSize = null, double?fileGrowth = null, FileGrowthType?growthType = null, double?maxSize = null)
        {
            string fileName = string.Format(PRIMARY_FILE_FORMAT, dataFolderPath, fileGroup.Parent.Name);

            if (!fileGrowth.HasValue || !growthType.HasValue)
            {
                KeyValuePair <double, FileGrowthType> autoGrowth = GetModelDBAutoGrowth();
                fileGrowth = autoGrowth.Key;
                growthType = autoGrowth.Value;
            }
            if (!initialSize.HasValue)
            {
                initialSize = GetModelDBInitialSize();
            }

            if (!maxSize.HasValue)
            {
                maxSize = GetModelDBMaxSize();
            }

            fileGroup.Files.Add(new DataFile(fileGroup, Path.GetFileNameWithoutExtension(fileName))
            {
                FileName      = fileName,
                IsPrimaryFile = true,
                Growth        = fileGrowth.Value,
                GrowthType    = growthType.Value,
                MaxSize       = maxSize.Value,
                Size          = initialSize.Value
            });
        }
Example #11
0
 public void PopulateCredentialsProfiles(FileGroup file)
 {
     if (_credentialsUI != null)
     {
         _credentialsUI.PopulateCredentialsProfiles(file);
     }
 }
Example #12
0
        /// <summary>
        /// Create a new file and save the file group.
        /// </summary>
        /// <param name="fileGroup">The file group defining the new file.</param>
        public void CreateFile(FileGroup fileGroup)
        {
            fileGroup.SaveFields();
            if (!File.Exists(BuildFilePath(fileGroup.FilePath, fileGroup.FileName).Replace('/', '\\')))
            {
                var dataDef  = Settings.FindBaseFile(fileGroup.BaseFileName);
                var f        = GenDataBase.DataLoader.LoadData(BuildFilePath(dataDef.FilePath, dataDef.FileName)).AsDef();
                var d        = new GenDataBase(f);
                var fileName = BuildFilePath(fileGroup.FilePath, fileGroup.FileName);
                GenParameters.SaveToFile(d, fileName);
            }
            if (Settings.FindFileGroup(fileGroup.Name) == null)
            {
                Settings.Model.GenSettingsList[0].AddFileGroup(fileGroup.Name, fileGroup.FileName, fileGroup.FilePath,
                                                               fileGroup.BaseFileName, fileGroup.Profile, fileGroup.GeneratedFile);
            }

            if (fileGroup.BaseFileName == "Definition")
            {
                AddBaseFile(fileGroup);
            }

            SetFileGroup(fileGroup.Name);
            SaveSettings();
        }
Example #13
0
        public IOutput Create()
        {
            var group = new FileGroup("Responses");

            var sb = new StringBuilder();

            sb.Al($"namespace {_module.Namespace}.Core.Responses");
            sb.Al("{");
            sb.I(1).Al("public class PagedListResponse<T>");
            sb.I(1).Al("{");
            sb.I(2).Al("public IReadOnlyList<T> Items { get; }");
            sb.I(2).Al("public long TotalItemCount { get; }");
            sb.I(2).Al("public bool HasNextPage { get; }");
            sb.I(2).Al("public PagedListResponse(IEnumerable<T> items, long totalItemCount, bool hasNextPage)");
            sb.I(2).Al("{");
            sb.I(3).Al("Items = items.ToList();");
            sb.I(3).Al("TotalItemCount = totalItemCount;");
            sb.I(3).Al("HasNextPage = hasNextPage;");
            sb.I(2).Al("}");
            sb.I(1).Al("}");
            sb.Al("}");
            group.AddFile(new File("PagedListResponse.cs", sb.ToString(), canOverwrite: true));

            return(group);
        }
Example #14
0
        private TreeListNode addFileGroupToTree(
            TreeListNode parentNode,
            FileGroup fileGroup)
        {
            if (_ignoreFileGroup != null && _ignoreFileGroup.UniqueID == fileGroup.UniqueID)
            {
                return(null);
            }

            var fileGroupNode =
                AppendNode(
                    new object[]
            {
                null
            },
                    parentNode);

            // --

            updateFileGroupInTree(
                fileGroupNode,
                fileGroup);

            // --

            return(fileGroupNode);
        }
Example #15
0
    public IOutput AddFileGroup(IOutput output)
    {
        if (output is null)
        {
            var emptyFg = _fileGroups.FirstOrDefault(f => string.IsNullOrWhiteSpace(f.Name));
            if (emptyFg is null)
            {
                emptyFg = new FileGroup();
            }

            return(emptyFg);
        }

        if (output is not IFileGroup fileGroup)
        {
            return(Output.Empty);
        }

        var exsiting = _fileGroups.FirstOrDefault(f => f.Name == fileGroup.Name);

        if (exsiting is null)
        {
            _fileGroups.Add(fileGroup);
            return(fileGroup);
        }
        else
        {
            foreach (var file in fileGroup.Files)
            {
                exsiting.AddFile(file);
            }

            return(exsiting);
        }
    }
		public void TakeFullSnapshot(
			FileGroup[] fileGroups,
			string[] languageCodes, // Source _and_ destination.
			BackgroundWorker bw)
		{
			languageCodes = make2(languageCodes);

			bw.ReportProgress(0, Resources.SnapshotController_TakeFullSnapshot_Taking_snapshots_);

			var fgIndex = 0;
			foreach (var fileGroup in fileGroups)
			{
				bw.ReportProgress(
					0,
					string.Format(
						Resources.SnapshotController_TakeFullSnapshot_Taking_snapshot__0__of__1__for_file_group___2_____,
						fgIndex + 1,
						fileGroups.Length,
						fileGroup.GetNameIntelligent(Project)));

				if (bw.CancellationPending)
				{
					throw new OperationCanceledException();
				}

				doTakeSnapshot(fileGroup, languageCodes, bw);
				fgIndex++;
			}
		}
        /// <summary>
        /// Creates the build database
        /// </summary>
        /// <param name="sqlServer">The server instance against which the build database must be deployed</param>
        /// <param name="databaseName">The name of the new database</param>
        private void CreateDatabase(Server sqlServer, string databaseName)
        {
            if (sqlServer.Databases.Contains(databaseName))
            {
                // assume the previous extract crashed without clean up -> drop the databaseName and allow clean create:
                this.database = sqlServer.Databases[databaseName];

                this.DropDatabase();
            }

            Utilities.Logger.LogInformation("Creating temporary build database {0}...", databaseName);
            this.database = new Database(sqlServer, databaseName);

            FileGroup fg = new FileGroup(this.database, "PRIMARY");
            DataFile  df = new DataFile(fg, string.Concat("DB_Build", databaseName, "_Data"), Path.Combine(sqlServer.Information.MasterDBPath, databaseName + ".mdf"));

            df.Size       = 20480;
            df.GrowthType = FileGrowthType.KB;
            df.Growth     = 20480;
            fg.Files.Add(df);
            this.database.FileGroups.Add(fg);

            LogFile lf = new LogFile(this.database, string.Concat("DB_Build", databaseName, "_Log"), Path.Combine(sqlServer.Information.MasterDBPath, databaseName + ".ldf"));

            lf.Size       = 10240;
            lf.GrowthType = FileGrowthType.KB;
            lf.Growth     = 10240;
            this.database.LogFiles.Add(lf);

            this.database.Create();
        }
Example #18
0
        public static FileGroup NewPrimaryFileGroup(ref Database newDb)
        {
            var primaryFG = new FileGroup(newDb, "PRIMARY");

            newDb.FileGroups.Add(primaryFG);
            return(primaryFG);
        }
Example #19
0
        /// <summary>
        /// Creates a database
        /// </summary>
        /// <param name="sqlServer">The server instance where the database should be created</param>
        /// <param name="targetDatabase">The name of the database to create</param>
        /// <returns>The Database if successful</returns>
        private Database CreateDatabase(Server sqlServer, string targetDatabase)
        {
            Database database;

            if (sqlServer.Databases.Contains(targetDatabase))
            {
                database = sqlServer.Databases[targetDatabase];
            }
            else
            {
                Utilities.Logger.LogInformation("Creating new database {0}...", targetDatabase);
                database = new Database(sqlServer, targetDatabase);
                database.CompatibilityLevel = CompatibilityLevel.Version90;

                FileGroup fg = new FileGroup(database, "PRIMARY");
                DataFile  df = new DataFile(fg, string.Concat(targetDatabase, "_Data"), Path.Combine(sqlServer.Information.MasterDBPath, targetDatabase + ".mdf"));
                df.Size       = 20480;
                df.GrowthType = FileGrowthType.KB;
                df.Growth     = 20480;
                fg.Files.Add(df);
                database.FileGroups.Add(fg);

                LogFile lf = new LogFile(database, string.Concat(targetDatabase, "_Log"), Path.Combine(sqlServer.Information.MasterDBPath, targetDatabase + ".ldf"));
                lf.Size       = 10240;
                lf.GrowthType = FileGrowthType.KB;
                lf.Growth     = 10240;
                database.LogFiles.Add(lf);

                database.Create();

                Utilities.Logger.LogInformation("Database {0} creation complete ...", targetDatabase);
            }

            return(database);
        }
        /// <summary>
        /// Opens the with dialog.
        /// </summary>
        public void OpenWithDialog()
        {
            using (var ofd = new OpenFileDialog())
            {
                ofd.Multiselect      = true;
                ofd.Filter           = $@"{Resources.SR_MainForm_openToolStripMenuItemClick_ResourceFiles} (*.resx;*.resw)|*.resx;*.resw";
                ofd.RestoreDirectory = true;

                var initialDir =
                    ConvertHelper.ToString(
                        PersistanceHelper.RestoreValue(
                            MainForm.UserStorageIntelligent,
                            @"filesInitialDir"));
                ofd.InitialDirectory = initialDir;

                if (ofd.ShowDialog(this) == DialogResult.OK)
                {
                    PersistanceHelper.SaveValue(
                        MainForm.UserStorageIntelligent,
                        @"filesInitialDir",
                        ZlpPathHelper.GetDirectoryPathNameFromFilePath(ofd.FileName));

                    var fileGroup =
                        FileGroup.CheckCreate(
                            MainForm.Current.ProjectFilesControl.Project ?? Project.Empty,
                            ofd.FileNames);

                    bool isNew;
                    var  editorControl =
                        checkGetAddEditorControl(fileGroup, out isNew);

                    editorControl.OpenWithDialog(fileGroup);
                }
            }
        }
Example #21
0
        private static Database CreateDb(Server server, string databaseName, string directory)
        {
            Database db = new Database(server, databaseName);

            db.DatabaseOptions.AutoClose = true;
            db.DatabaseOptions.AutoShrink = true;
            db.DatabaseOptions.UserAccess = DatabaseUserAccess.Multiple;

            FileGroup fileGroup = new FileGroup(db, "PRIMARY");
            db.FileGroups.Add(fileGroup);
            DataFile dataFile = new DataFile(fileGroup, databaseName + "_Data");
            fileGroup.Files.Add(dataFile);
            dataFile.FileName = Path.Combine(Path.GetFullPath(directory), databaseName + ".mdf");
            dataFile.Size = 5.0 * 1024.0;
            dataFile.Growth = 10.0;
            dataFile.GrowthType = FileGrowthType.Percent;

            LogFile logFile = new LogFile(db, databaseName + "_Log");
            db.LogFiles.Add(logFile);
            logFile.FileName = Path.Combine(Path.GetFullPath(directory), databaseName + ".ldf");
            logFile.Size = 2.5 * 1024.0;
            logFile.GrowthType = FileGrowthType.Percent;
            logFile.Growth = 10.0;

            db.Create(false);
            return db;
        }
Example #22
0
        private int GetRemoteFileGroup(string address, int localFileGroupId)
        {
            FileGroup        local  = DataContext.Table <FileGroup>().QueryRecordWhere("ID = {0}", localFileGroupId);
            List <FileGroup> remote = WebAPIHub.GetRecords(address, "FileGroup", "all").Select(x => (FileGroup)x).ToList();

            int id;

            if (local != null && !remote.Where(x => x.DataStartTime.Equals(local.DataStartTime) && x.DataEndTime.Equals(local.DataEndTime) && x.ProcessingStartTime.Equals(local.ProcessingStartTime) && x.ProcessingEndTime.Equals(local.ProcessingEndTime)).Any())
            {
                FileGroup record = new FileGroup()
                {
                    DataStartTime       = local.DataStartTime,
                    DataEndTime         = local.DataEndTime,
                    ProcessingStartTime = local.ProcessingStartTime,
                    ProcessingEndTime   = local.ProcessingEndTime,
                    Error    = local.Error,
                    FileHash = local.FileHash
                };
                id = WebAPIHub.CreateRecord(address, "FileGroup", JObject.FromObject(record));
            }
            else
            {
                id = remote.Where(x => x.DataStartTime.Equals(local.DataStartTime) && x.DataEndTime.Equals(local.DataEndTime) && x.ProcessingStartTime.Equals(local.ProcessingStartTime) && x.ProcessingEndTime.Equals(local.ProcessingEndTime)).First().ID;
            }

            SyncDataFiles(address, localFileGroupId, id);

            return(id);
        }
Example #23
0
        /// <summary>Implements the Exec method of the IDTCommandTarget interface. This is called when the command is invoked.</summary>
        /// <param term='commandName'>The name of the command to execute.</param>
        /// <param term='executeOption'>Describes how the command should be run.</param>
        /// <param term='varIn'>Parameters passed from the caller to the command handler.</param>
        /// <param term='varOut'>Parameters passed from the command handler to the caller.</param>
        /// <param term='handled'>Informs the caller if the command was handled or not.</param>
        /// <seealso class='Exec' />
        public void Exec(string commandName, vsCommandExecOption executeOption, ref object varIn, ref object varOut, ref bool handled)
        {
            //System.Windows.Forms.MessageBox.Show("exec");

            handled = false;
            if(executeOption == vsCommandExecOption.vsCommandExecOptionDoDefault && AcceptedCommand(commandName))
            {
                bool bForward = true;
                if(commandName == "FileSwitch2008.Connect.PrevFile")
                {
                    bForward = false;
                }

                Project fileproject = _addInInstance.DTE.ActiveDocument.ProjectItem.ContainingProject;
                string fullname =_addInInstance.DTE.ActiveDocument.FullName;

                FileGroup group = new FileGroup(fileproject, fullname.ToLower());

                string newfile = bForward ? group.Next() : group.Prev();

                _applicationObject.ItemOperations.OpenFile(newfile, Constants.vsViewKindCode);

                handled = true;
                return;
            }
        }
 private static void FillFiles(FileGroup filegroup, string connectionString)
 {
     using (SqlConnection conn = new SqlConnection(connectionString))
     {
         using (SqlCommand command = new SqlCommand(GetSQLFile(filegroup), conn))
         {
             conn.Open();
             using (SqlDataReader reader = command.ExecuteReader())
             {
                 while (reader.Read())
                 {
                     FileGroupFile item = new FileGroupFile(filegroup);
                     item.Id              = (int)reader["file_id"];
                     item.Name            = reader["name"].ToString();
                     item.Owner           = "";
                     item.Growth          = (int)reader["growth"];
                     item.IsPercentGrowth = (bool)reader["is_percent_growth"];
                     item.IsSparse        = (bool)reader["is_sparse"];
                     item.MaxSize         = (int)reader["max_size"];
                     item.PhysicalName    = reader["physical_name"].ToString();
                     item.Size            = (int)reader["size"];
                     item.Type            = (byte)reader["type"];
                     filegroup.Files.Add(item);
                 }
             }
         }
     }
 }
Example #25
0
        public IOutput Create()
        {
            var projectName = _module.Namespace + ".Common";
            var project     = (IProject) new Project(projectName)
            {
                Path = System.IO.Path.Combine("src", projectName)
            };

            var files = new FileGroup();

            project.AddFileGroup(files);

            var sb = new StringBuilder();

            sb.Al("<Project Sdk=\"Microsoft.NET.Sdk\">");
            sb.B();
            sb.I(1).Al("<PropertyGroup>");
            sb.I(2).Al("<TargetFramework>net5.0</TargetFramework>");
            sb.I(2).Al($"<RootNamespace>{project.Name}</RootNamespace>");
            sb.I(2).Al("<LangVersion>Preview</LangVersion>");
            sb.I(2).Al($"<Nullable>enable</Nullable>");
            sb.I(1).Al("</PropertyGroup>");
            sb.B();
            sb.I(1).Al("<ItemGroup>");
            sb.I(2).Al($"<PackageReference Include=\"CSharpFunctionalExtensions\" Version=\"{Settings.Packages.GetVersion("CSharpFunctionalExtensions", "2.17.0")}\" />");
            sb.I(1).Al("</ItemGroup>");
            sb.B();
            sb.Al("</Project>");

            var projectFile = new File(project.Name + ".csproj", sb.ToString());

            files.AddFile(projectFile);

            return(project);
        }
        /// <summary>
        /// 利用SMO创建数据库
        /// </summary>
        public static void CreateDatabase(string databaseName, string dbPath)
        {
            try
            {
                //创建ServerConnection的实例
                ServerConnection connection = new ServerConnection();
                //指定连接字符串
                connection.ConnectionString = @"Data Source=.\ACALSQLEXPRESS;Initial Catalog=master;User ID=sa;Password=ACal@Server123456;";
                //"Data Source=goodapp;Initial Catalog=master;User ID=sa;Password=root;";
                //实例化Server
                Server server = new Server(connection);

                #region [创建数据库对象]
                //检查在数据库是否已经存在该数据库
                var queryDatabase = from Database temp in server.Databases
                                    where string.Equals(temp.Name, databaseName, StringComparison.CurrentCultureIgnoreCase)
                                    select temp;
                Database database = queryDatabase.FirstOrDefault <Database>();
                //如果存在就删除
                if (database != null)
                {
                    database.Drop();
                }

                database = new Database(server, databaseName);
                //指定数据库数据文件细节
                FileGroup fileGroup = new FileGroup {
                    Name = "PRIMARY", Parent = database, IsDefault = false
                };
                DataFile dataFile = new DataFile
                {
                    Name     = databaseName + "_data",
                    Parent   = fileGroup,
                    FileName = dbPath + databaseName + ".mdf"
                };
                fileGroup.Files.Add(dataFile);
                //指定数据库日志文件细节
                LogFile logFile = new LogFile
                {
                    Name     = databaseName + "_log",
                    Parent   = database,
                    FileName = dbPath + databaseName + ".ldf"
                };

                database.FileGroups.Add(fileGroup);
                database.LogFiles.Add(logFile);

                database.Create();
                #endregion
            }
            catch (Exception exc)
            {
                var message = exc.Message;
                Console.WriteLine(exc.ToString());
            }
            finally
            {
                //Console.ReadKey();
            }
        }
Example #27
0
        /// <summary>
        /// Open form for saving open files as a group.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void saveOpenFilesAsGroupToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (tabControl1.TabPages.Count > 0)
            {
                var groupForm = new CreateGroupForm {
                    StartPosition = FormStartPosition.CenterParent
                };
                var result = groupForm.ShowDialog();

                if (result != DialogResult.OK)
                {
                    return;
                }

                var tabFiles = (
                    from TabPage tabPage
                    in tabControl1.TabPages
                    select new TabFile {
                    TabName = tabPage.Text, File = tabPage.ToolTipText, Name = tabPage.Name
                })
                               .ToList();

                var group = new FileGroup {
                    GroupName = groupForm.name, Tabfiles = tabFiles
                };
                _groups.FileGroups.Add(@group);

                FileGroupHandler.Save(_groups);
            }
            else
            {
                MessageBox.Show("No open files to group.");
            }
        }
Example #28
0
        public IOutput Create()
        {
            var group = new FileGroup("Aggregates");

            var sb = new StringBuilder();

            sb.Al($"namespace {_module.Namespace}.Core.Aggregates");
            sb.Al("{");
            sb.I(1).Al("public abstract class Aggregate: Aggregate<Guid>, IAggregate");
            sb.I(1).Al("{ }");
            sb.B();
            sb.I(1).Al("public abstract class Aggregate<T>: IAggregate<T> where T : notnull");
            sb.I(1).Al("{");
            sb.B();
            sb.I(2).Al("public T Id { get; protected set; } = default!;");
            sb.B();
            sb.I(2).Al("public int Version { get; protected set; }");
            sb.B();
            sb.I(2).Al("[NonSerialized] private readonly Queue<IEvent> uncommittedEvents = new Queue<IEvent>();");
            sb.B();
            sb.I(2).Al("public virtual void When(object @event) { }");
            sb.B();
            sb.I(2).Al("public IEvent[] DequeueUncommittedEvents()");
            sb.I(2).Al("{");
            sb.I(3).Al("var dequeuedEvents = uncommittedEvents.ToArray();");
            sb.B();
            sb.I(3).Al("uncommittedEvents.Clear();");
            sb.B();
            sb.I(3).Al("return dequeuedEvents;");
            sb.I(2).Al("}");
            sb.B();
            sb.I(2).Al("protected void Enqueue(IEvent @event)");
            sb.I(2).Al("{");
            sb.I(3).Al("uncommittedEvents.Enqueue(@event);");
            sb.I(2).Al("}");
            sb.I(1).Al("}");
            sb.Al("}");

            group.AddFile(new File("Aggregate.cs", sb.ToString(), canOverwrite: true));
            sb.Clear();

            sb.Al($"namespace {_module.Namespace}.Core.Aggregates");
            sb.Al("{");
            sb.I(1).Al("public interface IAggregate: IAggregate<Guid>");
            sb.B();
            sb.I(1).Al("{ }");
            sb.B();
            sb.I(1).Al("public interface IAggregate<out T>: IProjection");
            sb.I(1).Al("{");
            sb.I(2).Al("T Id { get; }");
            sb.I(2).Al("int Version { get; }");
            sb.B();
            sb.I(2).Al("IEvent[] DequeueUncommittedEvents();");
            sb.I(1).Al("}");
            sb.Al("}");

            group.AddFile(new File("IAggregate.cs", sb.ToString(), canOverwrite: true));

            return(group);
        }
Example #29
0
        public static Event GetEvent(this TableOperations <Event> eventTable, FileGroup fileGroup, DataGroup dataGroup)
        {
            int      fileGroupID = fileGroup.ID;
            int      lineID      = dataGroup.Line.ID;
            DateTime startTime   = dataGroup.StartTime;
            DateTime endTime     = dataGroup.EndTime;
            int      samples     = dataGroup.Samples;

            IDbDataParameter startTimeParameter = new SqlParameter()
            {
                ParameterName = nameof(dataGroup.StartTime),
                DbType        = DbType.DateTime2,
                Value         = startTime
            };

            IDbDataParameter endTimeParameter = new SqlParameter()
            {
                ParameterName = nameof(dataGroup.EndTime),
                DbType        = DbType.DateTime2,
                Value         = endTime
            };

            RecordRestriction recordRestriction =
                new RecordRestriction("FileGroupID = {0}", fileGroupID) &
                new RecordRestriction("LineID = {0}", lineID) &
                new RecordRestriction("StartTime = {0}", startTimeParameter) &
                new RecordRestriction("EndTime = {0}", endTimeParameter) &
                new RecordRestriction("Samples = {0}", samples);

            return(eventTable.QueryRecord(recordRestriction));
        }
        private static string generateWorksheetName(
            PreparedInformation preparedInformation,
            FileGroup fileGroup,
            Project project)
        {
            // http://social.msdn.microsoft.com/Forums/en-US/vsto/thread/84c0c4d2-52b9-4502-bece-fdc616db05f8

            const int maxLength = 31;

            var ni =
                (preparedInformation.UseCrypticExcelExportSheetNames
                    ? fileGroup.UniqueID.ToString()
                    : fileGroup.GetNameIntelligent(project))
                .Replace('\\', '#')
                .Replace('/', '#')
                .Replace('?', '_')
                .Replace('*', '_')
                .Replace('[', '_')
                .Replace(']', '_')
                .Replace(':', '_');
            //var cs = fileGroup.Checksum.ToString();

            //var s1 = string.Format( @" ({0})", cs );
            //var len = maxLength - s1.Length;

            var ni2 = FileGroup.ShortenFilePath(ni, maxLength);

            return(ni2);
        }
Example #31
0
        private static string GetFilesInFileGroup2008(FileGroup filegroup)
        {
            StringBuilder sql = new StringBuilder();

            sql.Append("select file_id,type,name,physical_name,size,max_size,growth,is_sparse,is_percent_growth ");
            sql.Append("from sys.database_files WHERE data_space_id = " + filegroup.Id.ToString());
            return(sql.ToString());
        }
Example #32
0
        private static List <XElement> GetPathElements(FileGroup fileGroup)
        {
            List <XElement> pathElements = fileGroup.DataFiles
                                           .Select(dataFile => new XElement("path", dataFile.FilePath))
                                           .ToList();

            return(pathElements);
        }
Example #33
0
        private static string GetFilesInFileGroup2000(FileGroup filegroup)
        {
            StringBuilder sql = new StringBuilder();

            sql.Append("select convert(int,fileid) as file_id,type=convert(tinyint,(status&64)/64),name,filename as physical_name,size,maxsize as max_size,growth,convert(bit,0) as is_sparse,is_percent_growth =convert(bit,status & 1048576) ");
            sql.Append("FROM  sysfiles where groupid=" + filegroup.Id.ToString());
            return(sql.ToString());
        }
		/// <summary>
		/// Gets the base name.
		/// </summary>
		/// <remarks>
		/// E.g. for:
		///  - Main.master.resx
		///  - Main.master.de.resx
		///  - Main.master.en-us.resx
		/// it would be "Main.master"
		/// 
		/// E.g. for:
		///  - Properties.resx
		///  - Properties.de.resx
		/// it would be "Properties".
		/// </remarks>
		/// <value>The base name.</value>
		public string GetBaseName(
			FileGroup fileGroup)
		{
			string baseName;
			string extension;
			string optionalDefaultType;

			doGetBaseName(
				fileGroup,
				out baseName,
				out extension,
				out optionalDefaultType);
			return baseName;
		}
        public void CreateSnapshot(DbConnectionInfo connectionInfo, string databaseName, string snapshotDatabaseName = null)
        {
            if (connectionInfo == null)
                throw new ArgumentNullException("connectionInfo must be initialized to create a snapshot.");
            if (string.IsNullOrWhiteSpace(databaseName))
                throw new ArgumentNullException("databaseName is required to create a snapshot.");

            // 1. Initiate db connection
            Server server = connectionInfo.GetServer();

            // 2. Check if DB Exists
            Database db = server.Databases[databaseName];
            if (db == null)
                throw new ArgumentOutOfRangeException(string.Format("The database {0} does not exists.", databaseName));

            var snapshot = db.IsDatabaseSnapshot;
            var hasSnapshots = db.IsDatabaseSnapshotBase;

            string dbSnapshotName = string.IsNullOrWhiteSpace(snapshotDatabaseName) ? databaseName + "_" + DateTime.UtcNow.ToString("yyMMdd") : snapshotDatabaseName;

            Database snapshotDatabase = new Database(server, dbSnapshotName);
            snapshotDatabase.DatabaseSnapshotBaseName = db.Name;
            foreach (FileGroup fileGroup in db.FileGroups)
            {
                FileGroup fg = new FileGroup(snapshotDatabase, fileGroup.Name);
                snapshotDatabase.FileGroups.Add(fg);
            }

            foreach (FileGroup fileGroup in db.FileGroups)
            {
                foreach (DataFile dataFile in fileGroup.Files)
                {
                    var df = new DataFile(snapshotDatabase.FileGroups[fileGroup.Name],
                                            dataFile.Name,
                                            Path.Combine(db.PrimaryFilePath, string.Format("{0}_{1}.ss", dataFile.Name, snapshotDatabaseName)));
                    snapshotDatabase.FileGroups[fileGroup.Name].Files.Add(df);
                }
            }
            // 3.

            snapshotDatabase.Create();
        }
        private bool isMatchingFileGroup(FileGroup group)
        {
            foreach (var allowedGroup in _groups)
            {
                if (allowedGroup.GetChecksum(_project) == group.GetChecksum(_project))
                {
                    return true;
                }
            }

            return false;
        }
		private void buttonOK_Click(object sender, EventArgs e)
		{
			_result = null;

			using (new WaitCursor(this, WaitCursorOption.ShortSleep))
			{
				var cultures = getCultures();

				var baseFolderPath = baseFolderTextEdit.Text.Trim();
				var baseFileName = baseFileNameTextEdit.Text.Trim();

				var extension = @"." + extensionComboBoxEdit.Text.Trim('.');

				var created = 0;

				using (new BackgroundWorkerLongProgressGui(
					delegate(object snd, DoWorkEventArgs args)
					{
						try
						{
							var bw = (BackgroundWorker)snd;

							// --
							// First pass, add all in-memory to check for same file group.

							var fg = new FileGroup(_project);

							if (cultures != null)
							{
								foreach (var culture in cultures)
								{
									var fileName =
										_project.IsNeutralLanguage(culture)
											? baseFileName + extension
											: generateFileName(fg, culture);

									fg.Add(new FileInformation(fg)
											{
												File = new ZlpFileInfo(fileName)
											});
								}

								// Look for same entries.
								if (_project.FileGroups.HasFileGroupWithChecksum(
									fg.GetChecksum(_project)))
								{
									throw new MessageBoxException(
										this,
										Resources.SR_ProjectFilesUserControl_AddResourceFilesWithDialog_ExistsInTheProject,
										MessageBoxIcon.Information);
								}
								else
								{
									// --
									// Second pass, add all existing.

									fg = new FileGroup(_project);

									foreach (var culture in cultures)
									{
										if (bw.CancellationPending)
										{
											throw new OperationCanceledException();
										}

										var fileName =
											_project.IsNeutralLanguage(culture)
												? baseFileName + extension
												: generateFileName(fg, culture);

										FileInformation ffi;

										if (_project.IsNeutralLanguage(culture))
										{
											ffi = new FileInformation(fg)
													{
														File = new ZlpFileInfo(ZlpPathHelper.Combine(baseFolderPath, fileName))
													};
											fg.Add(ffi);
										}
										else
										{
											ffi =
												fg.CreateAndAddNewFile(
													baseFolderPath,
													fileName,
													culture.Name);
										}

										// Must create real file.
										ZlpIOHelper.WriteAllText(ffi.File.FullName, Resources.SR_EmptyResourceFile);

										created++;
									}
								}
							}

							if (_projectFolder != null)
							{
								fg.ProjectFolder = _projectFolder;
							}

							_project.FileGroups.Add(fg);
							_project.MarkAsModified();

							_result = fg;

						}
						catch (OperationCanceledException)
						{
							// Ignore.
						}
					},
					Resources.SR_CreateNewFilesForm_Creating,
					BackgroundWorkerLongProgressGui.CancellationMode.Cancelable,
					this))
				{
				}

				// --

				XtraMessageBox.Show(
					this,
					string.Format(
						Resources.SR_CreateNewFilesForm_Finished03,
						created),
					@"Zeta Resource Editor",
					MessageBoxButtons.OK,
					MessageBoxIcon.Information);
			}
		}
		internal bool OpenWithDialog(
			FileGroup fileGroup)
		{
			var r = DoSaveFiles(
				SaveOptions.OnlyIfModified |
					SaveOptions.AskConfirm);

			if (r == DialogResult.OK)
			{
				DoLoadFiles(fileGroup, fileGroup.Project);

				// Immediately stores.
				MainForm.AddMruFiles(fileGroup.JoinedFilePaths);

				GridEditableData = fileGroup;
				return true;
			}
			else
			{
				return false;
			}
		}
Example #39
0
		public void FileGroupWriter(string name, int count,int size, bool withidx, bool isdefault,string test){
			var fg = new FileGroup{Name = name, FileCount = count, FileSize = size, WithIndex = withidx, IsDefault = isdefault};
			var writer = new FileGroupWriter(fg){NoComment = true, NoDelimiter = true,Mode = ScriptMode.Create,Dialect = DbDialect.SqlServer};
			Assert.AreEqual(test,writer.ToString().Trim());
		}
Example #40
0
        private void CreateDatabase(string dbFilename, string dbName, string remoteDbFilename)
        {
            Log.Inform("Database not found - creating...");
            var accFile = dbFilename;
            if (remoteDbFilename.IsNotNullOrEmpty())
                accFile = remoteDbFilename;
            var dir = Path.GetDirectoryName(accFile);
            if (dir.IsNotNullOrEmpty())
            {
                if (!Directory.Exists(dir))
                {
                    Log.Inform("Creating database directory: " + dir);
                    Directory.CreateDirectory(dir);
                }
            }
            Database = new Database(server, dbName);
            var fileGroup = new FileGroup(Database, "PRIMARY");
            var dataFile = new DataFile(fileGroup, dbFilename, dbFilename);
            dataFile.Growth = 1024;
            dataFile.GrowthType = FileGrowthType.KB;
            fileGroup.Files.Add(dataFile);

            Database.FileGroups.Add(fileGroup);
            Database.DatabaseOptions.AutoShrink = true;
            server.Databases.Add(new Database(server, dbName));
            Database.Create();
            //server.AttachDatabase(sb.AttachDBFilename, new StringCollection { sb.AttachDBFilename });
        }
		public void Initialize(
			FileGroup fileGroup)
		{
			_fileGroup = fileGroup;
		}
		internal void Initialize(
			FileGroup fileGroup )
		{
			_fileGroup = fileGroup;
		}
		// ADDED: adds resources from file Info lists.
		// I have changed a method doAutomaticallyAddResourceFiles to fill file groups. 
		// You can use same method if you call this method from there. 
		// ATTENTION: LanguageCodeDetection was modified a bit to support variable amount 
		// of point in base name. New method GetBaseName(IInheritedSettings settings, string fileName) 
		// was added to get same base name FileGroup gets.
		public void DoAutomaticallyAddResourceFilesFromList(
			BackgroundWorker backgroundWorker,
			ProjectFolder parentProjectFolder,
			ref int fileGroupCount,
			ref int fileCount,
			ICollection<ZlpFileInfo> fileList)
		{
			if (backgroundWorker.CancellationPending)
			{
				throw new OperationCanceledException();
			}
			else if (fileList != null && fileList.Count > 0)
			{
				var fileGroups = Project.FileGroups;
				//if (parentProjectFolder != null)
				//{
				//    fileGroups = parentProjectFolder.ChildFileGroups;
				//}
				foreach (var filePath in fileList)
				{
					if (backgroundWorker.CancellationPending)
					{
						throw new OperationCanceledException();
					}
					//other algorithm to determine base name to allow multiple points inside name
					var baseFileName = LanguageCodeDetection.GetBaseName(Project, filePath.Name);

					var wantAddResourceFile =
						checkWantAddResourceFile(filePath);

					if (wantAddResourceFile)
					{
						//find right file group

						var path = filePath;
						var fileGroup = fileGroups.Find(
							g =>
							string.Compare(g.BaseName, baseFileName, true) == 0 &&
							string.Compare(g.FolderPath.FullName, path.Directory.FullName, true) == 0);

						if (fileGroup == null)
						{
							fileGroup =
								new FileGroup(Project)
								{
									ProjectFolder = parentProjectFolder
								};

							// Look for same entries.
							if (!Project.FileGroups.HasFileGroupWithChecksum(
								fileGroup.GetChecksum(Project)))
							{
								fileGroups.Add(fileGroup);

								fileGroupCount++;
							}
						}

						fileGroup.Add(
							new FileInformation(fileGroup)
							{
								File = filePath
							});

						fileCount++;
					}
				}
			}
		}
        public static void CopyDatabase(MyArgs parms)
        {
            //remove trailing slash on the path if provided by user
            if (parms.PathToLocalMdf.EndsWith("\\"))
                parms.PathToLocalMdf = parms.PathToLocalMdf.Substring(0, parms.PathToLocalMdf.Length - 1);

            //Set Source SQL Server (SQL Azure)
            Server sourceServer = new Server(new ServerConnection(parms.SourceServer, parms.SourceUser, parms.SourcePassword));
            Database sourceDatabase = sourceServer.Databases[parms.SourceDatabase];

            //Set Destination SQL Server (SQL IaaS)
            Server destServer = new Server(new ServerConnection(parms.DestinationServer, parms.DestinationUser, parms.DestinationPassword));
            Database destDatabase = null;

            //Drop the detination database if it exits
            if (destServer.Databases.Contains(parms.DestinationDatabase))
            {
                Console.Write($"Destintation DB {parms.DestinationDatabase} on {destServer.Name} Exists. Dropping.");
                destServer.KillDatabase(parms.DestinationDatabase);
                Console.WriteLine(" . . . Done!");
            }

            //create the temp database on SQL IaaS
            Console.Write($"Creating Destintation DB {parms.DestinationDatabase} on {destServer.Name}.");
            destDatabase = new Database(destServer, parms.DestinationDatabase);

            var fg = new FileGroup(destDatabase, "PRIMARY");
            destDatabase.FileGroups.Add(fg);

            var df = new DataFile(fg, $"{parms.DestinationDatabase}_data");
            fg.Files.Add(df);
            df.FileName = $"{parms.PathToLocalMdf}\\{parms.DestinationDatabase}.mdf";
            df.IsPrimaryFile = true;
            df.Growth = 10;
            df.GrowthType = FileGrowthType.Percent;

            destDatabase.Create();
            Console.WriteLine(" . . . Done!");

            //Transfer the schema and data from SQL Azure to SQL IaaS
            Console.WriteLine("Starting Transfer...");
            Transfer transfer = new Transfer(sourceDatabase);
            transfer.DataTransferEvent += (object sender, DataTransferEventArgs e) =>
            {
                Console.WriteLine($"{e.DataTransferEventType}: {e.Message}");
            };

            transfer.CopyAllObjects = true;
            transfer.Options.WithDependencies = true;
            transfer.Options.Triggers = true;
            transfer.Options.Indexes = true;
            transfer.Options.ClusteredIndexes = true;
            transfer.Options.Default = true;
            transfer.Options.DriAll = true;
            transfer.CopyData = true;

            transfer.DestinationServer = parms.DestinationServer;
            transfer.DestinationDatabase = parms.DestinationDatabase;

            transfer.TransferData();

            Console.WriteLine("Transfer Complete!");

            //Create a backup credential in the SQL IaaS instance to perform the backup to Azure Blob
            Console.Write("Creating Backup Credential...");
            if (destServer.Credentials.Contains("BackupCred"))
            {
                Console.Write(" Dropping ");
                destServer.Credentials["BackupCred"].Drop();
            }

            Credential credential = new Credential(destServer, "BackupCred");
            credential.Create(parms.StorageAccountName, parms.StorageKey);
            Console.WriteLine(" Complete!");

            string storageEndpoint = $"https://{parms.StorageAccountName}.{parms.StorageEndpointBase}/{parms.StorageContainer}/{parms.StorageFileBase}-{DateTime.UtcNow:yyyy-MM-dd-HH-mm}.bak";

            //Perform the backup from SQL IaaS to Azure Blob
            //https://msdn.microsoft.com/en-us/library/dn435916.aspx
            Console.WriteLine("Starting Backup...");
            Backup backup = new Backup();
            backup.Action = BackupActionType.Database;
            backup.Database = parms.DestinationDatabase;
            backup.Devices.Add(new BackupDeviceItem(storageEndpoint, DeviceType.Url, "BackupCred"));
            backup.CredentialName = "BackupCred";
            backup.Incremental = false;
            backup.SqlBackup(destServer);
            Console.WriteLine("Backup Complete!");
        }
		private static string generateFileName(
			FileGroup fileGroup,
			CultureInfo culture)
		{
			var pattern =
				new LanguageCodeDetection(fileGroup.Project).IsNeutralCulture(
					fileGroup.ParentSettings,
					culture)
					? fileGroup.Project.NeutralLanguageFileNamePattern
					: fileGroup.Project.NonNeutralLanguageFileNamePattern;

			pattern = pattern.Replace(@"[basename]", fileGroup.BaseName);
			pattern = pattern.Replace(@"[languagecode]", culture.Name);
			pattern = pattern.Replace(@"[extension]", fileGroup.BaseExtension);
			pattern = pattern.Replace(@"[optionaldefaulttypes]", fileGroup.BaseOptionalDefaultType);

			return pattern;
		}
		private TreeListNode addFileGroupToTree(
			TreeListNode parentNode,
			FileGroup fileGroup)
		{
			var fileGroupNode =
				treeView.AppendNode(
					new object[]
						{
							null
						},
					parentNode);

			// --

			updateFileGroupInTree(
				fileGroupNode,
				fileGroup);

			// --

			addFileGroupFilesToTree(fileGroupNode);

			// --

			return fileGroupNode;
		}
Example #47
0
        /// <summary>
        /// Create a new database based on user input.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void CreateButton_Click(object sender, System.EventArgs e)
        {
            // Create the database
            Cursor csr = null;
            String sDatabaseName;
            Database db;
            FileGroup fg;
            DataFile df;
            LogFile lf;
            ListViewItem DatabaseListViewItem;

            try
            {
                csr = this.Cursor;   // Save the old cursor
                this.Cursor = Cursors.WaitCursor;   // Display the waiting cursor

                // Get the name of the new database
                sDatabaseName = NewDatabaseTextBox.Text;

                // Check for new non-zero length name
                if (sDatabaseName.Length == 0)
                {
                    ExceptionMessageBox emb = new ExceptionMessageBox();
                    emb.Text = Properties.Resources.NoDatabaseName;
                    emb.Show(this);

                    return;
                }

                // Ensure we have the current list of databases to check.
                SqlServerSelection.Databases.Refresh();

                // Refresh database list
                ShowDatabases(false);

                // Is database name new and unique?
                if (SqlServerSelection.Databases.Contains(sDatabaseName))
                {
                    ExceptionMessageBox emb = new ExceptionMessageBox();
                    emb.Text = Properties.Resources.DuplicateDatabaseName;
                    emb.Show(this);

                    return;
                }

                // Instantiate a new database object
                db = new Database(SqlServerSelection, sDatabaseName);

                // This may also be accomplished like so:
                // db = new Database();
                // db.Parent = SqlServerSelection;
                // db.Name = sDatabaseName;

                // Create a new file group named PRIMARY
                fg = new FileGroup(db, @"PRIMARY");

                // Create a new data file and add it to the file group's Files collection
                // Give the data file a physical filename using the master database path of the server
                df = new DataFile(fg, sDatabaseName + @"_Data0",
                    SqlServerSelection.Information.MasterDBPath + @"\"
                    + sDatabaseName + @"_Data0" + @".mdf");

                // Set the growth type to KB
                df.GrowthType = FileGrowthType.KB;

                // Set the growth size in KB
                df.Growth = 1024;

                // Set initial size in KB (optional)
                df.Size = 10240;

                // Set the maximum size in KB
                df.MaxSize = 20480;

                // Add file to file group
                fg.Files.Add(df);

                // Create a new data file and add it to the file group's Files collection
                // Give the data file a physical filename using the master database path of the server
                df = new DataFile(fg, sDatabaseName + @"_Data1",
                    SqlServerSelection.Information.MasterDBPath + @"\"
                    + sDatabaseName + @"_Data1" + @".ndf");

                // Set the growth type to KB
                df.GrowthType = FileGrowthType.KB;

                // Set the growth size in KB
                df.Growth = 1024;

                // Set initial size in KB (optional)
                df.Size = 2048;

                // Set the maximum size in KB
                df.MaxSize = 8192;

                // Add file to file group
                fg.Files.Add(df);

                // Add the new file group to the database's FileGroups collection
                db.FileGroups.Add(fg);

                // Create a new file group named SECONDARY
                fg = new FileGroup(db, @"SECONDARY");

                // Create a new data file and add it to the file group's Files collection
                // Give the data file a physical filename using the master database path of the server
                df = new DataFile(fg, sDatabaseName + @"_Data2",
                    SqlServerSelection.Information.MasterDBPath + @"\"
                    + sDatabaseName + @"_Data2" + @".ndf");

                // Set the growth type to KB
                df.GrowthType = FileGrowthType.KB;

                // Set the growth size in KB
                df.Growth = 512;

                // Set initial size in KB (optional)
                df.Size = 1024;

                // Set the maximum size in KB
                df.MaxSize = 4096;

                // Add file to file group
                fg.Files.Add(df);

                // Create a new data file and add it to the file group's Files collection
                // Give the data file a physical filename using the master database path
                df = new DataFile(fg, sDatabaseName + @"_Data3",
                    SqlServerSelection.Information.MasterDBPath + @"\"
                    + sDatabaseName + @"_Data3" + @".ndf");

                // Set the growth type to KB
                df.GrowthType = FileGrowthType.KB;

                // Set the growth size in KB
                df.Growth = 512; // In KB

                // Set initial size in KB (optional)
                df.Size = 1024; // Set initial size in KB (optional)

                // Set the maximum size in KB
                df.MaxSize = 4096;

                // Add file to file group
                fg.Files.Add(df);

                // Add the new file group to the database's FileGroups collection
                db.FileGroups.Add(fg);

                // Define the database transaction log.
                lf = new LogFile(db, sDatabaseName + @"_Log",
                    SqlServerSelection.Information.MasterDBPath + @"\" + sDatabaseName +
                    @"_Log" + @".ldf");

                // Set the growth type to KB
                lf.GrowthType = FileGrowthType.KB;

                // Set the growth size in KB
                lf.Growth = 1024; // In KB

                // Set initial size in KB (optional)
                lf.Size = 2048;  // Set initial size in KB (optional)

                // Set the maximum size in KB
                lf.MaxSize = 8192;  // In KB

                // Add file to file group
                db.LogFiles.Add(lf);

                // Create the database as defined.
                db.Create();

                // Refresh database list
                ShowDatabases(false);

                // Find and select the database just created
                DatabaseListViewItem =
                    DatabasesListView.FindItemWithText(sDatabaseName);
                DatabaseListViewItem.Selected = true;
                DatabaseListViewItem.EnsureVisible();
            }
            catch (SmoException ex)
            {
                ExceptionMessageBox emb = new ExceptionMessageBox(ex);
                emb.Show(this);
            }
            finally
            {
                // Clean up.
                db = null;
                fg = null;
                df = null;
                lf = null;

                UpdateControls();

                this.Cursor = csr;  // Restore the original cursor
            }
        }
Example #48
0
		/// <summary>
		/// </summary>
		/// <param name="schema"></param>
		public FileGroupWriter(FileGroup schema){
			FileGroup = schema;
			Parameters = FileGroup;
		}
		/// <summary>
		/// Updates the file group in tree.
		/// </summary>
		/// <param name="fileGroupNode">The file group node.</param>
		/// <param name="fileGroup">The file group.</param>
		private void updateFileGroupInTree(
			TreeListNode fileGroupNode,
			FileGroup fileGroup)
		{
			fileGroupNode[0] = fileGroup.GetNameIntelligent(Project);
			fileGroupNode.ImageIndex = fileGroupNode.SelectImageIndex = getImageIndex(@"group");
			fileGroupNode.Tag = fileGroup;
			fileGroupNode.StateImageIndex = (int)FileGroupStateColor.Grey; //(int)fileGroup.TranslationStateColor;

			updateNodeStateImage(fileGroupNode, AsynchronousMode.Asynchronous);

			UpdateUI();
		}
		public void AddExistingResourceFilesWithDialog()
		{
			using (var ofd = new OpenFileDialog())
			{
				ofd.Multiselect = true;
				ofd.Filter = string.Format(@"{0} (*.resx;*.resw)|*.resx;*.resw",
					Resources.SR_MainForm_openToolStripMenuItemClick_ResourceFiles);
				ofd.RestoreDirectory = true;

				var initialDir =
					ConvertHelper.ToString(
						PersistanceHelper.RestoreValue(
							MainForm.UserStorageIntelligent,
							@"filesInitialDir"));
				ofd.InitialDirectory = initialDir;

				if (ofd.ShowDialog(this) == DialogResult.OK)
				{
					PersistanceHelper.SaveValue(
						MainForm.UserStorageIntelligent,
						@"filesInitialDir",
						ZlpPathHelper.GetDirectoryPathNameFromFilePath(ofd.FileName));

					// --

					var fileGroup = new FileGroup(Project);

					foreach (var filePath in ofd.FileNames)
					{
						fileGroup.Add(new FileInformation(fileGroup)
						{
							File = new ZlpFileInfo(filePath)
						});
					}

					// Look for same entries.
					if (Project.FileGroups.HasFileGroupWithChecksum(
						fileGroup.GetChecksum(Project)))
					{
						throw new MessageBoxException(
							this,
							Resources.SR_ProjectFilesUserControl_AddResourceFilesWithDialog_ExistsInTheProject,
							MessageBoxIcon.Information);
					}
					else
					{
						var parentProjectFolder =
							treeView.SelectedNode.Tag as ProjectFolder;

						if (parentProjectFolder != null)
						{
							fileGroup.ProjectFolder = parentProjectFolder;
						}

						Project.FileGroups.Add(fileGroup);
						Project.MarkAsModified();

						var node = addFileGroupToTree(treeView.SelectedNode, fileGroup);

						// --

						sortTree();

						treeView.SelectedNode = node;

						// Immediately open for editing.
						editResourceFiles();

						UpdateUI();
					}
				}
			}
		}
        private void Create()
        {
            this.LogTaskMessage(string.Format(CultureInfo.CurrentCulture, "Creating Database: {0}", this.DatabaseItem.ItemSpec));
            if (this.CheckDatabaseExists())
            {
                if (this.Force)
                {
                    this.Delete();
                }
                else
                {
                    this.Log.LogError(string.Format(CultureInfo.CurrentCulture, "Database already exists: {0}. Set Force to true to delete an existing Database.", this.DatabaseItem.ItemSpec));
                    return;
                }
            }

            SMO.Database newDatabase = new SMO.Database(this.sqlServer, this.DatabaseItem.ItemSpec);
            if (this.DataFilePath != null)
            {
                FileGroup fileGroup = new FileGroup(newDatabase, this.FileGroupName);
                DataFile dataFile = new DataFile(fileGroup, this.DatabaseItem.ItemSpec, this.DataFilePath.GetMetadata("FullPath"));
                fileGroup.Files.Add(dataFile);
                newDatabase.FileGroups.Add(fileGroup);
            }

            if (this.LogFilePath != null)
            {
                if (string.IsNullOrEmpty(this.LogName))
                {
                    this.LogName = this.DatabaseItem.ItemSpec + "_log";
                }

                LogFile logFile = new LogFile(newDatabase, this.LogName, this.LogFilePath.GetMetadata("FullPath"));
                newDatabase.LogFiles.Add(logFile);
            }
            
            if (!string.IsNullOrEmpty(this.Collation))
            {
                newDatabase.Collation = this.Collation;
            }

            newDatabase.Create();
        }
Example #52
0
        static void Main(string[] args)
        {
            //Parse command line parameters
            Dictionary<string, string> param = new Dictionary<string, string>();
            foreach (var v in args)
            {
                int p = v.IndexOf("=");
                if (p > 0)
                {
                    param.Add(v.Substring(0, p), v.Substring(p + 1, v.Length - p - 1));
                }
            }

            if (param.Count == 0)
            {
                //just show help
                ShowUsage();
                WriteLine("Press any key to close");
                Console.ReadKey();
                Environment.Exit(0);
            }

            string server;
            string database;
            string newDatabase = null;
            string user = null;
            string password = null;
            string databaseFileName = "";
            if (!param.TryGetValue("server", out server)) server = ".";
            if (!param.TryGetValue("db", out database)) WarnAndExit("\"db\" command line parameter was not specified");
            if (!param.TryGetValue("newdb", out newDatabase)) newDatabase = null;
            if (!param.TryGetValue("user", out user)) user = null;
            if (!param.TryGetValue("password", out password)) password = null;
            if (!param.TryGetValue("filename", out databaseFileName)) databaseFileName = null;
            if (string.IsNullOrEmpty(newDatabase)) newDatabase = database + "_Unicode";

            //Connect to the specified server
            ServerConnection connection = new ServerConnection(server);
            Database db = null;
            Server svr = null;
            if (string.IsNullOrEmpty(user))
            {
                connection.LoginSecure = true; //Windows authentication
            }
            else
            {
                connection.LoginSecure = false;
                connection.Login = user;
                connection.Password = password;
            }
            try
            {
                svr = new Server(connection);
                db = svr.Databases[database];
            }
            catch (Exception e)
            {
                WarnAndExit(string.Format("Could not connect to server \"{0}\": {1}", server, e.Message));
            }
            if (db == null) WarnAndExit(string.Format("Database \"{0}\" does not exist on the server \"{1}\"", database, server));

            //create new database

            Database newDB = svr.Databases[newDatabase];
            if (newDB != null)
            {
                try
                {
                    Notify(string.Format("Dropping the existing \"{0}\" database", newDatabase));
                    svr.KillAllProcesses(newDatabase);
                    svr.KillDatabase(newDatabase);
                }
                catch (Exception e)
                {
                    ReportException(e);
                }
                newDB = svr.Databases[newDatabase];
            }
            if (newDB != null)
            {
                WriteLine(string.Format("Target database \"{0}\" already exists. All existing data will be deleted", newDatabase), OutputKind.Warning);
                //store views/tables/triggers in a list
                List<View> oldViews = new List<View>();
                foreach (View v in newDB.Views) if (!v.IsSystemObject) oldViews.Add(v);
                List<Table> oldTables = new List<Table>();
                foreach (Table t in newDB.Tables) if (!t.IsSystemObject) oldTables.Add(t);
                List<Trigger> oldTriggers = new List<Trigger>();
                foreach (Trigger t in newDB.Triggers) if (!t.IsSystemObject) oldTriggers.Add(t);
                //delete 'em
                foreach (Trigger t in oldTriggers) t.Drop();
                foreach (View v in oldViews) v.Drop();
                foreach (Table t in oldTables) t.Drop();
            }
            else
            {
                WriteLine(string.Format("Creating new database \"{0}\" ", newDatabase), OutputKind.Info);
                newDB = new Database(svr, newDatabase);
                newDB.Collation = db.Collation;
                newDB.DefaultSchema = db.DefaultSchema; //should it be "sysdba"?
                FileGroup dbFG = new FileGroup(newDB, "PRIMARY");
                newDB.FileGroups.Add(dbFG);

                //Now add primary db file to file group
                if (string.IsNullOrEmpty(databaseFileName))
                {
                    string oldDatabaseFilename = db.FileGroups[0].Files[0].FileName;
                    string directory = Path.GetDirectoryName(oldDatabaseFilename);
                    databaseFileName = directory + @"\" + newDatabase + ".mdf";
                }

                DataFile df1 = new DataFile(dbFG, "SalesLogix_Data");
                dbFG.Files.Add(df1);
                df1.FileName = databaseFileName;
                df1.Size = 10.0*1024.0;
                df1.GrowthType = FileGrowthType.Percent;
                df1.Growth = 25.0;
                try
                {
                    newDB.Create();
                }
                catch (Exception e)
                {
                    WriteLine(string.Format("Could not create database \"{0}\"", newDatabase), OutputKind.Error);
                    ReportException(e);
                    WarnAndExit("");
                }
            }

            //copy the users
            foreach (User oldUser in db.Users)
            {
                User newUser = newDB.Users[oldUser.Name];
                if (newUser == null)
                {
                    Notify("Processing user  " + oldUser.Name);
                    try
                    {
                        newUser = new User(newDB, oldUser.Name);
                        newUser.DefaultSchema = oldUser.DefaultSchema;
                        newUser.UserType = oldUser.UserType;
                        newUser.Login = oldUser.Login;
                        newDB.Users.Add(newUser);
                        newUser.Create();

                        StringCollection roles = oldUser.EnumRoles();
                        foreach (string role in roles) newUser.AddToRole(role);
                        newUser.Alter();
                    }
                    catch (Exception e)
                    {
                        ReportException(e);
                    }
                }
            }

            //copy schemas
            foreach (Schema oldSchema in db.Schemas)
            {
                Schema newSchema = newDB.Schemas[oldSchema.Name];
                if (newSchema == null)
                {
                    Notify("Processing schema  " + oldSchema.Name);
                    try
                    {
                        newSchema = new Schema(newDB, oldSchema.Name);
                        newSchema.Owner = oldSchema.Owner;
                        newDB.Schemas.Add(newSchema);
                        newSchema.Create();
                    }
                    catch (Exception e)
                    {
                        ReportException(e);
                    }
                }
            }

            //copy datatype
            foreach (UserDefinedDataType oldType in db.UserDefinedDataTypes)
            {
                UserDefinedDataType newType = newDB.UserDefinedDataTypes[string.Format("[{0}].[{1}]", oldType.Owner, oldType.Name)];
                if (newType == null) newType = newDB.UserDefinedDataTypes[oldType.Name];
                if (newType == null)
                {
                    Notify("Processing user data type  " + oldType.Name);
                    try
                    {
                        newType = new UserDefinedDataType(newDB, oldType.Name, oldType.Schema);
                        newType.Owner = oldType.Owner;
                        //adjust the type correctly
                        string systemType = oldType.SystemType;
                        switch (systemType.ToUpper())
                        {
                            case "VARCHAR":
                                {
                                    systemType = "NVARCHAR";
                                    break;
                                }
                            case "CHAR":
                                {
                                    systemType = "NCHAR";
                                    break;
                                }
                            case "TEXT":
                                {
                                    systemType = "NTEXT";
                                    break;
                                }
                        }
                        newType.SystemType = systemType;
                        newType.Length = oldType.Length;
                        newType.Nullable = oldType.Nullable;
                        newType.Default = oldType.Default;
                        newType.DefaultSchema = oldType.DefaultSchema;
                        newType.NumericPrecision = oldType.NumericPrecision;
                        newType.NumericScale = oldType.NumericScale;
                        newType.Rule = oldType.Rule;
                        newType.RuleSchema = oldType.RuleSchema;
                        newDB.UserDefinedDataTypes.Add(newType);
                        newType.Create();
                    }
                    catch (Exception e)
                    {
                        ReportException(e);
                    }
                }
            }

            //copy the schema
            StringBuilder sb = new StringBuilder();
            ScriptingOptions options = new ScriptingOptions();
            options.ClusteredIndexes = true;
            options.Default = true;
            options.DriAll = true;
            options.Indexes = true;
            options.IncludeHeaders = true;
            options.DriAllConstraints = true;
            options.DriIndexes = true;
            options.FullTextIndexes = true;
            options.ExtendedProperties = true;
            options.NoCollation = true; //we will convert TEXT to NTEXT anyway
            options.NoCommandTerminator = false; //we do need this - otherwise CREATE VIEW has problems
            options.ClusteredIndexes = true;
            options.NonClusteredIndexes = true;
            options.SchemaQualify = true;
            options.ScriptSchema = true;
            options.SchemaQualifyForeignKeysReferences = true;
            options.IncludeDatabaseContext = false; //since we wil be executing in a different DB context

            options.Triggers = true;

            //copy tables
            foreach (Table table in db.Tables)
            {
                if (!table.IsSystemObject)
                {
                    Table oldTable = newDB.Tables[table.Name];
                    if (oldTable != null)
                    {
                        try
                        {
                            Notify("Dropping existing table " + oldTable.Name);
                            oldTable.Drop();
                        }
                        catch (Exception e)
                        {
                            ReportException(e);
                        }
                    }

                    sb.Length = 0;
                    //don't script inserts - we run out of memory
                    options.ScriptData = false;
                    StringCollection coll = table.Script(options);

                    foreach (string str in coll)
                    {
                        sb.AppendLine(str);
                    }
                    Notify("Creating table " + table.Name);
                    string sql = ChangeAnsiToUnicode(sb.ToString());
                    try
                    {
                        newDB.ExecuteNonQuery(sql);
                    }
                    catch (Exception e)
                    {
                        ReportException(e, sql);
                    }
                    var x = Missing.Value;
                }
            }

            //copy views
            foreach (View view in db.Views)
            {
                if (!view.IsSystemObject)
                {
                    View oldView = newDB.Views[view.Name];
                    if (oldView != null)
                    {
                        try
                        {
                            Notify("Dropping existing view " + oldView.Name);
                            oldView.Drop();
                        }
                        catch (Exception e)
                        {
                            ReportException(e);
                        }
                    }

                    sb.Length = 0;
                    StringCollection coll = view.Script(options);
                    foreach (string str in coll)
                    {
                        string line = str; //make it a local avriable since we change it below
                        if (line.Trim().StartsWith("create view", true, CultureInfo.CurrentCulture))
                        {
                            //'CREATE VIEW' must be the first statement in a query batch.
                            sb.AppendLine("GO");
                            //make sure we have the right schema when we call CREATE VIEW
                            if ((line.ToUpper().IndexOf(".[" + view.Name.ToUpper()) < 0) && //if there is no preceeing "]." before [viewname], the schema is not specified
                                (line.ToUpper().IndexOf("SYSDBA." + view.Name.ToUpper()) < 0))
                            {
                                int p = line.ToUpper().IndexOf(string.Format("[{0}]", view.Name.ToUpper()));
                                if (p >= 0)
                                {
                                    line = line.Replace(string.Format("[{0}]", view.Name), string.Format("[sysdba].[{0}]", view.Name));
                                }
                                else
                                {
                                    p = line.ToUpper().IndexOf(string.Format("CREATE VIEW {0}", view.Name.ToUpper()));
                                    if (p >= 0)
                                    {
                                        line = line.ToUpper().Replace(string.Format("CREATE VIEW {0}", view.Name), string.Format("CREATE VIEW [sysdba].[{0}]", view.Name));
                                    }
                                }
                            }
                        }
                        sb.AppendLine(line);
                    }
                    try
                    {
                        Notify("Creating view " + view.Name);
                        newDB.ExecuteNonQuery(sb.ToString());
                    }
                    catch (Exception e)
                    {
                        ReportException(e, sb.ToString());
                    }
                }
            }

            //now stuff existing data into the new db
            string connectionString = "";
            if (string.IsNullOrEmpty(user))
            {
                //Windows Auth
                connectionString = string.Format("Integrated Security=SSPI;Persist Security Info=False;Initial Catalog={0};Data Source={1}",
                                                newDatabase, server);
            }
            else
            {
                //SQL Auth
                connectionString = string.Format("Password={0};Persist Security Info=True;User ID={1};Initial Catalog={2};Data Source={3}",
                                                 password, user, newDatabase, server);
            }
            SqlConnection newConnection = new SqlConnection(connectionString);
            newConnection.Open();
            SqlBulkCopy bulkCopy = new SqlBulkCopy(newConnection);
            bulkCopy.BulkCopyTimeout = int.MaxValue;

            foreach (Table table in db.Tables)
            {
                if (!table.IsSystemObject)
                {
                    try
                    {
                        Notify("Copying data to table " + table.Name);
                        string sql = string.Format("SELECT * FROM {0}.{1}", table.Owner, table.Name);
                        using (DataSet dataset = db.ExecuteWithResults(sql))
                        {
                            bulkCopy.DestinationTableName = string.Format("{0}.{1}", table.Owner, table.Name);
                            if (dataset.Tables.Count > 0)
                            {
                                DataTable t = dataset.Tables[0];
                                bulkCopy.WriteToServer(t);
                            }
                        }
                    }
                    catch (Exception e)
                    {
                        ReportException(e);
                    }
                }
                GC.Collect(); //we can use lots of memory above!
            }

            //make sure the DB is marked as Unicode
            string markAsUnicodeSQL = "UPDATE SYSDBA.SYSTEMINFO SET UNICODE = 'T' ";
            try
            {
                Notify("Marking the new database as Unicode enabled");
                newDB.ExecuteNonQuery(markAsUnicodeSQL);
            }
            catch (Exception e)
            {
                ReportException(e, markAsUnicodeSQL);
            }

            //convert the virtual file system
            Notify("Updating VIRTUALFILESYSTEM table...");
            try
            {
                //we need a conneciton for updates since SMO won't let us use parameters for updates
                //when we update large binary fields (VIRTUALFILESYSTEM.ITEMDATA)
                string updateConnectionString = "";
                if (string.IsNullOrEmpty(user))
                {
                    //Windows Auth
                    updateConnectionString = string.Format("Integrated Security=SSPI;Persist Security Info=False;Initial Catalog={0};Data Source={1}",
                                                    newDatabase, server);
                }
                else
                {
                    //SQL Auth
                    updateConnectionString = string.Format("Password={0};Persist Security Info=True;User ID={1};Initial Catalog={2};Data Source={3}",
                                                     password, user, newDatabase, server);
                }
                SqlConnection updateConnection = new SqlConnection(updateConnectionString);
                updateConnection.Open();

                string vfsSql =
                    "SELECT VIRTUALFILESYSTEMID, ITEMNAME, ITEMDATA, ISCOMPRESSED FROM SYSDBA.VIRTUALFILESYSTEM WHERE ITEMNAME LIKE '%.entity.xml' ";
                using (DataSet vfsDataset = newDB.ExecuteWithResults(vfsSql))
                {
                    if (vfsDataset.Tables.Count > 0)
                    {
                        DataTable t = vfsDataset.Tables[0];
                        foreach (DataRow row in t.Rows)
                        {
                            string itemName = (string) row["ITEMNAME"];
                            string[] arrItemName = itemName.Split(new string[] {"."}, StringSplitOptions.None);
                            //Name.TABLE.entity.xml
                            if (arrItemName.Length > 2)
                            {
                                string entityName = arrItemName[0];
                                string tableName = arrItemName[1];
                                Notify(string.Format("Updating entity {0} (Table {1})", entityName, tableName));
                                try
                                {
                                    Table table = null;
                                    foreach (Table currTable in newDB.Tables)
                                    {
                                        if ((String.Compare(currTable.Name, tableName, true) == 0) && (String.Compare(currTable.Owner, "sysdba", true) == 0))
                                        {
                                            table = currTable;
                                            break;
                                        }
                                    }
                                    if (table != null)
                                    {
                                        object ItemData = row["ITEMDATA"]; //we expect an array
                                        if (ItemData != null)
                                        {
                                            object strIsCompressed = row["ISCOMPRESSED"];
                                            Boolean bIsCompressed = (strIsCompressed != null) &&
                                                                    (string.Compare((string) strIsCompressed, "T", true) ==
                                                                     0);
                                            using (var memoryStream = UnpackItemData((byte[]) ItemData, bIsCompressed))
                                            {
                                                XmlDocument xmlEntityDocument = new XmlDocument();
                                                memoryStream.Position = 0;
                                                xmlEntityDocument.Load(memoryStream);
                                                Boolean XmlModified = false;
                                                foreach (Column column in table.Columns)
                                                {
                                                    //is this a string derived type?
                                                    SqlDataType dataType = column.DataType.SqlDataType;
                                                    if (column.DataType.SqlDataType == SqlDataType.UserDefinedDataType)
                                                    {
                                                        UserDefinedDataType colType = newDB.UserDefinedDataTypes[string.Format("[{0}].[{1}]", column.DataType.Schema, column.DataType.Name)];
                                                        if (colType == null) colType = newDB.UserDefinedDataTypes[column.DataType.Name];
                                                        if (colType != null)
                                                        {
                                                            switch (colType.SystemType.ToUpper())
                                                            {
                                                                case "NVARCHAR":
                                                                    {
                                                                        dataType = SqlDataType.NVarChar;
                                                                        break;
                                                                    }
                                                                case "NCHAR":
                                                                    {
                                                                        dataType = SqlDataType.NChar;
                                                                        break;
                                                                    }
                                                                case "NTEXT":
                                                                    {
                                                                        dataType = SqlDataType.NText;
                                                                        break;
                                                                    }
                                                            }
                                                        }
                                                    }

                                                    if ((dataType == SqlDataType.NChar) ||
                                                        (dataType == SqlDataType.NText) ||
                                                        (dataType == SqlDataType.NVarChar) ||
                                                        (dataType == SqlDataType.NVarCharMax)
                                                        )
                                                    {
                                                        XmlModified |= ModifyEntityColumn(xmlEntityDocument, column.Name);
                                                    }
                                                }
                                                if (XmlModified)
                                                {
                                                    //now save it
                                                    memoryStream.SetLength(0);
                                                    xmlEntityDocument.Save(memoryStream);
                                                    memoryStream.Position = 0;
                                                    byte[] newData = PackItemData(memoryStream, true, ref bIsCompressed);

                                                    string updateSql =
                                                        string.Format(
                                                            "UPDATE sysdba.VIRTUALFILESYSTEM SET ITEMDATA = @DATA, ISCOMPRESSED = @COMPRESSED WHERE VIRTUALFILESYSTEMID = '{0}'",
                                                            row["VIRTUALFILESYSTEMID"]
                                                            );
                                                    SqlParameter parameter;
                                                    SqlCommand command = new SqlCommand(updateSql, updateConnection);
                                                    parameter = command.Parameters.Add("@DATA", SqlDbType.Image);
                                                    parameter.Value = newData;
                                                    parameter = command.Parameters.Add("@COMPRESSED", SqlDbType.NVarChar);
                                                    parameter.Value = bIsCompressed ? "T" : "F";
                                                    command.ExecuteNonQuery();
                                                }
                                            }
                                        }
                                    }
                                }
                                catch (Exception e)
                                {
                                    ReportException(e);
                                }
                            }
                        }
                    }
                }
            }
            catch (Exception e)
            {
                ReportException(e);
            }
            GC.Collect();
        }