Esempio n. 1
0
        public async Task DelFissure([Remainder] string msg)
        {
            bool addCheck   = false;
            var  theAccount = DbStorage.GetGuildInfo(Context.Guild.Id);

            for (int i = 0; i < theAccount.Fissures.WantedFissures.Count; i++)
            {
                if (theAccount.Fissures.WantedFissures[i].ToLower().Contains(msg.ToLower()))
                {
                    theAccount.Fissures.WantedFissures.Remove(msg);
                    DbStorage.UpdateDb(Context.Guild.Id, theAccount);
                    addCheck = true;
                    break;
                }
            }

            if (addCheck == false)
            {
                await Context.Channel.SendMessageAsync($"{msg} not found in list!");

                return;
            }

            await Context.Channel.SendMessageAsync($"{msg} removed from list!");
        }
Esempio n. 2
0
        public static async Task CleanUpFissures()
        {
            var warjson     = GetWarframeInfo();
            var wardata     = Warframe.FromJson(warjson);
            var thefissures = wardata.ActiveMissions;

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

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

            foreach (var t in thefissures)
            {
                knownFis.Add(t.Id.Oid);
            }
            var accounts = DbStorage.GetDb();

            foreach (var guild in accounts)
            {
                foreach (var t in guild.Fissures.KnownFissures)
                {
                    if (!knownFis.Contains(t))
                    {
                        fisList.Add(t);
                    }
                }
                var account = DbStorage.GetGuildInfo(guild.Guild);

                foreach (var t in fisList)
                {
                    account.Fissures.KnownFissures.Remove(t);
                }
                DbStorage.UpdateDb(guild.Guild, guild);
            }
            await Task.Delay(1000);
        }
        public ActionResult Export(string exportType)
        {
            GridView gv = new GridView();


            if (exportType.Equals("1"))
            {
                var dataSource = DbStorage.GetAuctions(false);

                gv.DataSource = dataSource;
            }
            else
            {
                var dataSource = DbStorage.GetAuctions(true);

                gv.DataSource = dataSource;
            }

            gv.DataBind();
            Response.ClearContent();
            Response.Buffer = true;
            Response.AddHeader("content-disposition", "attachment; filename=Список аукционов.xls");
            Response.ContentType = "application/ms-excel";
            Response.Charset     = "";
            StringWriter   sw  = new StringWriter();
            HtmlTextWriter htw = new HtmlTextWriter(sw);

            gv.RenderControl(htw);
            Response.Output.Write(sw.ToString());
            Response.Flush();
            Response.End();

            return(RedirectToAction("Active"));
        }
Esempio n. 4
0
        public void NoteHistoryIsSaved()
        {
            var sample_notes = DbStorageTests.GetSampleNotes();

            using (var storage = new DbStorage(this.connFactory, this.testUser.Username, this.testUser.Manifest, use_history: true)) {
                foreach (var note in sample_notes)
                {
                    storage.SaveNote(note);
                }
            }

            // modify the notes
            using (var storage = new DbStorage(this.connFactory, this.testUser.Username, this.testUser.Manifest, use_history: true)) {
                foreach (var note in sample_notes)
                {
                    note.Title = "Random new title";
                    storage.SaveNote(note);
                }
            }

            // for each note there should exist a backup copy
            foreach (var note in sample_notes)
            {
                using (var db = connFactory.OpenDbConnection()) {
                    var archived_note = db.FirstOrDefault <DBArchivedNote> (n => n.Guid == note.Guid);
                    Assert.IsNotNull(archived_note);
                    Assert.AreNotEqual("Random new title", archived_note.Title);
                }
            }
        }
        protected override AjaxResult ProcessRequestInternal(HttpContext context)
        {
            var login = AuthModule.GetAuthLogin();

            AntiFlood.CheckFlood($"{context.Request.CurrentExecutionFilePath}:{login}");

            var flags = DbStorage.FindFlags(login);

            if (ElCapitan.GameEnded(flags))
            {
                throw new HttpException(403, "The End");
            }

            var user = DbStorage.FindUserByLogin(login);

            if (user == null)
            {
                throw new HttpException(403, "Access denied");
            }

            if (user.EndTime != DateTime.MinValue && user.EndTime < DateTime.UtcNow)
            {
                throw new HttpException(403, "The End");
            }

            var question = context.Request.Form["question"].TrimToNull();

            if (question == null)
            {
                throw new HttpException(400, "Message is empty");
            }

            if (question.Length > Settings.MaxMsgLength)
            {
                throw new HttpException(400, "Message too large");
            }

            Flag flag;

            File[]   files;
            DateTime timer;

            var answer = ElCapitan.GetAnswer(question, flags, out flag, out files, out timer);
            var msg    = new Msg {
                Text = answer, Time = DateTime.UtcNow, Type = MsgType.Answer
            };

            DbStorage.AddDialog(login, new Msg {
                Text = question, Time = DateTime.UtcNow, Type = MsgType.Question
            }, new[] { msg }, flag, files);

            return(new AjaxResult {
                Messages = new[] { msg }, Files = files, Score = flag != null ? 1 : 0, Timer = timer == DateTime.MinValue ? DateTime.MinValue : (user.EndTime != DateTime.MinValue ? user.EndTime : timer)
            });
        }
        protected override void OnLoad(EventArgs e)
        {
            Response.SetCacheServerAndPrivate(30, true);

            var scores = DbStorage.FindScores();

            Array.ForEach(scores, score => score.Value = (double)score.Stars / ElCapitan.FlagsCount);

            ScoresList.DataSource = scores.Where(score => !score.Name.StartsWith("observer_", StringComparison.InvariantCultureIgnoreCase));
            ScoresList.DataBind();
        }
        public ActionResult Create(Auction auction)
        {
            auction.orderDate   = DateTime.Now;
            auction.auctionDate = DateTime.Now.AddDays(-1);
            auction.status      = false;
            auction.winner      = "";

            DbStorage.CreateAuction(auction);

            return(View("Success"));
        }
 public ActionResult InsertGood(Good good)
 {
     if (Request.RequestType == "POST" && good != null)
     {
         DbStorage.GetSuppliers()[0].goods.Add(good);
         return(RedirectToAction("Index"));
     }
     else
     {
         return(View());
     }
 }
Esempio n. 9
0
        private static async Task CheckAlarms()
        {
            var thetime = Utilities.GetCetusTime();

            if (string.IsNullOrEmpty(thetime))
            {
                return;
            }
            long ignoreMe;

            if (!Int64.TryParse(thetime, out ignoreMe))
            {
                return;
            }
            var timecheck = Int64.Parse(thetime);

            timecheck = timecheck - 50;
            var json = string.Empty;

            var alarmUsers = DbStorage.GetAlarmDb();

            foreach (var t in alarmUsers)
            {
                if (t.AlarmOn)
                {
                    var curtime       = DateTime.Now;
                    var announcedtime = t.TimeAlerted;
                    var checktime     = curtime.Subtract(announcedtime).TotalMinutes;
                    if (timecheck < 0)
                    {
                        return;
                    }
                    if (checktime < 55)
                    {
                        continue; // check and see how long its been since last alerted ( in minutes )
                    }
                    if (timecheck <= t.AlarmDelay)
                    {
                        var user = t.DiscordId;
                        await Global.Client.GetUser(user)
                        .SendMessageAsync($"this is your **{timecheck}** minute warning till Cetus nighttime!");

                        // var dmChannel = dmPerson.GetOrCreateDMChannelAsync();
                        // await dmChannel.(alarmUsers[i].AlarmChannel,
                        //    $"<@{alarmUsers[i].DiscordId}> this is your **{timecheck}** minute warning till Cetus nighttime!");
                        //var theuser = UserAccounts.UserAccounts.GetAlarmUser(alarmUsers[i].DiscordId, alarmUsers[i].AlarmDelay);
                        var datime = DateTime.Now;
                        t.TimeAlerted = datime;
                        DbStorage.UpdateAlarmuser(t.DiscordId, t);
                    }
                }
            }
        }
Esempio n. 10
0
        public IActionResult Post()
        {
            string body;

            using (StreamReader sr = new StreamReader(Request.Body))
            {
                body = sr.ReadToEnd();
            }
            User user = JsonConvert.DeserializeObject <User>(body);

            DbStorage.Users().Add(user);
            return(Ok($"User with id {DbStorage.Users().Count} added!"));
        }
Esempio n. 11
0
        public async Task SetDelay([Remainder] string msg)
        {
            int delaytime = 5;

            if (Int32.TryParse(msg, out delaytime))
            {
                var delayaccount = DbStorage.GetGuildInfo(Context.Guild.Id);
                var checkedtime  = Int32.Parse(msg);
                delayaccount.AlertDelay = checkedtime;
                DbStorage.UpdateDb(Context.Guild.Id, delayaccount);
                await Context.Channel.SendMessageAsync($"Messages will be sent every **{msg}** minutes!");
            }
        }
Esempio n. 12
0
        public DatabaseNoteRepository(string username)
        {
            dbConnection = DbConfig.GetConnection();
            dbUser       = dbConnection.First <DBUser> (u => u.Username == username);

            storage = new DbStorage(dbUser);
            engine  = new Engine(storage);

            if (dbUser.Manifest == null || string.IsNullOrEmpty(dbUser.Manifest.ServerId))
            {
                // the user may not yet have synced
                dbUser.Manifest.ServerId = Guid.NewGuid().ToString();
            }
        }
        public ActionResult SaveCommertical(HttpPostedFileBase file)
        {
            var path = Server.MapPath("~/Resources/Trash");

            var fullPath = string.Format("{0}/{1}", path, file.FileName);

            if (System.IO.File.Exists(fullPath))
            {
                System.IO.File.Delete(fullPath);
            }
            file.SaveAs(fullPath);
            DbStorage.GetSuppliers()[0].commercialFile = "Resources/Trash/" + file.FileName;

            return(RedirectToAction("Index"));
        }
Esempio n. 14
0
 public ActionResult <User> GetUserById(int id)
 {
     try
     {
         return(DbStorage.Users()[id - 1]);
     }
     catch (ArgumentOutOfRangeException)
     {
         return(NotFound($"User with id {id} does not exist."));
     }
     catch (Exception ex)
     {
         return(BadRequest($"Please fix your request: {ex.Message}"));
     }
 }
Esempio n. 15
0
        public DatabaseNoteRepository(IDbConnectionFactory factory, DbStorageFactory storageFactory, IUser user) : base(factory)
        {
            this.storage = storageFactory.GetDbStorage(user);
            engine       = new Engine(storage);

            using (var db = connFactory.OpenDbConnection()) {
                this.dbUser = db.Select <DBUser> (u => u.Username == user.Username)[0];
            }

            if (dbUser.Manifest == null || string.IsNullOrEmpty(dbUser.Manifest.ServerId))
            {
                // the user may not yet have synced
                dbUser.Manifest.ServerId = Guid.NewGuid().ToString();
            }
        }
        public JsonResult GeneralStatisticChart()
        {
            var res = DbStorage.GetAuctions(true).Where(a => !string.IsNullOrEmpty(a.winner) && a.winner.Equals(DbStorage.GetSuppliers()[0].name));

            List <GeneralStatistic> pItems = new List <GeneralStatistic>();

            pItems.Add(new GeneralStatistic {
                Name = "Выигранные", Number = res.Count()
            });
            pItems.Add(new GeneralStatistic {
                Name = "Проигранные", Number = 0
            });

            return(Json(pItems, JsonRequestBehavior.AllowGet));
        }
Esempio n. 17
0
        public void CheckCreatorAndReader()
        {
            using (var context = PrepareContext())
            {
                CleanDatabase(context);
                var storageSaver = new DbStorage(context);
                var creator      = new ListItemCreator(storageSaver);

                creator.Add("a list item");

                var item = context.ToDoListItems.Single();
                Assert.False(item.IsDone);
                Assert.Equal("a list item", item.Name);
            }
        }
        public ActionResult GoodAndSupplier(string key)
        {
            var auction = DbStorage.GetAuctions(true).Where(a => a.lotName.ToLower().Contains(key.ToLower())).FirstOrDefault();

            if (auction != null)
            {
                var supplier = DbStorage.GetSupplier(auction.winner);

                if (supplier != null)
                {
                    return(View(supplier));
                }
            }
            return(View(new Supplier()));
        }
Esempio n. 19
0
 protected override void OnCreate(Bundle savedInstanceState)
 {
     base.OnCreate(savedInstanceState);
     SetContentView(Resource.Layout.Main);
     db2          = Manager.SharedInstance.GetDatabase("dbase");///test code
     messagesList = new List <MessageModel>();
     db           = new DbStorage();
     FindViews();
     HandleEvents();
     messagesList.Clear();
     // messagesList= db.GetItems();
     GetItems();
     mListView.Adapter = new MessagesAdapter(this, messagesList);
     StartSync();
 }
        public ActionResult UploadOrder(string auctionNumber, HttpPostedFileBase file)
        {
            var path     = HttpContext.Server.MapPath("~/Resources/Trash/");
            var fileName = file.FileName;

            if (System.IO.File.Exists(string.Format("{0}{1}", path, fileName)))
            {
                System.IO.File.Delete(string.Format("{0}{1}", path, fileName));
            }

            file.SaveAs(string.Format("{0}{1}", path, fileName));

            DbStorage.PutFileToAuction(auctionNumber, "/Resources/Trash/" + fileName);

            return(RedirectToAction("Details", new { auctionNumber = auctionNumber }));
        }
Esempio n. 21
0
        public void DateLocalIsCorrectlyStored()
        {
            DbStorage storage = new DbStorage(connFactory, testUser.Username, testUser.Manifest);

            var tomboy_note = new Note();

            tomboy_note.ChangeDate         = new DateTime(2000, 1, 1, 0, 0, 0, DateTimeKind.Local);
            tomboy_note.CreateDate         = tomboy_note.ChangeDate;
            tomboy_note.MetadataChangeDate = tomboy_note.ChangeDate;

            storage.SaveNote(tomboy_note);
            var stored_note = storage.GetNotes().Values.First();

            storage.Dispose();

            Assert.AreEqual(tomboy_note.ChangeDate, stored_note.ChangeDate.ToUniversalTime());
        }
Esempio n. 22
0
        public static string AddFissures(ulong guildId, string msg)
        {
            var guilddata = DbStorage.GetGuildInfo(guildId);

            var json    = File.ReadAllText("SystemLang/WFdata.json");
            var thedata = JsonConvert.DeserializeObject <Dictionary <string, string> >(json);

            if (guilddata.Fissures == null)
            {
                goto next;
            }


            for (int i = 0; i < guilddata.Fissures.WantedFissures.Count; ++i)
            {
                if (guilddata.Fissures.WantedFissures[i] == msg)
                {
                    return("not added");
                }
            }
next:
            foreach (var fissure in thedata)
            {
                if (msg.ToLower() == fissure.Value.ToLower())
                {
                    guilddata.Fissures.WantedFissures.Add(msg);

                    using (var db = new LiteDatabase(@"Data\guilds.db"))
                    {
                        var guilds  = db.GetCollection <UserAccount.GuildAccounts>("guilds");
                        var results = guilds.FindOne(x => x.Guild == guildId);
                        if (results == null)
                        {
                            guilds.Insert(guilddata);
                        }

                        guilds.Update(guilddata);
                    }

                    break;
                }
            }

            return("added");
        }
Esempio n. 23
0
        public ActionResult DoUpload(IFormFile file)
        {
            using (var stream = file.OpenReadStream())
            {
                var xs      = new XmlSerializer(typeof(StorageModel));
                var storage = (StorageModel)xs.Deserialize(stream);


                using (var db = new StorageDbContext())
                {
                    var dbs = new DbStorage()
                    {
                        Name        = storage.Name,
                        Capacity    = storage.Capacity,
                        Address     = storage.Address,
                        StorageType = storage.StorageType,
                    };
                    dbs.Items = new Collection <DbItem>();
                    foreach (var item in storage.Items)
                    {
                        dbs.Items.Add(new DbItem()
                        {
                            Name         = item.Name,
                            Price        = item.Price,
                            Units        = item.Units,
                            Manufacturer = item.Manufacturer
                        });
                    }
                    dbs.Workers = new Collection <DbWorkers>();
                    foreach (var worker in storage.Workers)
                    {
                        dbs.Workers.Add(new DbWorkers()
                        {
                            Name       = worker.Name,
                            Position   = worker.Position,
                            Experience = worker.Experience,
                        });
                    }
                    db.StorageFacilities.Add(dbs);
                    db.SaveChanges();
                }

                return(View(storage));
            }
        }
Esempio n. 24
0
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
        {
            //loggerFactory.AddConsole(Configuration.GetSection("Logging"));
            loggerFactory.AddJsonConsole();
            loggerFactory.AddDebug();

            app.UseWebSockets();

            //var storage = new InMemoryStorage();
            var storage       = new DbStorage("Host=127.0.0.1;Username=doublemazeuser;Password=mycoolpass;Database=doublemaze");
            var world         = new World(storage, loggerFactory);
            var outConnection = new OutputConnectionManager(x => world.Pipe.Post(new PlayerDisconnected(x)));

            app.Map("/test", (_app) => _app.UseMiddleware <WebSocketManagerMiddleware>(outConnection, world, storage, loggerFactory));

            app.UseStaticFiles();
            app.UseMvc();
        }
        public ActionResult GoodAndSuppliers(string key)
        {
            var             auctions  = DbStorage.GetAuctions(true).Where(a => a.lotName.ToLower().Contains(key.ToLower()));
            List <Supplier> suppliers = new List <Supplier>();
            Supplier        supplier  = new Supplier();

            foreach (var item in auctions)
            {
                if (suppliers.Where(s => s.name == item.winner).Count() < 1)
                {
                    supplier = DbStorage.GetSupplier(item.winner);
                    supplier.goods.Insert(0, DbStorage.GetGood(item.lotName));
                    suppliers.Add(supplier);
                }
            }

            return(View(suppliers));
        }
        public JsonResult GeneralStatisticChart()
        {
            var res = DbStorage.GetAuctions(true, true);

            List <GeneralStatistic> pItems = new List <GeneralStatistic>();

            pItems.Add(new GeneralStatistic {
                Name = "Ожидаемые", Number = res.Where(r => r.status == false).ToList().Count()
            });
            pItems.Add(new GeneralStatistic {
                Name = "Состоявшиеся", Number = res.Where(r => r.status == true).ToList().Count()
            });
            pItems.Add(new GeneralStatistic {
                Name = "Не состоявшиеся", Number = 0
            });

            return(Json(pItems, JsonRequestBehavior.AllowGet));
        }
Esempio n. 27
0
        private static async Task CheckGuildAlerts()
        {
            var guildAccounts = DbStorage.GetDb();

            foreach (var t in guildAccounts)
            {
                if (t.AlertsChannel == 0)
                {
                    return;
                }
                if (!t.CheckAlerts == false)
                {
                    ulong tempguild = t.Guild;
                    ulong tempchan  = t.AlertsChannel;
                    await CheckAlertRewards(tempguild, tempchan);
                }
            }
        }
        public async Task ListRewards()
        {
            ulong guildid     = Context.Guild.Id;
            var   embed       = new EmbedBuilder();
            var   theaccounts = DbStorage.GetGuildInfo(guildid);

            if (theaccounts.Rewards.WantedRewards.Count == 0)
            {
                return;
            }

            for (int i = 0; i < theaccounts.Rewards.WantedRewards.Count; i++)
            {
                embed.AddField($"Item {i + 1} : ", $"**{theaccounts.Rewards.WantedRewards[i]}**");
            }

            embed.WithTitle($"Current list of wanted items for **{Context.Guild.Name}");
            await Context.Channel.SendMessageAsync("", false, embed.Build());
        }
        protected override void OnLoad(EventArgs e)
        {
            Login = AuthModule.GetAuthLogin();

            var msgs  = DbStorage.FindMessages(Login);
            var files = DbStorage.FindFiles(Login);

            if (msgs.Length == 0)
            {
                var answer = new Msg {
                    Text = ElCapitan.StartMessage, Time = DateTime.UtcNow, Type = MsgType.Answer
                };
                DbStorage.AddDialog(Login, null, new[] { answer }, null, files = ElCapitan.StartFiles);
                msgs = new[] { answer };
            }

            Chat.Messages  = msgs;
            Explorer.Files = files;

            var score = DbStorage.FindScores(Login).FirstOrDefault();

            if (score != null)
            {
                Avatar = score.Avatar;
                Stars  = score.Stars;
            }

            var flags = DbStorage.FindFlags(Login);

            HasBombTimer = ElCapitan.HasBombTimer(flags);

            var user = DbStorage.FindUserByLogin(Login);

            if (user == null)
            {
                throw new HttpException(403, "Access denied");
            }

            EndTime = user.EndTime != DateTime.MinValue ? user.EndTime : Settings.BombTimerEnd;

            StartBombTimer.Visible = HasBombTimer;
        }
        public async Task ListWantedFissures()
        {
            ulong guildid     = Context.Guild.Id;
            var   embed       = new EmbedBuilder();
            var   theaccounts = DbStorage.GetGuildInfo(guildid);

            if (theaccounts.Fissures.WantedFissures.Count == 0)
            {
                return;
            }

            for (int i = 1; i < theaccounts.Fissures.WantedFissures.Count; i++)
            {
                embed.AddField($"Fissure {i} : ", $"**{theaccounts.Fissures.WantedFissures[i]}**");
            }
            embed.WithColor(new Color(188, 66, 244));
            embed.WithFooter("warframe alert ver 1.0", "http://3rdshifters.org/headerLogo.png");
            embed.WithTitle($"Current list of wanted fissures for **{Context.Guild.Name}**");
            await Context.Channel.SendMessageAsync("", false, embed.Build());
        }