예제 #1
0
        public void UpdateRarity(IList <BuddyItem> items)
        {
            // This will need a custom table, mapping 'yellow' to priority 0 and the like
            Logger.Debug("Updating item rarities");

            // TODO: Change player item to buddy item
            string sql = $@"
                SELECT {DatabaseItemTable.Record} as Record, {DatabaseItemStatTable.TextValue} as Rarity 
                FROM {DatabaseItemTable.Table} item, {DatabaseItemStatTable.Table} stat
                WHERE item.{DatabaseItemTable.Id} = stat.{DatabaseItemStatTable.Item}
                AND {DatabaseItemStatTable.Stat} = 'itemClassification'
                AND ({DatabaseItemTable.Record} IN (SELECT {BuddyItemsTable.BaseRecord} FROM {BuddyItemsTable.Table} WHERE {BuddyItemsTable.Rarity} IS NULL)
                    OR {DatabaseItemTable.Record} IN (SELECT {BuddyItemsTable.PrefixRecord} FROM {BuddyItemsTable.Table} WHERE {BuddyItemsTable.Rarity} IS NULL)
                    OR {DatabaseItemTable.Record} IN (SELECT {BuddyItemsTable.SuffixRecord} FROM {BuddyItemsTable.Table} WHERE {BuddyItemsTable.Rarity} IS NULL)
                )";

            IList <RarityRow> rows;

            using (ISession session = SessionCreator.OpenSession()) {
                using (session.BeginTransaction()) {
                    rows = session.CreateSQLQuery(sql)
                           .SetResultTransformer(Transformers.AliasToBean <RarityRow>())
                           .List <RarityRow>();
                }
            }

            Logger.Debug("Updating the rarity for buddy items");
            string updateSql = $"UPDATE {BuddyItemsTable.Table} SET {BuddyItemsTable.Rarity} = :rarity WHERE {BuddyItemsTable.RemoteItemId} = :id";

            using (ISession session = SessionCreator.OpenSession()) {
                using (ITransaction transaction = session.BeginTransaction()) {
                    foreach (var item in items)
                    {
                        string rarity = GetRarity(item, rows);
                        session.CreateSQLQuery(updateSql)
                        .SetParameter("id", item.RemoteItemId)
                        .SetParameter("rarity", rarity)
                        .ExecuteUpdate();
                    }

                    transaction.Commit();
                }
            }

            Logger.Debug("Rarities updated");
        }
예제 #2
0
        private HttpResponse RouteRequest()
        {
            var matchedRoutes = this.routes
                                .Where(r => Regex.Match(this.request.Url, r.UrlRegex).Success)
                                .ToList();

            if (!matchedRoutes.Any())
            {
                return(HttpResponseBuilder.NotFound());
            }

            var route = matchedRoutes.FirstOrDefault(r => r.Method == this.request.Method);

            if (route == null)
            {
                return(new HttpResponse()
                {
                    StatusCode = ResponseStatusCode.MethodNotAllowed
                });
            }

            try
            {
                HttpResponse resultResponse;
                if (!this.request.Header.Cookies.ContainsKey("sessionId") || this.request.Session == null)
                {
                    var session       = SessionCreator.Create();
                    var sessionCookie = new Cookie("sessionId", session.Id + "; HttpOnly; path=/");
                    this.request.Session = session;
                    resultResponse       = route.Callable(this.request);
                    resultResponse.Header.AddCookie(sessionCookie);
                }
                else
                {
                    resultResponse = route.Callable(this.request);
                }

                return(resultResponse);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                Console.WriteLine(ex.StackTrace);
                return(HttpResponseBuilder.InternalServerError());
            }
        }
예제 #3
0
        public void SetUuid(string uuid)
        {
            using (ISession session = SessionCreator.OpenSession()) {
                using (ITransaction transaction = session.BeginTransaction()) {
                    if (session.CreateQuery("UPDATE DatabaseSetting SET V2 = :value WHERE Id = 'Uuid'")
                        .SetParameter("value", uuid)
                        .ExecuteUpdate() == 0)
                    {
                        session.Save(new DatabaseSetting {
                            Id = "Uuid", V2 = uuid
                        });
                    }

                    transaction.Commit();
                }
            }
        }
예제 #4
0
        public void Logout(HttpResponse response, string sessionId)
        {
            var login = this.Data.Logins.Query().FirstOrDefault(l => l.SessionId == sessionId && l.IsActive);

            if (login != null)
            {
                this.Data.Logins.Delete(login);
            }

            this.Data.SaveChanges();

            var session = SessionCreator.Create();

            var sessionCookie = new Cookie("sessionId", session.Id + "; HttpOnly; path=/");

            response.Header.AddCookie(sessionCookie);
        }
예제 #5
0
        /// <summary>
        /// Update the "IsHardcore" flag depending on being an old Hard
        /// </summary>
        public void UpdateHardcoreSettings()
        {
            using (ISession session = SessionCreator.OpenSession()) {
                using (ITransaction transaction = session.BeginTransaction()) {
                    bool value = (bool)Properties.Settings.Default.IsHardcore;
                    int  n     = session.CreateQuery("UPDATE PlayerItem SET IsHardcore = :val WHERE IsHardcore IS NULL")
                                 .SetParameter("val", value)
                                 .ExecuteUpdate();

                    if (n > 0)
                    {
                        transaction.Commit();
                        Logger.InfoFormat("Updated the IsHardcore flag for {0} items to: {1}", n, value);
                    }
                }
            }
        }
예제 #6
0
        public void DeleteAll(bool isHardcore)
        {
            using (ISession session = SessionCreator.OpenSession()) {
                using (ITransaction transaction = session.BeginTransaction()) {
                    if (isHardcore)
                    {
                        session.CreateQuery("DELETE FROM RecipeItem WHERE IsHardcore").ExecuteUpdate();
                    }
                    else
                    {
                        session.CreateQuery("DELETE FROM RecipeItem WHERE NOT IsHardcore").ExecuteUpdate();
                    }

                    transaction.Commit();
                }
            }
        }
예제 #7
0
        public void SetAzureIds(List <AzureUploadedItem> mappings)
        {
            using (var session = SessionCreator.OpenSession()) {
                using (var transaction = session.BeginTransaction()) {
                    foreach (var entry in mappings)
                    {
                        session.CreateQuery($"UPDATE PlayerItem SET {PlayerItemTable.AzureUuid} = :uuid, {PlayerItemTable.AzurePartition} = :partition WHERE Id = :id")
                        .SetParameter("uuid", entry.Id)
                        .SetParameter("partition", entry.Partition)
                        .SetParameter("id", entry.LocalId)
                        .ExecuteUpdate();
                    }

                    transaction.Commit();
                }
            }
        }
예제 #8
0
        public void Update(IList <PlayerItem> items, bool clearOnlineId)
        {
            const string table = nameof(PlayerItem);
            const string stack = nameof(PlayerItem.StackCount);
            var          id    = nameof(PlayerItem.Id);

            using (ISession session = SessionCreator.OpenSession()) {
                using (ITransaction transaction = session.BeginTransaction()) {
                    foreach (var item in items)
                    {
                        // This is if an item has been deleted due to a transfer to stash

                        /*
                         * if (clearOnlineId && !string.IsNullOrEmpty(item.AzureUuid) ) {
                         *  session.CreateSQLQuery($"INSERT OR IGNORE INTO {DeletedPlayerItemTable.Table} ({DeletedPlayerItemTable.Id}) VALUES (:id)")
                         *      .SetParameter("id", item.OnlineId.Value)
                         *      .ExecuteUpdate();
                         *
                         *  item.OnlineId = null;
                         * }*/

                        session.CreateQuery($"UPDATE {table} SET {stack} = :count, {PlayerItemTable.AzureUuid} = :uuid WHERE {id} = :id")
                        .SetParameter("count", item.StackCount)
                        .SetParameter("id", item.Id)
                        .SetParameter("uuid", item.AzureUuid)
                        .ExecuteUpdate();
                    }

                    // insert into DeletedPlayerItem(oid) select onlineid from playeritem where onlineid is not null and stackcount <= 0 and id in (1,2,3)
                    session.CreateSQLQuery($" INSERT OR IGNORE INTO {DeletedPlayerItemTable.Table} ({DeletedPlayerItemTable.Id}, {DeletedPlayerItemTable.Partition}) " +
                                           $" SELECT {PlayerItemTable.AzureUuid}, {PlayerItemTable.AzurePartition} FROM {PlayerItemTable.Table} " +
                                           $" WHERE {PlayerItemTable.AzureUuid} IS NOT NULL " +
                                           $" AND {PlayerItemTable.Stackcount} <= 0 " +
                                           $" AND {PlayerItemTable.Id} IN ( :ids )")
                    .SetParameterList("ids", items.Select(m => m.Id).ToList())
                    .ExecuteUpdate();

                    // Delete any items with stacksize 0 (but only newly transferred ones, ignore any older items in case of errors)
                    session.CreateQuery($"DELETE FROM {table} WHERE {stack} <= 0 AND {id} IN ( :ids )")
                    .SetParameterList("ids", items.Select(m => m.Id).ToList())
                    .ExecuteUpdate();

                    transaction.Commit();
                }
            }
        }
예제 #9
0
        /// <summary>
        /// Update the internal timestamp indicating that a database update has taken place
        /// </summary>
        /// <param name="ts"></param>
        /// <returns></returns>
        public void UpdateDatabaseTimestamp(long ts)
        {
            using (ISession session = SessionCreator.OpenSession()) {
                using (ITransaction transaction = session.BeginTransaction()) {
                    if (session.CreateQuery("UPDATE DatabaseSetting SET V1 = :value WHERE Id = 'LastUpdate'")
                        .SetParameter("value", ts)
                        .ExecuteUpdate() == 0)
                    {
                        session.Save(new DatabaseSetting {
                            Id = "LastUpdate", V1 = ts
                        });
                    }

                    transaction.Commit();
                }
            }
        }
        public async Task HandleMessage()
        {
            // arrange
            string sessionId = await SessionCreator.CreateSessionAsync();

            var handler = new PublishNewSchemaDocumentHandler(
                Storage, SchemaRepository, PublishSchemaEventSender);

            var schema = new Schema("abc", "def");
            await SchemaRepository.AddSchemaAsync(schema);

            var environment = new Environment("abc", "def");
            await EnvironmentRepository.AddEnvironmentAsync(environment);

            var message = new PublishDocumentMessage(
                sessionId, environment.Id, schema.Id, "externalId", Array.Empty <Tag>());

            IFileContainer fileContainer = await Storage.CreateContainerAsync(sessionId);

            byte[] buffer = Encoding.UTF8.GetBytes(@"
                    type Query {
                        foo: String
                    }
                ");
            await fileContainer.CreateFileAsync("schema.graphql", buffer, 0, buffer.Length);

            // act
            await handler.HandleAsync(message, default);

            // assert
            var list = new List <PublishDocumentEvent>();

            using var cts = new CancellationTokenSource(5000);
            IAsyncEnumerable <PublishDocumentEvent> eventStream =
                await PublishSchemaEventReceiver.SubscribeAsync(sessionId, cts.Token);

            await foreach (PublishDocumentEvent eventMessage in
                           eventStream.WithCancellation(cts.Token))
            {
                list.Add(eventMessage);
            }
            list.MatchSnapshot(matchOption =>
                               matchOption.Assert(fieldOption =>
                                                  Assert.Equal(sessionId, fieldOption.Field <string>("[0].SessionId"))));
        }
예제 #11
0
 public ISet <ItemTag> GetValidClassItemTags()
 {
     using (var session = SessionCreator.OpenStatelessSession()) {
         using (session.BeginTransaction()) {
             return(session.CreateSQLQuery("SELECT * FROM ItemTag WHERE (Tag LIKE 'tagSkillClassName%' OR Tag LIKE 'tag%Class%SkillName00A') AND LENGTH(Name) > 1")
                    .SetResultTransformer(new AliasToBeanResultTransformer(typeof(ItemTag)))
                    .List <ItemTag>()
                    .Select(m => new ItemTag {
                 Name = m.Name,
                 Tag = m.Tag.Replace("tagSkillClassName", "class")
                       .Replace("tagGDX1Class07SkillName00A", "class07")
                       .Replace("tagGDX1Class08SkillName00A", "class08")
                       .Replace("tagGDX2Class09SkillName00A", "class09")   // TODO: A regex or similar to auto detect new classes?
             })
                    .ToHashSet());
         }
     }
 }
예제 #12
0
        public string GetSkillName(string skillRecord)
        {
            // TODO:
            // buffSkillName => New query, nature's blessing is a buff and thus has no name on the root
            string sql = $" SELECT t.{ItemTagTable.Name} FROM {DatabaseItemTable.Table} i, {DatabaseItemStatTable.Table} s, {ItemTagTable.Table} t " +
                         $" WHERE {DatabaseItemStatTable.Stat} = 'skillDisplayName' " +
                         $" AND s.{DatabaseItemStatTable.Item} = i.{DatabaseItemTable.Id} " +
                         $" AND i.{DatabaseItemTable.Record} = :record " +
                         $" AND t.{ItemTagTable.Id} = s.{DatabaseItemStatTable.TextValue} ";

            using (var session = SessionCreator.OpenSession()) {
                string result = session.CreateSQLQuery(sql)
                                .SetParameter("record", skillRecord)
                                .UniqueResult <string>();

                return(result);
            }
        }
예제 #13
0
        public void Import(List <PlayerItem> items)
        {
            Logger.Debug($"Importing {items.Count} new items");

            // Attempt to exclude any items already owned, only applicable for users with online sync enabled
            IList <long> existingItems;

            using (ISession session = SessionCreator.OpenSession()) {
                using (ITransaction transaction = session.BeginTransaction()) {
                    existingItems = session.CreateCriteria <PlayerItem>()
                                    .Add(Restrictions.Gt(nameof(PlayerItem.OnlineId), 0L))
                                    .SetProjection(Projections.Property(nameof(PlayerItem.OnlineId)))
                                    .List <long>();
                }
            }

            Save(items.Where(m => !m.OnlineId.HasValue || !existingItems.Contains(m.OnlineId.Value)));
        }
예제 #14
0
        public void Save(IEnumerable <DatabaseItemStat> objs, ProgressTracker progressTracker)
        {
            var databaseItemStats = objs as DatabaseItemStat[] ?? objs.ToArray();

            progressTracker.MaxValue = databaseItemStats.Length;
            using (ISession session = SessionCreator.OpenSession()) {
                using (ITransaction transaction = session.BeginTransaction()) {
                    foreach (var entry in databaseItemStats)
                    {
                        session.Save(entry);
                        progressTracker.Increment();
                    }
                    transaction.Commit();
                }
            }

            progressTracker.MaxProgress();
        }
예제 #15
0
        /// <summary>
        /// Get the path to the latest database parsed
        /// </summary>
        /// <returns></returns>
        public string GetCurrentDatabasePath()
        {
            using (ISession session = SessionCreator.OpenSession()) {
                using (ITransaction transaction = session.BeginTransaction()) {
                    object result = session.CreateCriteria <DatabaseSetting>()
                                    .Add(Restrictions.Eq("Id", "CurrentDatabase"))
                                    .UniqueResult();


                    if (result != null)
                    {
                        return((result as DatabaseSetting).V2);
                    }
                }
            }

            return(string.Empty);
        }
예제 #16
0
        public void Update(IList <PlayerItem> items, bool clearOnlineId)
        {
            var table = nameof(PlayerItem);
            var stack = nameof(PlayerItem.StackCount);
            var id    = nameof(PlayerItem.Id);

            using (ISession session = SessionCreator.OpenSession()) {
                using (ITransaction transaction = session.BeginTransaction()) {
                    foreach (var item in items)
                    {
                        if (clearOnlineId && item.OnlineId.HasValue)
                        {
                            session.CreateSQLQuery($"INSERT OR IGNORE INTO {DeletedPlayerItemTable.Table} ({DeletedPlayerItemTable.Id}) VALUES (:id)")
                            .SetParameter("id", item.OnlineId.Value)
                            .ExecuteUpdate();

                            item.OnlineId = null;
                        }

                        session.CreateQuery($"UPDATE {table} SET {stack} = :count, {PlayerItemTable.OnlineId} = :oid WHERE {id} = :id")
                        .SetParameter("count", item.StackCount)
                        .SetParameter("id", item.Id)
                        .SetParameter("oid", item.OnlineId)
                        .ExecuteUpdate();
                    }

                    // insert into DeletedPlayerItem(oid) select onlineid from playeritem where onlineid is not null and stackcount <= 0 and id in (1,2,3)
                    session.CreateSQLQuery($" INSERT OR IGNORE INTO {DeletedPlayerItemTable.Table} ({DeletedPlayerItemTable.Id}) " +
                                           $" SELECT {PlayerItemTable.OnlineId} FROM {PlayerItemTable.Table} " +
                                           $" WHERE {PlayerItemTable.OnlineId} IS NOT NULL " +
                                           $" AND {PlayerItemTable.Stackcount} <= 0 " +
                                           $" AND {PlayerItemTable.Id} IN ( :ids )")
                    .SetParameterList("ids", items.Select(m => m.Id).ToList())
                    .ExecuteUpdate();

                    // Delete any items with stacksize 0 (but only newly transferred ones, ignore any older items in case of errors)
                    session.CreateQuery($"DELETE FROM {table} WHERE {stack} <= 0 AND {id} IN ( :ids )")
                    .SetParameterList("ids", items.Select(m => m.Id).ToList())
                    .ExecuteUpdate();

                    transaction.Commit();
                }
            }
        }
예제 #17
0
        public void UpdateLevelRequirements(IList <BuddyItem> items)
        {
            Logger.Debug("Updating item level requirements");

            string sql = $@"
                SELECT {DatabaseItemTable.Record} as Record, {DatabaseItemStatTable.Value} as LevelRequirement 
                FROM {DatabaseItemTable.Table} item, {DatabaseItemStatTable.Table} stat
                WHERE item.{DatabaseItemTable.Id} = stat.{DatabaseItemStatTable.Item}
                AND {DatabaseItemStatTable.Stat} = 'levelRequirement'
                AND ({DatabaseItemTable.Record} IN (SELECT {BuddyItemsTable.BaseRecord} FROM {BuddyItemsTable.Table})
                    OR {DatabaseItemTable.Record} IN (SELECT {BuddyItemsTable.PrefixRecord} FROM {BuddyItemsTable.Table})
                    OR {DatabaseItemTable.Record} IN (SELECT {BuddyItemsTable.SuffixRecord} FROM {BuddyItemsTable.Table})
                )";

            IList <LevelRequirementRow> rows;

            using (ISession session = SessionCreator.OpenSession()) {
                using (session.BeginTransaction()) {
                    rows = session.CreateSQLQuery(sql)
                           .SetResultTransformer(Transformers.AliasToBean <LevelRequirementRow>())
                           .List <LevelRequirementRow>();
                }
            }

            Logger.Debug("Updating the level requirements for buddy items");
            string updateSql = $"UPDATE {BuddyItemsTable.Table} SET {BuddyItemsTable.LevelRequirement} = :requirement WHERE {BuddyItemsTable.RemoteItemId} = :id";

            using (ISession session = SessionCreator.OpenSession()) {
                using (ITransaction transaction = session.BeginTransaction()) {
                    foreach (var item in items)
                    {
                        var requirement = GetLevelRequirement(item, rows);
                        session.CreateSQLQuery(updateSql)
                        .SetParameter("id", item.RemoteItemId)
                        .SetParameter("requirement", requirement)
                        .ExecuteUpdate();
                    }

                    transaction.Commit();
                }
            }

            Logger.Debug("Level requirements updated");
        }
예제 #18
0
        /// <summary>
        /// Check whetever we need to recalculate item stats
        /// </summary>
        /// <returns></returns>
        public bool RequiresStatUpdate()
        {
            using (var session = SessionCreator.OpenSession()) {
                using (session.BeginTransaction()) {
                    var itemsLackingRarity = session.CreateCriteria <PlayerItem>().Add(Restrictions.IsNull("Rarity")).List().Count;

                    if (session.CreateCriteria <PlayerItem>().Add(Restrictions.IsNull("Rarity")).List().Count > 50)
                    {
                        Logger.Debug($"A stat parse is required, there are {itemsLackingRarity} items lacking rarity");

                        return(true);
                    }

                    if (session.CreateSQLQuery($"SELECT COUNT(*) as C FROM {SkillTable.Table}").UniqueResult <long>() <= 0)
                    {
                        Logger.Debug("A stat parse is required, there no entries in the skills table");

                        return(true);
                    }

                    var itemsLackingName = session.CreateCriteria <PlayerItem>().Add(Restrictions.IsNull("Name")).List().Count;

                    if (session.CreateCriteria <PlayerItem>().Add(Restrictions.IsNull("Name")).List().Count > 20)
                    {
                        Logger.Debug($"A stat parse is required, there are {itemsLackingName} items lacking a name");

                        return(true);
                    }

                    if (session.QueryOver <PlayerItemRecord>()
                        .ToRowCountInt64Query()
                        .SingleOrDefault <long>() == 0)
                    {
                        Logger.Debug("A stat parse is required, there no entries in the item records table");

                        return(true);
                    }

                    Logger.Debug("A stat parse is not required");

                    return(false);
                }
            }
        }
예제 #19
0
        /// <summary>
        /// Delete duplicate items (items duplicated via bugs, not simply similar items)
        /// </summary>
        public void DeleteDuplidates()
        {
            using (ISession session = SessionCreator.OpenSession()) {
                using (ITransaction transaction = session.BeginTransaction()) {
                    // Mark all duplicates for deletion from online backups
                    session.CreateSQLQuery(@"
insert into deletedplayeritem_v2(partition, id)
select azpartition_v2, azuuid_v2 FROM playeritem WHERE Id IN (
select Id from (
	SELECT COUNT(*) c, baserecord || prefixrecord || modifierrecord || suffixrecord || materiarecord || transmuterecord || seed as UQ, * FROM PlayerItem
	WHERE StackCount < 2
	AND baserecord NOT LIKE '%materia%'
	AND baserecord NOT LIKE '%questitems%'
	AND baserecord NOT LIKE '%potions%'
	AND baserecord NOT LIKE '%crafting%'
	group by UQ
	Order By Id desc
) x 
WHERE c >= 2) 
AND azpartition_v2 IS NOT NULL 
AND azuuid_v2 IS NOT NULL 
AND azuuid_v2 NOT IN (SELECT azuuid_v2 FROM deletedplayeritem_v2)
AND azuuid_v2 != ''
").ExecuteUpdate();
                    // Delete duplicates (if there are multiple, only one will be deleted)
                    int duplicatesDeleted = session.CreateSQLQuery(@"
DELETE FROM PlayerItem WHERE Id IN (
select Id from (
	SELECT COUNT(*) c, baserecord || prefixrecord || modifierrecord || suffixrecord || materiarecord || transmuterecord || seed as UQ, * FROM PlayerItem
	WHERE StackCount < 2
	AND baserecord NOT LIKE '%materia%'
	AND baserecord NOT LIKE '%questitems%'
	AND baserecord NOT LIKE '%potions%'
	AND baserecord NOT LIKE '%crafting%'
	group by UQ
	Order By Id desc
) x 
WHERE c >= 2
)").ExecuteUpdate();

                    transaction.Commit();
                }
            }
        }
예제 #20
0
        public Dictionary <string, string> MapItemBitmaps(List <string> records)
        {
            Dictionary <string, int> bitmapScores = new Dictionary <string, int> {
                ["bitmap"]                    = 10,
                ["relicBitmap"]               = 8,
                ["shardBitmap"]               = 6,
                ["artifactBitmap"]            = 4,
                ["noteBitmap"]                = 2,
                ["artifactFormulaBitmapName"] = 0
            };

            Dictionary <string, string> recordBitmap = new Dictionary <string, string>();

            foreach (string record in records)
            {
                recordBitmap[record] = record;
            }

            // Grab all the possible bitmaps for each record
            using (var session = SessionCreator.OpenSession()) {
                using (ITransaction transaction = session.BeginTransaction()) {
                    DatabaseItemStat stat = null;
                    DatabaseItem     P    = null;
                    var stats             = session.QueryOver <DatabaseItemStat>(() => stat)
                                            .JoinAlias(() => stat.Parent, () => P)
                                            .Where(m => P.Record.IsIn(records))
                                            .Where(m => m.Stat.IsIn(new string[] { "bitmap", "relicBitmap", "shardBitmap", "artifactBitmap", "noteBitmap", "artifactFormulaBitmapName" }))
                                            .List <DatabaseItemStat>();


                    // Find the best bitmap for each record
                    foreach (string record in records)
                    {
                        var best = stats.Where(m => m.Parent.Record.Equals(record)).OrderByDescending(m => bitmapScores[m.Stat]);
                        if (best.Any())
                        {
                            recordBitmap[record] = best.First().TextValue;
                        }
                    }
                }
            }

            return(recordBitmap);
        }
예제 #21
0
        private HttpResponse RouteRequest()
        {
            var routes = this.Routes
                         .Where(x => Regex.Match(Request.Url, x.UrlRegex).Success)
                         .ToList();

            if (!routes.Any())
            {
                return(HttpResponseBuilder.NotFound());
            }

            var route = routes.FirstOrDefault(x => x.Method == Request.Method);

            if (route == null)
            {
                return new HttpResponse()
                       {
                           StatusCode = ResponseStatusCode.MethodNotAllowed
                       }
            }
            ;

            // trigger the route handler...
            try
            {
                var response = route.Callable(Request);

                if (!Request.Header.Cookies.Contains("sessionId") || Request.Session == null)
                {
                    var session       = SessionCreator.Create();
                    var sessionCookie = new Cookie("sessionId", session.Id + "; HttpOnly; path=/");
                    response.Header.AddCookie(sessionCookie);
                }

                return(response);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                Console.WriteLine(ex.StackTrace);
                return(HttpResponseBuilder.InternalServerError());
            }
        }
    }
예제 #22
0
        public IList <ItemTag> GetClassItemTags()
        {
            const string namePattern = @"\[ms\](.*)\[fs\](.*)";

            using (var session = SessionCreator.OpenStatelessSession()) {
                using (session.BeginTransaction()) {
                    return(session.CreateCriteria <ItemTag>()
                           .Add(Restrictions.Like(nameof(ItemTag.Tag), "tagSkillClassName%"))
                           .List <ItemTag>()
                           .Select(m => new ItemTag {
                        Name = Regex.IsMatch(m.Name, namePattern)
                                ? Regex.Replace(m.Name, namePattern, "$1/$2")
                                : m.Name,
                        Tag = m.Tag.Replace("tagSkillClassName", "class")
                    })
                           .ToList());
                }
            }
        }
        public void CreatesNewSession()
        {
            var sessionId       = new SessionId("foo-bar-baz");
            var sessionState    = new New(sessionId);
            var creationDate    = DateTime.UnixEpoch;
            var expectedSession = new RawSession(sessionState, new SessionData(creationDate));

            var sessionIdGenerator = new Mock <ISessionIdGenerator>();

            sessionIdGenerator.Setup(g => g.Generate())
            .Returns(sessionId);
            var dateTimeFactory = new Mock <IDateTimeFactory>();

            dateTimeFactory.Setup(f => f.Now())
            .Returns(creationDate);
            var sessionCreator = new SessionCreator(sessionIdGenerator.Object, dateTimeFactory.Object);

            Assert.Equal(expectedSession, sessionCreator.CreateSession());
        }
예제 #24
0
        /// <summary>
        /// Get the timestamp for the last recipe update
        /// </summary>
        /// <returns></returns>

        /*
         * public long GetLastRecipeUpdate() {
         *  using (ISession session = sessionCreator.OpenSession()) {
         *      using (ITransaction transaction = session.BeginTransaction()) {
         *          object result = session.CreateCriteria<DatabaseSetting>().Add(Restrictions.Eq("Id", "LastRecipeUpdate")).UniqueResult();
         *          if (result != null) {
         *              DatabaseSetting s = result as DatabaseSetting;
         *              return s.V1;
         *          }
         *      }
         *  }
         *
         *  return 0L;
         * }*/

        /// <summary>
        /// Store the current database path
        /// Mainly just for displaying the currently loaded mod (if any)
        /// </summary>
        /// <param name="path"></param>
        public void UpdateCurrentDatabase(string path)
        {
            using (ISession session = SessionCreator.OpenSession()) {
                using (ITransaction transaction = session.BeginTransaction()) {
                    bool updated = session
                                   .CreateQuery("UPDATE DatabaseSetting SET V2 = :value WHERE Id = 'CurrentDatabase'")
                                   .SetParameter("value", path).ExecuteUpdate() != 0;

                    if (!updated)
                    {
                        session.Save(new DatabaseSetting {
                            Id = "CurrentDatabase", V2 = path
                        });
                    }

                    transaction.Commit();
                }
            }
        }
예제 #25
0
        public IList <ItemTag> GetValidClassItemTags()
        {
            Dictionary <string, string> result = new Dictionary <string, string>();

            using (var session = SessionCreator.OpenStatelessSession()) {
                using (ITransaction transaction = session.BeginTransaction()) {
                    return(session.CreateSQLQuery("SELECT * FROM ItemTag WHERE (Tag LIKE 'tagSkillClassName%' OR Tag LIKE 'tag%Class%SkillName00A') AND LENGTH(Name) > 1")
                           .SetResultTransformer(new AliasToBeanResultTransformer(typeof(ItemTag)))
                           .List <ItemTag>()
                           .Select(m => new ItemTag {
                        Name = m.Name,
                        Tag = m.Tag.Replace("tagSkillClassName", "class")
                              .Replace("tagGDX1Class07SkillName00A", "class07")
                              .Replace("tagGDX1Class08SkillName00A", "class08")
                    })
                           .ToList());
                }
            }
        }
예제 #26
0
        public void SaveOrUpdate(ICollection <DatabaseItem> items)
        {
            using (var session = SessionCreator.OpenSession()) {
                using (ITransaction transaction = session.BeginTransaction()) {
                    var records = items.Select(m => m.Record).ToList();
                    foreach (var list in splitList(records, 900))
                    {
                        session.CreateQuery("DELETE FROM DatabaseItemStat WHERE Parent.Id IN (SELECT Id FROM DatabaseItem WHERE Record IN ( :records ) )")
                        .SetParameterList("records", list)
                        .ExecuteUpdate();

                        session.CreateQuery("DELETE FROM DatabaseItem WHERE Record IN ( :records )")
                        .SetParameterList("records", list)
                        .ExecuteUpdate();
                    }
                    transaction.Commit();
                }
            }
            Save(items, false);
        }
예제 #27
0
        public void RemoveBuddy(long buddyId)
        {
            using (ISession session = SessionCreator.OpenSession()) {
                using (ITransaction transaction = session.BeginTransaction()) {
                    session.CreateSQLQuery($"DELETE FROM {BuddyItemsTable.Table} WHERE {BuddyItemsTable.BuddyId} = :id")
                    .SetParameter("id", buddyId)
                    .ExecuteUpdate();

                    session.CreateQuery("DELETE FROM BuddyStash WHERE UserId = :id")
                    .SetParameter("id", buddyId)
                    .ExecuteUpdate();

                    session.CreateQuery("DELETE FROM BuddySubscription WHERE Id = :id")
                    .SetParameter("id", buddyId)
                    .ExecuteUpdate();

                    transaction.Commit();
                }
            }
        }
예제 #28
0
        public IList <DatabaseItemStat> GetRecipeStats(ICollection <string> formulas)
        {
            using (ISession session = SessionCreator.OpenSession()) {
                using (ITransaction transaction = session.BeginTransaction()) {
                    var subquery = Subqueries.PropertyIn("P.Id", DetachedCriteria.For <DatabaseItem>()
                                                         .Add(Restrictions.In("Record", formulas.ToArray()))
                                                         .SetProjection(Projections.Property("Id"))
                                                         );

                    var desiredStats = new[] { "artifactName", "forcedRandomArtifactName" };

                    return(session.CreateCriteria <DatabaseItemStat>()
                           .Add(subquery)
                           .Add(Restrictions.In("Stat", desiredStats))
                           .CreateAlias("Parent", "P")
                           .AddOrder(Order.Desc("Stat"))
                           .List <DatabaseItemStat>());
                }
            }
        }
예제 #29
0
        public IList <DatabaseItemStat> GetRecipeItemStats(ICollection <string> items)
        {
            using (ISession session = SessionCreator.OpenSession()) {
                using (ITransaction transaction = session.BeginTransaction()) {
                    var subquery = Subqueries.PropertyIn("P.Id", DetachedCriteria.For <DatabaseItem>()
                                                         .Add(Restrictions.In("Record", items.Take(Math.Min(items.Count, 950)).ToArray()))
                                                         .SetProjection(Projections.Property("Id"))
                                                         );

                    string[] desiredStats = new string[] { "levelRequirement" };

                    return(session.CreateCriteria <DatabaseItemStat>()
                           .Add(subquery)
                           .Add(Restrictions.In("Stat", desiredStats))
                           .CreateAlias("Parent", "P")
                           .AddOrder(Order.Desc("Stat"))
                           .List <DatabaseItemStat>());
                }
            }
        }
예제 #30
0
        public void Clean()
        {
            // CREATE TABLE DatabaseItemStat_v2 (id_databaseitemstat  integer primary key autoincrement, id_databaseitem BIGINT, Stat TEXT, TextValue TEXT, val1 DOUBLE, constraint FK9663A5FC6B4AFA92 foreign key (id_databaseitem) references DatabaseItem_v2)
            string[] tables = new[] { "DatabaseItemStat_v2", "DatabaseItem_v2", "ItemTag" };
            string   fetchCreateTableQuery = "SELECT sql FROM sqlite_master WHERE type='table' AND name = :table";


            using (ISession session = SessionCreator.OpenSession()) {
                using (ITransaction transaction = session.BeginTransaction()) {
                    foreach (var table in tables)
                    {
                        string recreateQuery = session.CreateSQLQuery(fetchCreateTableQuery).SetParameter("table", table).UniqueResult <string>();
                        session.CreateSQLQuery("DROP TABLE IF EXISTS " + table).ExecuteUpdate();
                        session.CreateSQLQuery(recreateQuery).ExecuteUpdate();
                    }

                    transaction.Commit();
                }
            }
        }
 void Awake()
 {
     if (instance == null || instance == this)
         instance = this;
     else {
         DestroyImmediate(this);
     }
 }