Beispiel #1
0
 public static void OnDBError(Exception e)
 {
     DatabaseUtil.OnDBError(e, "This will erase all Accounts!");
 }
Beispiel #2
0
 public void ThenIVerifyFieldsInDatabase(Table table)
 {
     DatabaseUtil.verifyDataField(table);
 }
        internal static void Run()
        {
            DatabaseUtil.ReleaseConsole();
            var server = RealmServ.Instance;

            if (!server.IsRunning)
            {
                Thread.Sleep(300);
                Console.WriteLine("Press any key to exit...");
                Console.ReadKey();
            }
            else
            {
                Console.WriteLine("Console ready. Type ? for help");

                DefaultTrigger = new DefaultCmdTrigger
                {
                    Args = new RealmServerCmdArgs(null, false, null)
                };

                while (RealmServ.Instance.IsRunning)
                {
                    string line;
                    try
                    {
                        while (!Console.KeyAvailable && RealmServ.Instance.IsRunning)
                        {
                            Thread.Sleep(100);
                        }
                        if (!RealmServ.Instance.IsRunning)
                        {
                            break;
                        }
                        line = Console.ReadLine();
                    }
                    catch
                    {
                        // console shutdown
                        break;
                    }
                    if (line == null || !RealmServ.Instance.IsRunning)
                    {
                        break;
                    }
                    try
                    {
                        if (DatabaseUtil.IsWaiting)
                        {
                            DatabaseUtil.Input.Write(line);
                        }
                        else
                        {
                            var text = new StringStream(line);
                            DefaultTrigger.Text = text;
                            if (!DefaultTrigger.InitTrigger())
                            {
                                continue;
                            }

                            var isSelect = text.ConsumeNext(RealmCommandHandler.SelectCommandPrefix);
                            if (isSelect)
                            {
                                var cmd = RealmCommandHandler.Instance.SelectCommand(text);
                                if (cmd != null)
                                {
                                    Console.WriteLine(@"Selected: {0}", cmd);
                                    DefaultTrigger.SelectedCommand = cmd;
                                }
                                else if (DefaultTrigger.SelectedCommand != null)
                                {
                                    Console.WriteLine(@"Cleared Command selection.");
                                    DefaultTrigger.SelectedCommand = null;
                                }
                            }
                            else
                            {
                                bool dbl;
                                RealmCommandHandler.ConsumeCommandPrefix(text, out dbl);
                                DefaultTrigger.Args.Double = dbl;

                                RealmCommandHandler.Instance.ExecuteInContext(DefaultTrigger,
                                                                              OnExecuted,
                                                                              OnFail);
                            }
                        }
                    }
                    catch (Exception e)
                    {
                        LogUtil.ErrorException(e, false, "Failed to execute Command.");
                    }
                }
            }
        }
Beispiel #4
0
        private Globals()
        {
            // 添加两个提取方式组
            this.MainActGroup.Add(new ActGroup());
            this.MainActGroup.Add(new ActGroup());

            //
            // 加载所有提取方式
            //
            string strConnection = ConfigurationManager.ConnectionStrings["mdb_phone"].ToString();
            string strQuery      = "select * from edec_act_type";

            DataTable dt = DatabaseUtil.Query(strQuery, strConnection);

            if (dt.Rows.Count > 0)
            {
                foreach (DataRow tmpdr in dt.Rows)
                {
                    Act newAct = new Act()
                    {
                        Id   = int.Parse(tmpdr["ACT_ID"].ToString()),
                        Name = tmpdr["ACT_Name"].ToString()
                    };

                    //
                    // 添加提取方式
                    //

                    // 逻辑提取
                    if (newAct.Id == 101)
                    {
                        newAct.listExtractType.Add(new ActExtractType("机身系统信息"));
                        newAct.listExtractType.Add(new ActExtractType("机身电话簿"));
                        newAct.listExtractType.Add(new ActExtractType("机身通话记录"));
                        newAct.listExtractType.Add(new ActExtractType("机身短信息"));
                        newAct.listExtractType.Add(new ActExtractType("机身app列表"));
                    }
                    // 文件提取
                    else if (newAct.Id == 102)
                    {
                        newAct.listExtractType.Add(new ActExtractType("图片照片"));
                        newAct.listExtractType.Add(new ActExtractType("音频文件"));
                        newAct.listExtractType.Add(new ActExtractType("视频文件"));
                        newAct.listExtractType.Add(new ActExtractType("全部文件"));
                    }
                    // ADB备份
                    else if (newAct.Id == 103)
                    {
                        newAct.listExtractType.Add(new ActExtractType("备份全部"));
                        newAct.listExtractType.Add(new ActExtractType("微信降级"));
                        newAct.listExtractType.Add(new ActExtractType("QQ降级"));
                    }
                    // 手机系统备份
                    else if (newAct.Id == 104)
                    {
                        newAct.listExtractType.Add(new ActExtractType("华为"));
                        newAct.listExtractType.Add(new ActExtractType("小米"));
                        newAct.listExtractType.Add(new ActExtractType("oppo"));
                        newAct.listExtractType.Add(new ActExtractType("vivo"));
                        newAct.listExtractType.Add(new ActExtractType("联想"));
                    }
                    // Root提取, Recovery提取
                    else if (newAct.Id == 105 || newAct.Id == 106)
                    {
                        newAct.listExtractType.Add(new ActExtractType("镜像提取"));
                        newAct.listExtractType.Add(new ActExtractType("微信及其数据目录"));
                        newAct.listExtractType.Add(new ActExtractType("QQ及其数据目录"));
                        newAct.listExtractType.Add(new ActExtractType("选中目录"));
                    }

                    // 添加到提取方式组
                    if (newAct.Id < 200)
                    {
                        this.MainActGroup[0].Acts.Add(newAct);
                    }
                    else
                    {
                        this.MainActGroup[1].Acts.Add(newAct);
                    }
                }
            }
        }
Beispiel #5
0
 public void GivenIExecuteSelectQuery(string Query)
 {
     parameter.Add("EmpName", "amit");
     DatabaseUtil.executeQuery(Query);
 }
 protected void Application_EndRequest(Object sender, EventArgs e)
 {
     DatabaseUtil.CloseConnector();
 }
        private ClientVersionContext GetNewContext()
        {
            var opts = DatabaseUtil.GetContextOptions <ClientVersionContext>(Config);

            return(new ClientVersionContext(opts));
        }
Beispiel #8
0
        /// <summary>
        ///     Used to confirm if a user wants to submit their playtest request, or make further changes.
        /// </summary>
        /// <returns></returns>
        private async Task ConfirmRequest()
        {
            while (true)
            {
                var isValid = false;
                var index   = -1;
                await Display(
                    "Type the ID of the field you want to edit or type `Submit` to submit your playtest request.");

                _userMessage = await _interactive.NextMessageAsync(_context);

                if (_userMessage == null ||
                    _userMessage.Content.Equals("exit", StringComparison.OrdinalIgnoreCase))
                {
                    await CancelRequest();

                    return;
                }

                if (_userMessage.Content.Equals("submit", StringComparison.OrdinalIgnoreCase))
                {
                    if (_testRequest.Preferredserver != "No preference" && !_testRequest.Game.Equals(
                            DatabaseUtil.GetTestServer(_testRequest.Preferredserver).Game,
                            StringComparison.OrdinalIgnoreCase))
                    {
                        index   = 11;
                        isValid = true;
                    }
                    else
                    {
                        break;
                    }
                }

                if (!isValid)
                {
                    isValid = int.TryParse(_userMessage.Content, out index);
                }

                if (isValid && index >= 0 && index <= _arrayValues.Length)
                {
                    var valid = false;
                    await Display(_wizardText[index]);

                    while (!valid)
                    {
                        _userMessage = await _interactive.NextMessageAsync(_context);

                        valid = await ParseTestInformation(_arrayValues[index], _userMessage.Content);

                        if (_userMessage == null ||
                            _userMessage.Content.Equals("exit", StringComparison.OrdinalIgnoreCase))
                        {
                            await CancelRequest();

                            return;
                        }
                    }
                }
            }

            //Avoid rate limiting
            await Task.Delay(1000);

            //Attempt to store request in the DB
            if (DatabaseUtil.AddPlaytestRequests(_testRequest))
            {
                await _instructionsMessage.ModifyAsync(x =>
                                                       x.Content =
                                                       $"Request Submitted! If you have any feedback or suggestions of the scheduling process, please send {_dataService.AlertUser} a message!");

                await _embedMessage.ModifyAsync(x => x.Embed = RebuildEmbed().WithColor(240, 240, 240).Build());

                //Give them the quick request if they want to re-test.
                try
                {
                    //Try DM
                    await _context.User.SendMessageAsync(
                        $"Here is a quick request for your test to quickly submit again if something happens with this test.```>Request {_testRequest}```");
                }
                catch
                {
                    //Just reply instead
                    await _context.Channel.SendMessageAsync(
                        $"Here is a quick request for your test to quickly submit again if something happens with this test.```>Request {_testRequest}```");
                }

                var schedule = await _playtestService.GetUpcomingEvents(true, false);

                var creators = "";
                foreach (var c in _testRequest.CreatorsDiscord)
                {
                    creators += _dataService.GetSocketGuildUser(c).Mention + " ";
                }

                //Set as alert user just in case.
                var testingAdminMention = _dataService.AlertUser.Mention;
                var mentionChannel      = _dataService.AdminBotsChannel;

                if (_testRequest.Game.Equals("csgo", StringComparison.OrdinalIgnoreCase))
                {
                    testingAdminMention = _dataService.CSGOPlaytestAdmin.Mention;
                    mentionChannel      = _dataService.CSGOTestingChannel;
                }
                else if (_testRequest.Game.Equals("tf2", StringComparison.OrdinalIgnoreCase))
                {
                    testingAdminMention = _dataService.TF2PlaytestAdmin.Mention;
                    mentionChannel      = _dataService.TF2TestingChannel;
                }

                await _dataService.AdminBotsChannel.SendMessageAsync(
                    $"{testingAdminMention} a new playtest request for `{_testRequest.MapName}` has been submitted by {creators.Trim()}!",
                    embed : schedule.Build());

                //Users to mention.
                string mentions = null;
                _testRequest.CreatorsDiscord.ForEach(x => mentions += $"{_dataService.GetSocketGuildUser(x).Mention} ");

                var embed = await _workshop.HandleWorkshopEmbeds(_context.Message,
                                                                 $"[Map Images]({_testRequest.ImgurAlbum}) | [Playtesting Information](https://www.tophattwaffle.com/playtesting)",
                                                                 _testRequest.TestType, GeneralUtil.GetWorkshopIdFromFqdn(_testRequest.WorkshopURL));

                if (embed != null)
                {
                    await mentionChannel.SendMessageAsync($"{mentions} has submitted a playtest request!",
                                                          embed : embed.Build());
                }
                else
                {
                }

                await _log.LogMessage($"{_context.User} has requested a playtest!\n{_testRequest}", color : LOG_COLOR);
            }
            else
            {
                //Failed adding to the database. Give them a quick request to attempt resubmission later.
                await _instructionsMessage.ModifyAsync(x =>
                                                       x.Content = "An error occured creating the playtest request!");

                await _embedMessage.ModifyAsync(x => x.Embed = RebuildEmbed().WithColor(25, 25, 25).Build());

                //Give them the quick request if they want to re-test.
                try
                {
                    //Try DM
                    await _context.User.SendMessageAsync(
                        $"Here is a quick request for your test to quickly submit again later.```>Request {_testRequest}```");
                }
                catch
                {
                    //Just reply instead
                    await _context.Channel.SendMessageAsync(
                        $"Here is a quick request for your test to quickly submit again later.```>Request {_testRequest}```");
                }
            }
        }
Beispiel #9
0
        /// <summary>
        ///     Rebuilds the playtest embed with the most up to date information.
        /// </summary>
        /// <returns>EmbedBuilder object containing all relevant information</returns>
        private EmbedBuilder RebuildEmbed()
        {
            var embed = new EmbedBuilder()
                        .WithFooter($"Current CT Time: {DateTime.Now}")
                        .WithColor(new Color(0x752424));

            if (_testRequest.TestDate != new DateTime())
            {
                embed.AddField("[0] Test Date:", _testRequest.TestDate, true)
                .WithColor(new Color(0xa53737));
            }

            if (_testRequest.Emails.Count > 0)
            {
                embed.AddField("[1] Emails", string.Join("\n", _testRequest.Emails), true)
                .WithColor(new Color(0x9a4237));
            }

            if (!string.IsNullOrWhiteSpace(_testRequest.Game))
            {
                embed.AddField("[2] Game", _testRequest.Game, true)
                .WithColor(new Color(0x8f4d37));
            }

            if (!string.IsNullOrWhiteSpace(_testRequest.MapName))
            {
                embed.AddField("[3] Map Name", _testRequest.MapName, true)
                .WithColor(new Color(0x8f4d37));
            }

            if (_testRequest.CreatorsDiscord.Count > 0)
            {
                embed.AddField("[4] Creators", string.Join("\n", _testRequest.CreatorsDiscord), true)
                .WithColor(new Color(0x845837));
            }

            if (!string.IsNullOrWhiteSpace(_testRequest.ImgurAlbum))
            {
                embed.AddField("[5] Imgur Album", _testRequest.ImgurAlbum)
                .WithColor(new Color(0x796337));
            }

            if (!string.IsNullOrWhiteSpace(_testRequest.WorkshopURL))
            {
                embed.AddField("[6] Workshop URL", _testRequest.WorkshopURL)
                .WithColor(new Color(0x6e6e37));
            }

            if (!string.IsNullOrWhiteSpace(_testRequest.TestType))
            {
                embed.AddField("[7] Type", _testRequest.TestType, true)
                .WithColor(new Color(0x637937));
            }

            if (!string.IsNullOrWhiteSpace(_testRequest.TestGoals))
            {
                embed.AddField("[8] Description", _testRequest.TestGoals)
                .WithColor(new Color(0x588437));
            }

            if (_testRequest.Spawns > 0)
            {
                embed.AddField("[9] Spawns", _testRequest.Spawns, true)
                .WithColor(new Color(0x4d8f37));
            }

            if (_testRequest.PreviousTestDate != new DateTime())
            {
                embed.AddField("[10] Previous Test:", _testRequest.PreviousTestDate, true)
                .WithColor(new Color(0x429a37));
            }

            if (!string.IsNullOrWhiteSpace(_testRequest.Preferredserver))
            {
                embed.AddField("[11] Server:", _testRequest.Preferredserver, true)
                .WithColor(new Color(0x37a537));
            }

            //Only get new playtest conflict information if we get a new date. But always include it
            if (!_dateChecked)
            {
                _otherRequests  = DatabaseUtil.GetAllPlaytestRequests();
                _scheduledTests = _calendar.CheckForScheduleConflict(_testRequest.TestDate).Result;
                _dateChecked    = true;
            }

            var conflicts = "";

            if (_otherRequests != null && _otherRequests.ToList().Count > 0)
            {
                foreach (var req in _otherRequests.Where(x => x.TestDate == _testRequest.TestDate))
                {
                    conflicts +=
                        $"**Map:** `{req.MapName}`\n**Test Date:** `{req.TestDate}`\n**Status:** `Test Requested`\n\n";
                }
            }

            var modConflicts = "";

            if (_scheduledTests != null && _scheduledTests.Items.Count > 0)
            {
                foreach (var item in _scheduledTests.Items)
                {
                    if (item.Summary.Contains("unavailable", StringComparison.OrdinalIgnoreCase))
                    {
                        modConflicts += $"`{item.Summary.Replace(" - Click for details", "")}`\n";
                    }
                    else
                    {
                        conflicts +=
                            $"**Map:** `{item.Summary}`\n**Test Date:** `{item.Start.DateTime}`\n**Status:** `Scheduled`\n\n";
                    }
                }
            }
            if (conflicts.Length > 1)
            {
                conflicts = conflicts.Trim() +
                            " ```Schedule conflicts have been detected. You may continue to schedule, but your chances of being scheduled are less likely.```";
                embed.AddField("Schedule Conflicts Detected", conflicts);
                embed.WithColor(255, 0, 0);
            }

            if (modConflicts.Length > 1)
            {
                modConflicts = modConflicts.Trim() +
                               " ```These moderators are unavailable to run this test. You may still continue scheduling, as another moderator may accept this test.```";
                embed.AddField("Moderators Unavailable", modConflicts);
            }

            return(embed);
        }
Beispiel #10
0
 /// <summary>
 /// Check if the database connection is valid.
 /// </summary>
 /// <returns></returns>
 public bool TestDatabaseConnection()
 {
     return(DatabaseUtil.TestDatabaseConnection());
 }
Beispiel #11
0
        /// <summary>
        ///     Allows moderator to update or delete a playtest request. If confirmed, the event is added to the calendar.
        /// </summary>
        /// <returns></returns>
        private async Task ConfirmSchedule()
        {
            while (true)
            {
                //Variables used later.
                var index   = -1;
                var isValid = false;

                await Display(
                    "Type the ID of the field you want to edit or type `Schedule` to schedule the playtest.\n" +
                    "Type `delete` to delete this request completely.\n" +
                    "Type `save` to save the request and exit.");

                //User's input
                _userMessage = await _interactive.NextMessageAsync(_context);

                //Exiting
                if (_userMessage == null ||
                    _userMessage.Content.Equals("exit", StringComparison.OrdinalIgnoreCase))
                {
                    await CancelRequest();

                    return;
                }

                //We want to schedule the event
                if (_userMessage.Content.Equals("schedule", StringComparison.OrdinalIgnoreCase))
                {
                    //Server cannot be none when scheduling. Require it to be valid.
                    if (_testRequest.Preferredserver == "No preference")
                    {
                        index   = 11;
                        isValid = true;
                    }
                    else
                    {
                        break;
                    }
                }

                if (_userMessage.Content.Equals("save", StringComparison.OrdinalIgnoreCase))
                {
                    var saveResult = DatabaseUtil.UpdatePlaytestRequests(_testRequest);
                    var saveEmbed  = RebuildEmbed();
                    if (saveResult)
                    {
                        saveEmbed.WithColor(55, 55, 165);
                        await _instructionsMessage.ModifyAsync(x => x.Content = "Request saved!");

                        await _embedMessage.ModifyAsync(x => x.Embed = saveEmbed.Build());
                    }
                    else
                    {
                        saveEmbed.WithColor(165, 55, 55);
                        await _instructionsMessage.ModifyAsync(x =>
                                                               x.Content = "There was an issue saving the request");

                        await _embedMessage.ModifyAsync(x => x.Embed = saveEmbed.Build());
                    }

                    return;
                }

                //Deleting test
                if (_userMessage.Content.Equals("delete", StringComparison.OrdinalIgnoreCase))
                {
                    DatabaseUtil.RemovePlaytestRequest(_testRequest);
                    await _embedMessage.ModifyAsync(x => x.Embed = RebuildEmbed().WithColor(25, 25, 25).Build());

                    await _instructionsMessage.ModifyAsync(x => x.Content = "Request Deleted!");

                    await _userMessage.DeleteAsync();

                    return;
                }

                //Get the relevant index from the user message only if we aren't getting here from a forced server schedule.
                if (!isValid)
                {
                    isValid = int.TryParse(_userMessage.Content, out index);
                }

                //Valid number, and between the valid indexes?
                if (isValid && index >= 0 && index <= _arrayValues.Length)
                {
                    //Validate based on the index.
                    await Display(_wizardText[index]);

                    _userMessage = await _interactive.NextMessageAsync(_context);

                    if (_userMessage == null ||
                        _userMessage.Content.Equals("exit", StringComparison.OrdinalIgnoreCase))
                    {
                        await CancelRequest();

                        return;
                    }

                    //Loop until valid, or allow an exit.
                    while (!await ParseTestInformation(_arrayValues[index], _userMessage.Content))
                    {
                        //Invalid, let's try again.
                        _userMessage = await _interactive.NextMessageAsync(_context);

                        if (_userMessage.Content.Equals("exit", StringComparison.OrdinalIgnoreCase))
                        {
                            break;
                        }

                        //No reply - fully exit
                        if (_userMessage == null)
                        {
                            await CancelRequest();

                            return;
                        }
                    }
                }
            }

            //Scheduling
            if (!_context.IsPrivate)
            {
                await _userMessage.DeleteAsync();
            }

            var finalEmbed = RebuildEmbed();

            var eventAdded = await _calendar.AddTestEvent(_testRequest, _context.User);

            //Try added to calendar, if true we can move forward with alerting user of the schedule.
            if (eventAdded)
            {
                //Remove the test from the DB.
                DatabaseUtil.RemovePlaytestRequest(_testRequest);

                //Update display
                finalEmbed.WithColor(new Color(240, 240, 240));
                await _instructionsMessage.ModifyAsync(x => x.Content = "Test Scheduled!");

                await _embedMessage.ModifyAsync(x => x.Embed = finalEmbed.Build());

                //Build the string to mention all creators on the event.
                var    mentionChannel = _dataService.AdminBotsChannel;
                string mentions       = null;
                _testRequest.CreatorsDiscord.ForEach(x => mentions += $"{_dataService.GetSocketGuildUser(x).Mention} ");

                if (_testRequest.Game.Equals("csgo", StringComparison.OrdinalIgnoreCase))
                {
                    mentionChannel = _dataService.CSGOTestingChannel;
                }
                else if (_testRequest.Game.Equals("tf2", StringComparison.OrdinalIgnoreCase))
                {
                    mentionChannel = _dataService.TF2TestingChannel;
                }

                await mentionChannel.SendMessageAsync(
                    $"{mentions.Trim()} your playtest has been scheduled for `{_testRequest.TestDate}` (CT Timezone)");

                await _log.LogMessage($"{_context.User} has scheduled a playtest!\n{_testRequest}", color : LOG_COLOR);

                //Workshop embed.
                var ws      = new Workshop(_dataService, _log);
                var wbEmbed = await ws.HandleWorkshopEmbeds(_context.Message,
                                                            $"[Map Images]({_testRequest.ImgurAlbum}) | [Playtesting Information](https://www.tophattwaffle.com/playtesting)",
                                                            _testRequest.TestType, GeneralUtil.GetWorkshopIdFromFqdn(_testRequest.WorkshopURL));

                if (wbEmbed != null)
                {
                    await mentionChannel.SendMessageAsync(embed : wbEmbed.Build());
                }

                return;
            }

            //Failed to add to calendar.
            finalEmbed.WithColor(new Color(20, 20, 20));
            await _embedMessage.ModifyAsync(x => x.Embed = finalEmbed.Build());

            await _instructionsMessage.ModifyAsync(x => x.Content =
                                                   "An error occured working with the Google APIs, consult the logs.\n" +
                                                   "The playtest event may still have been created.");
        }
        static void Main(string[] args)
        {
            var cfgDB = ConfigurationManager.ConnectionStrings["Olimpus_Config"].ToString();
            var s1    = DatabaseUtil.CreateFactory <Modulo>(cfgDB, true).OpenSession();
            //s1.Close();

            var t = s1.BeginTransaction();

            var modulo = new Modulo()
            {
                Nome = "Workflow", Descricao = "Workflow"
            };

            s1.Save(modulo);

            modulo = new Modulo()
            {
                Nome = "Participantes", Descricao = "Participantes"
            };
            s1.Save(modulo);

            modulo = new Modulo()
            {
                Nome = "Imóvel", Descricao = "Imóvel"
            };
            s1.Save(modulo);

            modulo = new Modulo()
            {
                Nome = "Veículo", Descricao = "Veículo"
            };
            s1.Save(modulo);

            modulo = new Modulo()
            {
                Nome = "Ocorrência", Descricao = "Ocorrência"
            };
            s1.Save(modulo);

            modulo = new Modulo()
            {
                Nome = "GED", Descricao = "GED"
            };
            s1.Save(modulo);

            modulo = new Modulo()
            {
                Nome = "Checklist", Descricao = "Checklist"
            };
            s1.Save(modulo);

            modulo = new Modulo()
            {
                Nome = "Parecer", Descricao = "Parecer"
            };
            s1.Save(modulo);

            modulo = new Modulo()
            {
                Nome = "Análise de Crédito", Descricao = "Análise de Crédito"
            };
            s1.Save(modulo);

            modulo = new Modulo()
            {
                Nome = "Análise Jurídica", Descricao = "Análise Jurídica"
            };
            s1.Save(modulo);

            modulo = new Modulo()
            {
                Nome = "Contrato", Descricao = "Contrato"
            };
            s1.Save(modulo);

            modulo = new Modulo()
            {
                Nome = "Histórico", Descricao = "Histórico"
            };
            s1.Save(modulo);

            modulo = new Modulo()
            {
                Nome = "Ficha de Aprovação", Descricao = "Ficha de Aprovação"
            };
            s1.Save(modulo);

            var menu = new Menu()
            {
                Nome        = "Configurações",
                Ordem       = 1,
                Classe      = null,
                EnderecoURL = null,
                Filhos      = new Func <List <Menu> >(delegate
                {
                    var result = new List <Menu>
                    {
                        new Menu()
                        {
                            Nome        = "Tabelas",
                            Ordem       = 1,
                            Classe      = "fa fa-table",
                            EnderecoURL = null,
                            Filhos      = new Func <List <Menu> >(delegate
                            {
                                var result2 = new List <Menu>
                                {
                                    new Menu()
                                    {
                                        Nome        = "Empresas",
                                        Ordem       = 1,
                                        Classe      = "fa fa-clipboard pull-left",
                                        EnderecoURL = "/Empresa/Index"
                                    },
                                    new Menu()
                                    {
                                        Nome        = "Usuários",
                                        Ordem       = 2,
                                        Classe      = "fa fa-clipboard pull-left",
                                        EnderecoURL = "/Usuario/Index"
                                    }
                                };
                                return(result2);
                            }).Invoke()
                        }
                    };
                    return(result);
                }).Invoke(),
                Pai = null
            };

            s1.Save(menu);

            var usuario = new Usuario()
            {
                Logon       = "admin",
                Nome        = "Administrador",
                Senha       = "8R8O4DqbOHE0er7v2SOB9w==",
                DadosGerais = new DadosGerais()
                {
                    DataAdmissao = DateTime.Now, Status = Status.Ativo, Email = null
                }
            };

            s1.Save(usuario);

            t.Commit();
            //cfgDB = ConfigurationManager.ConnectionStrings["Olimpus_Business"].ToString();
            //s1 = DatabaseUtil.CreateFactory<Participante>(cfgDB, true).OpenSession();
            //s1.Close();
        }
Beispiel #13
0
 public static void TearDown()
 {
     // make sure we get rid of the Characters again (since we create so many)
     DatabaseUtil.DropSchema();
     DatabaseUtil.CreateSchema();
 }
Beispiel #14
0
        public static async Task Main(string[] args)
        {
            Console.Title = "Bot Ido";

            //Always download users to make sure we can always get them
            var config = new DiscordSocketConfig
            {
                AlwaysDownloadUsers = true
            };

            var interactiveConfig = new InteractiveServiceConfig
            {
                DefaultTimeout = TimeSpan.FromMinutes(10)
            };

            // Dependency injection. All objects use constructor injection.
            _client   = new DiscordSocketClient(config);
            _commands = new CommandService();
            _services = new ServiceCollection()
                        .AddSingleton(_client)
                        .AddSingleton(_commands)
                        .AddSingleton <GuildHandler>()
                        .AddSingleton <CommandHandler>()
                        .AddSingleton <LogHandler>()
                        .AddSingleton <UserHandler>()
                        .AddSingleton <ScheduleHandler>()
                        .AddSingleton <DataService>()
                        .AddSingleton <Random>()
                        .AddSingleton <GoogleCalendar>()
                        .AddSingleton <YouTube>()
                        .AddSingleton <ReservationService>()
                        .AddSingleton <PlaytestService>()
                        .AddSingleton <RconService>()
                        .AddSingleton <SrcdsLogService>()
                        .AddSingleton <VoiceChannelHandler>()
                        .AddSingleton <ToolsService>()
                        .AddSingleton <IHelpService, HelpService>()
                        .AddSingleton(s => new InteractiveService(_client, interactiveConfig))
                        .BuildServiceProvider();

            _dataService = _services.GetRequiredService <DataService>();
            _log         = _services.GetRequiredService <LogHandler>();
            _services.GetRequiredService <GuildHandler>();
            _services.GetRequiredService <ScheduleHandler>();
            await _services.GetRequiredService <CommandHandler>().InstallCommandsAsync();

            _services.GetRequiredService <UserHandler>();
            _services.GetRequiredService <VoiceChannelHandler>();
            _services.GetRequiredService <SrcdsLogService>();
            _services.GetRequiredService <ToolsService>();

            //Google APIs
            _services.GetRequiredService <GoogleCalendar>();
            _services.GetRequiredService <YouTube>();

            // Remember to keep token private or to read it from an
            // external source! In this case, we are reading the token
            // from an environment variable. If you do not know how to set-up
            // environment variables, you may find more information on the
            // Internet or by using other methods such as reading from
            // a configuration.

            await _client.LoginAsync(TokenType.Bot,
                                     _services.GetRequiredService <DataService>().RSettings.ProgramSettings.BotToken);

            _dataService.SetLogHandler(_services.GetRequiredService <LogHandler>());

            //Set handlers for static classes
            DatabaseUtil.SetHandlers(_services.GetRequiredService <LogHandler>(),
                                     _services.GetRequiredService <DataService>());
            DownloadHandler.SetHandlers(_services.GetRequiredService <LogHandler>(),
                                        _services.GetRequiredService <DataService>());
            GeneralUtil.SetHandlers(_services.GetRequiredService <LogHandler>(),
                                    _services.GetRequiredService <DataService>(), _services.GetRequiredService <Random>());
            DemoParser.SetHandlers(_services.GetRequiredService <LogHandler>(),
                                   _services.GetRequiredService <DataService>());
            HeatmapGenerator.SetHandlers(_services.GetRequiredService <LogHandler>(),
                                         _services.GetRequiredService <DataService>());

            await _client.StartAsync();

            // Block this task until the program is closed.
            await Task.Delay(-1);
        }
        /// <summary>
        ///     Builds an embed that shows upcoming playtest events and events from the queue
        /// </summary>
        /// <param name="getSchedule">Get events from Queue</param>
        /// <param name="getCalendar">Get events from Calendar</param>
        /// <returns>Built embed with events</returns>
        public async Task <EmbedBuilder> GetUpcomingEvents(bool getSchedule, bool getCalendar)
        {
            var author = "Current ";
            var embed  = new EmbedBuilder().WithColor(new Color(55, 55, 165))
                         .WithFooter($"Current CT Time: {DateTime.Now}")
                         .WithDescription("[View Testing Calendar](http://playtesting.tophattwaffle.com) " +
                                          "| [View Testing Requirements](https://www.tophattwaffle.com/playtesting) " +
                                          "| View Queue with `>Schedule`");

            if (getSchedule)
            {
                author += "Playtest Requests";
                var testQueue = DatabaseUtil.GetAllPlaytestRequests().ToList();
                //No tests found - do nothing
                if (testQueue.Count == 0)
                {
                    embed.AddField("No playtest requests found!", "Submit your own with: `>request`");
                }
                else
                {
                    for (var i = 0; i < testQueue.Count; i++)
                    {
                        //Don't have more than 24
                        if (embed.Fields.Count >= 24)
                        {
                            break;
                        }

                        var info = "Creator(s): ";
                        foreach (var creator in testQueue[i].CreatorsDiscord)
                        {
                            var user = _dataService.GetSocketGuildUser(creator);
                            if (user != null)
                            {
                                info += $"`{user}`, ";
                            }
                            else
                            {
                                info += $"Could not get user `{creator}`, ";
                            }
                        }

                        info  = info.Trim(',', ' ');
                        info += $"\nGame: `{testQueue[i].Game}`" +
                                $"\nRequested Time: `{testQueue[i].TestDate:ddd, MMM d, HH:mm}`" +
                                $"\n[Map Images]({testQueue[i].ImgurAlbum}) - " +
                                $"[Workshop Link]({testQueue[i].WorkshopURL})\n";

                        embed.AddField($"[{i}] - {testQueue[i].MapName} - {testQueue[i].TestType}", info, true);
                    }
                }
            }

            if (getCalendar)
            {
                //If we added requests, toss "and" in there.
                author += getSchedule ? " and " : "";

                author += "Scheduled Playtests";
                var testEvents = await _calendar.GetNextMonthAsync(DateTime.Now);

                if (testEvents.Items.Count == 0)
                {
                    embed.AddField("No scheduled playtests found!", "Submit yours with: `>request`");
                }
                else
                {
                    foreach (var item in testEvents.Items)
                    {
                        if (embed.Fields.Count >= 24)
                        {
                            break;
                        }

                        //Get the moderator for each test
                        var strippedHtml = item.Description.Replace("<br>", "\n").Replace("&nbsp;", "");
                        strippedHtml = Regex.Replace(strippedHtml, "<.*?>", string.Empty);
                        var description = strippedHtml.Trim().Split('\n')
                                          .Select(line => line.Substring(line.IndexOf(':') + 1).Trim()).ToImmutableArray();
                        var mod = _dataService.GetSocketUser(description.ElementAtOrDefault(4));

                        embed.AddField($"{item.Summary} - {description.ElementAtOrDefault(3)}",
                                       $"`Scheduled`\nStart Time: `{item.Start.DateTime:ddd, MMM d, HH:mm}`\nEnd Time: `{item.End.DateTime:ddd, MMM d, HH:mm}`\nModerator: {mod.Mention}",
                                       true);
                    }
                }
            }

            if (embed.Fields.Count >= 24)
            {
                embed.AddField("Max Fields Added",
                               "Somehow there are more items than Discord embeds allow. Some items omitted.");
            }

            embed.WithAuthor(author);
            return(embed);
        }
Beispiel #16
0
        /// <summary>
        ///     Parses, and validates information before it is stored in a playtest request object.
        /// </summary>
        /// <param name="type">Type of data to parse</param>
        /// <param name="data">Data to parse</param>
        /// <returns>True if information is valid, false otherwise</returns>
        private async Task <bool> ParseTestInformation(string type, string data)
        {
            if (string.IsNullOrWhiteSpace(data))
            {
                data = "Nothing provided yet!";
            }

            switch (type.ToLower())
            {
            case "date":
                if (DateTime.TryParse(data, out var dt))
                {
                    if (dt < DateTime.Now)
                    {
                        await Display($"Date cannot be in the past.\nYou provided `{data}`\n" + _wizardText[0]);

                        return(false);
                    }

                    if (dt > DateTime.Now.AddMonths(2))
                    {
                        await Display(
                            $"You cannot schedule more than 2 months in advance.\nYou provided `{data}`\n" +
                            _wizardText[0]);

                        return(false);
                    }

                    _testRequest.TestDate = dt;
                    _dateChecked          = false;
                    return(true);
                }

                await Display($"Unable to parse DateTime.\nYou provided `{data}`\n" + _wizardText[0]);

                return(false);

            case "emails":
                var emails = data.Split(',').Select(x => x.Trim()).ToArray();

                //Empty list in case we are editing this.
                _testRequest.Emails.Clear();
                _testRequest.Emails.TrimExcess();

                foreach (var email in emails)
                {
                    if (new EmailAddressAttribute().IsValid(email))
                    {
                        _testRequest.Emails.Add(email);
                    }
                    else
                    {
                        await Display($"Unable to parse email addresses.\nYou provided `{data}`\n" +
                                      _wizardText[1]);

                        return(false);
                    }
                }

                return(true);

            case "game":
                if (data.Contains("csgo", StringComparison.OrdinalIgnoreCase))
                {
                    _testRequest.Game = "CSGO";
                    return(true);
                }

                if (data.Contains("tf2", StringComparison.OrdinalIgnoreCase))
                {
                    await Display("**We are not currently running TF2 playtests. Sorry for the inconvenience!\n" +
                                  "Type `exit` to abort the playtest request.**");

                    //_testRequest.Game = "TF2";
                    //return true;
                    return(false);
                }

                await Display($"Invalid game.\nYou provided `{data}`\n" +
                              _wizardText[2]);

                return(false);


            case "mapname":
                _testRequest.MapName = data;
                return(true);

            case "discord":
                var creators = data.Split(',').Select(x => x.Trim());

                //Empty list in case we are editing this.
                _testRequest.CreatorsDiscord.Clear();
                _testRequest.CreatorsDiscord.TrimExcess();

                foreach (var creator in creators)
                {
                    var user = _dataService.GetSocketGuildUser(creator);
                    if (user != null)
                    {
                        _testRequest.CreatorsDiscord.Add($"{user.Id}");
                    }
                    else
                    {
                        await Display("Unable to parse creators!\n" +
                                      $"You provided `{data}`\n" + _wizardText[4]);

                        return(false);
                    }
                }

                return(true);

            case "imgur":
                if (GeneralUtil.ValidateUri(data) == null)
                {
                    await Display("Invalid URL! Be sure to include `https://`\n" +
                                  $"You provided `{data}`\n" + _wizardText[5]);

                    return(false);
                }

                if (GeneralUtil.GetImgurAlbum(data) == null)
                {
                    await Display("Invalid Imgur Album!\n" +
                                  $"You provided `{data}`\n" + _wizardText[5]);

                    return(false);
                }

                _testRequest.ImgurAlbum = data;
                return(true);

            case "workshop":
                if (GeneralUtil.ValidateUri(data) == null)
                {
                    await Display("Invalid URL! Be sure to include `https://`\n" +
                                  $"You provided `{data}`\n" + _wizardText[5]);

                    return(false);
                }

                if (GeneralUtil.ValidateWorkshopURL(data))
                {
                    _testRequest.WorkshopURL = data;
                    return(true);
                }

                await Display("Invalid Steam Workshop URL!\n" +
                              $"You provided `{data}`\n" + _wizardText[6]);

                return(false);

            case "type":
                _testRequest.TestType = data.Contains("comp", StringComparison.OrdinalIgnoreCase)
                        ? "Competitive"
                        : "Casual";

                return(true);

            case "description":
                _testRequest.TestGoals = string.IsNullOrWhiteSpace(data) ? "No information provided" : data;
                return(true);

            case "spawns":
                if (int.TryParse(data, out var spawn))
                {
                    _testRequest.Spawns = spawn;

                    return(true);
                }

                await Display("Unable to parse number of spawns\n" +
                              $"You provided `{data}`\n" + _wizardText[9]);

                return(false);

            case "previoustest":
                _testRequest.PreviousTestDate = DateTime.TryParse(data, out var pt) ? pt : DateTime.UnixEpoch;

                return(true);

            case "server":
                if (data.Equals("none", StringComparison.OrdinalIgnoreCase) ||
                    data.Equals("no preference", StringComparison.OrdinalIgnoreCase))
                {
                    _testRequest.Preferredserver = "No preference";
                    return(true);
                }

                //Make sure the server requested supports the game.
                var server = DatabaseUtil.GetTestServer(data);
                if (server != null && server.Game.Equals(_testRequest.Game, StringComparison.OrdinalIgnoreCase))
                {
                    _testRequest.Preferredserver = server.Address;
                    return(true);
                }

                var servers = DatabaseUtil.GetAllTestServers(_testRequest.Game);

                await Display("Unable to to find a valid server\n" +
                              $"You provided `{data}`\n" +
                              "Please provide a valid server id. Type `None` for no preference. Possible servers are:\n" +
                              $"`{string.Join("\n", servers.Select(x => x.ServerId).ToArray())}`");

                return(false);

            default:
                await Display("Unknown test information.");

                _requireAbort = true;
                return(false);
            }
        }
        /// <summary>
        ///     Attempts to get a previously created announcement message based on values that were stored in the DB.
        ///     If the located message does not match the current event it will be deleted.
        ///     If nothing can be located, it does nothing.
        /// </summary>
        /// <returns></returns>
        public async Task TryAttachPreviousAnnounceMessage()
        {
            await TryAttach("csgo");
            await TryAttach("tf2");

            async Task TryAttach(string game)
            {
                var testEvent = _calendar.GetNextPlaytestEvent(game);

                if (testEvent == null)
                {
                    if (_dataService.RSettings.ProgramSettings.Debug)
                    {
                        _ = _log.LogMessage($"No test to reattach to for {game}.", false, color: LOG_COLOR);
                    }

                    return;
                }

                //Get the last known message
                var oldMessage = DatabaseUtil.GetAnnouncementMessage(testEvent.Game);

                //No message found in the DB, do nothing. Likely to happen when DB is new.
                if (oldMessage == null)
                {
                    if (_dataService.RSettings.ProgramSettings.Debug)
                    {
                        _ = _log.LogMessage($"No message found in DB to reattach to for {game}", false,
                                            color: LOG_COLOR);
                    }

                    return;
                }

                //Make sure a test is valid
                if (!testEvent.IsValid)
                {
                    if (_dataService.RSettings.ProgramSettings.Debug)
                    {
                        _ = _log.LogMessage($"No valid test found to post for {game}", false, color: LOG_COLOR);
                    }

                    return;
                }

                _ = _log.LogMessage("Attempting to get old announcement message\n" +
                                    $"ID: {oldMessage.AnnouncementId} with title {oldMessage.Title}",
                                    false, color: LOG_COLOR);


                var eventTitle = testEvent.Title;

                if (eventTitle != null && eventTitle.Equals(oldMessage.Title))
                {
                    try
                    {
                        testEvent.SetAnnouncementMessage(
                            await testEvent.AnnouncmentChannel.GetMessageAsync(oldMessage.AnnouncementId) as
                            IUserMessage);

                        if (testEvent.AnnouncementMessage != null)
                        {
                            _ = _log.LogMessage($"Retrieved old announcement for: {testEvent.Title}", false,
                                                color: LOG_COLOR);
                        }
                    }
                    catch
                    {
                        _ = _log.LogMessage("Unable to retrieve old announcement message!", false, color: LOG_COLOR);
                    }

                    //Store the titles along with the game key so we can check against them later.
                    if (_knownTests.ContainsKey(testEvent.Game))
                    {
                        _knownTests.Remove(testEvent.Game);
                    }

                    _knownTests.Add(testEvent.Game, testEvent.EventEditTime.Value);
                }
                else
                {
                    _ = _log.LogMessage("Messages do not match, deleting old message", false, color: LOG_COLOR);
                    try
                    {
                        await testEvent.AnnouncmentChannel.DeleteMessageAsync(oldMessage.AnnouncementId);

                        testEvent.SetAnnouncementMessage(null);
                    }
                    catch
                    {
                        _ = _log.LogMessage("Could not delete old message - it was likely deleted manually",
                                            false, color: LOG_COLOR);
                    }
                }
            }
        }
Beispiel #18
0
 public void BootStorePreviousPlaytestEvent()
 {
     _previousPlaytestEvent = DatabaseUtil.GetPreviousTest();
 }
        protected DemoderationContext GetNewContext()
        {
            var opts = DatabaseUtil.GetContextOptions <DemoderationContext>(Config);

            return(new DemoderationContext(opts));
        }
Beispiel #20
0
 /// <summary>
 /// Update database connection information into application config file
 /// </summary>
 private void btnUpdateDBConnection_Click(object sender, EventArgs e)
 {
     DatabaseUtil.Update("MSSQL", this.txtHost.Text, int.Parse(this.txtPort.Text), this.txtUser.Text, this.txtPassword.Text, this.txtDatabaseName.Text);
 }
        public bool SaveDataToDB(ProjectAllocationFramework.Statues.ProgressChangedEventHandler OnProgress, List <ProjectEntity> entityList)
        {
            // The default database service is determined through configuration
            // and passed to the method as a parameter that can be generated
            // automatically through injection when the application initializes.
            if (entityList == null || entityList.Count == 0)
            {
                return(true);
            }

            bool result = false;


            int count = entityList.Count;

            using (DbConnection conn = db.CreateConnection())
            {
                conn.Open();
                DbTransaction trans = conn.BeginTransaction();

                try
                {
                    int i = 1;
                    foreach (ProjectEntity entity in entityList)
                    {
                        string strProjectCode = ConvertUtil.ToString(entity.ProjectCode); //Project Code
                        string strProjectName = ConvertUtil.ToString(entity.ProjectName); //Project Name
                        string strUser        = ConvertUtil.ToString(entity.User);        //User
                        int    intAction      = entity.Action;                            //Action

                        string sql = string.Empty;
                        if (intAction == 2)
                        {
                            sql = "DELETE FROM [Project] WHERE [ProjectCode]=@ProjectCode";
                        }
                        else
                        {
                            intAction = 0;
                            sql       = "SELECT ProjectCode FROM [Project] WHERE ProjectCode=@ProjectCode";
                            DbCommand cmd = DatabaseUtil.GetCommand(db.GetSqlStringCommand(sql));
                            cmd.Parameters.Clear();
                            db.AddInParameter(cmd, "ProjectCode", DbType.String, strProjectCode);

                            using (IDataReader reader = db.ExecuteReader(cmd))
                            {
                                while (reader.Read())
                                {
                                    intAction = 1;
                                    break;
                                }
                            }

                            if (intAction == 0)
                            {
                                sql = "INSERT INTO [Project](ProjectCode, ProjectName,Create_dt,Create_User,Update_dt,Update_User) VALUES (@ProjectCode, @ProjectName,datetime(),@Create_User,datetime(),@Update_User)";
                            }
                            else if (intAction == 1)
                            {
                                sql = "UPDATE [Project] SET [ProjectName] =@ProjectName,[Update_dt] =datetime(),[Update_User] =@Update_User WHERE [ProjectCode]=@ProjectCode";
                            }
                        }

                        DbCommand userCommand = DatabaseUtil.GetCommand(db.GetSqlStringCommand(sql));
                        userCommand.Parameters.Clear();

                        db.AddInParameter(userCommand, "ProjectCode", DbType.String, strProjectCode);
                        db.AddInParameter(userCommand, "ProjectName", DbType.String, strProjectName);
                        db.AddInParameter(userCommand, "Create_User", DbType.String, strUser);
                        db.AddInParameter(userCommand, "Update_User", DbType.String, strUser);
                        db.AddInParameter(userCommand, "Action", DbType.Int32, intAction);

                        db.ExecuteNonQuery(userCommand, trans);

                        if (OnProgress != null)
                        {
                            string InfomationMessage = string.Format(ProjectAllocationResource.Message.Common_Master_Save_Info, i);
                            int    Percentage        = (int)(i * Constant.ProgressBarMaximum / count);

                            ProjectAllocationFramework.Statues.ProgressChangedEventArgs args = new ProjectAllocationFramework.Statues.ProgressChangedEventArgs(InfomationMessage, Percentage, null);
                            OnProgress(this, args);
                        }
                        //if success
                        entity.ReadOnly = true;
                        i++;
                    }

                    // Commit the transaction.
                    trans.Commit();

                    result = true;
                }
                catch
                {
                    // Roll back the transaction.
                    trans.Rollback();
                    throw;
                }
                conn.Close();

                return(result);
            }
        }
 public void Setup()
 {
     DatabaseUtil.DropDbIfCollationIncorrect();
     DatabaseUtil.CreateDbIfNotExists();
 }
Beispiel #23
0
 public void GivenIHaveClientDatabaseDetails(string DBName)
 {
     DatabaseUtil.setClient(DBName);
 }
Beispiel #24
0
 public CVEUpdater(DatabaseUtil databaseUtil, List <CVEItem> cveItems, LogWriter logWriter)
 {
     this.databaseUtil = databaseUtil;
     this.cveItems     = cveItems;
     this.logWriter    = logWriter;
 }
Beispiel #25
0
 public void ThenVerifyFromExecutedQuery(Table table)
 {
     DatabaseUtil.verifyDataInTable(table);
 }
Beispiel #26
0
        // 下载本地文件
        // TODO: 限制 nMaxLength 最大值
        // parameters:
        //      strStyle    "uploadedPartial" 表示操作都是针对已上载临时部分的。比如希望获得这个局部的长度,时间戳,等等
        //                  "taskID" 在进行 taskResult 和 taskStop 操作时用 taskID 来指定任务 ID
        //                  "beginTask" 表示本次启动了任务但并不等待任务完成。outputTimestamp 参数会返回 taskID(byte [] 用 UTF-8 Encoding 解释)
        //                  "getTaskResult" 获取任务是否结束的信息和两个返回参数值
        //                  "stopTask" 停止一个任务
        // return:
        //      -2      文件不存在
        //		-1      出错
        //		>= 0	成功,返回最大长度
        public long GetFile(
            string strFilePath,
            long lStart,
            int nLength,
            int nMaxLength,
            string strStyle,
            out byte[] destBuffer,
            out byte[] outputTimestamp,
            out string strError)
        {
            destBuffer      = null;
            outputTimestamp = null;
            strError        = "";

            bool isPartial = StringUtil.IsInList("uploadedPartial", strStyle);

            long lTotalLength = 0;

            strFilePath = strFilePath.Replace("/", "\\");

            FileInfo file = null;

            if (isPartial)
            {
                string strNewFileName = GetNewFileName(strFilePath);
                file = new FileInfo(strNewFileName);
                if (file.Exists == false)
                {
                    strError = " dp2Library 服务器不存在属于 '" + strFilePath + "' 的已上载局部文件";
                    return(-2);
                }
            }
            else
            {
                file = new FileInfo(strFilePath);
                if (file.Exists == false)
                {
                    strError = " dp2Library 服务器不存在物理路径为 '" + strFilePath + "' 的文件";
                    return(-2);
                }
            }
            file.Refresh();

            // 1.取时间戳
            if (StringUtil.IsInList("timestamp", strStyle) == true)
            {
                string strNewFileName = GetNewFileName(strFilePath);
                if (File.Exists(strNewFileName) == true)
                {
                    outputTimestamp = FileUtil.GetFileTimestamp(strNewFileName);
                }
                else
                {
                    outputTimestamp = FileUtil.GetFileTimestamp(strFilePath);
                }
            }

#if NO
            // 2.取元数据
            if (StringUtil.IsInList("metadata", strStyle) == true)
            {
                string strMetadataFileName = DatabaseUtil.GetMetadataFileName(strFilePath);
                if (File.Exists(strMetadataFileName) == true)
                {
                    strMetadata = FileUtil.File2StringE(strMetadataFileName);
                }
            }
#endif

            // 3.取range
            if (StringUtil.IsInList("range", strStyle) == true)
            {
                string strRangeFileName = GetRangeFileName(strFilePath);
                if (File.Exists(strRangeFileName) == true)
                {
                    string strText        = FileUtil.File2StringE(strRangeFileName);
                    string strTotalLength = "";
                    string strRange       = "";
                    StringUtil.ParseTwoPart(strText, "|", out strRange, out strTotalLength);
                }
            }

            // 4.长度
            lTotalLength = file.Length;
            // 这个长度有时候会有迟滞
            // https://stackoverflow.com/questions/7828132/getting-current-file-length-fileinfo-length-caching-and-stale-information

            // 2020/3/1
            // lTotalLength = GetFileLength(strFilePath);

            /*
             * // 2020/2/29
             * // 如果是正在获取当日的操作日志文件
             * if (PathUtil.IsEqual(strFilePath, this.OperLog.CurrentFileName))
             * {
             *  // 如果刚才通过 FileInfo.Length 获得的文件长度不准确
             *  if (lTotalLength < this.OperLog.GetCurrentStreamLength())
             *  {
             *      // this.OperLog.ReOpen();
             *      lTotalLength = this.OperLog.GetCurrentStreamLength();
             *  }
             * }
             */

            // 5.有data风格时,才会取数据
            if (StringUtil.IsInList("data", strStyle) == true)
            {
                if (nLength == 0)  // 取0长度
                {
                    destBuffer = new byte[0];
                    return(lTotalLength);
                }

                // 检查范围是否合法
                // return:
                //		-1  出错
                //		0   成功
                int nRet = ConvertUtil.GetRealLengthNew(lStart,
                                                        nLength,
                                                        lTotalLength,
                                                        nMaxLength,
                                                        out long lOutputLength,
                                                        out strError);
                if (nRet == -1)
                {
                    return(-1);
                }

                if (lOutputLength == 0)
                {
                    destBuffer = new byte[lOutputLength];
                }
                else
                {
#if NO
                    using (FileStream s = new FileStream(strFilePath,
                                                         FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
                    {
                        destBuffer = new byte[lOutputLength];

                        Debug.Assert(lStart >= 0, "");

                        s.Seek(lStart, SeekOrigin.Begin);
                        int readed = s.Read(destBuffer,
                                            0,
                                            (int)lOutputLength);
                        if (readed < lOutputLength)
                        {
                            // 2017/9/4
                            strError = "希望从文件偏移 " + lStart + " 开始读入 " + lOutputLength + " 字节,但只成功读入了 " + readed + " 字节";
                            return(-1);
                        }
                    }
#endif
                    StreamItem s = this._physicalFileCache.GetStream(strFilePath,
                                                                     FileMode.Open,
                                                                     FileAccess.Read,
                                                                     lStart > 10 * 1024);
                    try
                    {
                        destBuffer = new byte[lOutputLength];

                        Debug.Assert(lStart >= 0, "");
                        Debug.Assert(s.FileStream != null, "");

                        s.FileStream.FastSeek(lStart);
                        int readed = s.FileStream.Read(destBuffer,
                                                       0,
                                                       (int)lOutputLength);
                        if (readed < lOutputLength)
                        {
                            strError = "希望从文件偏移 " + lStart + " 开始读入 " + lOutputLength + " 字节,但只成功读入了 " + readed + " 字节";
                            return(-1);
                        }
                    }
                    finally
                    {
                        _physicalFileCache.ReturnStream(s);
                    }

                    /*
                     * // 2020/2/29
                     * // 顺序获取到最后一次,则清除缓存事项。这样可以确保后面再次获取 FileInfo 的时候能准确一些
                     * if (lStart + lOutputLength >= lTotalLength)
                     * {
                     *  _physicalFileCache.ClearItems(strFilePath);
                     * }
                     */
                }
            }

            // TODO: 测试一下获取 30G 尺寸的文件的 MD5 需要多少时间
            // 取 MD5
            if (StringUtil.IsInList("md5", strStyle) == true)
            {
                if (StringUtil.IsInList("beginTask", strStyle))
                {
                    var taskID = _md5Tasks.StartMd5Task(strFilePath);
                    outputTimestamp = Encoding.UTF8.GetBytes(taskID);
                }
                else if (StringUtil.IsInList("getTaskResult", strStyle) ||
                         StringUtil.IsInList("stopTask", strStyle))
                {
                    var taskID = StringUtil.GetParameterByPrefix(strStyle, "taskID");
                    if (string.IsNullOrEmpty(taskID))
                    {
                        strError = "没有提供 taskID";
                        return(-1);
                    }
                    var task = _md5Tasks.FindMd5Task(taskID);
                    if (task == null)
                    {
                        strError = $"没有找到 taskID 为 '{taskID}' 的 MD5 任务";
                        return(-1);
                    }
                    if (StringUtil.IsInList("getTaskResult", strStyle))
                    {
                        if (task.Result == null)
                        {
                            outputTimestamp = null;
                            return(0);   // 表示任务尚未完成
                        }
                        outputTimestamp = ByteArray.GetTimeStampByteArray(task.Result.ErrorCode);
                        _md5Tasks.RemoveMd5Task(taskID);
                        return(1);   // 表示任务已经完成
                    }

                    _md5Tasks.StopMd5Task(taskID);
                    return(0);
                }
                else
                {
                    outputTimestamp = FileUtil.GetFileMd5(strFilePath);
                }
            }

            return(lTotalLength);
        }
Beispiel #27
0
        private static void ExecuteSqlScriptAndOutputResult(RunnableScriptObject message, bool impersonatedContext)
        {
            var connectionString = message.BuildConnectionString(impersonatedContext);

            DatabaseUtil.RunArbitrarySqlScript(message.Contents, connectionString);
        }
Beispiel #28
0
 public void RemoveValue(string key)
 {
     DatabaseUtil.ExecuteNonQuery(
         "DELETE FROM KeyValueStore WHERE ExtensionId = @ExtensionId AND [Key] = @Key",
         CreateQueryParams(key));
 }
Beispiel #29
0
        // 下载本地文件
        // TODO: 限制 nMaxLength 最大值
        // return:
        //      -2      文件不存在
        //		-1      出错
        //		>= 0	成功,返回最大长度
        public long GetFile(
            string strFilePath,
            long lStart,
            int nLength,
            int nMaxLength,
            string strStyle,
            out byte[] destBuffer,
            out byte[] outputTimestamp,
            out string strError)
        {
            destBuffer      = null;
            outputTimestamp = null;
            strError        = "";

            long lTotalLength = 0;

            strFilePath = strFilePath.Replace("/", "\\");
            FileInfo file = new FileInfo(strFilePath);

            if (file.Exists == false)
            {
                strError = " dp2Library 服务器不存在物理路径为 '" + strFilePath + "' 的文件";
                return(-2);
            }

            // 1.取时间戳
            if (StringUtil.IsInList("timestamp", strStyle) == true)
            {
                string strNewFileName = GetNewFileName(strFilePath);
                if (File.Exists(strNewFileName) == true)
                {
                    outputTimestamp = FileUtil.GetFileTimestamp(strNewFileName);
                }
                else
                {
                    outputTimestamp = FileUtil.GetFileTimestamp(strFilePath);
                }
            }

#if NO
            // 2.取元数据
            if (StringUtil.IsInList("metadata", strStyle) == true)
            {
                string strMetadataFileName = DatabaseUtil.GetMetadataFileName(strFilePath);
                if (File.Exists(strMetadataFileName) == true)
                {
                    strMetadata = FileUtil.File2StringE(strMetadataFileName);
                }
            }
#endif

            // 3.取range
            if (StringUtil.IsInList("range", strStyle) == true)
            {
                string strRangeFileName = GetRangeFileName(strFilePath);
                if (File.Exists(strRangeFileName) == true)
                {
                    string strText        = FileUtil.File2StringE(strRangeFileName);
                    string strTotalLength = "";
                    string strRange       = "";
                    StringUtil.ParseTwoPart(strText, "|", out strRange, out strTotalLength);
                }
            }

            // 4.长度
            lTotalLength = file.Length;

            // 5.有data风格时,才会取数据
            if (StringUtil.IsInList("data", strStyle) == true)
            {
                if (nLength == 0)  // 取0长度
                {
                    destBuffer = new byte[0];
                    return(lTotalLength);
                }

                // 检查范围是否合法
                long lOutputLength;
                // return:
                //		-1  出错
                //		0   成功
                int nRet = ConvertUtil.GetRealLengthNew(lStart,
                                                        nLength,
                                                        lTotalLength,
                                                        nMaxLength,
                                                        out lOutputLength,
                                                        out strError);
                if (nRet == -1)
                {
                    return(-1);
                }

                if (lOutputLength == 0)
                {
                    destBuffer = new byte[lOutputLength];
                }
                else
                {
#if NO
                    using (FileStream s = new FileStream(strFilePath,
                                                         FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
                    {
                        destBuffer = new byte[lOutputLength];

                        Debug.Assert(lStart >= 0, "");

                        s.Seek(lStart, SeekOrigin.Begin);
                        int readed = s.Read(destBuffer,
                                            0,
                                            (int)lOutputLength);
                        if (readed < lOutputLength)
                        {
                            // 2017/9/4
                            strError = "希望从文件偏移 " + lStart + " 开始读入 " + lOutputLength + " 字节,但只成功读入了 " + readed + " 字节";
                            return(-1);
                        }
                    }
#endif
                    StreamItem s = this._physicalFileCache.GetStream(strFilePath,
                                                                     FileMode.Open, FileAccess.Read, lStart > 10 * 1024);
                    try
                    {
                        destBuffer = new byte[lOutputLength];

                        Debug.Assert(lStart >= 0, "");
                        Debug.Assert(s.FileStream != null, "");

                        s.FileStream.FastSeek(lStart);
                        int readed = s.FileStream.Read(destBuffer,
                                                       0,
                                                       (int)lOutputLength);
                        if (readed < lOutputLength)
                        {
                            strError = "希望从文件偏移 " + lStart + " 开始读入 " + lOutputLength + " 字节,但只成功读入了 " + readed + " 字节";
                            return(-1);
                        }
                    }
                    finally
                    {
                        _physicalFileCache.ReturnStream(s);
                    }
                }
            }

            // 取 MD5
            if (StringUtil.IsInList("md5", strStyle) == true)
            {
#if NO
                string strNewFileName = GetNewFileName(strFilePath);
                if (File.Exists(strNewFileName) == true)
                {
                    outputTimestamp = FileUtil.GetFileMd5(strNewFileName);
                }
                else
                {
                    outputTimestamp = FileUtil.GetFileMd5(strFilePath);
                }
#endif
                outputTimestamp = FileUtil.GetFileMd5(strFilePath);
            }

            return(lTotalLength);
        }
        protected AParentDefStatWidget(D def, DefType type)
        {
            this.Def  = def;
            this.type = type;

            this.autoApplySettingsInput = new BoolInputWidget <D>(
                def, "InGameDefEditor.AutoApplySettings".Translate(),
                d => IsAutoApply,
                (d, applyAuto) =>
            {
                if (applyAuto)
                {
                    if (!Defs.ApplyStatsAutoDefs.Add(d))
                    {
                        Log.Warning($"Failed to apply auto load to {Util.GetLabel(d)}");
                    }
                    else
                    {
                        AddDefsToAutoApply(true);
                    }
                }
                else
                {
                    if (!Defs.ApplyStatsAutoDefs.Remove(d))
                    {
                        Log.Warning($"Failed to remove auto load from {Util.GetLabel(d)}");
                    }
                    else
                    {
                        AddDefsToAutoApply(false);
                    }
                }
            });

            this.disableDefInput = new BoolInputWidget <D>(
                def, "InGameDefEditor.DisableDef".Translate(),
                d => IsDisabled,
                (d, isDisabled) =>
            {
                if (isDisabled)
                {
                    if (!Defs.DisabledDefs.Add(d))
                    {
                        Log.Warning($"Failed to disable {this.DisplayLabel}");
                    }
                    else
                    {
                        Defs.ApplyStatsAutoDefs.Remove(d);
                        DatabaseUtil.Remove(d);
                    }
                }
                else
                {
                    if (!Defs.DisabledDefs.Remove(d))
                    {
                        Log.Warning($"Failed to enable {this.DisplayLabel}");
                    }
                    else
                    {
                        DatabaseUtil.Add(d);
                    }
                }
            }, d =>
            {
                bool enabled = Current.Game == null || IsDisabled;
                return(new AInputWidget <D, bool> .ShouldDrawInputResult(enabled, (enabled) ? "" : "Cannot disabled defs while a game is not running."));
            });
        }