コード例 #1
0
        public static string[] GetNpcs()
        {
            int           count = 0;
            List <string> list  = new List <string>();

            ScriptEntry[] entrys = ScriptDatabase.GetType(EScriptContent.Npc);

            for (int i = 0; i < entrys.Length; i++)
            {
                if (entrys[i].Type != EScriptType.Path)
                {
                    continue;
                }
                if (File.Exists(entrys[i].Path) == false)
                {
                    CConsole.ErrorLine("Cant find File/Path: \"" + entrys[i].Path + "\"! Skipping...");
                    continue;
                }

                list.Add(entrys[i].Path);
                CConsole.InfoLine("\t#{0}: \"{1}\"", (++count), entrys[i].Path);
            }

            return(list.ToArray());
        }
コード例 #2
0
 public void Initialize(ScriptDatabase sdb, SMOScriptOptions options, AsyncUpdateStatus updateStatus, AsyncNotificationEventArgs eventArgs, string outputDir)
 {
     _sdb           = sdb;
     _smoScriptOpts = options;
     _updateStatus  = updateStatus;
     _eventArgs     = eventArgs;
     _outputDir     = outputDir;
 }
コード例 #3
0
    //public List<Dictionary<DesireColor, string>> encounterAnswers = new List<Dictionary<DesireColor, string>>();

    // Use this for initialization
    void Start()
    {
        //Acquire database
        scriptDatabase = GameObject.Find("ControllerGame").GetComponent <ScriptDatabase>();

        //Answer initialization belongs in other function
        activeAnswers = LoadAnswers(currentEncounter);
        answerColors  = ShuffleColorList(answerColors);
    }
コード例 #4
0
        public SqlScriptServiceTests()
        {
            var settings = new CommonDatabaseSettings();

            _database = new ScriptDatabase(settings);
            AssertionOptions.AssertEquivalencyUsing(options =>
            {
                options.Using <DateTime>(ctx => ctx.Subject.Should().BeCloseTo(ctx.Expectation)).WhenTypeIs <DateTime>();
                options.Using <DateTimeOffset>(ctx => ctx.Subject.Should().BeCloseTo(ctx.Expectation)).WhenTypeIs <DateTimeOffset>();
                return(options);
            });
        }
コード例 #5
0
 public SqlScriptRepository(ScriptDatabase database)
 {
     _database = database;
     _database.SetupOnce();
 }
コード例 #6
0
        public List <string> GenerateScriptFromSourceServer(ServerConnection sc, List <DatabaseObject> objectList)
        {
            var dtStart = DateTime.Now;
            AsyncUpdateStatus updateStatus = GenScriptAsyncUpdateStatusHandler;
            var          args   = new AsyncNotificationEventArgs(NotificationEventFunctionCode.GenerateScriptFromSQLServer, 0, "", CommonFunc.FormatString("Process started at {0} -- UTC -> {1} ... ", dtStart.ToString(CultureInfo.CurrentUICulture), dtStart.ToUniversalTime().ToString(CultureInfo.CurrentUICulture)) + Environment.NewLine, Color.DarkBlue);
            StreamWriter swTSQL = null;

            SqlSmoObject[] smoTriggers   = null;
            Object         sender        = System.Threading.Thread.CurrentThread;
            var            smoScriptOpts = SMOScriptOptions.CreateFromConfig();

            updateStatus(args);

            sc.Connect();

            var ss  = new Server(sc);
            var db  = ss.Databases[sc.DatabaseName];
            var sdb = new ScriptDatabase();

            sdb.Initialize(ss, db, updateStatus, smoScriptOpts, swTSQL);

            args.DisplayText     = "";
            args.StatusMsg       = "Sorting objects by dependency ...";
            args.PercentComplete = 1;
            updateStatus(args);

            var sorted             = GetSortedObjects(db, objectList);
            var sp                 = new SourceProcessor();
            var tempPathForBCPData = Path.Combine(Path.GetTempPath(), "/BCPData");

            Directory.CreateDirectory(tempPathForBCPData);
            sp.Initialize(sdb, smoScriptOpts, updateStatus, args, tempPathForBCPData);

            //NOTE: This is what does the magic!
            if (sp.Process(sorted, 30))
            {
                return(output);
            }

            if (!Regex.IsMatch(smoScriptOpts.ScriptTableAndOrData, smoScriptOpts.GetLocalizedStringValue("ScriptOptionsTableData"), RegexOptions.IgnoreCase))
            {
                if (sp.Process(DatabaseObjectsTypes.Triggers, smoTriggers, 95))
                {
                    return(output);
                }
            }

            var dtEnd      = DateTime.Now;
            var tsDuration = dtEnd.Subtract(dtStart);
            var sHour      = tsDuration.Minutes == 1 ? " hour, " : " hours, ";
            var sMin       = tsDuration.Minutes == 1 ? " minute and " : " minutes and ";
            var sSecs      = tsDuration.Seconds == 1 ? " second" : " seconds";

            args.StatusMsg    = "Done!";
            args.DisplayColor = Color.DarkCyan;

            if (smoScriptOpts.CheckCompatibility() == 1)
            {
                args.DisplayText = CommonFunc.FormatString(@"No analysis done on script.
Processing finished at {0} -- UTC -> {1}
Total processing time: {2}", dtEnd.ToString(CultureInfo.CurrentUICulture), dtEnd.ToUniversalTime().ToString(CultureInfo.CurrentUICulture), tsDuration.Hours + sHour + tsDuration.Minutes.ToString(CultureInfo.CurrentUICulture) + sMin + tsDuration.Seconds.ToString(CultureInfo.CurrentUICulture) + sSecs);
            }
            else
            {
                args.DisplayText = CommonFunc.FormatString(@"Analysis completed at {0} -- UTC -> {1}
Any issues discovered will be reported above.
Total processing time: {2}", dtEnd.ToString(CultureInfo.CurrentUICulture), dtEnd.ToUniversalTime().ToString(CultureInfo.CurrentUICulture), tsDuration.Hours + sHour + tsDuration.Minutes.ToString(CultureInfo.CurrentUICulture) + sMin + tsDuration.Seconds.ToString(CultureInfo.CurrentUICulture) + sSecs);
            }
            args.PercentComplete = 100;
            updateStatus(args);
            return(output);
        }
コード例 #7
0
ファイル: MegaloAction.cs プロジェクト: MegaMech/nitrogen
 static MegaloAction()
 {
     Database = new ScriptDatabase(new XmlDefinitionsTransport(Resources.ActionDatabase));
 }
コード例 #8
0
ファイル: SourceServer.cs プロジェクト: hismightiness/Dnn.EVS
        public void GenerateScriptFromSourceServer(Server sourceServer, Database sourceDatabase, StreamWriter swTSQL, AsyncUpdateStatus updateStatus, string outputDir, ObjectSelector objectFilter)
        {
            _updateStatus   = updateStatus;
            _smoScriptOpts  = SMOScriptOptions.CreateFromConfig();
            _ObjectSelector = objectFilter;

            //if (_smoScriptOpts.TargetServer == _smoScriptOpts.GetLocalizedStringValue("ServerType_AzureSQLDatabase"))
            //{
            //    _ObjectSelector.Assemblies.Script = false;
            //    _ObjectSelector.SchemaCollections.Script = false;
            //}

            DateTime dtStart = DateTime.Now;
            AsyncNotificationEventArgs eventArgs = new AsyncNotificationEventArgs(NotificationEventFunctionCode.GenerateScriptFromSQLServer, 0, "", CommonFunc.FormatString(Properties.Resources.MessageProcessStarted, dtStart.ToString(CultureInfo.CurrentUICulture), dtStart.ToUniversalTime().ToString(CultureInfo.CurrentUICulture)) + Environment.NewLine, Color.DarkBlue);

            _updateStatus(eventArgs);

            ScriptDatabase sdb = new ScriptDatabase();

            sdb.Initialize(sourceServer, sourceDatabase, _updateStatus, _smoScriptOpts, swTSQL, true);

            eventArgs.DisplayText     = "";
            eventArgs.StatusMsg       = Properties.Resources.MessageSorting;
            eventArgs.PercentComplete = 1;
            _updateStatus(eventArgs);

            // Tables, Views, Stored Procedures, and Triggers can all have dependencies.  GetSortedObjects returns
            // these objects in dependency order.

            SqlSmoObject[] smoAssemblies         = GetAssemblies(sourceDatabase);
            SqlSmoObject[] smoPartitionFunctions = GetPartitionFunctions(sourceDatabase);
            SqlSmoObject[] smoPartitionSchemes   = GetPartitionSchemes(sourceDatabase);
            SqlSmoObject[] smoTriggers           = GetTriggers(sourceServer, sourceDatabase);
            SqlSmoObject[] smoRoles      = GetRoles(sourceDatabase);
            SqlSmoObject[] smoSchemas    = GetSchemas(sourceDatabase);
            SqlSmoObject[] smoSchemaCols = GetSchemaCollections(sourceServer, sourceDatabase);
            SqlSmoObject[] smoUDTs       = GetUDTs(sourceDatabase);
            SqlSmoObject[] smoUDTTs      = GetUDTTs(sourceDatabase);
            SqlSmoObject[] smoSynonyms   = GetSynonyms(sourceDatabase);
            SqlSmoObject[] sorted        = GetSortedObjects(sourceDatabase);

            if (Regex.IsMatch(_smoScriptOpts.ScriptDropCreate, _smoScriptOpts.GetLocalizedStringValue("SOSDrop"), RegexOptions.IgnoreCase) ||
                Regex.IsMatch(_smoScriptOpts.ScriptDropCreate, _smoScriptOpts.GetLocalizedStringValue("SOSDropCreate"), RegexOptions.IgnoreCase))
            {
                eventArgs.StatusMsg       = Properties.Resources.MessageCreatingDropScripts;
                eventArgs.PercentComplete = 2;
                _updateStatus(eventArgs);

                ScriptDrops(sorted, smoRoles, smoSchemas, smoSchemaCols, smoUDTs, smoUDTTs, smoAssemblies, smoSynonyms, smoPartitionFunctions, smoPartitionSchemes, sdb);
            }

            if (Regex.IsMatch(_smoScriptOpts.ScriptDropCreate, _smoScriptOpts.GetLocalizedStringValue("SOSCreate"), RegexOptions.IgnoreCase) ||
                Regex.IsMatch(_smoScriptOpts.ScriptDropCreate, _smoScriptOpts.GetLocalizedStringValue("SOSDropCreate"), RegexOptions.IgnoreCase))
            {
                SourceProcessor sp = new SourceProcessor();
                sp.Initialize(sdb, _smoScriptOpts, _updateStatus, eventArgs, outputDir);

                // Roles, Schemas, XML Schema Collections and UDT have no dependencies.  Thus we process one at a time.

                if (!Regex.IsMatch(_smoScriptOpts.ScriptTableAndOrData, _smoScriptOpts.GetLocalizedStringValue("ScriptOptionsTableData"), RegexOptions.IgnoreCase))
                {
                    if (sp.Process(DatabaseObjectsTypes.Assemblies, smoAssemblies, 3))
                    {
                        return;
                    }
                    if (sp.Process(DatabaseObjectsTypes.PartitionFunctions, smoPartitionFunctions, 6))
                    {
                        return;
                    }
                    if (sp.Process(DatabaseObjectsTypes.PartitionSchemes, smoPartitionSchemes, 9))
                    {
                        return;
                    }
                    if (sp.Process(DatabaseObjectsTypes.Roles, smoRoles, 12))
                    {
                        return;
                    }
                    if (sp.Process(DatabaseObjectsTypes.Schemas, smoSchemas, 15))
                    {
                        return;
                    }
                    if (sp.Process(DatabaseObjectsTypes.XMLSchemaCollections, smoSchemaCols, 20))
                    {
                        return;
                    }
                    if (sp.Process(DatabaseObjectsTypes.UserDefinedDataTypes, smoUDTs, 25))
                    {
                        return;
                    }
                    if (sp.Process(DatabaseObjectsTypes.UserDefinedTableTypes, smoUDTTs, 30))
                    {
                        return;
                    }
                    if (sp.Process(DatabaseObjectsTypes.Synonyms, smoSynonyms, 35))
                    {
                        return;
                    }
                }
                if (sp.Process(sorted, 40))
                {
                    return;
                }

                if (!Regex.IsMatch(_smoScriptOpts.ScriptTableAndOrData, _smoScriptOpts.GetLocalizedStringValue("ScriptOptionsTableData"), RegexOptions.IgnoreCase))
                {
                    if (sp.Process(DatabaseObjectsTypes.Triggers, smoTriggers, 95))
                    {
                        return;
                    }
                }
            }

            if (swTSQL != null)
            {
                swTSQL.Flush();
                swTSQL.Close();
            }

            DateTime dtEnd      = DateTime.Now;
            TimeSpan tsDuration = dtEnd.Subtract(dtStart);
            string   sHour      = tsDuration.Minutes == 1 ? Properties.Resources.MessageHour : Properties.Resources.MessageHours;
            string   sMin       = tsDuration.Minutes == 1 ? Properties.Resources.MessageMinute : Properties.Resources.MessageMinutes;
            string   sSecs      = tsDuration.Seconds == 1 ? Properties.Resources.MessageSecond : Properties.Resources.MessageSeconds;

            eventArgs.StatusMsg    = Properties.Resources.Done;
            eventArgs.DisplayColor = Color.DarkCyan;

            if (_smoScriptOpts.CheckCompatibility() == 1)
            {
                eventArgs.DisplayText = CommonFunc.FormatString(Properties.Resources.MessageFinishedNoAnalysis, dtEnd.ToString(CultureInfo.CurrentUICulture), dtEnd.ToUniversalTime().ToString(CultureInfo.CurrentUICulture), tsDuration.Hours + sHour + tsDuration.Minutes.ToString(CultureInfo.CurrentUICulture) + sMin + tsDuration.Seconds.ToString(CultureInfo.CurrentUICulture) + sSecs);
            }
            else
            {
                eventArgs.DisplayText = CommonFunc.FormatString(Properties.Resources.MessageFinishedWithAnalysis, dtEnd.ToString(CultureInfo.CurrentUICulture), dtEnd.ToUniversalTime().ToString(CultureInfo.CurrentUICulture), tsDuration.Hours + sHour + tsDuration.Minutes.ToString(CultureInfo.CurrentUICulture) + sMin + tsDuration.Seconds.ToString(CultureInfo.CurrentUICulture) + sSecs);
            }
            eventArgs.PercentComplete = 100;
            _updateStatus(eventArgs);
        }
コード例 #9
0
ファイル: SourceServer.cs プロジェクト: hismightiness/Dnn.EVS
        private void ScriptDrops(SqlSmoObject[] sorted, SqlSmoObject[] smoRoles, SqlSmoObject[] smoSchemas, SqlSmoObject[] smoSchemasCols, SqlSmoObject[] smoUDTs, SqlSmoObject[] smoUDTTs, SqlSmoObject[] smoAssemblies, SqlSmoObject[] smoSynonyms, SqlSmoObject[] smoPartitionFunctions, SqlSmoObject[] smoPartitionSchemes, ScriptDatabase sdb)
        {
            int objCount = sorted.Count <SqlSmoObject>();

            if (objCount == 0)
            {
                return;
            }

            SqlSmoObject[] smoReverseSorted = new SqlSmoObject[objCount];
            for (int index = 0; index < objCount; index++)
            {
                smoReverseSorted[index] = sorted[objCount - 1 - index];
            }

            if (sorted.Count <SqlSmoObject>() > 0)
            {
                sdb.ScriptDrops(smoReverseSorted);
            }
            if (smoUDTs.Count <SqlSmoObject>() > 0)
            {
                sdb.ScriptDrops(smoUDTs);
            }
            if (smoUDTTs.Count <SqlSmoObject>() > 0)
            {
                sdb.ScriptDrops(smoUDTTs);
            }
            if (smoSchemas.Count <SqlSmoObject>() > 0)
            {
                sdb.ScriptDrops(smoSchemas);
            }
            if (smoSchemasCols.Count <SqlSmoObject>() > 0)
            {
                sdb.ScriptDrops(smoSchemasCols);
            }
            if (smoRoles.Count <SqlSmoObject>() > 0)
            {
                SqlSmoObject[] roles = new SqlSmoObject[1];
                foreach (SqlSmoObject role in smoRoles)
                {
                    roles[0] = role;
                    sdb.ScriptDrops(roles);
                }
            }
            if (smoSynonyms.Count <SqlSmoObject>() > 0)
            {
                sdb.ScriptDrops(smoSynonyms);
            }
            if (smoAssemblies.Count <SqlSmoObject>() > 0)
            {
                sdb.ScriptDrops(smoAssemblies);
            }
            if (smoPartitionFunctions.Count <SqlSmoObject>() > 0)
            {
                sdb.ScriptDrops(smoPartitionFunctions);
            }
            if (smoPartitionSchemes.Count <SqlSmoObject>() > 0)
            {
                sdb.ScriptDrops(smoPartitionSchemes);
            }
        }
コード例 #10
0
        private List <Azure> ParseFile(string fileToProcess, bool parseFile)
        {
            var startTime   = DateTime.Now;
            var messageList = new List <Azure> {
                new Azure(fileToProcess, MessageTypes.Info, "Beginning Azure Check.")
            };

            var sdb     = new ScriptDatabase();
            var options = SMOScriptOptions.CreateFromConfig();

            sdb.Initialize(_output.StatusUpdateHandler, options, false);

            /****************************************************************/

            var  sqlText = CommonFunc.GetTextFromFile(fileToProcess);
            var  cah     = new CommentAreaHelper();
            long totalCharacterOffset = 0;
            var  bCommentedLine       = false;

            var sqlCmds = new List <string>();

            if (parseFile)
            {
                var sb = new StringBuilder();
                cah.FindCommentAreas(sqlText);
                foreach (var line in cah.Lines)
                {
                    if (line.Equals("GO", StringComparison.OrdinalIgnoreCase))
                    {
                        if (!cah.IsIndexInComments(totalCharacterOffset))
                        {
                            sqlCmds.Add(sb.ToString());
                            sb.Length = 0;
                        }
                        else
                        {
                            sb.Append(line + Environment.NewLine);
                        }
                    }
                    else
                    {
                        sb.Append(line + Environment.NewLine);
                    }
                    totalCharacterOffset += line.Length + cah.CrLf;
                }

                //first we will remove the comments.
                var r         = new Regex(@"(/\*([^*]|[\r\n]|(\*+([^*/]|[\r\n])))*\*+/)|(--.*)");
                var remainder = r.Replace(sb.ToString(), string.Empty).Trim();

                if (remainder.Length > 8)
                {
                    messageList.Add(new Azure(fileToProcess, MessageTypes.Warning, "Final Section of T-SQL didn't finish with a 'GO' command."));
                    sb.Append("GO" + Environment.NewLine);
                    sqlCmds.Add(sb.ToString());
                }
                else //this will re-add the comments and such so that the output files will better match the input files.
                {
                    sqlCmds.Add(sb.ToString());
                }
            }
            else
            {
                sqlCmds.Add(sqlText);
            }

            var numCmds = sqlCmds.Count;

            if (numCmds == 0)
            {
                messageList.Add(new Azure(fileToProcess, MessageTypes.Info, "No data to process"));

                return(messageList);
            }

            var loopCtr = 0;

            messageList.Add(new Azure(fileToProcess, MessageTypes.Info, string.Format("Processing {0} out of {1}", loopCtr, numCmds)));

            totalCharacterOffset = 0;

            foreach (var cmd in sqlCmds)
            {
                ++loopCtr;

                if (cmd.Length == 0 || cmd.Equals(Environment.NewLine))
                {
                    continue;
                }

                foreach (CommentArea ca in cah.CommentAreas)
                {
                    if (ca.Start == totalCharacterOffset && ca.End == totalCharacterOffset + cmd.Length - cah.CrLf - 1) // note that the -1 is to put you at zero based counting
                    {
                        bCommentedLine = true;
                        break;
                    }
                    bCommentedLine = false;
                }
                totalCharacterOffset += cmd.Length + cah.CrLf;

                if (parseFile && !bCommentedLine && !(cmd.StartsWith("/*~") || cmd.StartsWith("~*/")))
                {
                    if (Regex.IsMatch(cmd, "(CREATE|ALTER)\\sPROCEDURE", RegexOptions.IgnoreCase))
                    {
                        sdb.ParseFileTSQLGo(cmd);
                    }
                    else if (Regex.IsMatch(cmd, "(CREATE|ALTER)\\sTABLE", RegexOptions.IgnoreCase))
                    {
                        sdb.ParseFileTable(cmd);
                    }
                    else if (Regex.IsMatch(cmd, "CREATE\\sXML\\sSCHEMA\\sCOLLECTION", RegexOptions.IgnoreCase))
                    {
                        sdb.ParseFileXMLSchemaCollections(cmd);
                    }
                    else if (Regex.IsMatch(cmd, "CREATE\\sTYPE", RegexOptions.IgnoreCase))
                    {
                        sdb.ParseFileUDT(cmd);
                    }
                    else if (Regex.IsMatch(cmd, "CREATE\\s[a-z\\s]*\\sINDEX", RegexOptions.IgnoreCase))
                    {
                        sdb.ParseFileIndex(cmd);
                    }
                    else if (Regex.IsMatch(cmd, "CREATE ROLE", RegexOptions.IgnoreCase))
                    {
                        sdb.ParseFileRole(cmd);
                    }
                    else
                    {
                        sdb.ParseFileTSQLGo(cmd);
                    }
                }
                else
                {
                    sdb.OutputSQLString(cmd, Color.Black);
                }



                if (loopCtr % 20 == 0)
                {
                    messageList.Add(new Azure(fileToProcess, MessageTypes.Info, string.Format("Processing {0} out of {1} - %{2} Complete", loopCtr, numCmds, (int)((loopCtr / (float)numCmds) * 100.0))));
                }
            }

            var endTime = DateTime.Now;

            messageList.Add(new Azure(fileToProcess, MessageTypes.Info, string.Format(
                                          "{1}Total processing time --> {0}",
                                          endTime.Subtract(startTime),
                                          "--~")));

            return(messageList);
        }
コード例 #11
0
        public bool ParseFile(SMOScriptOptions options, bool _ParseFile, AsyncNotificationEventArgs e)
        {
            DateTime       startTime = DateTime.Now;
            ScriptDatabase sdb       = new ScriptDatabase();

            if (e.FunctionCode == NotificationEventFunctionCode.ParseFolder)
            {
                FileInfo fi = new FileInfo(_FileToProcess);
                _SwTsql = new StreamWriter(_TargetFile, false);
                sdb.Initialize(_Output.StatusUpdateHandler, options, false, _FileToProcess, _SwTsql);
            }
            else
            {
                sdb.Initialize(_Output.StatusUpdateHandler, options, false);
            }
            /****************************************************************/
            string            sqlText = CommonFunc.GetTextFromFile(_FileToProcess);
            CommentAreaHelper cah     = new CommentAreaHelper();
            long totalCharacterOffset = 0;
            bool bCommentedLine       = false;

            List <string> sqlCmds = new List <string>();

            if (_ParseFile)
            {
                StringBuilder sb = new StringBuilder();
                cah.FindCommentAreas(sqlText);
                foreach (string line in cah.Lines)
                {
                    if (line.Equals(Properties.Resources.Go, StringComparison.OrdinalIgnoreCase))
                    {
                        if (!cah.IsIndexInComments(totalCharacterOffset))
                        {
                            sqlCmds.Add(sb.ToString());
                            sb.Length = 0;
                        }
                        else
                        {
                            sb.Append(line + Environment.NewLine);
                        }
                    }
                    else
                    {
                        sb.Append(line + Environment.NewLine);
                    }
                    totalCharacterOffset += line.Length + cah.CrLf;
                }

                if (sb.Length > 0)
                {
                    sqlCmds.Add(sb.ToString());
                    sb.Length = 0;
                }
            }
            else
            {
                sqlCmds.Add(sqlText);
            }

            int numCmds = sqlCmds.Count();
            int loopCtr = 0;

            if (numCmds == 0)
            {
                e.DisplayText = CommonFunc.FormatString(Properties.Resources.MessageNoDataToProcess + Environment.NewLine, _FileToProcess);
                if (e.FunctionCode == NotificationEventFunctionCode.ParseFile)
                {
                    e.PercentComplete = 100;
                }
                else if (e.FunctionCode == NotificationEventFunctionCode.ParseFolder)
                {
                    e.FilesProcessed++;
                }
                _Output.StatusUpdateHandler(e);
                return(false);
            }
            e.DisplayColor = Color.DarkBlue;
            e.DisplayText  = "";
            if (e.FunctionCode == NotificationEventFunctionCode.ParseFile)
            {
                e.StatusMsg       = CommonFunc.FormatString(Properties.Resources.MessageProcessingStatus, loopCtr.ToString(), numCmds.ToString());
                e.PercentComplete = 0;
            }
            else if (e.FunctionCode == NotificationEventFunctionCode.ParseFolder)
            {
                e.TotalDenominator = e.TotalDenominator + numCmds;
            }
            _Output.StatusUpdateHandler(e);
            totalCharacterOffset = 0;

            foreach (string cmd in sqlCmds)
            {
                ++loopCtr;

                if (AsyncProcessingStatus.CancelProcessing)
                {
                    break;
                }
                if (cmd.Length == 0 || cmd.Equals(Environment.NewLine))
                {
                    continue;
                }

                foreach (CommentArea ca in cah.CommentAreas)
                {
                    if (ca.Start == totalCharacterOffset && ca.End == totalCharacterOffset + cmd.Length - cah.CrLf - 1) // note that the -1 is to put you at zero based counting
                    {
                        bCommentedLine = true;
                        break;
                    }
                    bCommentedLine = false;
                }
                totalCharacterOffset += cmd.Length + cah.CrLf;

                if (_ParseFile && !bCommentedLine && !(cmd.StartsWith("/*~") || cmd.StartsWith("~*/")))
                {
                    if (Regex.IsMatch(cmd, "(CREATE|ALTER)\\sPROCEDURE", RegexOptions.IgnoreCase))
                    {
                        sdb.ParseFileTSQLGo(cmd);
                    }
                    else if (Regex.IsMatch(cmd, "(CREATE|ALTER)\\sTABLE", RegexOptions.IgnoreCase))
                    {
                        sdb.ParseFileTable(cmd);
                    }
                    else if (Regex.IsMatch(cmd, "CREATE\\sXML\\sSCHEMA\\sCOLLECTION", RegexOptions.IgnoreCase))
                    {
                        sdb.ParseFileXMLSchemaCollections(cmd);
                    }
                    else if (Regex.IsMatch(cmd, "CREATE\\sTYPE", RegexOptions.IgnoreCase))
                    {
                        sdb.ParseFileUDT(cmd);
                    }
                    else if (Regex.IsMatch(cmd, "CREATE\\s[a-z\\s]*\\sINDEX", RegexOptions.IgnoreCase))
                    {
                        sdb.ParseFileIndex(cmd);
                    }
                    else if (Regex.IsMatch(cmd, "(CREATE|ALTER)\\sROLE", RegexOptions.IgnoreCase))
                    {
                        sdb.ParseFileRole(cmd);
                    }
                    else if (Regex.IsMatch(cmd, "(CREATE|ALTER)\\sSYNONYM", RegexOptions.IgnoreCase))
                    {
                        sdb.ParseFileSynonyms(cmd);
                    }
                    else if (Regex.IsMatch(cmd, "(CREATE|ALTER)\\sSCHEMA", RegexOptions.IgnoreCase))
                    {
                        sdb.ParseFileSchemas(cmd);
                    }
                    else if (Regex.IsMatch(cmd, "(CREATE|ALTER)\\sASSEMBLY", RegexOptions.IgnoreCase))
                    {
                        sdb.ParseFileAssemblies(cmd);
                    }
                    else if (Regex.IsMatch(cmd, "(CREATE|ALTER)\\sPARTITIONFUNCTIONS", RegexOptions.IgnoreCase))
                    {
                        sdb.ParseFilePartitionFunctions(cmd);
                    }
                    else if (Regex.IsMatch(cmd, "(CREATE|ALTER)\\sPARTITIONSCHEMES", RegexOptions.IgnoreCase))
                    {
                        sdb.ParseFilePartitionSchemes(cmd);
                    }
                    else
                    {
                        sdb.ParseFileTSQLGo(cmd);
                    }
                    if (e.FunctionCode == NotificationEventFunctionCode.ParseFolder)
                    {
                        e.NumeratorComplete = e.NumeratorComplete + 1;
                    }
                }
                else
                {
                    sdb.OutputSQLString(cmd, Color.Black);
                }
                if (loopCtr % 20 == 0)
                {
                    e.DisplayColor = Color.DarkBlue;
                    e.DisplayText  = "";
                    if (e.FunctionCode == NotificationEventFunctionCode.ParseFile)
                    {
                        e.PercentComplete = (int)(((float)loopCtr / (float)numCmds) * 100.0);
                        e.StatusMsg       = CommonFunc.FormatString(Properties.Resources.MessageProcessingStatus, loopCtr.ToString(), numCmds.ToString());
                    }
                    else if (e.FunctionCode == NotificationEventFunctionCode.ParseFolder)
                    {
                        e.PercentComplete = (int)(((float)e.NumeratorComplete / (float)e.TotalDenominator) * 100);
                    }
                    _Output.StatusUpdateHandler(e);
                }
            }
            DateTime endTime = DateTime.Now;

            if (e.FunctionCode == NotificationEventFunctionCode.ParseFile)
            {
                if (AsyncProcessingStatus.CancelProcessing)
                {
                    e.DisplayText = CommonFunc.FormatString(Properties.Resources.MessageCanceledProcessing, DateTime.Now.ToString()) + Environment.NewLine;
                    e.StatusMsg   = Properties.Resources.MessageCanceled;
                }
                else
                {
                    e.DisplayColor = Color.DarkCyan;
                    if (_ParseFile)
                    {
                        e.DisplayText = Properties.Resources.AnalysisComplete + Environment.NewLine;
                    }
                    else
                    {
                        e.DisplayText = Properties.Resources.MessageFileReadAndReady;
                    }
                    e.StatusMsg = Properties.Resources.Done;
                }
                e.PercentComplete = 100;
                e.DisplayText     = CommonFunc.FormatString(Properties.Resources.MessageTotalFileProcessingTime + Environment.NewLine,
                                                            endTime.Subtract(startTime).ToString(),
                                                            Properties.Resources.RemoveComment,
                                                            _FileToProcess.ToString());
                _Output.StatusUpdateHandler(e);
            }
            else if (e.FunctionCode == NotificationEventFunctionCode.ParseFolder)
            {
                _SwTsql.Flush();
                _SwTsql.Close();
                if (sdb.IssuesFound == true)
                {
                    e.DisplayText = Properties.Resources.MessageFileChangedState +
                                    CommonFunc.FormatString(Properties.Resources.MessageTotalFileProcessingTime,
                                                            endTime.Subtract(startTime).ToString(), _FileToProcess.ToString()) + Environment.NewLine;
                    e.DisplayColor = Color.Brown;
                }
                else
                {
                    e.DisplayText = Properties.Resources.MessageFileNoChangeState +
                                    CommonFunc.FormatString(Properties.Resources.MessageTotalFileProcessingTime,
                                                            endTime.Subtract(startTime).ToString(), _FileToProcess.ToString()) + Environment.NewLine;
                    e.DisplayColor = Color.DarkBlue;
                }
                _Output.StatusUpdateHandler(e);
                e.FilesProcessed++;
            }
            return(sdb.IssuesFound);
        }
コード例 #12
0
        public static void Main(string[] args)
        {
            // If we set the exceptionhandler also in debug, VS wont throw them and i cant react in Debug-mode
            // They will be printed to the console interface
#if !DEBUG
            AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);
#endif
            AppDomain.CurrentDomain.ProcessExit += new EventHandler(CurrentDomain_ProcessExit);
#if !DEBUG
            try {
#endif

            // Cleanup before loading any other data
            GC.Collect(GC.MaxGeneration, GCCollectionMode.Forced);

            // Save some infos about our thread and assembly
            mThread   = Thread.CurrentThread;
            mProcess  = Process.GetCurrentProcess();
            mAssembly = Assembly.GetEntryAssembly();
            if (mThread != null)
            {
                // We set a name on our core thread
                mThread.Name = "Core Thread";
            }

            // Initialize our timer manager
            TimerThread ttObj = new TimerThread();
            mTimerThread      = new Thread(new ThreadStart(ttObj.TimerMain));
            mTimerThread.Name = "Timer Thread";

            // Prepare console for a large output
            int width = Math.Min(100, Console.LargestWindowWidth - 2);
            Console.CursorVisible = false;
            Console.Clear();
            Console.WindowLeft = Console.WindowTop = 0;
            if (Console.WindowWidth < width)
            {
                Console.WindowWidth = width;
            }

            // Real fullscreen mode *_*
#if REAL_FULLSCREEN
            IntPtr hConsole = GetStdHandle(-11);
            SetConsoleDisplayMode(hConsole, 0);
#endif

            // Set colors for the logo printer
            LogoPrinter.PrefixColor    = EConsoleColor.Blue;
            LogoPrinter.SufixColor     = EConsoleColor.Blue;
            LogoPrinter.TextColor      = EConsoleColor.Gray;
            LogoPrinter.CopyrightColor = EConsoleColor.Status;
            LogoPrinter.PrintLogo();

            // Output some infos about version and that
            Version ver = mAssembly.GetName().Version;
            ServerConsole.StatusLine("Rovolution Server - Version {0}.{1}.{2}.{3}", ver.Major, ver.Minor, ver.Build, ver.Revision);

            // Set error and exception handler (dll import)
            mConsoleEventHandler = new ConsoleEventHandler(OnConsoleEvent);
            SetConsoleCtrlHandler(mConsoleEventHandler, true);

            // Read server config
            mAppConf = new ApplicationSettings();
            mAppConf.ReadAll();

            // Mysql init
            Stopwatch watch = Stopwatch.StartNew();
            ServerConsole.Info("Connecting to SQL Server {0}...", mAppConf.Connection["DB Server"]);
            mDatabase = new RovolutionDatabase(Conf.Connection["DB Server"], int.Parse(Conf.Connection["DB Port"]), Conf.Connection["DB User"], Conf.Connection["DB Password"], Conf.Connection["DB Database"]);
            GodLesZ.Library.MySql.EMysqlConnectionError conRes = mDatabase.Prepare();
            if (conRes != GodLesZ.Library.MySql.EMysqlConnectionError.None)
            {
                ServerConsole.WriteLine(EConsoleColor.Error, " failed!");
                throw new Exception("Failed to open Database Connection! Type: " + conRes.ToString() + Environment.NewLine + (mDatabase.LastError != null ? ", Message: " + mDatabase.LastError.Message : ""));
            }
            watch.Stop();
            ServerConsole.WriteLine(EConsoleColor.Status, " done! Needed {0:F2} sec", watch.Elapsed.TotalSeconds);
            watch = null;

            // Load scripts (including events & that)
            ScriptDatabase.Initialize(@"Scripts\ScriptList.xml");

            ScriptCompiler.Compile(AppDomain.CurrentDomain.BaseDirectory + Path.Combine(Settings.Default.MainConfDir, Settings.Default.ScriptAssemblies), true, true);
            // Load assemblies for debug
            // TODO: we should load the assemblies for debugging
            //		 so VS could hijack them and we could debug them at runtime
            //		 also need the *.pdb files for this..

            // Packets handler
            PacketLoader.Initialize();

            // Initialize World events
            ScriptCompiler.Initialize("Rovolution.Server.Scripts");

            // Now we are able load our ressources
            World.Load();

            // Content init done, load Socket pool
            SocketPool.Create();
            mSocketConnector = new SocketConnector(mAppConf.Connection["Server IP"], mAppConf.Connection.GetInt("Server Port"));
            PacketHandlers.Initialize();

            // Start Timer Thread
            mTimerThread.Start();

            // Start timer for checking connections
            NetState.Initialize();


            // Initialize & load finished
            // Clean
            GC.Collect(GC.MaxGeneration, GCCollectionMode.Forced);


            // Trigger ServerStarted event
            Events.InvokeServerStarted();


            DateTime now, last = DateTime.Now;
            const int sampleInterval   = 100;
            const float ticksPerSecond = (float)(TimeSpan.TicksPerSecond * sampleInterval);
            int sample = 0;

            // The server loop
            // - looks for new sockets and process all packets
            while (mSignal.WaitOne())
            {
                // Refresh timer
                Timer.Slice();

                // Kick out old connections
                NetState.FlushAll();
                NetState.ProcessDisposedQueue();
                // Catch new connections
                mSocketConnector.Slice();

                if (Slice != null)
                {
                    Slice();
                }

                // just for Diagnostics
                if ((++sample % sampleInterval) == 0)
                {
                    now = DateTime.Now;
                    mCyclesPerSecond[mCycleIndex++ % mCyclesPerSecond.Length] = ticksPerSecond / (now.Ticks - last.Ticks);
                    last = now;
                }
            }
#if !DEBUG
        }

        catch (Exception e) {
            CurrentDomain_UnhandledException(null, new UnhandledExceptionEventArgs(e, true));
        }
#endif
        }
コード例 #13
0
    //Premade characters
    //public CharacterTemplate coppermouth = new CharacterTemplate(
    //	"Coppermouth", Color.green, Color.yellow, Color.white,
    //	new CharacterPoolProfile(10, 10, 8, 4, 10, 4, 5, 8, 4));

    //Tactic[] tacticsLookup = new Tactic[]{
    //	new Tactic("Basic Shot", TacticType.Action, new CharacterPoolProfile( 0, 0, 0, 0, 0, DamageType.None))
    //};

    void Awake()
    {
        _instance = this;
    }
        public void ParseFile(string _FileToProcess, bool _ParseFile)
        {
            DateTime startTime           = DateTime.Now;
            AsyncNotificationEventArgs e = new AsyncNotificationEventArgs(NotificationEventFunctionCode.ParseFile, 0, "", "", Color.Black);

            ScriptDatabase sdb = new ScriptDatabase();

            sdb.Initialize(_Output.StatusUpdateHandler, SMOScriptOptions.CreateFromConfig(), false);

            /****************************************************************/

            string            sqlText = CommonFunc.GetTextFromFile(_FileToProcess);
            CommentAreaHelper cah     = new CommentAreaHelper();
            long totalCharacterOffset = 0;
            bool bCommentedLine       = false;

            List <string> sqlCmds = new List <string>();

            if (_ParseFile)
            {
                StringBuilder sb = new StringBuilder();
                cah.FindCommentAreas(sqlText);
                foreach (string line in cah.Lines)
                {
                    if (line.Equals(Properties.Resources.Go, StringComparison.OrdinalIgnoreCase))
                    {
                        if (!cah.IsIndexInComments(totalCharacterOffset))
                        {
                            sqlCmds.Add(sb.ToString());
                            sb.Length = 0;
                        }
                        else
                        {
                            sb.Append(line + Environment.NewLine);
                        }
                    }
                    else
                    {
                        sb.Append(line + Environment.NewLine);
                    }
                    totalCharacterOffset += line.Length + cah.CrLf;
                }
            }
            else
            {
                sqlCmds.Add(sqlText);
            }

            int numCmds = sqlCmds.Count();

            if (numCmds == 0)
            {
                e.PercentComplete = 100;
                e.DisplayText     = "No data to process";
                _Output.StatusUpdateHandler(e);
                return;
            }

            int loopCtr = 0;

            e.DisplayColor    = Color.DarkBlue;
            e.DisplayText     = "";
            e.StatusMsg       = "Processing " + loopCtr.ToString() + " out of " + numCmds.ToString();
            e.PercentComplete = 0;
            _Output.StatusUpdateHandler(e);
            totalCharacterOffset = 0;

            foreach (string cmd in sqlCmds)
            {
                ++loopCtr;

                if (AsyncProcessingStatus.CancelProcessing)
                {
                    break;
                }
                if (cmd.Length == 0 || cmd.Equals(Environment.NewLine))
                {
                    continue;
                }

                foreach (CommentArea ca in cah.CommentAreas)
                {
                    if (ca.Start == totalCharacterOffset && ca.End == totalCharacterOffset + cmd.Length - cah.CrLf - 1) // note that the -1 is to put you at zero based counting
                    {
                        bCommentedLine = true;
                        break;
                    }
                    bCommentedLine = false;
                }
                totalCharacterOffset += cmd.Length + cah.CrLf;

                if (_ParseFile && !bCommentedLine && !(cmd.StartsWith("/*~") || cmd.StartsWith("~*/")))
                {
                    if (Regex.IsMatch(cmd, "(CREATE|ALTER)\\sPROCEDURE", RegexOptions.IgnoreCase))
                    {
                        sdb.ParseFileTSQLGo(cmd);
                    }
                    else if (Regex.IsMatch(cmd, "(CREATE|ALTER)\\sTABLE", RegexOptions.IgnoreCase))
                    {
                        sdb.ParseFileTable(cmd);
                    }
                    else if (Regex.IsMatch(cmd, "CREATE\\sXML\\sSCHEMA\\sCOLLECTION", RegexOptions.IgnoreCase))
                    {
                        sdb.ParseFileXMLSchemaCollections(cmd);
                    }
                    else if (Regex.IsMatch(cmd, "CREATE\\sTYPE", RegexOptions.IgnoreCase))
                    {
                        sdb.ParseFileUDT(cmd);
                    }
                    else if (Regex.IsMatch(cmd, "CREATE\\s[a-z\\s]*\\sINDEX", RegexOptions.IgnoreCase))
                    {
                        sdb.ParseFileIndex(cmd);
                    }
                    else if (Regex.IsMatch(cmd, "CREATE ROLE", RegexOptions.IgnoreCase))
                    {
                        sdb.ParseFileRole(cmd);
                    }
                    else
                    {
                        sdb.ParseFileTSQLGo(cmd);
                    }
                }
                else
                {
                    sdb.OutputSQLString(cmd, Color.Black);
                }

                if (loopCtr % 20 == 0)
                {
                    e.PercentComplete = (int)(((float)loopCtr / (float)numCmds) * 100.0);
                    e.DisplayColor    = Color.DarkBlue;
                    e.DisplayText     = "";
                    e.StatusMsg       = "Processing " + loopCtr.ToString() + " out of " + numCmds.ToString();
                    _Output.StatusUpdateHandler(e);
                }
            }

            if (AsyncProcessingStatus.CancelProcessing)
            {
                e.DisplayText = "Canceled processing ..." + Environment.NewLine;
                e.StatusMsg   = "Canceled!";
            }
            else
            {
                e.DisplayColor = Color.DarkCyan;
                if (_ParseFile)
                {
                    e.DisplayText = Properties.Resources.AnalysisComplete + Environment.NewLine;
                }
                else
                {
                    e.DisplayText = "File read and ready for processing.";
                }
                e.StatusMsg = "Done!";
            }
            e.PercentComplete = 100;
            _Output.StatusUpdateHandler(e);

            DateTime endTime = DateTime.Now;

            e.DisplayText = string.Format(
                "{1}Total processing time --> {0}",
                endTime.Subtract(startTime).ToString(),
                Properties.Resources.RemoveComment);
            _Output.StatusUpdateHandler(e);
        }