public ScientistRepository()
 {
     if (_databaseModule == null)
     {
         _databaseModule = new DatabaseModule();
     }
 }
        public JsonResult UpdateScientist(Scientists _scientists)
        {
            var response = new UpdateScientistResponse()
            {
                Result = false
            };

            #region Update
            using (var session = DatabaseModule.OpenSession())
            {
                using (var tran = session.BeginTransaction())
                {
                    if (!string.IsNullOrEmpty(_scientists.FirstName.ToString().Trim()) && !string.IsNullOrEmpty(_scientists.LastName.ToString().Trim()))
                    {
                        session.Update(_scientists); //Update
                        tran.Commit();
                        response.Result        = true;
                        response.ResultMessage = "Updated succesfully"; // TODO : Make dynamic and localized
                    }
                }
            }
            return(Json(response));

            #endregion
        }
 public ScientistUnitOfWork()
 {
     if (_databaseModule == null)
     {
         _databaseModule = new DatabaseModule();
     }
 }
Ejemplo n.º 4
0
        private async void Tick(object state)
        {
            // Perform tasks every minute
            // Update status
            _client.Logger.LogInformation($"MechaSquidski | Updating status", DateTime.Now);
            var nextpayload = _activities.GetNextActivity();

            if (nextpayload.Status.Contains("NUMBER_GUILDS"))
            {
                nextpayload.Status = nextpayload.Status.Replace("NUMBER_GUILDS", _client.Guilds.Count.ToString());
            }
            await _client.UpdateStatusAsync(new DiscordActivity(nextpayload.Status, nextpayload.ActType));

            // Check if time is currently BACKUP_TIME_HOUR, if it is then
            var DateTimeComparison = DateTime.Now;

            if (DateTimeComparison.Hour == BACKUP_TIME_HOUR && DateTimeComparison.Minute == 0)
            {
                // If we've made it here, its time to automatically backup the database
                _client.Logger.LogInformation($"MechaSquidski | Starting automatic database backup...", DateTime.Now);
                await DatabaseModule.BackupDatabase();

                if (DatabaseModule.HitException != null)
                {
                    _client.Logger.LogWarning($"MechaSquidski | Database could not be backed up due to {DatabaseModule.HitException.Message}", DateTime.Now);
                }
                else
                {
                    _client.Logger.LogInformation($"MechaSquidski | Automatic database backup successful", DateTime.Now);
                }
            }

            // Schedule next timer
            _timer?.Change(TIMER_INTERVAL, Timeout.Infinite);
        }
Ejemplo n.º 5
0
        public async Task Impersonate(CommandContext ctx, [RemainingText] DiscordMember member)
        {
            if (ctx.Channel.Id == 572662006692315138)
            {
                await ctx.RespondAsync("This command is temporarily restricted from usage in this channel.");

                return;
            }
            await ctx.RespondAsync("Generating impersonation (this might take a second!)");

            var userStrings = await DatabaseModule.GetUserMessages(member.Id);

            if (DatabaseModule.HitException != null)
            {
                await ctx.RespondAsync($"An error occured: {DatabaseModule.HitException.Message}");

                return;
            }
            var ListArray = userStrings.ToArray();

            if (ListArray.Length < 1)
            {
                await ctx.RespondAsync("No data detected for that user!");

                return;
            }

            if (ListArray.Length < 100)
            {
                await ctx.RespondAsync($"{member.Username} is currently at **{ListArray.Length}%** of minimum data needed to impersonate.");

                return;
            }
            await ImpersonateMarkov(ctx, member, ListArray);
        }
Ejemplo n.º 6
0
        public async Task KetalQuote(CommandContext ctx, [Description("Which quote number you would like to get")] int quotenumber = 9999)
        {
            var thisketalquote        = new KetalQuote();
            var KetalQuotesObjectList = await DatabaseModule.GetKetalQuotes();

            if (quotenumber == 9999)
            {
                var rnd = new Random();
                int r   = rnd.Next(KetalQuotesObjectList.Count);
                thisketalquote = KetalQuotesObjectList[r];
            }
            else
            {
                thisketalquote = (from quotes in KetalQuotesObjectList where quotes.QuoteNumber == quotenumber select quotes).Single();
            }

            var embed = new DiscordEmbedBuilder
            {
                Color       = new DiscordColor(0xFF00FF),
                Description = thisketalquote.Quote,
                Title       = $"Ketal Quote #{thisketalquote.QuoteNumber}",
                Timestamp   = DateTime.UtcNow,
            };

            embed.WithFooter($"Ketal on {thisketalquote.Footer}");
            await ctx.RespondAsync(embed : embed.Build());
        }
Ejemplo n.º 7
0
        public JsonResult UpdateInvention(Inventions _invention)
        {
            var response = new UpdateInventionResponse()
            {
                Result = false
            };

            #region Update
            using (var session = DatabaseModule.OpenSession())
            {
                using (var tran = session.BeginTransaction())
                {
                    if (!string.IsNullOrEmpty(_invention.Description.ToString().Trim()) || _invention.ScientistID.ID > 0)
                    {
                        session.Update(_invention); //Update
                        tran.Commit();
                        response.Result        = true;
                        response.ResultMessage = "Updated succesfully"; // TODO : Make dynamic and localized
                    }
                }
            }
            return(Json(response));

            #endregion
        }
Ejemplo n.º 8
0
        public void TestSelectAllJobs()
        {
            String[] jobs = DatabaseModule.SelectAllJobs("Michael");
            Assert.AreEqual("job1", jobs[0]);
            Assert.AreEqual("job2", jobs[1]);
            Assert.AreEqual("job3", jobs[2]);
            Assert.AreEqual("job4", jobs[3]);


            String[] jobs2 = DatabaseModule.SelectAllJobs("Michael", new DateTime(2012, 09, 30));
            Assert.AreEqual("job1", jobs2[0]);
            Assert.AreEqual("job2", jobs2[1]);
            Assert.AreEqual("job3", jobs2[2]);
            Assert.AreEqual("job4", jobs2[3]);


            String[] jobs3 = DatabaseModule.SelectAllJobs("Michael", new DateTime(2012, 09, 30), new DateTime(2012, 10, 10));
            Assert.AreEqual("job1", jobs3[0]);
            Assert.AreEqual("job2", jobs3[1]);
            Assert.AreEqual("job3", jobs3[2]);
            Assert.AreEqual("job4", jobs3[3]);

            String[] jobs4 = DatabaseModule.SelectAllJobs("Michael", new DateTime(2012, 12, 10));
            Assert.AreEqual(0, jobs4.Length);
        }
Ejemplo n.º 9
0
        public void TestSelectAllJobs()
        {
            int[] jobs = DatabaseModule.SelectAllJobs("Michael");
            Assert.AreEqual(1, jobs[0]);
            Assert.AreEqual(2, jobs[1]);
            Assert.AreEqual(3, jobs[2]);
            Assert.AreEqual(4, jobs[3]);


            int[] jobs2 = DatabaseModule.SelectAllJobs("Michael", new DateTime(2012, 09, 30));
            Assert.AreEqual(1, jobs2[0]);
            Assert.AreEqual(2, jobs2[1]);
            Assert.AreEqual(3, jobs2[2]);
            Assert.AreEqual(4, jobs2[3]);


            int[] jobs3 = DatabaseModule.SelectAllJobs("Michael", new DateTime(2012, 09, 30), new DateTime(2012, 10, 10));
            Assert.AreEqual(1, jobs3[0]);
            Assert.AreEqual(2, jobs3[1]);
            Assert.AreEqual(3, jobs3[2]);
            Assert.AreEqual(4, jobs3[3]);

            int[] jobs4 = DatabaseModule.SelectAllJobs("Michael", new DateTime(2012, 12, 10));
            Assert.AreEqual(0, jobs4.Length);
        }
Ejemplo n.º 10
0
 public JsonResult AjaxMethod(int id)
 {
     using (var session = DatabaseModule.OpenSession())
     {
         var scientistResult = session.QueryOver <Scientists>().Where(x => x.ID == id).List();
         return(Json(scientistResult, JsonRequestBehavior.AllowGet));
     }
 }
Ejemplo n.º 11
0
 public JsonResult GetScientists()
 {
     using (var session = DatabaseModule.OpenSession())
     {
         var scientistResult = session.QueryOver <Scientists>().List();
         return(Json(scientistResult, JsonRequestBehavior.AllowGet));
     }
 }
Ejemplo n.º 12
0
        public ActionResult Index()
        {
            using (var session = DatabaseModule.OpenSession())
            {
                #region Select

                var inventionsResult = session.QueryOver <Inventions>()
                                       .Where(x => x.InventionID > 0).Fetch(l => l.ScientistID).Default.List();

                //var inventionsResult = session.QueryOver<Inventions>().List();
                var scientistResult = session.QueryOver <Scientists>().List();

                DataModel dataModel = new DataModel {
                    Invention = (List <Inventions>)inventionsResult, Scientists = (List <Scientists>)scientistResult
                };

                #endregion


                #region Update
                //using (var transaction = session.BeginTransaction())
                //{

                //    var record = session.QueryOver<Scientists>().Where(x => x.ID ==
                //         session.QueryOver<Scientists>().Select(
                //     Projections.Max<Scientists>(a => a.ID)).SingleOrDefault<int>()).List();

                //    List<Scientists> personel = (List<Scientists>)record;
                //    personel[0].LastName = "Gidici";
                //    personel[0].Title = "Software Developer";

                //    Scientists personelForUpdate = personel[0];

                //    session.Update(personelForUpdate);

                //    transaction.Commit();
                //}
                #endregion

                #region Delete
                //using (ITransaction transaction = session.BeginTransaction())
                //{
                //    //var record = session.QueryOver<Personel>().OrderBy(u => u.Id).Desc.SingleOrDefault();

                //    var record = session.QueryOver<Scientists>().Where(x => x.ID ==
                //        session.QueryOver<Scientists>().Select(
                //    Projections.Max<Scientists>(a => a.ID)).SingleOrDefault<int>()).List(); //Getting last Record

                //    List<Scientists> personel = (List<Scientists>)record;

                //    session.Delete(personel[0]);
                //    transaction.Commit();
                //}
                #endregion

                return(View(dataModel));
            }
        }
Ejemplo n.º 13
0
        public async Task AddServer(CommandContext ctx, string Id, string ServerId, string Description, string Address, string RconPassword, string FtpUser, string FtpPath, string FtpType, string Game)
        {
            var newserver = new Server {
                Id = Int32.Parse(Id), ServerId = ServerId, Description = Description, Address = Address, RconPassword = RconPassword, FtpUser = FtpUser, FtpPath = FtpPath, FtpType = FtpType, Game = Game
            };
            await DatabaseModule.AddTestServer(newserver);

            await ctx.RespondAsync($"Added {newserver.Id} to server list!");
        }
Ejemplo n.º 14
0
        public JsonResult GetInventions()
        {
            using (var session = DatabaseModule.OpenSession())
            {
                //var inventionsResult = session.QueryOver<Inventions>()
                // .Where(x => x.InventionID > 0).Fetch(l => l.ScientistID).Default.List();

                var inventionsResult = session.QueryOver <Inventions>().List();
                return(Json(inventionsResult, JsonRequestBehavior.AllowGet));
            }
        }
Ejemplo n.º 15
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.Configure <AppConfig>(Configuration.GetSection("AppConfig"));
            var DbConfiguration = Configuration.GetConnectionString("Dev");

            if (_currentEnvironment.IsDevelopment())
            {
                DbConfiguration = Configuration.GetConnectionString("Dev");
            }

            DatabaseModule.Register(services, DbConfiguration);
        }
Ejemplo n.º 16
0
        public async Task Recalculate(CommandContext ctx, int startFrom = 1)
        {
            if (ctx.Guild.Id != 572662006692315136)
            {
                await ctx.RespondAsync("Command is not usable within this guild");

                return;
            }
            if (!ctx.Member.Id.ToString().Contains("107967155928088576") && !ctx.Member.Id.ToString().Contains("66318815247466496"))
            {
                await ctx.RespondAsync("You are not authorized to use this");

                return;
            }

            await ctx.RespondAsync("Starting recalculation");

            Dictionary <string, string> steamIdToPlayerId = new Dictionary <string, string>();
            //Reset all player ELO first
            List <string> ids = await DatabaseModule.GetPlayerMatchmakingStatsIds();

            for (int i = 0; i < ids.Count; i++)
            {
                PlayerData player = await DatabaseModule.GetPlayerMatchmakingStats(ids[i]);

                player = new PlayerData()
                {
                    ID         = player.ID,
                    Name       = player.Name,
                    CurrentElo = 1000
                };

                steamIdToPlayerId.Add(await DatabaseModule.GetPlayerSteamIDFromDiscordID(player.ID), player.ID);

                await DatabaseModule.DeletePlayerStats(ids[i]);

                await DatabaseModule.AddPlayerMatchmakingStat(player);

                await ctx.RespondAsync("Reset player " + player.Name + "'s stats");
            }

            List <string> squidCoinIds = await DatabaseModule.GetPlayerSquidIds();

            for (int i = 0; i < squidCoinIds.Count; i++)
            {
                await DatabaseModule.DeleteSquidCoinPlayer(squidCoinIds[i]);
            }

            //Go through all the matches and recalculate their ELO
            await MatchmakingModule.RecalculateAllElo(ctx, steamIdToPlayerId, startFrom);
        }
Ejemplo n.º 17
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);

            // In production, the Angular files will be served from this directory
            services.AddSpaStaticFiles(configuration =>
            {
                configuration.RootPath = "ClientApp/dist";
            });

            DatabaseModule.Register(services, Configuration.GetConnectionString("DefaultConnection"), GetType().Assembly.FullName);
            ServiceModule.Register(services);

            services.AddHostedService <DownloadFeedHostedService>();
        }
Ejemplo n.º 18
0
        public ActionResult About()
        {
            using (var session = DatabaseModule.OpenSession())
            {
                #region Select
                var       inventionsResult = session.QueryOver <Inventions>().List();
                var       scientistResult  = session.QueryOver <Scientists>().List();
                DataModel dataModel        = new DataModel {
                    Invention = (List <Inventions>)inventionsResult, Scientists = (List <Scientists>)scientistResult
                };
                #endregion

                return(View(dataModel));
            }
        }
Ejemplo n.º 19
0
        public AuthorizationDbContext CreateDbContext(string[] args)
        {
            var envName = Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT");

            //IConfiguration configuration = new ConfigurationBuilder()
            //    .SetBasePath(Directory.GetCurrentDirectory())
            //    .AddJsonFile($"moduleName.{envName}.json", optional: false)
            //    .Build()
            //    .GetSection("Module");
            //var optionsBuilder = new DbContextOptionsBuilder();
            //optionsBuilder.Configure(configuration);
            var dbContextOptionsBuilder = DatabaseModule.CreateDbContextOptionsBuilder("Server=localhost;Database=pl_server_db;User Id=pl_server_user;Password=zaq1@WSX;");

            return(new AuthorizationDbContext(dbContextOptionsBuilder.Options));
        }
Ejemplo n.º 20
0
        private async Task <Task> Client_MessageCreated(DiscordClient s, MessageCreateEventArgs e)
        {
            if (e.Message.Content.StartsWith(">") || string.IsNullOrWhiteSpace(e.Message.Content) || e.Message.Content.StartsWith("+"))
            {
                return(Task.CompletedTask);
            }

            await DatabaseModule.AddNewUserMessage(e.Author.Id, e.Message.Content);

            if (DatabaseModule.HitException != null)
            {
                Console.WriteLine("FAILED");
            }

            return(Task.CompletedTask);
        }
Ejemplo n.º 21
0
        public ActionResult About(Inventions _dataModel)
        {
            #region Insert
            using (var session = DatabaseModule.OpenSession())
            {
                using (var tran = session.BeginTransaction())
                {
                    Inventions inventionsEntities = new Inventions {
                        InventionID = _dataModel.InventionID, ScientistID = _dataModel.ScientistID
                    };
                    session.Save(inventionsEntities);
                    tran.Commit();

                    return(View());
                }
            }
            #endregion
        }
        public ActionResult Save(Scientists dataModel)
        {
            #region Insert
            using (var session = DatabaseModule.OpenSession())
            {
                using (var tran = session.BeginTransaction())
                {
                    Scientists scientistEntities = new Scientists {
                        FirstName = dataModel.FirstName, LastName = dataModel.LastName, Title = dataModel.Title
                    };
                    session.Save(scientistEntities);
                    tran.Commit();

                    return(View());
                }
            }
            #endregion
        }
Ejemplo n.º 23
0
        public async Task GetServerList(CommandContext ctx)
        {
            var serverlist = await DatabaseModule.GetServerList();

            var embed = new DiscordEmbedBuilder
            {
                Color     = new DiscordColor(0x3277a8),
                Title     = "Server List",
                Timestamp = DateTime.UtcNow,
            };

            foreach (var server in serverlist)
            {
                embed.AddField(server.Address, $"`{server.Game}`\n{server.Description}");
            }

            await ctx.RespondAsync(embed : embed);
        }
Ejemplo n.º 24
0
        public void EntaoLancamento(decimal valorDoLancamento, string numeroDoProtocolo)
        {
            var numeroDoProtocoloEsperado = world[nameof(numeroDoProtocolo)].ToString();

            var table = DatabaseModule.ExecuteForTest($"SELECT * FROM ContaLancamentos WHERE ProtocoloId = {numeroDoProtocoloEsperado}");

            table.Rows.Should().HaveCountGreaterThan(0);

            var row = table.Rows[0];

            var saldoDaConta = Convert.ToDecimal(row["Valor"], CultureInfo.InvariantCulture);

            saldoDaConta.Should().Be(valorDoLancamento);

            numeroDoProtocolo.Should().Be(numeroDoProtocoloEsperado);

            mediatorMock.Verify(mediator => mediator.Publish(It.IsAny <EventoDeLancamentoFinanceiroProcessado>(), CancellationToken.None));
        }
Ejemplo n.º 25
0
        public async Task AddKetalQuote(CommandContext ctx)
        {
            // Todo: replace this with a generic "get largest number" function in the database once its done so we don't have to grab all the quotes
            var KetalQuotesObjectList = await DatabaseModule.GetKetalQuotes();

            var interactivity = ctx.Client.GetInteractivity();

            await ctx.RespondAsync("Please enter the quote (type 'exit' to exit the interactive session)");

            var quote = await interactivity.WaitForMessageAsync(kq => kq.Author == ctx.User, TimeSpan.FromSeconds(60));

            if (quote.Result.Content.ToLower() == "exit")
            {
                await ctx.RespondAsync("Exiting...");

                return;
            }

            await ctx.RespondAsync("Please enter the footer (type 'exit' to exit the interactive session)");

            var footer = await interactivity.WaitForMessageAsync(kq => kq.Author == ctx.User, TimeSpan.FromSeconds(60));

            if (quote.Result.Content.ToLower() == "exit")
            {
                await ctx.RespondAsync("Exiting...");

                return;
            }

            await ctx.RespondAsync("Building Quote...");

            var test = (from quotes in KetalQuotesObjectList select quotes.QuoteNumber).ToArray();

            var num = test.Max();

            var newQuote = new KetalQuote {
                Quote = quote.Result.Content, Footer = footer.Result.Content, QuoteNumber = num + 1
            };
            await DatabaseModule.AddKetalQuote(newQuote.QuoteNumber, newQuote.Quote, newQuote.Footer);

            await ctx.RespondAsync($"Quote successfully added as #{num+1}");
        }
Ejemplo n.º 26
0
        public async Task Register(CommandContext ctx, string steamId = "")
        {
            if (ctx.Guild.Id != 572662006692315136)
            {
                await ctx.RespondAsync("Command is not usable within this guild");

                return;
            }
            if (steamId == string.Empty)
            {
                await ctx.RespondAsync("You need to enter the id. Example: >register 76561198065593279 (Find your Steam ID here: https://steamidfinder.com/)");

                return;
            }

            bool failedToConvert = false;

            try
            {
                System.Convert.ToInt64(steamId);
            }
            catch (Exception e)
            {
                Console.WriteLine($"Failed to convert because {e.Message}.");
                failedToConvert = true;
            }
            if (steamId.Contains("STEAM") || steamId.Contains("[U") || failedToConvert)
            {
                await ctx.RespondAsync("Steam ID needs to be in the SteamID64 format! Example: >register 76561198065593279 (Find your Steam ID here: https://steamidfinder.com/)");

                return;
            }
            string existingId = await DatabaseModule.GetPlayerSteamIDFromDiscordID(ctx.Member.Id.ToString());

            if (existingId != string.Empty)
            {
                await DatabaseModule.DeletePlayerSteamID(ctx.Member.Id.ToString());
            }
            await DatabaseModule.AddPlayerSteamID(ctx.Member.Id.ToString(), steamId);

            await ctx.RespondAsync("Steam ID added");
        }
Ejemplo n.º 27
0
        public async Task GetMapList(CommandContext ctx)
        {
            if (ctx.Guild.Id != 572662006692315136)
            {
                await ctx.RespondAsync("Command is not usable within this guild");

                return;
            }
            var result = await DatabaseModule.GetAllMapNames();

            result.Sort();
            string responsestring = "List of maps available:\n```\n";

            foreach (var item in result)
            {
                responsestring += $"{item}, ";
            }
            responsestring += "\n```";
            await ctx.RespondAsync(responsestring);
        }
Ejemplo n.º 28
0
        public async Task SquidCoinCheck(CommandContext ctx, string discordId = "")
        {
            if (ctx.Guild.Id != 572662006692315136)
            {
                await ctx.RespondAsync("Command is not usable within this guild");

                return;
            }
            if (discordId == string.Empty)
            {
                discordId = ctx.Member.Id.ToString();
            }

            long coin = await DatabaseModule.GetPlayerSquidCoin(discordId);

            DiscordUser user = await ctx.Client.GetUserAsync(System.Convert.ToUInt64(discordId));

            string response = user.Username + " has " + coin + DiscordEmoji.FromName(ctx.Client, SQUIDCOIN);
            await ctx.RespondAsync(response);
        }
Ejemplo n.º 29
0
 public ActionResult Contact(Invention _invention)
 {
     #region Insert
     using (var session = DatabaseModule.OpenSession())
     {
         using (var tran = session.BeginTransaction())
         {
             if (_invention.Description != null || _invention.ScientistID != null)
             {
                 Inventions inventions = new Inventions {
                     ScientistID = _invention.ScientistID, Description = _invention.Description.ToString()
                 };
                 session.Save(inventions);
                 tran.Commit();
             }
             return(View());
         }
     }
     #endregion
 }
Ejemplo n.º 30
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            var xmlFile = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml";
            var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile);

            SwaggerServiceModule.Register(services, new SwaggerIntegrationHelper
            {
                Description = "Account Microservice Api",
                Email       = "*****@*****.**",
                JWTISSUER   = Configuration["AppConfig:JWTISSUER"],
                JWTKEY      = Configuration["AppConfig:JWTKEY"],
                Title       = "Api",
                Version     = "V1",
                xmlPath     = xmlPath
            });
            var DbConfiguration = Configuration.GetConnectionString("Dev");

            services.Configure <AppCustomConfig>(Configuration.GetSection("AppConfig"));
            DatabaseModule.Register(services, DbConfiguration);
            RepositoryModule.Register(services);
            ServiceModule.Register(services);
            services.AddControllers();
            services.AddApiVersioning(
                options =>
            {
                // reporting api versions will return the headers "api-supported-versions" and "api-deprecated-versions"
                options.ReportApiVersions = true;
            });
            services.AddVersionedApiExplorer(
                options =>
            {
                // add the versioned api explorer, which also adds IApiVersionDescriptionProvider service
                // note: the specified format code will format the version as "'v'major[.minor][-status]"
                options.GroupNameFormat = "'v'VVV";

                // note: this option is only necessary when versioning by url segment. the SubstitutionFormat
                // can also be used to control the format of the API version in route templates
                options.SubstituteApiVersionInUrl = true;
            });
        }