Пример #1
0
        public void ParsTournamentMinusMultistringXml()
        {
            ConfigurationManager.AppSettings["CreateDatabase"] = "0";

            string sXmlString = "";

            DatabaseCache.EnsureDatabaseCache();
            BetDomainMap.EnsureInstance();
            using (var reader = new StreamReader("dc.xml"))
            {
                sXmlString = reader.ReadToEnd();
            }
            var srlc            = LineSerializeHelper.StringToObject <SportRadarLineContainer>(sXmlString);
            UpdateStatistics us = new UpdateStatistics();

            var fsr = LineSr.SyncRoutines(eUpdateType.PreMatches, string.Format("SportRadar Pre-Match Update. DataSyncCacheId = {0}", 0), false, us, delegate(object objParam)
            {
                return(ProviderHelper.MergeFromSportRadarLineContainer(srlc, 0));
            });

            Assert.AreEqual(fsr, eFileSyncResult.Succeeded);
            var instance = LineSr.Instance.AllObjects.Groups.Where(x => x.Value.SvrGroupId == 5263).First();

            Assert.AreEqual(8, instance.Value.Strings.Count);
            Assert.AreEqual("Pro A", instance.Value.GetDisplayName("EN"));
        }
Пример #2
0
        private void HandleGetSimpleNewsManagerPosts(ZipArchive zip, XenonCMSContext DB)
        {
            string RequestDomain = Globals.GetRequestDomain(ControllerContext.RequestContext.HttpContext);
            int    SiteId        = DB.Sites.Single(x => x.Domain == RequestDomain).Id;

            // Handle the NewsManager posts files
            var PostsFiles = GetSimpleGetXmlDocuments(zip, "posts/");

            foreach (var KVP in PostsFiles)
            {
                // Update existing or add new post
                // TODO GetSimple has a "tags" tag
                string Slug = Path.GetFileNameWithoutExtension(KVP.Key);
                var    SBP  = DB.SiteBlogPosts.SingleOrDefault(x => (x.Site.Domain == RequestDomain) && (x.Slug == Slug)) ?? new SiteBlogPost();
                SBP.DateLastUpdated = Convert.ToDateTime(KVP.Value.DocumentElement.SelectSingleNode("date").InnerText);
                SBP.DatePosted      = Convert.ToDateTime(KVP.Value.DocumentElement.SelectSingleNode("date").InnerText);
                SBP.FullPostText    = HttpUtility.HtmlDecode(KVP.Value.DocumentElement.SelectSingleNode("content").InnerText);
                SBP.SiteId          = SiteId;
                SBP.Slug            = Slug;
                SBP.Title           = HttpUtility.HtmlDecode(KVP.Value.DocumentElement.SelectSingleNode("title").InnerText);
                if (SBP.Id <= 0)
                {
                    DB.SiteBlogPosts.Add(SBP);
                }
                DB.SaveChanges();
                DatabaseCache.ResetBlogIndex(ControllerContext.RequestContext.HttpContext);
            }
        }
Пример #3
0
 private static void SubscribeTable(string table, Connection connection, DatabaseCache cache)
 {
     Task.Run(async() =>
     {
         var result = await R.Db("Aetheria").Table(table).Changes()
                      .RunChangesAsync <DatabaseEntry>(connection);
         while (await result.MoveNextAsync())
         {
             var change = result.Current;
             if (change.OldValue == null)
             {
                 _logger.Log(LogLevel.Information,
                             $"Received change from RethinkDB {table} table (Entry Created): {change.NewValue.GetType()} {(change.NewValue as INamedEntry)?.EntryName ?? ""}:{change.NewValue.ID}");
                 cache.Add(change.NewValue, true);
             }
             else if (change.NewValue == null)
             {
                 _logger.Log(LogLevel.Information,
                             $"Received change from RethinkDB {table} table (Entry Deleted): {change.OldValue.GetType()} {(change.OldValue as INamedEntry)?.EntryName ?? ""}:{change.OldValue.ID}");
                 cache.Delete(change.NewValue, true);
             }
             else
             {
                 _logger.Log(LogLevel.Information,
                             $"Received change from RethinkDB {table} table: {change.NewValue.GetType()} {(change.NewValue as INamedEntry)?.EntryName ?? ""}:{change.NewValue.ID}");
                 cache.Add(change.NewValue, true);
             }
         }
     });
 }
Пример #4
0
        public async Task TestRealmsGetter()
        {
            const string         connectionString = "Data Source=(LocalDb)\\MSSQLLocalDB;Initial Catalog=GuildTools;Integrated Security=True";
            KeyedResourceManager manager          = new KeyedResourceManager();

            BlizzardApiSecrets blizzardSecrets = new BlizzardApiSecrets()
            {
                ClientId     = this.config.GetValue <string>("BlizzardApiSecrets:ClientId"),
                ClientSecret = this.config.GetValue <string>("BlizzardApiSecrets:ClientSecret")
            };

            HttpClient        client      = new HttpClient();
            IMemoryCache      memoryCache = new MemoryCache(new MemoryCacheOptions());
            GuildToolsContext context     = new GuildToolsContext(SqlServerDbContextOptionsExtensions.UseSqlServer(new DbContextOptionsBuilder(), connectionString).Options as DbContextOptions);
            IDatabaseCache    dbCache     = new DatabaseCache(context) as IDatabaseCache;

            IDataRepository  repo            = new DataRepository(context);
            IBlizzardService blizzardService = new BlizzardService(repo, this.config, client);

            RealmsCache cache = new RealmsCache(blizzardService, memoryCache, dbCache, manager);

            DateTime initial = DateTime.Now;

            var realms = await cache.GetRealms(EF.Models.Enums.GameRegionEnum.US);

            DateTime second       = DateTime.Now;
            TimeSpan sinceInitial = second - initial;

            var realms2 = await cache.GetRealms(EF.Models.Enums.GameRegionEnum.US);

            DateTime third       = DateTime.Now;
            TimeSpan sinceSecond = third - second;

            int x = 42;
        }
Пример #5
0
        /// <summary>
        /// Gets a season of a tv series by the database id of the series and the sequence number of the season.
        /// </summary>
        /// <param name="tvSeriesId">The if of the tv series.</param>
        /// <param name="seasonNumber">The sequence number of the season.</param>
        /// <returns>The season</returns>
        public static async Task <Season> GetSeasonAsync(int tvSeriesId, int seasonNumber)
        {
            Season season = null;
            var    series = DatabaseCache.GetObject <TVSeries>(tvSeriesId);

            if (series != null)
            {
                var summary = series.SeasonSummaries.FirstOrDefault(s => s.SeasonNumber == seasonNumber);
                if (summary != null)
                {
                    season = DatabaseCache.GetObject <Season>(summary.Id);
                }
            }
            if (season == null)
            {
                var request = new Request <Season>("tv/" + tvSeriesId + "/season/" + seasonNumber);
                if (!string.IsNullOrEmpty(Language))
                {
                    request.AddParameter("language", Language);
                }
                season = await request.ProcesRequestAsync();

                DatabaseCache.SetObject(season.Id, season);
            }
            return(season);
        }
Пример #6
0
        static void Main(string[] args)
        {
            StockcurrentTimeMillis();

            Logger.Init();
            StartTime = Environment.TickCount;
            Settings.Initialize();
            Logger.Info("Settings loaded !");

            Logger.Stage("Database");
            DatabaseManager.Initialize();
            DatabaseCache.Initialize();

            Logger.Stage("Plugins");
            AdminCommandManager.Initialize();
            PlayerCommandManager.Initialize();
            ScriptKernel.Load();
            JSKernel.Load();

            Logger.Stage("Network");
            Network.InterClient.Initialize();
            Network.WorldServer.Initialize();

            Logger.Info("Tera started in " + (Environment.TickCount - StartTime) + "ms");

            while (true)
            {
                Console.ReadLine();
            }
        }
Пример #7
0
        public ModYoutube()
        {
            AddCommands(new []
            {
                new Command
                {
                    Name        = "disableannouncements",
                    IsAdminOnly = true,
                    ActionAsync = async(msg) =>
                    {
                        var chat = DatabaseCache.Chats.First(x => x.Id == msg.Chat.Id);
                        chat.DisableAnnouncements = false;

                        await DatabaseCache.UpdateChat(chat);

                        return(new TextCommandAnswer("Понял, вырубаю"));
                    }
                },
                new Command
                {
                    Name        = "enableannouncements",
                    IsAdminOnly = true,
                    ActionAsync = async(msg) =>
                    {
                        var chat = DatabaseCache.Chats.First(x => x.Id == msg.Chat.Id);
                        chat.DisableAnnouncements = true;

                        await DatabaseCache.UpdateChat(chat);

                        return(new TextCommandAnswer("Понял, врубаю"));
                    }
                },
                new Command
                {
                    Name        = "newscores",
                    ActionAsync = async(msg) =>
                    {
                        try
                        {
                            int amount = int.Parse(msg.Text.Remove(0, 10));
                            if (amount > 20)
                            {
                                return(new TextCommandAnswer(await GetLastScores(default_score_amount)));
                            }
                            else
                            {
                                return(new TextCommandAnswer(await GetLastScores(amount)));
                            }
                        }
                        catch (Exception)
                        {
                            return(new TextCommandAnswer(await GetLastScores(default_score_amount)));
                        }
                    }
                }
            });
        }
Пример #8
0
        private void ResoreCacheIfExists()
        {
            var c  = _database.GetCollection <Cache>(CollectionCache);
            var ci = c.Find(LiteDB.Query.All(), 0, 1).FirstOrDefault();

            if (ci != null)
            {
                DatabaseCache.RestoreFrom(ci);
            }
        }
Пример #9
0
 public void EnsureDatabase(bool isTestMode)
 {
     DatabaseManager.EnsureDatabase(isTestMode);
     if (isTestMode)
     {
         CreateTestMatches();
     }
     DatabaseCache.EnsureDatabaseCache();
     LineSr.EnsureFromCache();
 }
Пример #10
0
        public void DatabaseCacheTest_2()
        {
            DatabaseCacheTest();

            var provider    = new SQLiteDataProvider(@"..\..\..\test_database\resources\covid.db");
            var cacheSystem = new DatabaseCache();

            cacheSystem.Attach(provider);
            cacheSystem.CheckUpdate();    //check if the data is fresh (yesterday is present in the db) and update the db if not
        }
Пример #11
0
        public ActionResult Edit(Edit viewModel)
        {
            if (ModelState.IsValid)
            {
                string RequestDomain = Globals.GetRequestDomain(ControllerContext.RequestContext.HttpContext);

                SitePage EditedPage = db.SitePages.SingleOrDefault(x => (x.Id == viewModel.Id) && (x.Site.Domain == RequestDomain));
                if (EditedPage == null)
                {
                    return(HttpNotFound());
                }
                else
                {
                    // Ensure slug is unique
                    string OldSlug = EditedPage.Slug;
                    string NewSlug = Globals.GetSlug(viewModel.Slug, true);
                    if ((OldSlug != NewSlug) && (db.SitePages.Any(x => (x.Site.Domain == RequestDomain) && (x.Slug == NewSlug))))
                    {
                        ModelState.AddModelError("SlugAlreadyUsed", "Slug has already been used");
                        viewModel.GetLayouts();
                        viewModel.GetParents(db);
                        return(View(viewModel));
                    }
                    else
                    {
                        // View model to domain model
                        ModelConverter.Convert(viewModel, EditedPage);

                        // Assign values for fields not on form
                        EditedPage.DateLastUpdated = DateTime.Now;

                        // Transform values
                        EditedPage.Slug = NewSlug;
                        EditedPage.Html = Globals.SaveImagesToDisk(EditedPage.Html, ControllerContext.HttpContext);

                        // Save changes
                        db.Entry(EditedPage).State = EntityState.Modified;
                        db.SaveChanges();

                        // Update cache
                        DatabaseCache.RemoveSitePage(ControllerContext.RequestContext.HttpContext, OldSlug);
                        DatabaseCache.RemoveSitePage(ControllerContext.RequestContext.HttpContext, NewSlug);
                        DatabaseCache.ResetNavMenuItems(ControllerContext.RequestContext.HttpContext);

                        return(RedirectToAction("Index"));
                    }
                }
            }
            else
            {
                viewModel.GetLayouts();
                viewModel.GetParents(db);
                return(View(viewModel));
            }
        }
Пример #12
0
        public void AddWorksAsExpectedBeforeReachingCapacity()
        {
            DatabaseCache <int> cache = new DatabaseCache <int>(10);

            for (int i = 0; i < 10; ++i)
            {
                Assert.IsFalse(cache.Contains(i));
                cache.Add(i);
                Assert.IsTrue(cache.Contains(i));
            }
        }
 /// <summary>
 /// データベースのキャッシュを初期化
 /// </summary>
 private void InitializeCache()
 {
     try
     {
         _cache = new DatabaseCache <AuthenticationData>(this.container.Context.AuthenticationData);
     }
     catch (Exception ex)
     {
         this.container.Error(ex);
     }
 }
Пример #14
0
        private static async Task GetTable(string table, Connection connection, DatabaseCache cache)
        {
            var result = await R.Db("Aetheria").Table(table).RunCursorAsync <DatabaseEntry>(connection);

            while (await result.MoveNextAsync())
            {
                var entry = result.Current;
                _logger.Log(LogLevel.Information,
                            $"Received {table} entry from RethinkDB: {entry.GetType()} {(entry as INamedEntry)?.EntryName ?? ""}:{entry.ID}");
                cache.Add(entry, true);
            }
        }
Пример #15
0
        public void ExtractTableParameters(string TableName, IDbDataAdapter adapter,
                                           out DatabaseCache InsertCache,
                                           out DatabaseCache DeleteCache,
                                           out DatabaseCache UpdateCache,
                                           out DatabaseCache IsExistCache,
                                           out DataTable dt
                                           )
        {
            adapter.SelectCommand.CommandText = "select top 1 * from " + TableName;

            DataSet ds = new DataSet();

            dt = adapter.FillSchema(ds, SchemaType.Source)[0];

            dt.TableName = TableName;

            SqlCommandBuilder builder = new SqlCommandBuilder(adapter as SqlDataAdapter);

            builder.ConflictOption = ConflictOption.OverwriteChanges;
            //builder.SetAllValues = false;
            SqlCommand InsertCmd = builder.GetInsertCommand(true);

            builder.ConflictOption = ConflictOption.OverwriteChanges;



            InsertCache = new DatabaseCache(InsertCmd.CommandText, InsertCmd.Parameters);
            InsertCache.CurrentTable = dt;

            foreach (DataColumn c in dt.Columns)
            {
                if (c.AutoIncrement)
                {
                    InsertCache.IsHaveAutoIncrement = true;
                    InsertCache.SQL += ";Select @@IDENTITY;";
                    break;
                }
            }

            SqlCommand UpdateCmd = builder.GetUpdateCommand(true);

            UpdateCache = new DatabaseCache(UpdateCmd.CommandText, UpdateCmd.Parameters);
            UpdateCache.CurrentTable = dt;

            SqlCommand DeleteCmd = builder.GetDeleteCommand(true);

            DeleteCache = new DatabaseCache(DeleteCmd.CommandText, DeleteCmd.Parameters);
            DeleteCache.CurrentTable = dt;

            IsExistCache = new DatabaseCache(DeleteCmd.CommandText, DeleteCmd.Parameters);
            IsExistCache.CurrentTable = dt;
            IsExistCache.SQL          = IsExistCache.SQL.Replace("DELETE FROM [" + TableName + "]", "Select count(1) from [" + TableName + "] with(nolock) ");
        }
Пример #16
0
        /// <summary>
        /// Get the credits of a specific movie.
        /// </summary>
        /// <param name="PersonID">The id of the person.</param>
        /// <returns>The credits.</returns>
        public static async Task <Credit> GetCreditsAsync(int PersonID)
        {
            Credit credits = DatabaseCache.GetObject <Credit>(PersonID);

            if (credits == null)
            {
                Request <Credit> request = new Request <Credit>("person/" + PersonID.ToString() + "/credits");
                credits = await request.ProcesRequestAsync();

                DatabaseCache.SetObject(PersonID, credits);
            }
            return(credits);
        }
Пример #17
0
        /// <summary>
        /// The images of a specific person.
        /// </summary>
        /// <param name="PersonID">The id of the specified person.</param>
        /// <returns>A list of images</returns>
        public static async Task <IReadOnlyList <Profile> > GetImageAsync(int PersonID)
        {
            IReadOnlyList <Profile> profile = DatabaseCache.GetObject <IReadOnlyList <Profile> >(PersonID);

            if (profile == null)
            {
                Request <Profile> request = new Request <Profile>("person/" + PersonID.ToString() + "/images");
                profile = await request.ProcesRequestListAsync("profiles");

                DatabaseCache.SetObject(PersonID, profile);
            }
            return(profile);
        }
Пример #18
0
        /// <summary>
        /// Gets the credits of a specific movie.
        /// </summary>
        /// <param name="movieId">The id of the movie.</param>
        /// <returns>The credits of the movie.</returns>
        public static async Task <Credits> GetMovieCreditsAsync(int movieId)
        {
            var credits = DatabaseCache.GetObject <Credits>(movieId);

            if (credits == null)
            {
                var request = new Request <Credits>(string.Format("movie/{0}/casts", movieId));
                credits = await request.ProcesRequestAsync();

                DatabaseCache.SetObject(movieId, credits);
            }
            return(credits);
        }
Пример #19
0
 public override void Execute(WorldClient client, CommandParameters parameters)
 {
     if (parameters.Lenght > 0)
     {
         DatabaseCache.Save();
         Network.WorldServer.Clients.ForEach(x => x.Disconnect());
         Environment.Exit(0);
     }
     else
     {
         client.Send(new ConsoleMessage("Parametres invalide !", ConsoleColorEnum.RED));
     }
 }
Пример #20
0
        /// <summary>
        /// Gets a specific company
        /// </summary>
        /// <param name="companyId">Id of the requested company.</param>
        /// <returns>The company that is associated to the id.</returns>
        public static async Task <Company> GetCompanyAsync(int companyId)
        {
            var company = DatabaseCache.GetObject <Company>(companyId);

            if (company == null)
            {
                var request = new Request <Company>("company/" + companyId);
                company = await request.ProcesRequestAsync();

                DatabaseCache.SetObject(companyId, company);
            }
            return(company);
        }
Пример #21
0
        /// <summary>
        /// Gets the credits of a specific movie.
        /// </summary>
        /// <param name="MovieID">The id of the movie.</param>
        /// <returns>The credits of the movie.</returns>
        public static async Task <Credits> GetMovieCastAsync(int MovieID)
        {
            Credits credits = DatabaseCache.GetObject <Credits>(MovieID);

            if (credits == null)
            {
                Request <Credits> request = new Request <Credits>(string.Format("movie/{0}/casts", MovieID));
                credits = await request.ProcesRequestAsync();

                DatabaseCache.SetObject(MovieID, credits);
            }
            return(credits);
        }
Пример #22
0
        /// <summary>
        /// The images of a specific person.
        /// </summary>
        /// <param name="personId">The id of the specified person.</param>
        /// <returns>A list of images</returns>
        public static async Task <IReadOnlyList <Profile> > GetImageAsync(int personId)
        {
            var profile = DatabaseCache.GetObject <IReadOnlyList <Profile> >(personId);

            if (profile == null)
            {
                var request = new Request <Profile>("person/" + personId + "/images");
                profile = await request.ProcesRequestListAsync("profiles");

                DatabaseCache.SetObject(personId, profile);
            }
            return(profile);
        }
Пример #23
0
        /// <summary>
        /// Gets a specific company
        /// </summary>
        /// <param name="CompanyId">Id of the requested company.</param>
        /// <returns>The company that is associated to the id.</returns>
        public static async Task <Company> GetCompanyAsync(int CompanyId)
        {
            Company company = DatabaseCache.GetObject <Company>(CompanyId);

            if (company == null)
            {
                Request <Company> request = new Request <Company>("company/" + CompanyId.ToString());
                company = await request.ProcesRequestAsync();

                DatabaseCache.SetObject(CompanyId, company);
            }
            return(company);
        }
Пример #24
0
        /// <summary>
        /// Get a specific collection
        /// </summary>
        /// <param name="collectionId">Id of the collection</param>
        /// <returns>The collection</returns>
        public static async Task <Collection> GetCollectionAsync(int collectionId)
        {
            var collection = DatabaseCache.GetObject <Collection>(collectionId);

            if (collection == null) //Bug Fix
            {
                var request = new Request <Collection>("collection/" + collectionId);
                collection = await request.ProcesRequestAsync();

                DatabaseCache.SetObject(collectionId, collection);
            }
            return(collection);
        }
Пример #25
0
        /// <summary>
        /// Get the credits of a specific movie.
        /// </summary>
        /// <param name="personId">The id of the person.</param>
        /// <returns>The credits.</returns>
        public static async Task <Credit> GetCreditsAsync(int personId)
        {
            var credits = DatabaseCache.GetObject <Credit>(personId);

            if (credits == null)
            {
                var request = new Request <Credit>("person/" + personId + "/credits");
                credits = await request.ProcesRequestAsync();

                DatabaseCache.SetObject(personId, credits);
            }
            return(credits);
        }
Пример #26
0
        /// <summary>
        /// Gets the images that are associated with the collection.
        /// </summary>
        /// <param name="collectionId">Id of the collection</param>
        /// <returns>The image set of the collection.</returns>
        public static async Task <Image> GetCollectionImagesAsync(int collectionId)
        {
            var images = DatabaseCache.GetObject <Image>(collectionId);

            if (images != null)
            {
                var request = new Request <Image>("collection/" + collectionId + "/images");
                images = await request.ProcesRequestAsync();

                DatabaseCache.SetObject(collectionId, images);
            }
            return(images);
        }
Пример #27
0
        /// <summary>
        /// Gets the images that are associated with the collection.
        /// </summary>
        /// <param name="CollectionId">Id of the collection</param>
        /// <returns>The image set of the collection.</returns>
        public static async Task <Images> GetCollectionImagesAsync(int CollectionId)
        {
            Images images = DatabaseCache.GetObject <Images>(CollectionId);

            if (images != null)
            {
                Request <Images> request = new Request <Images>("collection/" + CollectionId.ToString() + "/images");
                images = await request.ProcesRequestAsync();

                DatabaseCache.SetObject(CollectionId, images);
            }
            return(images);
        }
Пример #28
0
        /// <summary>
        /// Get a specific collection
        /// </summary>
        /// <param name="CollectionId">Id of the collection</param>
        /// <returns>The collection</returns>
        public static async Task <Collection> GetCollectionAsync(int CollectionId)
        {
            Collection collection = DatabaseCache.GetObject <Collection>(CollectionId);

            if (collection != null)
            {
                Request <Collection> request = new Request <Collection>("collection/" + CollectionId.ToString());
                collection = await request.ProcesRequestAsync();

                DatabaseCache.SetObject(CollectionId, collection);
            }
            return(collection);
        }
Пример #29
0
        //
        // GET: /Cms/
        public ActionResult Index(string url)
        {
            // Clean up the url parameter
            if (string.IsNullOrWhiteSpace(url))
            {
                url = "home";
            }
            else
            {
                url = url.ToLower().Trim('/');
                if (url.EndsWith("/index"))
                {
                    url = url.Substring(0, url.LastIndexOf("/"));
                }
            }

            // Check if we cached the page
            SitePage Page = DatabaseCache.GetSitePage(ControllerContext.RequestContext.HttpContext, url);

            if (Page == null)
            {
                string RequestDomain = Globals.GetRequestDomain(ControllerContext.RequestContext.HttpContext);
                using (XenonCMSContext DB = new XenonCMSContext())
                {
                    Page = DB.SitePages.SingleOrDefault(x => (x.Slug == url) && (x.Site.Domain == RequestDomain));
                }
                DatabaseCache.AddSitePage(ControllerContext.RequestContext.HttpContext, Page);
            }

            // Ensure retrieved page is valid
            if (Page == null)
            {
                if (Globals.IsNewSite(ControllerContext.RequestContext.HttpContext))
                {
                    return(RedirectToAction("Install", "Cms"));
                }
                else
                {
                    return(HttpNotFound());
                }
            }
            else
            {
                ViewBag.Layout          = Page.Layout;
                ViewBag.Title           = Page.Title;
                ViewBag.ShowTitleOnPage = Page.ShowTitleOnPage;
                ViewBag.Html            = Page.Html;
                ViewBag.DateLastUpdated = Page.DateLastUpdated;
                return(View());
            }
        }
Пример #30
0
        private void HandleGetSimplePages(ZipArchive zip, XenonCMSContext DB)
        {
            string RequestDomain = Globals.GetRequestDomain(ControllerContext.RequestContext.HttpContext);
            int    SiteId        = DB.Sites.Single(x => x.Domain == RequestDomain).Id;

            // Handle the pages files
            var PagesFiles = GetSimpleGetXmlDocuments(zip, "pages/");

            foreach (var KVP in PagesFiles)
            {
                // Get slug so we can skip built-in pages
                string Parent = KVP.Value.DocumentElement.SelectSingleNode("parent").InnerText;
                string Url    = KVP.Value.DocumentElement.SelectSingleNode("url").InnerText;
                string Slug   = string.IsNullOrWhiteSpace(Parent) ? Url : Parent + "/" + Url;
                if (Slug == "index")
                {
                    Slug = "home";
                }
                if ((Slug == "blog") || (Slug == "contact") || (Slug == "news"))
                {
                    // TODO Skipping these built-ins
                }
                else
                {
                    // Update existing or add new page
                    // TODO GetSimple has a "meta" tag,
                    var SP = DB.SitePages.SingleOrDefault(x => (x.Site.Domain == RequestDomain) && (x.Slug == Slug)) ?? new SitePage();
                    SP.DateAdded       = Convert.ToDateTime(KVP.Value.DocumentElement.SelectSingleNode("pubDate").InnerText);
                    SP.DateLastUpdated = Convert.ToDateTime(KVP.Value.DocumentElement.SelectSingleNode("pubDate").InnerText);
                    SP.DisplayOrder    = Convert.ToInt32(KVP.Value.DocumentElement.SelectSingleNode("menuOrder").InnerText);
                    SP.Html            = HttpUtility.HtmlDecode(KVP.Value.DocumentElement.SelectSingleNode("content").InnerText);
                    SP.Layout          = "NormalNoSidebar"; // TODO there is a "template" tag
                    SP.ParentId        = 0;                 // TODO there is a "parent" tag
                    SP.RequireAdmin    = false;             // TODO "private" tag
                    SP.RightAlign      = false;
                    SP.ShowInMenu      = (KVP.Value.DocumentElement.SelectSingleNode("menuStatus").InnerText == "Y");
                    SP.ShowTitleOnPage = true;
                    SP.SiteId          = SiteId;
                    SP.Slug            = Slug;
                    SP.Text            = HttpUtility.HtmlDecode(KVP.Value.DocumentElement.SelectSingleNode("menu").InnerText); // TODO Rename text to something more intuitive
                    SP.Title           = HttpUtility.HtmlDecode(KVP.Value.DocumentElement.SelectSingleNode("title").InnerText);
                    if (SP.Id <= 0)
                    {
                        DB.SitePages.Add(SP);
                    }
                    DB.SaveChanges();
                    DatabaseCache.ResetNavMenuItems(ControllerContext.RequestContext.HttpContext);
                    DatabaseCache.RemoveSitePage(ControllerContext.RequestContext.HttpContext, Slug);
                }
            }
        }
Пример #31
0
        public void DatabaseCacheAllAroundTest()
        {
            _testName = MethodInfo.GetCurrentMethod().Name.GetHashCode().ToString();
            Cleanup();

            var seed = new Seed32();

            var cleanEntities = TestResourceFactory.GetMockClassAObjects(500);
            var dirtyEntities = TestResourceFactory.GetMockClassAObjects(500);

            cleanEntities.ToList().ForEach(c => c.Id = seed.Increment());
            dirtyEntities.ToList().ForEach(d => d.Id = seed.Increment());

            var db = new DatabaseCache<int, MockClassA>(false, 2048, new BinConverter32());

            db.CacheItem(cleanEntities.First().Id);

            //with manual caching
            foreach (var e in cleanEntities)
                db.UpdateCache(e.Id, e, false, false);

            Assert.AreEqual(1, db.Count);
            Assert.IsTrue(db.Contains(cleanEntities.First().Id));
            Assert.AreEqual(cleanEntities.First().Name, db.GetFromCache(cleanEntities.First().Id).Name);

            //with autoCache
            foreach (var e in cleanEntities)
                db.UpdateCache(e.Id, e, true, false);

            Assert.AreEqual(500, db.Count);

            db.Detach(cleanEntities.First().Id);

            Assert.AreEqual(499, db.Count);
            Assert.IsFalse(db.Contains(cleanEntities.First().Id));
            Assert.IsNull(db.GetFromCache(cleanEntities.First().Id));

            db.CacheSize = 400;

            db.UpdateCache(cleanEntities.First().Id, cleanEntities.First(), true, false);

            Assert.AreEqual(201, db.Count);
            Assert.IsFalse(db.IsNew(cleanEntities.First().Id));

            db.ClearCache();

            Assert.AreEqual(0, db.Count);
        }
Пример #32
0
        public void ExtractTableParameters(string TableName, IDbDataAdapter adapter, 
            out DatabaseCache InsertCache, 
            out DatabaseCache DeleteCache,
            out DatabaseCache UpdateCache,
            out DatabaseCache IsExistCache,
            out DataTable dt
            )
        {
            adapter.SelectCommand.CommandText = "select top 1 * from " + TableName;

            DataSet ds = new DataSet();

            dt = adapter.FillSchema(ds, SchemaType.Source)[0];

            dt.TableName = TableName;

            SqlCommandBuilder builder = new SqlCommandBuilder(adapter as SqlDataAdapter);

            builder.ConflictOption = ConflictOption.OverwriteChanges;
            //builder.SetAllValues = false;
            SqlCommand InsertCmd = builder.GetInsertCommand(true);
            builder.ConflictOption = ConflictOption.OverwriteChanges;

            InsertCache = new DatabaseCache(InsertCmd.CommandText, InsertCmd.Parameters);
            InsertCache.CurrentTable = dt;

            foreach (DataColumn c in dt.Columns)
            {
                if (c.AutoIncrement)
                {
                    InsertCache.IsHaveAutoIncrement = true;
                    InsertCache.SQL += ";Select @@IDENTITY;";
                    break;
                }
            }

            SqlCommand UpdateCmd = builder.GetUpdateCommand(true);
            UpdateCache = new DatabaseCache(UpdateCmd.CommandText, UpdateCmd.Parameters);
            UpdateCache.CurrentTable = dt;

            SqlCommand DeleteCmd = builder.GetDeleteCommand(true);
            DeleteCache = new DatabaseCache(DeleteCmd.CommandText, DeleteCmd.Parameters);
            DeleteCache.CurrentTable = dt;

            IsExistCache = new DatabaseCache(DeleteCmd.CommandText, DeleteCmd.Parameters);
            IsExistCache.CurrentTable = dt;
            IsExistCache.SQL = IsExistCache.SQL.Replace("DELETE FROM [" + TableName + "]", "Select count(1) from [" + TableName + "] with(nolock) ");
        }
Пример #33
0
        public void FlushRequestAndUnloadDirtyTest()
        {
            _testName = MethodInfo.GetCurrentMethod().Name.GetHashCode().ToString();
            Cleanup();

            var seed = new Seed32();

            var dirtyEntities = TestResourceFactory.GetMockClassAObjects(500);

            dirtyEntities.ToList().ForEach(d => d.Id = seed.Increment());

            var db = new DatabaseCache<int, MockClassA>(false, 2048, new BinConverter32());
            db.CacheSize = 400;

            db.FlushRequested += new EventHandler(delegate(object sender, EventArgs e)
            {
                var dbparam = sender as DatabaseCache<int, MockClassA>;
                Assert.AreEqual(dbparam.CacheSize + 1, dbparam.DirtyCount);

                var dirtyItems = dbparam.UnloadDirtyItems();

                Assert.AreEqual(0, dbparam.DirtyCount);
                Assert.AreEqual(0, dbparam.Count);
            });

            foreach (var d in dirtyEntities)
                db.UpdateCache(d.Id, d, true, true);

            db.Sweep();
        }
Пример #34
0
Файл: MySQL.cs Проект: xqgzh/Z
        public void ExtractTableParameters(string TableName, IDbDataAdapter adapter,
    out DatabaseCache InsertCache,
    out DatabaseCache DeleteCache,
    out DatabaseCache UpdateCache,
    out DatabaseCache IsExistCache,
    out DataTable dt
    )
        {
            MySqlDataAdapter adap = adapter as MySqlDataAdapter;

            adap.FillLoadOption = LoadOption.OverwriteChanges;
            adapter.SelectCommand.CommandText = "select * from " + TableName;

            DataSet ds = new DataSet();

            dt = adapter.FillSchema(ds, SchemaType.Source)[0];

            dt.TableName = TableName;

            InsertCache = new DatabaseCache(string.Empty, new IDataParameter[dt.Columns.Count]);
            DeleteCache = new DatabaseCache(string.Empty, new IDataParameter[dt.PrimaryKey.Length]);
            UpdateCache = new DatabaseCache(string.Empty, new IDataParameter[dt.Columns.Count]);
            IsExistCache = new DatabaseCache(string.Empty, new IDataParameter[dt.PrimaryKey.Length]);
            InsertCache.SQL = "insert into " + TableName + "(";
            DeleteCache.SQL = "delete from " + TableName + " where ";
            UpdateCache.SQL = "Update " + TableName + " set ";
            IsExistCache.SQL = "select count(1) from " + TableName + " where ";

            InsertCache.SQL += StringTools.JoinString(dt.Columns, string.Empty, string.Empty, ",", false);
            InsertCache.SQL += ") values(";
            InsertCache.SQL += StringTools.JoinString(dt.Columns, "?", string.Empty, ",", false);
            InsertCache.SQL += ");";

            Dictionary<string, DataColumn> PrimaryKeys = new Dictionary<string,DataColumn>();

            foreach (DataColumn c in dt.PrimaryKey)
            {
                if (c.AutoIncrement)
                    InsertCache.IsHaveAutoIncrement = true;

                PrimaryKeys.Add(c.ColumnName, c);
            }

            string s = " 1=1 ";

            foreach (DataColumn c in dt.Columns)
            {
                if (!PrimaryKeys.ContainsKey(c.ColumnName))
                {
                    UpdateCache.SQL += c.ColumnName + "=?" + c.ColumnName + ",";
                }
                else
                {
                    s += " And " + c.ColumnName + "=?" + c.ColumnName;
                }
            }

            if (UpdateCache.SQL.EndsWith(","))
                UpdateCache.SQL = UpdateCache.SQL.Remove(UpdateCache.SQL.Length - 1);

            UpdateCache.SQL += " Where ";

            DeleteCache.SQL += s;
            UpdateCache.SQL += s;
            IsExistCache.SQL += s;

            if (InsertCache.IsHaveAutoIncrement == true)
            {
                InsertCache.SQL += "select last_insert_id();";
            }

            InsertCache.Parameters = new IDataParameter[InsertCache.IsHaveAutoIncrement?dt.Columns.Count - 1:dt.Columns.Count];
            DeleteCache.Parameters = new IDataParameter[PrimaryKeys.Count];
            UpdateCache.Parameters = new IDataParameter[dt.Columns.Count];
            IsExistCache.Parameters = new IDataParameter[PrimaryKeys.Count];

            int InsertIndex = 0 , DeleteIndex = 0, UpdateIndex = 0;

            foreach (DataColumn c in dt.Columns)
            {
                IDataParameter p = adapter.SelectCommand.CreateParameter();
                p.ParameterName = "?" + c.ColumnName;
                p.SourceColumn = c.ColumnName;

                if (!c.AutoIncrement)
                {
                    InsertCache.Parameters[InsertIndex++] = p;
                }

                if (PrimaryKeys.ContainsKey(c.ColumnName))
                {
                    DeleteCache.Parameters[DeleteIndex] = p;
                    IsExistCache.Parameters[DeleteIndex] = p;
                    DeleteIndex++;
                }

                UpdateCache.Parameters[UpdateIndex] = p;
                UpdateIndex++;
            }

            InsertCache.CurrentTable = UpdateCache.CurrentTable = DeleteCache.CurrentTable = IsExistCache.CurrentTable = dt;
        }