Пример #1
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="serviceRecord"></param>
        private void AddPlayerToIdentities(ServiceRecord serviceRecord)
        {
            using (var sqlStorage = new SqlStorage())
            {
                var gamertag     = serviceRecord.Gamertag;
                var gamertagSafe = GamerIdentity.EscapeGamerId(gamertag);

                var gamerIdentity = sqlStorage.GamerIdentities.FirstOrDefault(g => g.GamerIdSafe == gamertagSafe);
                if (gamerIdentity == null)
                {
                    gamerIdentity = new GamerIdentity
                    {
                        GamerId     = gamertag,
                        GamerIdSafe = gamertagSafe,
                        Type        = IdentityType.XblGamertag
                    };
                    sqlStorage.GamerIdentities.Add(gamerIdentity);
                    sqlStorage.SaveChanges();
                }

                var halo4Identity = sqlStorage.Halo4Identities.FirstOrDefault(h => h.GamerIdentity.Id == gamerIdentity.Id) ??
                                    new Halo4Identity();

                halo4Identity.GamerIdentity   = gamerIdentity;
                halo4Identity.ServiceTag      = serviceRecord.ServiceTag;
                halo4Identity.FavouriteWeapon = serviceRecord.FavoriteWeaponName;
                halo4Identity.KillDeathRatio  = serviceRecord.GameModes.First(m => m.Id == GameMode.WarGames).KdRatio ?? 1.0;
                halo4Identity.PlayerModelUrl  = GetPlayerModelUrl(gamertag, pose: "posed");
                halo4Identity.TopCsr          = serviceRecord.TopSkillRank != null ? serviceRecord.TopSkillRank.CompetitiveSkillRank ?? 0 : 0;
                halo4Identity.TotalKills      = serviceRecord.GameModes.Sum(m => m.TotalKills);

                sqlStorage.Halo4Identities.AddOrUpdate(halo4Identity);
                sqlStorage.SaveChanges();
            }
        }
Пример #2
0
        private static HttpResponseMessage AuthorizedRequest(String url, AuthType authType, HttpMethod requestType,
                                                             Dictionary <String, String> headers)
        {
            if (headers == null)
            {
                headers = new Dictionary <string, string>();
            }

            Authentication authentication;

            using (var sqlStorage = new SqlStorage())
            {
                authentication = sqlStorage.Authentications.FirstOrDefault(a => a.Type == AuthenticationType.Halo4);
            }

            switch (authType)
            {
            case AuthType.Spartan:
                headers.Add("X-343-Authorization-Spartan", authentication != null && authentication.IsValid ? authentication.Key : "f**k");                         // error catch
                break;

            default:
                throw new ArgumentException();
            }

            return(UnauthorizedRequest(url, requestType, headers));
        }
Пример #3
0
        public ActionResult Destroy()
        {
            using (var sqlStorage = new SqlStorage())
            {
                var sessionIdentifier = Request.Cookies["SessionIdentifier"];
                if (sessionIdentifier != null)
                {
                    var sessionGuid = Guid.Parse(sessionIdentifier.Value);
                    var session     = sqlStorage.BranchSessions.Include(s => s.BranchIdentity).FirstOrDefault(s => s.Identifier == sessionGuid);
                    if (session != null)
                    {
                        sqlStorage.BranchSessions.First(s => s.Id == session.Id).Revoked = true;
                        sqlStorage.SaveChanges();
                    }
                }

                var myCookie = new HttpCookie("SessionIdentifier", "girl comes up to me and says \"what you drive?\" and i said \"BUGATTI\"")
                {
                    Expires = DateTime.UtcNow.AddDays(-69d)
                };
                Response.Cookies.Add(myCookie);

                return(RedirectToRoute("Welcome"));
            }
        }
Пример #4
0
        public static BranchIdentity GetAuthenticatedIdentity()
        {
            var sessionIdentifier = HttpContext.Current.Request.Cookies["SessionIdentifier"];

            if (sessionIdentifier == null)
            {
                return(null);
            }

            using (var sqlStorage = new SqlStorage())
            {
                sqlStorage.Configuration.LazyLoadingEnabled = false;

                // Validate Session
                var sessionGuid = Guid.Parse(sessionIdentifier.Value);
                var session     = sqlStorage.BranchSessions
                                  .Include(s => s.BranchIdentity)
                                  .Include(s => s.BranchIdentity.BranchRole)
                                  .Include(s => s.BranchIdentity.GamerIdentity)
                                  .Include(s => s.BranchIdentity.GamerIdentity.ReachIdentities)
                                  .Include(s => s.BranchIdentity.GamerIdentity.Halo4Identities)
                                  .FirstOrDefault(s => s.Identifier == sessionGuid);
                if (session == null)
                {
                    return(null);
                }

                // Return Branch Identity
                var valid = session.IsValid();
                return(valid ? session.BranchIdentity : null);
            }
        }
Пример #5
0
        /// <summary>Initializes a new instance of the <see cref="SQLiteDatabase" /> class.</summary>
        /// <param name="storage">The storage engine.</param>
        /// <param name="name">The name of the database.</param>
        public SQLiteDatabase(SQLiteStorage storage, string name)
            : base(storage, name)
        {
            var fields = new List <FieldProperties>
            {
                new FieldProperties {
                    Index = 0, DataType = DataType.String, Name = "type"
                },
                new FieldProperties {
                    Index = 1, DataType = DataType.String, Name = "name"
                },
                new FieldProperties {
                    Index = 2, DataType = DataType.String, Name = "tbname"
                },
                new FieldProperties {
                    Index = 3, DataType = DataType.Int64, Name = "rootpage"
                },
                new FieldProperties {
                    Index = 4, DataType = DataType.String, Name = "sql"
                }
            };

            foreach (var field in fields)
            {
                field.NameAtDatabase = field.Name;
                field.TypeAtDatabase = field.DataType;
                field.Validate();
            }

            var expected = RowLayout.CreateUntyped(name, fields.ToArray());
            var schema   = SqlStorage.QuerySchema(Name, "sqlite_master");

            SqlStorage.CheckLayout(expected, schema);
        }
Пример #6
0
        public ActionResult Destroy()
        {
            using (var sqlStorage = new SqlStorage())
            {
                var sessionIdentifier = Request.Cookies["SessionIdentifier"];
                if (sessionIdentifier != null)
                {
                    var sessionGuid = Guid.Parse(sessionIdentifier.Value);
                    var session = sqlStorage.BranchSessions.Include(s => s.BranchIdentity).FirstOrDefault(s => s.Identifier == sessionGuid);
                    if (session != null)
                    {
                        sqlStorage.BranchSessions.First(s => s.Id == session.Id).Revoked = true;
                        sqlStorage.SaveChanges();
                    }
                }

                var myCookie = new HttpCookie("SessionIdentifier", "girl comes up to me and says \"what you drive?\" and i said \"BUGATTI\"")
                {
                    Expires = DateTime.UtcNow.AddDays(-69d)
                };
                Response.Cookies.Add(myCookie);

                return RedirectToRoute("Welcome");
            }
        }
Пример #7
0
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            var username = (filterContext.ActionParameters["slug"] ?? "").ToString().Trim().ToLower();

            using (var sqlStorage = new SqlStorage())
            {
                sqlStorage.Configuration.LazyLoadingEnabled = false;

                var branchIdentity = sqlStorage.BranchIdentities
                    .Include(i => i.BranchRole)
                    .Include(i => i.GamerIdentity)
                    .Include(i => i.BranchIdentitySessions)
                    .Include(i => i.GamerIdentity.Halo4Identities)
                    .Include(i => i.GamerIdentity.ReachIdentities)
                    .FirstOrDefault(i => i.Username.ToLower() == username.ToLower());

                if (branchIdentity != null)
                {
                    filterContext.ActionParameters["BranchIdentity"] = branchIdentity;
                    return;
                }
            }

            filterContext.Result = FlashMessage.RedirectAndFlash(filterContext.HttpContext.Response,
                new RedirectToRouteResult("Search",
                    new RouteValueDictionary { { "q", username } }),
                FlashMessage.FlashMessageType.Info, "Unknown Branch Identity",
                string.Format("The identity '{0}' does not exist.", username));
        }
Пример #8
0
        //
        // GET: /Search/?q=
        public ActionResult Index(string q)
        {
            if (String.IsNullOrEmpty(q))
            {
                return(RedirectToAction("Index", "Home"));
            }

            using (var sqlStorage = new SqlStorage())
            {
                GlobalStorage.H4Manager.GetPlayerServiceRecord(q, true);
                GlobalStorage.HReachManager.GetPlayerServiceRecord(q, true);

                var halo4Identities =
                    sqlStorage.Halo4Identities.Include(i => i.GamerIdentity)
                    .Where(h => h.GamerIdentity.GamerId.Contains(q))
                    .Take(6)
                    .ToList();

                var reachIdentnties =
                    sqlStorage.ReachIdentities.Include(i => i.GamerIdentity)
                    .Where(h => h.GamerIdentity.GamerId.Contains(q))
                    .Take(6)
                    .ToList();

                // le render le model le
                return(View(new SearchViewModel(q, halo4Identities, reachIdentnties)));
            }
        }
Пример #9
0
        public static BranchIdentity GetAuthenticatedIdentity()
        {
            var sessionIdentifier = HttpContext.Current.Request.Cookies["SessionIdentifier"];
            if (sessionIdentifier == null)
                return null;

            using (var sqlStorage = new SqlStorage())
            {
                sqlStorage.Configuration.LazyLoadingEnabled = false;

                // Validate Session
                var sessionGuid = Guid.Parse(sessionIdentifier.Value);
                var session = sqlStorage.BranchSessions
                    .Include(s => s.BranchIdentity)
                    .Include(s => s.BranchIdentity.BranchRole)
                    .Include(s => s.BranchIdentity.GamerIdentity)
                    .Include(s => s.BranchIdentity.GamerIdentity.ReachIdentities)
                    .Include(s => s.BranchIdentity.GamerIdentity.Halo4Identities)
                    .FirstOrDefault(s => s.Identifier == sessionGuid);
                if (session == null)
                    return null;

                // Return Branch Identity
                var valid = session.IsValid();
                return valid ? session.BranchIdentity : null;
            }
        }
Пример #10
0
        public static void Main(string[] args)
        {
            const string connectionString =
                "Server=ProductiveDeveloperCode.database.windows.net;Database=TelegramDB;User Id=ProductiveDeveloper;Password=fDx-Vbt-Lvr-7Vg;";

            SqlStorage sqlStorage = new SqlStorage(connectionString);

            InMemoryStorage inMemoryStorage = new InMemoryStorage();

            TelegramReceiver reciver        = new TelegramReceiver("984957183:AAECP59aHpYez0iBzmw_QBMb-sxMRgO5vpM");
            TelegramSender   telegramSender = new TelegramSender(reciver.botClient);
            Reminder         reminder       = new Reminder(telegramSender);


            BotDomain botDomain = new BotDomain(telegramSender, reciver, sqlStorage, inMemoryStorage, reminder);

            Console.WriteLine(reciver.GetHelloFromBot());
            reciver.Run();

            while (true)
            {
                Thread.Sleep(1800000);
                reminder.RemindersUpdate();
            }
        }
Пример #11
0
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            var username = (filterContext.ActionParameters["slug"] ?? "").ToString().Trim().ToLower();

            using (var sqlStorage = new SqlStorage())
            {
                sqlStorage.Configuration.LazyLoadingEnabled = false;

                var branchIdentity = sqlStorage.BranchIdentities
                                     .Include(i => i.BranchRole)
                                     .Include(i => i.GamerIdentity)
                                     .Include(i => i.BranchIdentitySessions)
                                     .Include(i => i.GamerIdentity.Halo4Identities)
                                     .Include(i => i.GamerIdentity.ReachIdentities)
                                     .FirstOrDefault(i => i.Username.ToLower() == username.ToLower());

                if (branchIdentity != null)
                {
                    filterContext.ActionParameters["BranchIdentity"] = branchIdentity;
                    return;
                }
            }

            filterContext.Result = FlashMessage.RedirectAndFlash(filterContext.HttpContext.Response,
                                                                 new RedirectToRouteResult("Search",
                                                                                           new RouteValueDictionary {
                { "q", username }
            }),
                                                                 FlashMessage.FlashMessageType.Info, "Unknown Branch Identity",
                                                                 string.Format("The identity '{0}' does not exist.", username));
        }
Пример #12
0
        static void Main(string[] args)
        {
            const string connectionStringTemplate =
                "Data Source={0};" +
                "Initial Catalog={1};" +
                "Integrated Security=true";

            string conenctionString = string.Format(connectionStringTemplate, @"localhost\SQLEXPRESS", "Storage");

            var repository = new SqlStorage(conenctionString);

            #region testing

            var reminder1 = new ReminderItemRestricted
            {
                ContactId = "Tom",
                Date      = DateTimeOffset.Now,
                Message   = "hi tommy",
                Status    = (ReminderItemStatus)1
            };

            var newid = repository.Add(reminder1);
            Console.WriteLine(newid);

            ReminderItem reminder = repository.Get(newid);
            Console.WriteLine(reminder.ContactId);

            var list = repository.Get(ReminderItemStatus.Ready);

            int m = 0;
            foreach (var rem in list)
            {
                ++m;
            }
            Console.WriteLine(m);

            repository.UpdateStatus(newid, ReminderItemStatus.Failed);

            reminder = repository.Get(newid);
            Console.WriteLine(reminder.Status);

            List <Guid> ids = new List <Guid>
            {
                Guid.Parse("D19F4EF4-3C36-453C-8384-76B27ACF8C92"),
                Guid.Parse("67E41C35-B81E-4CC4-9BE3-77B34AE4865F"),
                Guid.Parse("27283CA6-295E-42F3-B6D6-7C2003B6CA9A"),
                Guid.Parse("A31EA458-43B0-47E6-850D-7C36ADC40EB1"),
                Guid.Parse("D8D495B9-D907-4456-8E47-8FB270F48060"),
            };

            repository.UpdateStatus(ids, ReminderItemStatus.Awaiting);

            #endregion
        }
Пример #13
0
        /// <inheritdoc />
        protected override string[] GetTableNames()
        {
            var result = new List <string>();
            var rows   = SqlStorage.Query(database: Name, table: "sqlite_master",
                                          cmd: "SELECT name, type FROM sqlite_master WHERE type='table' AND name NOT LIKE 'sqlite_%'");

            foreach (var row in rows)
            {
                result.Add((string)row[0]);
            }

            return(result.ToArray());
        }
Пример #14
0
        /// <inheritdoc />
        protected override string[] GetTableNames()
        {
            var result = new List <string>();
            var rows   = SqlStorage.Query("EXEC stables @table_owner='dbo',@table_qualifier='" + Name + "';");

            foreach (var row in rows)
            {
                var tableName = (string)row[2];
                result.Add(tableName);
            }

            return(result.ToArray());
        }
Пример #15
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="serviceRecord"></param>
        private static void AddPlayerToIdentities(ServiceRecord serviceRecord)
        {
            using (var sqlStorage = new SqlStorage())
            {
                var gamertag     = serviceRecord.Player.Gamertag;
                var gamertagSafe = GamerIdentity.EscapeGamerId(gamertag);

                var gamerIdentity = sqlStorage.GamerIdentities.FirstOrDefault(g => g.GamerIdSafe == gamertagSafe);
                if (gamerIdentity == null)
                {
                    gamerIdentity = new GamerIdentity
                    {
                        GamerId     = gamertag,
                        GamerIdSafe = gamertagSafe,
                        Type        = IdentityType.XblGamertag
                    };
                    sqlStorage.GamerIdentities.Add(gamerIdentity);
                    sqlStorage.SaveChanges();
                }

                var reachIdentity = sqlStorage.ReachIdentities.FirstOrDefault(h => h.GamerIdentity.Id == gamerIdentity.Id) ??
                                    new ReachIdentity();

                reachIdentity.GamerIdentity    = gamerIdentity;
                reachIdentity.ServiceTag       = serviceRecord.Player.ServiceTag;
                reachIdentity.PlayerModelUrl   = String.Format("https://spartans.svc.halowaypoint.com/players/{0}/Reach/spartans/fullbody", gamertag);
                reachIdentity.CompetitiveKills = serviceRecord.Player.MultiplayerKills;
                reachIdentity.Rank             = serviceRecord.Player.CurrentRankName;
                reachIdentity.TotalGames       = serviceRecord.Player.GamesTotal;

                if (serviceRecord.Player.MultiplayerDeaths > 0)
                {
                    var ratio = (float)serviceRecord.Player.MultiplayerKills / serviceRecord.Player.MultiplayerDeaths;
                    reachIdentity.KillDeathRatio = Math.Round(Convert.ToDouble(ratio), 2, MidpointRounding.AwayFromZero);
                }
                else
                {
                    reachIdentity.KillDeathRatio = serviceRecord.Player.MultiplayerKills;
                }

                sqlStorage.ReachIdentities.AddOrUpdate(reachIdentity);
                try
                {
                    sqlStorage.SaveChanges();
                }
                catch (Exception e)
                {
                }
            }
        }
Пример #16
0
        /// <summary>
        /// </summary>
        /// <returns></returns>
        public bool CheckApiValidity()
        {
            using (var sqlStorage = new SqlStorage())
            {
                var authentication = sqlStorage.Authentications.FirstOrDefault(a => a.Type == AuthenticationType.Halo4);

                if (authentication == null || !authentication.IsValid)
                {
                    return(false);
                }

                return(authentication.Key != null);
            }
        }
Пример #17
0
        /// <inheritdoc />
        protected override string[] GetTableNames()
        {
            var result = new List <string>();
            var rows   = SqlStorage.Query(database: "information_schema", table: "TABLES",
                                          cmd: "SELECT table_name,table_schema,table_type FROM information_schema.TABLES where table_type='BASE TABLE' AND table_schema LIKE " +
                                          SqlStorage.EscapeString(Name));

            foreach (var row in rows)
            {
                result.Add((string)row[0]);
            }

            return(result.ToArray());
        }
Пример #18
0
        public SqlStorageTests()
        {
            _dbName = $"minion_test_db_{Guid.NewGuid().ToString().Replace("-", "")}";
            _conn   =
                "Server=.\\SQLExpress;Trusted_Connection=True;MultipleActiveResultSets=true;Integrated Security=SSPI;Pooling=false;";

            using (var connection = new SqlConnection(_conn))
            {
                connection.Execute("CREATE Database " + _dbName);
            }

            Store = new SqlStorage(DateService, $"Server=.\\SQLExpress;Database={_dbName};Trusted_Connection=True;MultipleActiveResultSets=true;Integrated Security=SSPI;Pooling=false;");

            Task.WaitAll(Store.InitAsync());
        }
Пример #19
0
        public CSqlReader(SqlConnection sql, SqlCommand command, SqlStorage storage)
        {
            this._cmd = command;
            this._con = sql;
            switch (storage)
            {
            case SqlStorage.ExecuteReader:
                rdr = command.ExecuteReader();
                break;

            case SqlStorage.ExecuteNonQuery:
                command.ExecuteNonQuery();
                break;
            }
        }
Пример #20
0
        public ActionResult Create(CreateSessionViewModel viewModel)
        {
            if (!ModelState.IsValid)
            {
                return(View(viewModel));
            }

            using (var sqlStorage = new SqlStorage())
            {
                // trimmin
                viewModel.Username = (viewModel.Username ?? "").Trim();

                var branchIdentity =
                    sqlStorage.BranchIdentities.FirstOrDefault(
                        i => i.Email.ToLower() == viewModel.Username.ToLower() || i.Username.ToLower() == viewModel.Username.ToLower());
                if (branchIdentity == null)
                {
                    ModelState.AddModelError("Username", "An Identity with that Username/Email doesn't exist.");
                    return(View(viewModel));
                }

                if (!Pbkdf2Crypto.ValidateHash(viewModel.Password, branchIdentity.PasswordHash, branchIdentity.PasswordSalt, branchIdentity.PasswordIterations))
                {
                    ModelState.AddModelError("Password", "Incorrect Password.");
                    return(View(viewModel));
                }

                // Create Session
                var ipAddress     = Request.ServerVariables.Get("HTTP_CF_CONNECTING_IP") ?? Request.UserHostAddress;
                var branchSession = BranchSession.Create(ipAddress, Request.UserAgent, branchIdentity, viewModel.RememberMe);
                sqlStorage.BranchSessions.Add(branchSession);
                branchIdentity.BranchIdentitySessions.Add(branchSession);

                // Set Cookie
                var cookie = new HttpCookie("SessionIdentifier", branchSession.Identifier.ToString())
                {
                    Expires = branchSession.ExpiresAt
                };
                Response.SetCookie(cookie);
                sqlStorage.SaveChanges();

                return(RedirectToRoute("BranchIdentityView", new { controller = "Home", action = "Index", slug = branchIdentity.Username }));
            }
        }
Пример #21
0
        public ActionResult Create(CreateSessionViewModel viewModel)
        {
            if (!ModelState.IsValid) return View(viewModel);

            using (var sqlStorage = new SqlStorage())
            {
                // trimmin
                viewModel.Username = (viewModel.Username ?? "").Trim();

                var branchIdentity =
                    sqlStorage.BranchIdentities.FirstOrDefault(
                        i => i.Email.ToLower() == viewModel.Username.ToLower() || i.Username.ToLower() == viewModel.Username.ToLower());
                if (branchIdentity == null)
                {
                    ModelState.AddModelError("Username", "An Identity with that Username/Email doesn't exist.");
                    return View(viewModel);
                }

                if (!Pbkdf2Crypto.ValidateHash(viewModel.Password, branchIdentity.PasswordHash, branchIdentity.PasswordSalt, branchIdentity.PasswordIterations))
                {
                    ModelState.AddModelError("Password", "Incorrect Password.");
                    return View(viewModel);
                }

                // Create Session
                var ipAddress = Request.ServerVariables.Get("HTTP_CF_CONNECTING_IP") ?? Request.UserHostAddress;
                var branchSession = BranchSession.Create(ipAddress, Request.UserAgent, branchIdentity, viewModel.RememberMe);
                sqlStorage.BranchSessions.Add(branchSession);
                branchIdentity.BranchIdentitySessions.Add(branchSession);

                // Set Cookie
                var cookie = new HttpCookie("SessionIdentifier", branchSession.Identifier.ToString())
                {
                    Expires = branchSession.ExpiresAt
                };
                Response.SetCookie(cookie);
                sqlStorage.SaveChanges();

                return RedirectToRoute("BranchIdentityView", new { controller = "Home", action = "Index", slug = branchIdentity.Username });
            }
        }
Пример #22
0
        public IEnumerable<object> GetIdentities(string id)
        {
            using (var sqlStorage = new SqlStorage())
            {
                var halo4Identities =
                    sqlStorage.Halo4Identities.Where(i => i.GamerIdentity.GamerIdSafe.Contains(id)).Take(4).ToList().Select(h => new
                    {
                        Ident = "Halo 4",
                        Url = Url.Route("Halo4_ServiceRecord", new { gamertag = h.GamerIdentity.GamerId }),
                        h.FavouriteWeapon,
                        h.KillDeathRatio,
                        h.PlayerModelUrl,
                        h.TopCsr,
                        h.TotalKills,
                        h.GamerIdentity.GamerId,
                        h.ServiceTag,
                        GamerIdType = h.GamerIdentity.Type
                    });
                var reachIdentities =
                    sqlStorage.ReachIdentities.Where(i => i.GamerIdentity.GamerIdSafe.Contains(id)).Take(4).ToList().Select(h => new
                    {
                        Ident = "Halo: Reach",
                        Url = Url.Route("Reach_ServiceRecord", new { gamertag = h.GamerIdentity.GamerId }),
                        h.CompetitiveKills,
                        h.KillDeathRatio,
                        h.PlayerModelUrl,
                        h.Rank,
                        h.TotalGames,
                        h.GamerIdentity.GamerId,
                        h.ServiceTag,
                        GamerIdType = h.GamerIdentity.Type
                    });

                var idents = new List<object>();
                idents.AddRange(halo4Identities);
                idents.AddRange(reachIdentities);

                return idents;
            }
        }
Пример #23
0
        public IEnumerable <object> GetIdentities(string id)
        {
            using (var sqlStorage = new SqlStorage())
            {
                var halo4Identities =
                    sqlStorage.Halo4Identities.Where(i => i.GamerIdentity.GamerIdSafe.Contains(id)).Take(4).ToList().Select(h => new
                {
                    Ident = "Halo 4",
                    Url   = Url.Route("Halo4_ServiceRecord", new { gamertag = h.GamerIdentity.GamerId }),
                    h.FavouriteWeapon,
                    h.KillDeathRatio,
                    h.PlayerModelUrl,
                    h.TopCsr,
                    h.TotalKills,
                    h.GamerIdentity.GamerId,
                    h.ServiceTag,
                    GamerIdType = h.GamerIdentity.Type
                });
                var reachIdentities =
                    sqlStorage.ReachIdentities.Where(i => i.GamerIdentity.GamerIdSafe.Contains(id)).Take(4).ToList().Select(h => new
                {
                    Ident = "Halo: Reach",
                    Url   = Url.Route("Reach_ServiceRecord", new { gamertag = h.GamerIdentity.GamerId }),
                    h.CompetitiveKills,
                    h.KillDeathRatio,
                    h.PlayerModelUrl,
                    h.Rank,
                    h.TotalGames,
                    h.GamerIdentity.GamerId,
                    h.ServiceTag,
                    GamerIdType = h.GamerIdentity.Type
                });

                var idents = new List <object>();
                idents.AddRange(halo4Identities);
                idents.AddRange(reachIdentities);

                return(idents);
            }
        }
Пример #24
0
        public Program(IConfiguration config)
        {
#if !COREFX
            ServicePointManager.DefaultConnectionLimit = 500;
            ServicePointManager.Expect100Continue      = false;
            ServicePointManager.UseNagleAlgorithm      = false;
#endif

            var ats   = config.GetSection("AtsStorage");
            var sql   = config.GetSection("SqlStorage");
            var redis = config.GetSection("RedisCache");

            var startTime = DateTime.UtcNow;
            _dataSources = new List <DataSource>();
            for (int i = 0; i < 15; i++)
            {
                _dataSources.Add(new DataSource(new BasicKey {
                    Id = Guid.NewGuid(), Sampling = Sampling.Daily
                }, startTime, TimeSpan.FromMilliseconds(1)));
            }

            var dats = new AtsStorage <BasicKey, BasicEntry>(
                ats.GetSection("ConnectionString").Value,
                new ConcurrencyControl(AtsStorage <BasicKey, BasicEntry> .DefaultReadParallelism, AtsStorage <BasicKey, BasicEntry> .DefaultWriteParallelism),
                new YearlyPartitioningProvider <BasicKey>(),
                new YearlyTableProvider <BasicKey>("DatsTables13"),
                this);

            var dsql = new SqlStorage <BasicKey, BasicEntry>(
                "SqlTable3",
                sql.GetSection("ConnectionString").Value,
                new ConcurrencyControl(5, 5),
                this);

            var switchDate = new DateTime(2018, 9, 27, 15, 40, 0, DateTimeKind.Utc);

            var selector = new TestStorageSelector(new StorageSelection <BasicKey, BasicEntry, IStorage <BasicKey, BasicEntry> >[]
            {
                new StorageSelection <BasicKey, BasicEntry, IStorage <BasicKey, BasicEntry> >(dats, switchDate, null),
                new StorageSelection <BasicKey, BasicEntry, IStorage <BasicKey, BasicEntry> >(dsql, null, switchDate),
                //new StorageSelection<BasicKey, BasicEntry, IStorage<BasicKey, BasicEntry>>( dats ),
            });

            var vats = new AtsVolumeStorage <BasicKey, BasicEntry>(
                "VatsTable1",
                ats.GetSection("ConnectionString").Value,
                new ConcurrencyControl(AtsVolumeStorage <BasicKey, BasicEntry> .DefaultReadParallelism, AtsVolumeStorage <BasicKey, BasicEntry> .DefaultWriteParallelism),
                new YearlyPartitioningProvider <BasicKey>(),
                this);

            var tfs = new TemporaryFileStorage <BasicKey, BasicEntry>(
                @"C:\tsdb\cache",
                TemporaryFileStorage <BasicKey, BasicEntry> .DefaultMaxFileSize,
                TemporaryFileStorage <BasicKey, BasicEntry> .DefaultMaxStorageSize,
                this);

            //var client = new TsdbClient<BasicKey, BasicEntry>( selector, vats, tfs, this );

            //var batcher = new TsdbWriteBatcher<BasicKey, BasicEntry>( client, PublicationType.None, TimeSpan.FromSeconds( 5 ), 20000, this );

            //ThreadPool.QueueUserWorkItem( obj => batcher.Handle() );

            ////var engine = new TsdbEngine<BasicKey, BasicEntry>( this, client );
            ////engine.StartAsync().Wait();

            //Console.WriteLine( $"Info: Writing entries..." );
            //while( true )
            //{
            //   var now = DateTime.UtcNow;
            //   foreach( var ds in _dataSources )
            //   {
            //      var serie = ds.GetEntries( now );

            //      batcher.Write( serie );
            //   }

            //   Thread.Sleep( 1000 );
            //}



            var typeStorage          = new TestTypedKeyStorage(_dataSources.Select(x => x.Id));
            var client               = new TsdbClient <BasicKey, BasicEntry>(selector, tfs, this);
            var aggregationFunctions = new AggregationTsdbClient <BasicKey, BasicEntry, MeasureType>(dats, typeStorage, this);

            var batcher = new TsdbWriteBatcher <BasicKey, BasicEntry>(client, PublicationType.None, Publish.Locally, false, TimeSpan.FromSeconds(5), 20000, this);

            ThreadPool.QueueUserWorkItem(obj => batcher.Handle());

            Console.WriteLine($"Info: Writing entries...");
            for (int i = 0; i < 3600; i++)
            {
                var now = DateTime.UtcNow;
                foreach (var ds in _dataSources)
                {
                    var serie = ds.GetEntries(now);

                    batcher.Write(serie);
                }

                Thread.Sleep(1000);
            }

            var from = switchDate.AddSeconds(-5);
            var to   = switchDate.AddSeconds(5);

            var id = DefaultKeyConverter <Guid> .Current.ConvertAsync("fsmVxkSDCkKOcdV9t52R4A").Result;

            var result = client.ReadAsync(new BasicKey {
                Id = id, Sampling = Sampling.Daily
            }, from, to).Result;

            Console.WriteLine(result);



            //Thread.Sleep( 30000 );
            //Console.WriteLine( $"Info: Reading groupings..." );
            //var test = client.ReadLatestAsync( _dataSources[ 0 ].Id, 100 ).Result;
            //Console.WriteLine( "Latest since: " + test.Entries.Count );

            //// make optional or nullable...
            ////var result = client.ReadLatestAsync( _dataSources.Select( x => x.Id ), 10 ).Result;
            //var fields = AggregationParameters.Fields( new AggregatedField( "Value", AggregationFunction.Average ) );
            //var result = aggregationFunctions.ReadGroupsAsync( "Temperature", fields, from, to, AggregationParameters.NoTagRequirements, new[] { "Placement" } ).Result;
            //Console.WriteLine( result.Sum( x => x.Entries.Count ) );

            //result = aggregationFunctions.ReadGroupsAsync( "Temperature", fields, from, to, AggregationParameters.NoTagRequirements, AggregationParameters.NoGroupings ).Result;
            //Console.WriteLine( result.Sum( x => x.Entries.Count ) );
        }
Пример #25
0
        /// <summary>
        ///     Updates the stored spartan tokens used for authenticating with 343's backend api systems.
        /// </summary>
        /// <returns>A boolean saying if everything was</returns>
        public static bool UpdateAuthentication(AzureStorage storage)
        {
            using (var sqlStorage = new SqlStorage())
            {
                var everythingWentGucci = false;
                var strResponse         = "";
                var httpClient          = new HttpClient();

                // Try up to 10 times
                for (var i = 0; i < 10; i++)
                {
                    var response = httpClient.Get(CloudConfigurationManager.GetSetting("SpartanTokenApi"));

                    if (response.StatusCode == HttpStatusCode.OK && !String.IsNullOrEmpty(response.RawText.Trim()))
                    {
                        try
                        {
                            strResponse = response.RawText;

                            var waypointToken = JsonConvert.DeserializeObject <Halo4Waypoint>(response.RawText);
                            if (waypointToken != null && !String.IsNullOrWhiteSpace(waypointToken.SpartanToken))
                            {
                                var authentication = new Models.Sql.Authentication
                                {
                                    Type    = AuthenticationType.Halo4,
                                    IsValid = true,
                                    Key     = waypointToken.SpartanToken
                                };
                                sqlStorage.Authentications.AddOrUpdate(a => a.Type, authentication);
                                sqlStorage.SaveChanges();

                                everythingWentGucci = true;
                            }
                        }
                        catch (Exception ex)
                        {
                            Trace.TraceError(ex.ToString());
                            everythingWentGucci = false;
                        }
                    }

                    if (everythingWentGucci)
                    {
                        break;
                    }
                }


                if (everythingWentGucci)
                {
                    return(true);
                }

                // make sure halo 4 auth row has been deleted
                var invalidAuthentication = sqlStorage.Authentications.FirstOrDefault(a => a.Type == AuthenticationType.Halo4);
                if (invalidAuthentication != null)
                {
                    invalidAuthentication.Key     = null;
                    invalidAuthentication.IsValid = false;
                }

                // send glorious email!
                var text =
                    String.Format(
                        "Sup guys, {0}Halo 4's authenication failed to update. Might want to look into it. Below is the response the server recieved from the auth service: {0}{0}{1}{0}{0}Best Regards,{0}Branch",
                        Environment.NewLine, strResponse);

                new Web(new NetworkCredential(CloudConfigurationManager.GetSetting("SendGridUser"),
                                              CloudConfigurationManager.GetSetting("SendGridPass"))).Deliver(
                    new SendGridMessage(new MailAddress("*****@*****.**"),
                                        new[]
                {
                    new MailAddress(CloudConfigurationManager.GetSetting("SendGridTo")),
                    new MailAddress("*****@*****.**"),
                },
                                        "[Halo 4] Authentication Failed", null, text));

                sqlStorage.SaveChanges();

                return(false);
            }
        }
Пример #26
0
        /// <inheritdoc />
        public override ITable CreateTable(RowLayout layout, TableFlags flags)
        {
            if (layout == null)
            {
                throw new ArgumentNullException(nameof(layout));
            }

            if (layout.Name.HasInvalidChars(ASCII.Strings.SafeName))
            {
                throw new ArgumentException($"Table name {layout.Name} contains invalid chars!");
            }

            var utf8Charset = ((MySqlStorage)Storage).CharacterSet;

            LogCreateTable(layout);
            var queryText = new StringBuilder();

            queryText.Append($"CREATE TABLE {SqlStorage.FQTN(Name, layout.Name)} (");
            for (var i = 0; i < layout.FieldCount; i++)
            {
                var fieldProperties = layout[i];
                if (i > 0)
                {
                    queryText.Append(',');
                }

                queryText.Append(SqlStorage.EscapeFieldName(fieldProperties));
                queryText.Append(' ');
                switch (fieldProperties.TypeAtDatabase)
                {
                case DataType.Binary:
                    if (fieldProperties.MaximumLength <= 0)
                    {
                        queryText.Append("LONGBLOB");
                    }
                    else if (fieldProperties.MaximumLength <= 255)
                    {
                        queryText.Append("TINYBLOB");
                    }
                    else if (fieldProperties.MaximumLength <= 65535)
                    {
                        queryText.Append("BLOB");
                    }
                    else if (fieldProperties.MaximumLength <= 16777215)
                    {
                        queryText.Append("MEDIUMBLOB");
                    }
                    else
                    {
                        queryText.Append("LONGBLOB");
                    }

                    break;

                case DataType.Bool:
                    queryText.Append("TINYINT(1)");
                    break;

                case DataType.DateTime:
                    switch (fieldProperties.DateTimeType)
                    {
                    case DateTimeType.Undefined:
                    case DateTimeType.Native:
                        queryText.Append("DATETIME");
                        break;

                    case DateTimeType.DoubleEpoch:
                    case DateTimeType.DoubleSeconds:
                        queryText.Append("DOUBLE");
                        break;

                    case DateTimeType.DecimalSeconds:
                        queryText.Append("DECIMAL(65,30)");
                        break;

                    case DateTimeType.BigIntHumanReadable:
                    case DateTimeType.BigIntTicks:
                        queryText.Append("BIGINT");
                        break;

                    default: throw new NotImplementedException();
                    }

                    break;

                case DataType.TimeSpan:
                    switch (fieldProperties.DateTimeType)
                    {
                    case DateTimeType.Undefined:
                    case DateTimeType.Native:
                        queryText.Append("TIME");
                        break;

                    case DateTimeType.DoubleEpoch:
                    case DateTimeType.DoubleSeconds:
                        queryText.Append("DOUBLE");
                        break;

                    case DateTimeType.DecimalSeconds:
                        queryText.Append("DECIMAL(65,30)");
                        break;

                    case DateTimeType.BigIntHumanReadable:
                    case DateTimeType.BigIntTicks:
                        queryText.Append("BIGINT");
                        break;

                    default: throw new NotImplementedException();
                    }

                    break;

                case DataType.Int8:
                    queryText.Append("TINYINT");
                    break;

                case DataType.Int16:
                    queryText.Append("SMALLINT");
                    break;

                case DataType.Int32:
                    queryText.Append("INTEGER");
                    break;

                case DataType.Int64:
                    queryText.Append("BIGINT");
                    break;

                case DataType.Single:
                    queryText.Append("FLOAT");
                    break;

                case DataType.Double:
                    queryText.Append("DOUBLE");
                    break;

                case DataType.Enum:
                    queryText.Append("BIGINT");
                    break;

                case DataType.UInt8:
                    queryText.Append("TINYINT UNSIGNED");
                    break;

                case DataType.UInt16:
                    queryText.Append("SMALLINT UNSIGNED");
                    break;

                case DataType.UInt32:
                    queryText.Append("INTEGER UNSIGNED");
                    break;

                case DataType.UInt64:
                    queryText.Append("BIGINT UNSIGNED");
                    break;

                case DataType.User:
                case DataType.String:
                    if (fieldProperties.MaximumLength <= 0)
                    {
                        queryText.Append("LONGTEXT");
                    }
                    else if (fieldProperties.MaximumLength <= 255)
                    {
                        queryText.Append($"VARCHAR({fieldProperties.MaximumLength})");
                    }
                    else if (fieldProperties.MaximumLength <= 65535)
                    {
                        queryText.Append("TEXT");
                    }
                    else if (fieldProperties.MaximumLength <= 16777215)
                    {
                        queryText.Append("MEDIUMTEXT");
                    }
                    else
                    {
                        queryText.Append("LONGTEXT");
                    }

                    switch (fieldProperties.StringEncoding)
                    {
                    case StringEncoding.Undefined:
                    case StringEncoding.ASCII:
                        queryText.Append(" CHARACTER SET latin1 COLLATE latin1_general_ci");
                        break;

                    case StringEncoding.UTF8:
                        queryText.Append($" CHARACTER SET utf8mb4 COLLATE {utf8Charset}_general_ci");
                        break;

                    case StringEncoding.UTF16:
                        queryText.Append(" CHARACTER SET ucs2 COLLATE ucs2_general_ci");
                        break;

                    case StringEncoding.UTF32:
                        queryText.Append(" CHARACTER SET utf32 COLLATE utf32_general_ci");
                        break;

                    default: throw new NotSupportedException($"MYSQL Server does not support {fieldProperties.StringEncoding}!");
                    }

                    break;

                case DataType.Decimal:
                    if (fieldProperties.MaximumLength > 0)
                    {
                        var precision = (int)fieldProperties.MaximumLength;
                        var scale     = (int)((fieldProperties.MaximumLength - precision) * 100);
                        if (scale >= precision)
                        {
                            throw new ArgumentOutOfRangeException(
                                      $"Field {fieldProperties.Name} has an invalid MaximumLength of {precision},{scale}. Correct values range from s,p = 1,0 to 65,30(default value) with 0 < s < p!");
                        }

                        queryText.Append($"DECIMAL({precision},{scale})");
                    }
                    else
                    {
                        queryText.Append("DECIMAL(65,30)");
                    }

                    break;

                default: throw new NotImplementedException($"Unknown DataType {fieldProperties.DataType}!");
                }

                if ((fieldProperties.Flags & FieldFlags.AutoIncrement) != 0)
                {
                    queryText.Append(" AUTO_INCREMENT");
                }

                if ((fieldProperties.Flags & FieldFlags.Unique) != 0)
                {
                    queryText.Append(" UNIQUE");
                    switch (fieldProperties.TypeAtDatabase)
                    {
                    case DataType.Bool:
                    case DataType.Char:
                    case DataType.DateTime:
                    case DataType.Decimal:
                    case DataType.Double:
                    case DataType.Enum:
                    case DataType.Int8:
                    case DataType.Int16:
                    case DataType.Int32:
                    case DataType.Int64:
                    case DataType.UInt8:
                    case DataType.UInt16:
                    case DataType.UInt32:
                    case DataType.UInt64:
                    case DataType.Single:
                    case DataType.TimeSpan:
                        break;

                    case DataType.String:
                        if (fieldProperties.MaximumLength <= 0)
                        {
                            throw new NotSupportedException(
                                      $"Unique string fields without length are not supported! Please define Field.MaxLength at tableName {layout.Name} field {fieldProperties.Name}");
                        }

                        break;

                    default: throw new NotSupportedException($"Uniqueness for tableName {layout.Name} field {fieldProperties.Name} is not supported!");
                    }
                }

                if (fieldProperties.Description != null)
                {
                    if (fieldProperties.Description.HasInvalidChars(ASCII.Strings.Printable))
                    {
                        throw new ArgumentException("Description of field '{0}' contains invalid chars!", fieldProperties.Name);
                    }

                    queryText.Append(" COMMENT '" + fieldProperties.Description.Substring(0, 60) + "'");
                }
            }

            if (layout.Identifier.Any())
            {
                queryText.Append(",PRIMARY KEY(");
                var count = 0;
                foreach (var field in layout.Identifier)
                {
                    if (count++ > 0)
                    {
                        queryText.Append(',');
                    }

                    queryText.Append(SqlStorage.EscapeFieldName(field));
                }

                queryText.Append(')');
            }

            queryText.Append(')');
            if ((flags & TableFlags.InMemory) != 0)
            {
                queryText.Append(" ENGINE = MEMORY");
            }

            SqlStorage.Execute(database: Name, table: layout.Name, cmd: queryText.ToString());
            try
            {
                for (var i = 0; i < layout.FieldCount; i++)
                {
                    var field = layout[i];
                    if ((field.Flags & FieldFlags.ID) != 0)
                    {
                        continue;
                    }

                    if ((field.Flags & FieldFlags.Index) != 0)
                    {
                        string command;
                        switch (field.DataType)
                        {
                        case DataType.Binary:
                        case DataType.String:
                        case DataType.User:
                            var size = (int)field.MaximumLength;
                            if (size < 1)
                            {
                                size = 32;
                            }

                            command =
                                $"CREATE INDEX `idx_{layout.Name}_{field.Name}` ON {SqlStorage.FQTN(Name, layout.Name)} ({SqlStorage.EscapeFieldName(field)} ({size}))";
                            break;

                        case DataType.Bool:
                        case DataType.Char:
                        case DataType.DateTime:
                        case DataType.Decimal:
                        case DataType.Double:
                        case DataType.Enum:
                        case DataType.Int16:
                        case DataType.Int32:
                        case DataType.Int64:
                        case DataType.Int8:
                        case DataType.Single:
                        case DataType.TimeSpan:
                        case DataType.UInt16:
                        case DataType.UInt32:
                        case DataType.UInt64:
                        case DataType.UInt8:
                            command =
                                $"CREATE INDEX `idx_{layout.Name}_{field.Name}` ON {SqlStorage.FQTN(Name, layout.Name)} ({SqlStorage.EscapeFieldName(field)})";
                            break;

                        default: throw new NotSupportedException($"INDEX for datatype of field {field} is not supported!");
                        }

                        SqlStorage.Execute(database: Name, table: layout.Name, cmd: command);
                    }
                }
            }
            catch
            {
                DeleteTable(layout.Name);
                throw;
            }

            return(GetTable(layout));
        }
Пример #27
0
        /// <inheritdoc />
        public override ITable CreateTable(RowLayout layout, TableFlags flags)
        {
            if (layout == null)
            {
                throw new ArgumentNullException(nameof(layout));
            }

            LogCreateTable(layout);
            if ((flags & TableFlags.InMemory) != 0)
            {
                throw new NotSupportedException($"Table '{layout.Name}' does not support TableFlags.{TableFlags.InMemory}");
            }

            if (layout.Name.HasInvalidChars(ASCII.Strings.SafeName))
            {
                throw new ArgumentException($"Table name {layout.Name} contains invalid chars!");
            }

            var queryText = new StringBuilder();

            queryText.Append($"CREATE TABLE {SqlStorage.FQTN(Name, layout.Name)} (");
            for (var i = 0; i < layout.FieldCount; i++)
            {
                var fieldProperties = layout[i];
                if (i > 0)
                {
                    queryText.Append(",");
                }

                queryText.Append(fieldProperties.NameAtDatabase + " ");
                switch (fieldProperties.DataType)
                {
                case DataType.Binary:
                    queryText.Append("VARBINARY(MAX)");
                    break;

                case DataType.Bool:
                    queryText.Append("BIT");
                    break;

                case DataType.DateTime:
                    switch (fieldProperties.DateTimeType)
                    {
                    case DateTimeType.Undefined:
                    case DateTimeType.Native:
                        queryText.Append("DATETIME");
                        break;

                    case DateTimeType.DoubleSeconds:
                    case DateTimeType.DoubleEpoch:
                        queryText.Append("FLOAT(53)");
                        break;

                    case DateTimeType.DecimalSeconds:
                        queryText.Append("NUMERIC(28,8)");
                        break;

                    case DateTimeType.BigIntHumanReadable:
                    case DateTimeType.BigIntTicks:
                        queryText.Append("BIGINT");
                        break;

                    default: throw new NotImplementedException();
                    }

                    break;

                case DataType.TimeSpan:
                    switch (fieldProperties.DateTimeType)
                    {
                    case DateTimeType.Undefined:
                    case DateTimeType.Native:
                        queryText.Append("TIMESPAN");
                        break;

                    case DateTimeType.DoubleEpoch:
                    case DateTimeType.DoubleSeconds:
                        queryText.Append("FLOAT(53)");
                        break;

                    case DateTimeType.DecimalSeconds:
                        queryText.Append("NUMERIC(28,8)");
                        break;

                    case DateTimeType.BigIntHumanReadable:
                    case DateTimeType.BigIntTicks:
                        queryText.Append("BIGINT");
                        break;

                    default: throw new NotImplementedException();
                    }

                    break;

                case DataType.Int8:
                    queryText.Append("SMALLINT");
                    break;

                case DataType.Int16:
                    queryText.Append("SMALLINT");
                    break;

                case DataType.Int32:
                    queryText.Append("INTEGER");
                    break;

                case DataType.Int64:
                    queryText.Append("BIGINT");
                    break;

                case DataType.Single:
                    queryText.Append("REAL");
                    break;

                case DataType.Double:
                    queryText.Append("FLOAT(53)");
                    break;

                case DataType.Enum:
                    queryText.Append("BIGINT");
                    break;

                case DataType.User:
                case DataType.String:
                    switch (fieldProperties.StringEncoding)
                    {
                    case StringEncoding.ASCII:
                        if ((fieldProperties.MaximumLength > 0) && (fieldProperties.MaximumLength <= 255))
                        {
                            queryText.AppendFormat("VARCHAR({0})", fieldProperties.MaximumLength);
                        }
                        else
                        {
                            queryText.Append("VARCHAR(MAX)");
                        }

                        break;

                    case StringEncoding.UTF16:
                    case StringEncoding.UTF8:
                        if ((fieldProperties.MaximumLength > 0) && (fieldProperties.MaximumLength <= 255))
                        {
                            queryText.AppendFormat("NVARCHAR({0})", fieldProperties.MaximumLength);
                        }
                        else
                        {
                            queryText.Append("NVARCHAR(MAX)");
                        }

                        break;

                    default: throw new NotSupportedException($"MSSQL Server does not support {fieldProperties.StringEncoding}!");
                    }

                    break;

                case DataType.Decimal:
                    if (fieldProperties.MaximumLength > 0)
                    {
                        var l_PreDecimal = (int)fieldProperties.MaximumLength;
                        var l_Temp       = (fieldProperties.MaximumLength - l_PreDecimal) * 100;
                        var l_Decimal    = (int)l_Temp;
                        if ((l_Decimal >= l_PreDecimal) || (l_Decimal != l_Temp))
                        {
                            throw new ArgumentOutOfRangeException(
                                      $"Field {fieldProperties.Name} has an invalid MaximumLength of {l_PreDecimal},{l_Decimal}. Correct values range from s,p = 1,0 to 28,27 with 0 < s < p!");
                        }

                        queryText.AppendFormat("NUMERIC({0},{1})", l_PreDecimal, l_Decimal);
                    }
                    else
                    {
                        queryText.Append("NUMERIC(28,8)");
                    }

                    break;

                default: throw new NotImplementedException($"Unknown DataType {fieldProperties.DataType}!");
                }

                if ((fieldProperties.Flags & FieldFlags.ID) != 0)
                {
                    queryText.Append(" PRIMARY KEY");
                }

                if ((fieldProperties.Flags & FieldFlags.AutoIncrement) != 0)
                {
                    queryText.Append(" IDENTITY");
                }

                if ((fieldProperties.Flags & FieldFlags.Unique) != 0)
                {
                    queryText.Append(" UNIQUE");
                    switch (fieldProperties.TypeAtDatabase)
                    {
                    case DataType.Bool:
                    case DataType.Char:
                    case DataType.DateTime:
                    case DataType.Decimal:
                    case DataType.Double:
                    case DataType.Enum:
                    case DataType.Int8:
                    case DataType.Int16:
                    case DataType.Int32:
                    case DataType.Int64:
                    case DataType.UInt8:
                    case DataType.UInt16:
                    case DataType.UInt32:
                    case DataType.UInt64:
                    case DataType.Single:
                    case DataType.TimeSpan:
                        break;

                    case DataType.String:
                        if (fieldProperties.MaximumLength <= 0)
                        {
                            throw new NotSupportedException(
                                      $"Unique string fields without length are not supported! Please define Field.MaxLength at table {layout.Name} field {fieldProperties.Name}");
                        }

                        break;

                    default: throw new NotSupportedException($"Uniqueness for table {layout.Name} field {fieldProperties.Name} is not supported!");
                    }
                }

                if (fieldProperties.Description != null)
                {
                    if (fieldProperties.Description.HasInvalidChars(ASCII.Strings.Printable))
                    {
                        throw new ArgumentException("Description of field '{0}' contains invalid chars!", fieldProperties.Name);
                    }

                    queryText.Append(" COMMENT '" + fieldProperties.Description.Substring(0, 60) + "'");
                }
            }

            queryText.Append(")");
            SqlStorage.Execute(database: Name, table: layout.Name, cmd: queryText.ToString());
            for (var i = 0; i < layout.FieldCount; i++)
            {
                var fieldProperties = layout[i];
                if ((fieldProperties.Flags & FieldFlags.ID) != 0)
                {
                    continue;
                }

                if ((fieldProperties.Flags & FieldFlags.Index) != 0)
                {
                    var command =
                        $"CREATE INDEX idx_{SqlStorage.EscapeString(fieldProperties.NameAtDatabase)} ON {SqlStorage.FQTN(Name, layout.Name)} ({SqlStorage.EscapeFieldName(fieldProperties)})";
                    SqlStorage.Execute(database: Name, table: layout.Name, cmd: command);
                }
            }

            return(GetTable(layout));
        }
Пример #28
0
        public ActionResult Index(CreateIdentityViewModel viewModel)
        {
            using (var sqlStorage = new SqlStorage())
            {
                if (!ModelState.IsValid)
                {
                    return(View(viewModel));
                }

                // Trimmin'
                viewModel.Email          = viewModel.Email.Trim();
                viewModel.FullName       = viewModel.FullName.Trim();
                viewModel.Gamertag       = viewModel.Gamertag.Trim();
                viewModel.Username       = viewModel.Username.Trim();
                viewModel.InvitationCode = viewModel.InvitationCode.Trim();

                // Validate uniqueness of Username and Email
                var user = sqlStorage.BranchIdentities
                           .FirstOrDefault(i =>
                                           i.Username.ToLower() == viewModel.Username.ToLower() ||
                                           i.Email.ToLower() == viewModel.Email.ToLower());
                if (user != null)
                {
                    ModelState.AddModelError("Username", "Either this username has already been taken, or that email has already been used.");
                    ModelState.AddModelError("Email", "Either this username has already been taken, or that email has already been used.");
                }

                // Validate Invite Code
                var invite =
                    sqlStorage.BranchIdentityInvitations.FirstOrDefault(
                        i => i.InvitationCode.ToLower() == viewModel.InvitationCode.ToLower() && !i.Used);
                if (invite == null)
                {
                    ModelState.AddModelError("InvitationCode", "This invite code has either been used or isn't valid. Sorry bae.");
                }

                // Check Password is identical
                if (viewModel.Password != viewModel.PasswordConfirm)
                {
                    ModelState.AddModelError("Password", "Your password and confirmation do not match.");
                }

                // Check Password Complexity
                var complexity = 0;
                if (Regex.IsMatch(viewModel.Password, @"\d+"))
                {
                    complexity++;
                }
                if (Regex.IsMatch(viewModel.Password, @"[a-z]+"))
                {
                    complexity++;
                }
                if (Regex.IsMatch(viewModel.Password, @"[A-Z]+"))
                {
                    complexity++;
                }
                if (Regex.IsMatch(viewModel.Password, @"[^a-zA-Z\d]+"))
                {
                    complexity++;
                }

                if (complexity < 2)
                {
                    ModelState.AddModelError("Password", "Your password is not complex enough.");
                }

                if (!ModelState.IsValid)
                {
                    viewModel.Password = viewModel.PasswordConfirm = "";
                    return(View(viewModel));
                }

                // All gucci, create Branch Identity
                var password       = Pbkdf2Crypto.ComputeHash(viewModel.Password, new Random().Next(1000, 1200));
                var branchIdentity = new BranchIdentity
                {
                    BranchRole               = sqlStorage.BranchRoles.First(r => r.Type == RoleType.User),
                    Email                    = viewModel.Email,
                    FullName                 = viewModel.FullName,
                    Username                 = viewModel.Username,
                    PasswordHash             = password.Hash,
                    PasswordIterations       = password.Iterations,
                    PasswordSalt             = password.Salt,
                    BranchIdentityInvitation = invite
                };

                // Set invite as used
// ReSharper disable once PossibleNullReferenceException
                invite.Used = true;

                // Check gamer ids
                GlobalStorage.H4Manager.GetPlayerServiceRecord(viewModel.Gamertag, true);
                GlobalStorage.HReachManager.GetPlayerServiceRecord(viewModel.Gamertag, true);
                var gamerIdSafe = GamerIdentity.EscapeGamerId(viewModel.Gamertag);
                var gamerId     = sqlStorage.GamerIdentities.FirstOrDefault(g => g.GamerIdSafe == gamerIdSafe);
                if (gamerId != null)
                {
                    branchIdentity.GamerIdentity = gamerId;
                }
                sqlStorage.BranchIdentities.Add(branchIdentity);
                sqlStorage.SaveChanges();

                var ipAddress     = Request.ServerVariables.Get("HTTP_CF_CONNECTING_IP") ?? Request.UserHostAddress;
                var branchSession = BranchSession.Create(ipAddress, Request.UserAgent, branchIdentity, false);
                sqlStorage.BranchSessions.Add(branchSession);

                var cookie = new HttpCookie("SessionIdentifier", branchSession.Identifier.ToString())
                {
                    Expires = branchSession.ExpiresAt
                };
                Response.SetCookie(cookie);
                sqlStorage.SaveChanges();

                return(RedirectToRoute("BranchIdentityView", new { controller = "Home", action = "Index", slug = branchIdentity.Username }));
            }
        }
Пример #29
0
 /// <inheritdoc />
 protected override string[] GetTableNames() =>
 SqlStorage.Query(database: Name, table: "pg_tables", cmd: "SELECT tablename FROM pg_tables").Select(r => r[0].ToString()).ToArray();
Пример #30
0
 public ExpirationManager(SqlStorage storage, TimeSpan checkInterval, string schema)
 {
     _storage       = storage ?? throw new ArgumentNullException(nameof(storage));
     _checkInterval = checkInterval;
     _schema        = schema ?? throw new ArgumentNullException(nameof(schema));
 }
Пример #31
0
        //
        // GET: /Search/Identity/{ident}?q={q}&page={page:0}
        public ActionResult Identity(string ident, string q, int?page = 0)
        {
            if (page == null || page < 0)
            {
                return(RedirectToAction("Identity", "Search", new { ident, q, page = 0 }));
            }

            if (String.IsNullOrEmpty(q))
            {
                return(FlashMessage.RedirectAndFlash(
                           Response, RedirectToAction("Index", "Home", new { area = "" }), FlashMessage.FlashMessageType.Info,
                           "Missing Search Term", "Ey man, there was no search term there."));
            }

            if (String.IsNullOrWhiteSpace(ident))
            {
                return(RedirectToAction("Index", "Search", new { q }));
            }

            SearchIdent searchIdent;

            if (!Enum.TryParse(ident, true, out searchIdent))
            {
                return(FlashMessage.RedirectAndFlash(
                           Response, RedirectToAction("Index", "Search"), FlashMessage.FlashMessageType.Info,
                           "Invalid Search Identity", "Now Now Bae.. You can't be searchin' like that."));
            }

            using (var sqlStorage = new SqlStorage())
            {
                List <Halo4Identity> halo4Identities = null;
                List <ReachIdentity> reachIdentities = null;

                bool hasMorePages;
                switch (searchIdent)
                {
                case SearchIdent.Halo4:
                    GlobalStorage.H4Manager.GetPlayerServiceRecord(q, true);
                    halo4Identities = sqlStorage.Halo4Identities
                                      .Include(i => i.GamerIdentity)
                                      .Where(i => i.GamerIdentity.GamerId.Contains(q))
                                      .OrderBy(i => i.GamerIdentity.GamerId)
                                      .Skip(12 * ((int)page))
                                      .Take(13)
                                      .ToList();

                    hasMorePages = halo4Identities.Count() == 13;
                    if (hasMorePages)
                    {
                        halo4Identities = halo4Identities.Take(12).ToList();
                    }
                    break;

                case SearchIdent.Reach:
                    GlobalStorage.HReachManager.GetPlayerServiceRecord(q, true);
                    reachIdentities = sqlStorage.ReachIdentities
                                      .Include(i => i.GamerIdentity)
                                      .Where(i => i.GamerIdentity.GamerId.Contains(q))
                                      .OrderBy(i => i.GamerIdentity.GamerId)
                                      .Skip(12 * ((int)page))
                                      .Take(13)
                                      .ToList();

                    hasMorePages = reachIdentities.Count() == 13;
                    if (hasMorePages)
                    {
                        reachIdentities = reachIdentities.Take(12).ToList();
                    }
                    break;

                default:
                    return(RedirectToAction("Index", "Search", new { q }));
                }

                return(View("Identity", new SearchIdentityViewModel(searchIdent, halo4Identities, reachIdentities, q, (int)page, hasMorePages)));
            }
        }
Пример #32
0
        /// <summary></summary>
        public void ConfigureServices(IServiceCollection services)
        {
            ApiName = Configuration["ApiName"];

            services.AddAuthentication("Basic").AddScheme <TokenAuthenticationOptions, TokenAuthenticationHandler>("Basic", o => { });
            services.AddAuthentication("Bearer").AddJwtBearer();

            services
            .AddMvc(config =>
            {
                var policy = new AuthorizationPolicyBuilder()
                             .RequireAuthenticatedUser()
                             .Build();
                config.Filters.Add(new AuthorizeFilter(policy));
            })
            .AddMvcOptions(options =>
            {
                options.EnableEndpointRouting             = false;
                options.AllowEmptyInputInBodyModelBinding = true;
            })
            .AddNewtonsoftJson(options =>
            {
                options.SerializerSettings.ContractResolver = new DefaultContractResolver();
                options.SerializerSettings.Converters.Add(new StringEnumConverter());
            });

            services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc("v1", new OpenApiInfo {
                    Title = ApiName, Version = "v1"
                });
                c.EnableAnnotations();

                var xmlFile = Path.ChangeExtension(typeof(Startup).Assembly.Location, ".xml");
                c.IncludeXmlComments(xmlFile);

                c.AddSecurityDefinition("basic", new OpenApiSecurityScheme
                {
                    Name        = "Authorization",
                    Type        = SecuritySchemeType.Http,
                    Scheme      = "basic",
                    In          = ParameterLocation.Header,
                    Description = "Basic Authorization header using the Bearer scheme."
                });

                c.AddSecurityRequirement(new OpenApiSecurityRequirement
                {
                    {
                        new OpenApiSecurityScheme
                        {
                            Reference = new OpenApiReference
                            {
                                Type = ReferenceType.SecurityScheme,
                                Id   = "basic"
                            }
                        },
                        new string[] {}
                    }
                });
            });

            var sqlConnectionString     = Configuration["Service:SqlConnectionString"];
            var storageConnectionString = Configuration["Service:StorageConnectionString"];

            if (!string.IsNullOrWhiteSpace(sqlConnectionString))
            {
                var sqlStorage = new SqlStorage(sqlConnectionString);
                services.AddSingleton <IStorage>(sqlStorage);
                new DatabasePatcherHandler().PatchIfNecessary(Configuration["Nexus:Environment"], sqlConnectionString, Configuration["Service:MasterConnectionString"]);
            }
            else if (!string.IsNullOrWhiteSpace(storageConnectionString))
            {
                var tableStorage = new TableStorage(storageConnectionString);
                services.AddSingleton <IStorage>(tableStorage);
            }
            else
            {
                services.AddSingleton <IStorage, MemoryStorage>();
            }
            services.AddSingleton <ITestLogic, TestLogic>();
        }
Пример #33
0
        //
        // GET: /Search/?q=
        public ActionResult Index(string q)
        {
            if (String.IsNullOrEmpty(q))
                return RedirectToAction("Index", "Home");

            using (var sqlStorage = new SqlStorage())
            {
                GlobalStorage.H4Manager.GetPlayerServiceRecord(q, true);
                GlobalStorage.HReachManager.GetPlayerServiceRecord(q, true);

                var halo4Identities =
                    sqlStorage.Halo4Identities.Include(i => i.GamerIdentity)
                        .Where(h => h.GamerIdentity.GamerId.Contains(q))
                        .Take(6)
                        .ToList();

                var reachIdentnties =
                    sqlStorage.ReachIdentities.Include(i => i.GamerIdentity)
                    .Where(h => h.GamerIdentity.GamerId.Contains(q))
                    .Take(6)
                    .ToList();

                // le render le model le
                return View(new SearchViewModel(q, halo4Identities, reachIdentnties));
            }
        }
Пример #34
0
        public ActionResult Index(CreateIdentityViewModel viewModel)
        {
            using (var sqlStorage = new SqlStorage())
            {
                if (!ModelState.IsValid) return View(viewModel);

                // Trimmin'
                viewModel.Email = viewModel.Email.Trim();
                viewModel.FullName = viewModel.FullName.Trim();
                viewModel.Gamertag = viewModel.Gamertag.Trim();
                viewModel.Username = viewModel.Username.Trim();
                viewModel.InvitationCode = viewModel.InvitationCode.Trim();

                // Validate uniqueness of Username and Email
                var user = sqlStorage.BranchIdentities
                    .FirstOrDefault(i =>
                        i.Username.ToLower() == viewModel.Username.ToLower() ||
                        i.Email.ToLower() == viewModel.Email.ToLower());
                if (user != null)
                {
                    ModelState.AddModelError("Username", "Either this username has already been taken, or that email has already been used.");
                    ModelState.AddModelError("Email", "Either this username has already been taken, or that email has already been used.");
                }

                // Validate Invite Code
                var invite =
                    sqlStorage.BranchIdentityInvitations.FirstOrDefault(
                        i => i.InvitationCode.ToLower() == viewModel.InvitationCode.ToLower() && !i.Used);
                if (invite == null)
                    ModelState.AddModelError("InvitationCode", "This invite code has either been used or isn't valid. Sorry bae.");

                // Check Password is identical
                if (viewModel.Password != viewModel.PasswordConfirm)
                    ModelState.AddModelError("Password", "Your password and confirmation do not match.");

                // Check Password Complexity
                var complexity = 0;
                if (Regex.IsMatch(viewModel.Password, @"\d+"))
                    complexity++;
                if (Regex.IsMatch(viewModel.Password, @"[a-z]+"))
                    complexity++;
                if (Regex.IsMatch(viewModel.Password, @"[A-Z]+"))
                    complexity++;
                if (Regex.IsMatch(viewModel.Password, @"[^a-zA-Z\d]+"))
                    complexity++;

                if (complexity < 2)
                    ModelState.AddModelError("Password", "Your password is not complex enough.");

                if (!ModelState.IsValid)
                {
                    viewModel.Password = viewModel.PasswordConfirm = "";
                    return View(viewModel);
                }

                // All gucci, create Branch Identity
                var password = Pbkdf2Crypto.ComputeHash(viewModel.Password, new Random().Next(1000, 1200));
                var branchIdentity = new BranchIdentity
                {
                    BranchRole = sqlStorage.BranchRoles.First(r => r.Type == RoleType.User),
                    Email = viewModel.Email,
                    FullName = viewModel.FullName,
                    Username = viewModel.Username,
                    PasswordHash = password.Hash,
                    PasswordIterations = password.Iterations,
                    PasswordSalt = password.Salt,
                    BranchIdentityInvitation = invite
                };

                // Set invite as used
            // ReSharper disable once PossibleNullReferenceException
                invite.Used = true;

                // Check gamer ids
                GlobalStorage.H4Manager.GetPlayerServiceRecord(viewModel.Gamertag, true);
                GlobalStorage.HReachManager.GetPlayerServiceRecord(viewModel.Gamertag, true);
                var gamerIdSafe = GamerIdentity.EscapeGamerId(viewModel.Gamertag);
                var gamerId = sqlStorage.GamerIdentities.FirstOrDefault(g => g.GamerIdSafe == gamerIdSafe);
                if (gamerId != null)
                    branchIdentity.GamerIdentity = gamerId;
                sqlStorage.BranchIdentities.Add(branchIdentity);
                sqlStorage.SaveChanges();

                var ipAddress = Request.ServerVariables.Get("HTTP_CF_CONNECTING_IP") ?? Request.UserHostAddress;
                var branchSession = BranchSession.Create(ipAddress, Request.UserAgent, branchIdentity, false);
                sqlStorage.BranchSessions.Add(branchSession);

                var cookie = new HttpCookie("SessionIdentifier", branchSession.Identifier.ToString())
                {
                    Expires = branchSession.ExpiresAt
                };
                Response.SetCookie(cookie);
                sqlStorage.SaveChanges();

                return RedirectToRoute("BranchIdentityView", new { controller = "Home", action = "Index", slug = branchIdentity.Username });
            }
        }
Пример #35
0
 /// <summary>Initializes a new instance of the <see cref="SqlConnectionPool" /> class.</summary>
 /// <param name="storage">The storage.</param>
 public SqlConnectionPool(SqlStorage storage) => this.storage = storage;
Пример #36
0
        /// <summary>
        ///     Updates the stored spartan tokens used for authenticating with 343's backend api systems.
        /// </summary>
        /// <returns>A boolean saying if everything was</returns>
        public static bool UpdateAuthentication(AzureStorage storage)
        {
            using (var sqlStorage = new SqlStorage())
            {
                var everythingWentGucci = false;
                var strResponse = "";
                var httpClient = new HttpClient();

                // Try up to 10 times
                for (var i = 0; i < 10; i++)
                {
                    var response = httpClient.Get(CloudConfigurationManager.GetSetting("SpartanTokenApi"));

                    if (response.StatusCode == HttpStatusCode.OK && !String.IsNullOrEmpty(response.RawText.Trim()))
                    {
                        try
                        {
                            strResponse = response.RawText;

                            var waypointToken = JsonConvert.DeserializeObject<Halo4Waypoint>(response.RawText);
                            if (waypointToken != null && !String.IsNullOrWhiteSpace(waypointToken.SpartanToken))
                            {
                                var authentication = new Models.Sql.Authentication
                                {
                                    Type = AuthenticationType.Halo4,
                                    IsValid = true,
                                    Key = waypointToken.SpartanToken
                                };
                                sqlStorage.Authentications.AddOrUpdate(a => a.Type, authentication);
                                sqlStorage.SaveChanges();

                                everythingWentGucci = true;
                            }
                        }
                        catch (Exception ex)
                        {
                            Trace.TraceError(ex.ToString());
                            everythingWentGucci = false;
                        }
                    }

                    if (everythingWentGucci)
                        break;
                }

                if (everythingWentGucci)
                    return true;

                // make sure halo 4 auth row has been deleted
                var invalidAuthentication = sqlStorage.Authentications.FirstOrDefault(a => a.Type == AuthenticationType.Halo4);
                if (invalidAuthentication != null)
                {
                    invalidAuthentication.Key = null;
                    invalidAuthentication.IsValid = false;
                }

                // send glorious email!
                var text =
                    String.Format(
                        "Sup guys, {0}Halo 4's authenication failed to update. Might want to look into it. Below is the response the server recieved from the auth service: {0}{0}{1}{0}{0}Best Regards,{0}Branch",
                        Environment.NewLine, strResponse);

                new Web(new NetworkCredential(CloudConfigurationManager.GetSetting("SendGridUser"),
                    CloudConfigurationManager.GetSetting("SendGridPass"))).Deliver(
                        new SendGridMessage(new MailAddress("*****@*****.**"),
                            new[]
                            {
                                new MailAddress(CloudConfigurationManager.GetSetting("SendGridTo")),
                                new MailAddress("*****@*****.**"),
                            },
                            "[Halo 4] Authentication Failed", null, text));

                sqlStorage.SaveChanges();

                return false;
            }
        }
Пример #37
0
        /// <summary>Adds a new tableName with the specified name.</summary>
        /// <param name="layout">Layout of the tableName.</param>
        /// <param name="flags">The flags for tableName creation.</param>
        /// <returns>Returns an <see cref="ITable" /> instance for the specified tableName.</returns>
        public override ITable CreateTable(RowLayout layout, TableFlags flags = default)
        {
            if (layout == null)
            {
                throw new ArgumentNullException(nameof(layout));
            }

            Trace.TraceInformation($"Creating tableName {layout}");
            if (layout.Name.HasInvalidChars(ASCII.Strings.SafeName))
            {
                throw new ArgumentException($"Table name {layout.Name} contains invalid chars!");
            }

            var queryText = new StringBuilder();

            queryText.Append("CREATE ");
            if ((flags & TableFlags.InMemory) != 0)
            {
                queryText.Append("UNLOGGED ");
            }

            queryText.Append($"TABLE {SqlStorage.FQTN(Name, layout.Name)} (");
            for (var i = 0; i < layout.FieldCount; i++)
            {
                var fieldProperties = layout[i];
                if (i > 0)
                {
                    queryText.Append(',');
                }

                var fieldName = SqlStorage.EscapeFieldName(fieldProperties);
                queryText.Append(fieldName);
                queryText.Append(' ');
                switch (fieldProperties.TypeAtDatabase)
                {
                case DataType.Binary:
                    if ((fieldProperties.Flags & FieldFlags.AutoIncrement) != 0)
                    {
                        throw new NotSupportedException($"AutoIncrement is not supported on data type {fieldProperties.TypeAtDatabase}");
                    }

                    queryText.Append("BYTEA");
                    break;

                case DataType.Bool:
                    if ((fieldProperties.Flags & FieldFlags.AutoIncrement) != 0)
                    {
                        throw new NotSupportedException($"AutoIncrement is not supported on data type {fieldProperties.TypeAtDatabase}");
                    }

                    queryText.Append("BOOL");
                    break;

                case DataType.DateTime:
                    if ((fieldProperties.Flags & FieldFlags.AutoIncrement) != 0)
                    {
                        throw new NotSupportedException($"AutoIncrement is not supported on data type {fieldProperties.TypeAtDatabase}");
                    }

                    queryText.Append("TIMESTAMP WITH TIME ZONE");
                    break;

                case DataType.TimeSpan:
                    if ((fieldProperties.Flags & FieldFlags.AutoIncrement) != 0)
                    {
                        throw new NotSupportedException($"AutoIncrement is not supported on data type {fieldProperties.TypeAtDatabase}");
                    }

                    queryText.Append("FLOAT8");
                    break;

                case DataType.Int8:
                    if ((fieldProperties.Flags & FieldFlags.AutoIncrement) != 0)
                    {
                        throw new NotSupportedException($"AutoIncrement is not supported on data type {fieldProperties.TypeAtDatabase}");
                    }

                    queryText.Append("SMALLINT");
                    break;

                case DataType.Int16:
                    if ((fieldProperties.Flags & FieldFlags.AutoIncrement) != 0)
                    {
                        queryText.Append("SMALLSERIAL");
                    }
                    else
                    {
                        queryText.Append("SMALLINT");
                    }

                    break;

                case DataType.Int32:
                    if ((fieldProperties.Flags & FieldFlags.AutoIncrement) != 0)
                    {
                        queryText.Append("SERIAL");
                    }
                    else
                    {
                        queryText.Append("INTEGER");
                    }

                    break;

                case DataType.Int64:
                    if ((fieldProperties.Flags & FieldFlags.AutoIncrement) != 0)
                    {
                        queryText.Append("BIGSERIAL");
                    }
                    else
                    {
                        queryText.Append("BIGINT");
                    }

                    break;

                case DataType.Single:
                    if ((fieldProperties.Flags & FieldFlags.AutoIncrement) != 0)
                    {
                        throw new NotSupportedException($"AutoIncrement is not supported on data type {fieldProperties.TypeAtDatabase}");
                    }

                    queryText.Append("FLOAT4");
                    break;

                case DataType.Double:
                    if ((fieldProperties.Flags & FieldFlags.AutoIncrement) != 0)
                    {
                        throw new NotSupportedException($"AutoIncrement is not supported on data type {fieldProperties.TypeAtDatabase}");
                    }

                    queryText.Append("FLOAT8");
                    break;

                case DataType.Enum:
                    if ((fieldProperties.Flags & FieldFlags.AutoIncrement) != 0)
                    {
                        throw new NotSupportedException($"AutoIncrement is not supported on data type {fieldProperties.TypeAtDatabase}");
                    }

                    queryText.Append("BIGINT");
                    break;

                case DataType.UInt8:
                    if ((fieldProperties.Flags & FieldFlags.AutoIncrement) != 0)
                    {
                        throw new NotSupportedException($"AutoIncrement is not supported on data type {fieldProperties.TypeAtDatabase}");
                    }

                    queryText.Append($"SMALLINT CHECK ({fieldName} >= 0 AND {fieldName} <= {byte.MaxValue})");
                    break;

                case DataType.UInt16:
                    if ((fieldProperties.Flags & FieldFlags.AutoIncrement) != 0)
                    {
                        throw new NotSupportedException($"AutoIncrement is not supported on data type {fieldProperties.TypeAtDatabase}");
                    }

                    queryText.Append($"INT CHECK ({fieldName} >= 0 AND {fieldName} <= {ushort.MaxValue})");
                    break;

                case DataType.UInt32:
                    if ((fieldProperties.Flags & FieldFlags.AutoIncrement) != 0)
                    {
                        throw new NotSupportedException($"AutoIncrement is not supported on data type {fieldProperties.TypeAtDatabase}");
                    }

                    queryText.Append($"BIGINT CHECK ({fieldName} >= 0 AND {fieldName} <= {uint.MaxValue})");
                    break;

                case DataType.UInt64:
                    if ((fieldProperties.Flags & FieldFlags.AutoIncrement) != 0)
                    {
                        throw new NotSupportedException($"AutoIncrement is not supported on data type {fieldProperties.TypeAtDatabase}");
                    }

                    queryText.Append($"NUMERIC(20,0) CHECK ({fieldName} >= 0 AND {fieldName} <= {ulong.MaxValue})");
                    break;

                case DataType.User:
                case DataType.String:
                    if ((fieldProperties.Flags & FieldFlags.AutoIncrement) != 0)
                    {
                        throw new NotSupportedException($"AutoIncrement is not supported on data type {fieldProperties.TypeAtDatabase}");
                    }

                    if (fieldProperties.MaximumLength <= 0)
                    {
                        queryText.Append("TEXT");
                    }
                    else
                    {
                        queryText.Append($"VARCHAR({fieldProperties.MaximumLength})");
                    }

                    break;

                case DataType.Decimal:
                    if ((fieldProperties.Flags & FieldFlags.AutoIncrement) != 0)
                    {
                        throw new NotSupportedException($"AutoIncrement is not supported on data type {fieldProperties.TypeAtDatabase}");
                    }

                    if (fieldProperties.MaximumLength > 0)
                    {
                        var precision = (int)fieldProperties.MaximumLength;
                        var scale     = (int)((fieldProperties.MaximumLength - precision) * 100);
                        if (scale >= precision)
                        {
                            throw new ArgumentOutOfRangeException(
                                      $"Field {fieldProperties.Name} has an invalid MaximumLength of {precision},{scale}. Correct values range from s,p = 1,0 to 65,30(default value) with 0 < s < p!");
                        }

                        queryText.Append($"DECIMAL({precision},{scale})");
                    }
                    else
                    {
                        queryText.Append("DECIMAL(65,30)");
                    }

                    break;

                default: throw new NotImplementedException($"Unknown DataType {fieldProperties.DataType}!");
                }

                if ((fieldProperties.Flags & FieldFlags.ID) != 0)
                {
                    queryText.Append(" PRIMARY KEY");
                }

                if ((fieldProperties.Flags & FieldFlags.Unique) != 0)
                {
                    queryText.Append(" UNIQUE");
                    switch (fieldProperties.TypeAtDatabase)
                    {
                    case DataType.Bool:
                    case DataType.Char:
                    case DataType.DateTime:
                    case DataType.Decimal:
                    case DataType.Double:
                    case DataType.Enum:
                    case DataType.Int8:
                    case DataType.Int16:
                    case DataType.Int32:
                    case DataType.Int64:
                    case DataType.UInt8:
                    case DataType.UInt16:
                    case DataType.UInt32:
                    case DataType.UInt64:
                    case DataType.Single:
                    case DataType.TimeSpan:
                        break;

                    case DataType.String:
                        if (fieldProperties.MaximumLength <= 0)
                        {
                            throw new NotSupportedException(
                                      $"Unique string fields without length are not supported! Please define Field.MaxLength at tableName {layout.Name} field {fieldProperties.Name}");
                        }

                        break;

                    default: throw new NotSupportedException($"Uniqueness for tableName {layout.Name} field {fieldProperties.Name} is not supported!");
                    }
                }

                if (fieldProperties.Description != null)
                {
                    if (fieldProperties.Description.HasInvalidChars(ASCII.Strings.Printable))
                    {
                        throw new ArgumentException("Description of field '{0}' contains invalid chars!", fieldProperties.Name);
                    }

                    queryText.Append(" COMMENT '" + fieldProperties.Description.Substring(0, 60) + "'");
                }
            }

            queryText.Append(')');
            SqlStorage.Execute(database: Name, table: layout.Name, cmd: queryText.ToString());
            for (var i = 0; i < layout.FieldCount; i++)
            {
                var fieldProperties = layout[i];
                if ((fieldProperties.Flags & FieldFlags.ID) != 0)
                {
                    continue;
                }

                if ((fieldProperties.Flags & FieldFlags.Index) != 0)
                {
                    var name = PgSqlStorage.GetObjectName($"idx_{layout.Name}_{fieldProperties.Name}");
                    var cmd  = $"CREATE INDEX {name} ON {SqlStorage.FQTN(Name, layout.Name)} ({SqlStorage.EscapeFieldName(fieldProperties)})";
                    SqlStorage.Execute(database: Name, table: layout.Name, cmd: cmd);
                }
            }

            return(GetTable(layout));
        }
Пример #38
0
        //
        // GET: /Search/Identity/{ident}?q={q}&page={page:0}
        public ActionResult Identity(string ident, string q, int? page = 0)
        {
            if (page == null || page < 0)
                return RedirectToAction("Identity", "Search", new { ident, q, page = 0 });

            if (String.IsNullOrEmpty(q))
                return FlashMessage.RedirectAndFlash(
                    Response, RedirectToAction("Index", "Home", new { area = "" }), FlashMessage.FlashMessageType.Info,
                    "Missing Search Term", "Ey man, there was no search term there.");

            if (String.IsNullOrWhiteSpace(ident))
                return RedirectToAction("Index", "Search", new { q });

            SearchIdent searchIdent;
            if (!Enum.TryParse(ident, true, out searchIdent))
                return FlashMessage.RedirectAndFlash(
                    Response, RedirectToAction("Index", "Search"), FlashMessage.FlashMessageType.Info,
                    "Invalid Search Identity", "Now Now Bae.. You can't be searchin' like that.");

            using (var sqlStorage = new SqlStorage())
            {
                List<Halo4Identity> halo4Identities = null;
                List<ReachIdentity> reachIdentities = null;

                bool hasMorePages;
                switch (searchIdent)
                {
                    case SearchIdent.Halo4:
                        GlobalStorage.H4Manager.GetPlayerServiceRecord(q, true);
                        halo4Identities = sqlStorage.Halo4Identities
                            .Include(i => i.GamerIdentity)
                            .Where(i => i.GamerIdentity.GamerId.Contains(q))
                            .OrderBy(i => i.GamerIdentity.GamerId)
                            .Skip(12*((int) page))
                            .Take(13)
                            .ToList();

                        hasMorePages = halo4Identities.Count() == 13;
                        if (hasMorePages) halo4Identities = halo4Identities.Take(12).ToList();
                        break;

                    case SearchIdent.Reach:
                        GlobalStorage.HReachManager.GetPlayerServiceRecord(q, true);
                        reachIdentities = sqlStorage.ReachIdentities
                            .Include(i => i.GamerIdentity)
                            .Where(i => i.GamerIdentity.GamerId.Contains(q))
                            .OrderBy(i => i.GamerIdentity.GamerId)
                            .Skip(12*((int) page))
                            .Take(13)
                            .ToList();

                        hasMorePages = reachIdentities.Count() == 13;
                        if (hasMorePages) reachIdentities = reachIdentities.Take(12).ToList();
                        break;

                    default:
                        return RedirectToAction("Index", "Search", new {q});
                }

                return View("Identity", new SearchIdentityViewModel(searchIdent, halo4Identities, reachIdentities, q, (int) page, hasMorePages));
            }
        }
Пример #39
0
        /// <inheritdoc />
        public override ITable CreateTable(RowLayout layout, TableFlags flags)
        {
            if (layout == null)
            {
                throw new ArgumentNullException(nameof(layout));
            }

            if ((flags & TableFlags.InMemory) != 0)
            {
                throw new NotSupportedException($"Table '{layout.Name}' does not support TableFlags.{flags}");
            }

            if (layout.Name.HasInvalidChars(ASCII.Strings.SafeName))
            {
                throw new ArgumentException($"Table name {layout.Name} contains invalid chars!");
            }

            var queryText = new StringBuilder();

            queryText.Append($"CREATE TABLE {SqlStorage.FQTN(Name, layout.Name)} (");
            for (var i = 0; i < layout.FieldCount; i++)
            {
                var fieldProperties = layout[i];
                if (i > 0)
                {
                    queryText.Append(",");
                }

                queryText.Append(fieldProperties.NameAtDatabase);
                queryText.Append(" ");
                var valueType = SQLiteStorage.GetValueType(fieldProperties.DataType);
                switch (valueType)
                {
                case SQLiteValueType.BLOB:
                    queryText.Append("BLOB");
                    break;

                case SQLiteValueType.INTEGER:
                    queryText.Append("INTEGER");
                    break;

                case SQLiteValueType.REAL:
                    queryText.Append("REAL");
                    break;

                case SQLiteValueType.TEXT:
                    queryText.Append("TEXT");
                    break;

                default: throw new NotImplementedException($"Unknown ValueType {valueType}!");
                }

                if ((fieldProperties.Flags & FieldFlags.ID) != 0)
                {
                    queryText.Append(" PRIMARY KEY");
                }

                if ((fieldProperties.Flags & FieldFlags.AutoIncrement) != 0)
                {
                    queryText.Append(" AUTOINCREMENT");
                }

                if ((fieldProperties.Flags & FieldFlags.Unique) != 0)
                {
                    queryText.Append(" UNIQUE");
                }
            }

            queryText.Append(")");
            SqlStorage.Execute(database: Name, table: layout.Name, cmd: queryText.ToString());
            for (var i = 0; i < layout.FieldCount; i++)
            {
                var fieldProperties = layout[i];
                if ((fieldProperties.Flags & FieldFlags.ID) != 0)
                {
                    continue;
                }

                if ((fieldProperties.Flags & FieldFlags.Index) != 0)
                {
                    var command = $"CREATE INDEX {"idx_" + layout.Name + "_" + fieldProperties.Name} ON {layout.Name} ({fieldProperties.Name})";
                    SqlStorage.Execute(database: Name, table: layout.Name, cmd: command);
                }
            }

            return(GetTable(layout));
        }