public void PreviewForDraftPostTest() { IRepository<Post> postRepo = new SimpleRepository<Post>(new InMemoryRepositoryDataSource<Post>(new List<Post> { new Post { Status = PostStatus.Published, Path ="2013/04/10/some-other-post", Posted = new DateTime(2013,4,10), Author = new User{ Email = "" }, BlogId = 1 }, new Post { Id = 1, Status = PostStatus.Draft, Path ="2013/04/14/some-post", Posted = new DateTime(2013,4,14), Author = new User{ Email = "", FirstName = "Joe", LastName = "Bloggs" }, DraftBody = "asdf", DraftTitle = "qwerty", BlogId = 1 } })); PostController sut = new PostController(postRepo, null, _blogRepo, _mockHttpContext.Object); var result = (ViewResult)sut.Preview(1); Assert.IsNotNull(result); var model = result.Model as PostModel; Assert.IsNotNull(model); var md = new MarkdownDeep.Markdown(); Assert.AreEqual("Joe Bloggs", model.Author.Name); Assert.AreEqual(md.Transform("asdf"), model.Body); Assert.AreEqual("qwerty", model.Title); }
public void DisplayPostTest() { IRepository<Post> postRepo = new SimpleRepository<Post>(new InMemoryRepositoryDataSource<Post>(new List<Post> { new Post { Status = PostStatus.Published, Path ="2013/04/10/some-other-post", Posted = new DateTime(2013,4,10), Author = new User{ Email = "" }, BlogId = 1 }, new Post { Status = PostStatus.Published, Path ="2013/04/14/some-post", Posted = new DateTime(2013,4,14), Author = new User{ Email = "" }, BlogId = 1 } })); var mockVisitLoggerService = new Mock<IVisitLoggerService>(); PostController sut = new PostController(postRepo, mockVisitLoggerService.Object, _blogRepo, _mockHttpContext.Object); var result = (ViewResult)sut.Display("2013/04/14/some-post"); Assert.IsNotNull(result); var model = result.Model as PostModel; Assert.IsNotNull(model); Assert.AreEqual(new DateTime(2013, 4, 14), model.Posted); }
public override void Init(string screenname, System.IO.TextWriter log) { base.Init(screenname, log); User = UsersCollection.PrimaryUsers().Where(x => x.TwitterScreenName == screenname).First(); repoPage = new SimpleRepository<ArticleStubPage>(screenname); repoIndex = new SimpleRepository<ArticleStubIndex>(screenname); }
/// <summary> /// Create a new SimpleRepository using the given connection string and data provider name as source. /// </summary> /// <param name="ConnectionString">The connection string to pass to the data provider.</param> /// <param name="ProviderName">The name of the data provider to use.</param> /// <returns></returns> public SimpleRepository OpenRepository(String ConnectionString, String ProviderName) { IDataProvider provider = ProviderFactory.GetProvider(ConnectionString, ProviderName); SimpleRepository result = new SimpleRepository(provider, SimpleRepositoryOptions.RunMigrations); NeedsVacuum[result] = false; return result; }
public PostRepository(BlogContext context) { _context = context; _simpleRepository = new SimpleRepository<Post, int>(_context, _context.Posts, post => post.ID); _retrieveAllRepository = new RetrieveAllRepository<Post>(_context.Posts); _matchingRepository = new MatchingRepository<Post, PostCriteria>(_context.Posts, ExpressionBuilder); _pagedRepository = new PagedRepository<Post, PostCriteria>(_context.Posts, ExpressionBuilder); }
public void RedirectToLatestPostWithOnePublishedPostsTest() { IRepository<Post> postRepo = new SimpleRepository<Post>(new InMemoryRepositoryDataSource<Post>(new List<Post> { new Post { Status = PostStatus.Published, Path ="2013/04/14/some-post", Posted = new DateTime(2013,4,14), BlogId = 1 } })); PostController sut = new PostController(postRepo, _blogRepo,_templateRepo, _mockHttpContext.Object); var result = sut.Index(); Assert.AreEqual("/2013/04/14/some-post", ((RedirectResult)result).Url); }
public void RedirectToLatestPostWithNoPostsTest() { IRepository<Post> postRepo = new SimpleRepository<Post>(new InMemoryRepositoryDataSource<Post>()); PostController sut = new PostController(postRepo, _blogRepo, _templateRepo, _mockHttpContext.Object); try { sut.Index(); } catch(HttpException ex) { Assert.AreEqual((int)HttpStatusCode.NotFound, ex.GetHttpCode()); throw; } }
public void EditPostContentTest() { var postRepo = new SimpleRepository<Post>(new InMemoryRepositoryDataSource<Post>(new List<Post> { new Post { Id=1, Status = PostStatus.Published, Title = "Test Title", Description = "Test Description", Body = "Test Body", Path ="2013/04/9/some-other-post", Posted = new DateTime(2013,4,9), Author = new User{ Email = "" }, BlogId = 1 }})); PostAuthoringController sut = new PostAuthoringController( postRepo, _postModificationRepo, _userRepo, _redirectRepo, _securableRepo, _blogRepo, _mockSecurityHelper.Object, new DateTimeProvider(), _mockHttpContext.Object); var result = sut.Edit(1,new Areas.Manage.Models.PostEditModel { Title = "New Title", Body = "New Body", Description = "New Description", Reposted = true, CanonicalUrl = "http://blog.con/new-post" }) as RedirectToRouteResult; Assert.IsNotNull(result); Assert.AreEqual("Index", result.RouteValues["action"]); Assert.AreEqual("Dashboard", result.RouteValues["controller"]); Assert.AreEqual(1, postRepo.GetAll().Count()); Assert.IsTrue(postRepo.GetAll().Last().HasDraftContent()); Assert.AreEqual("Test Title", postRepo.GetAll().Last().Title); Assert.AreEqual("Test Body", postRepo.GetAll().Last().Body); Assert.AreEqual("Test Description", postRepo.GetAll().Last().Description); Assert.AreEqual("New Title", postRepo.GetAll().Last().DraftTitle); Assert.AreEqual("New Body", postRepo.GetAll().Last().DraftBody); Assert.AreEqual("New Description", postRepo.GetAll().Last().DraftDescription); Assert.AreEqual("http://blog.con/new-post", postRepo.GetAll().Last().Canonical);//TODO Change this so that its also draft }
public void UnPublishPublishPostIsPublishedNoDraftContent() { var postRepo = new SimpleRepository<Post>(new InMemoryRepositoryDataSource<Post>(new List<Post> { new Post { Id=1, Status = PostStatus.Published, Title = "Test Title", Description = "Test Description", Body = "Test Body", Path ="2013/04/9/some-other-post", Posted = new DateTime(2013,4,9), Author = new User{ Email = "" }, BlogId = 1 }})); PostAuthoringController sut = new PostAuthoringController( postRepo, _postModificationRepo, _userRepo, _redirectRepo, _securableRepo, _blogRepo, _mockSecurityHelper.Object, new DateTimeProvider(), _mockHttpContext.Object); var result = sut.ConfirmUnPublish(1, new ConfirmPublishModel()) as JsonResult; Assert.IsNotNull(result); // This requires [assembly: InternalsVisibleTo("StaticVoid.Blog.Site.Tests")] in StaticVoid.Blog.Site so that we can read anon types, needing this is kinda lame // dynamic should just jams it in there by itself. I mean heck the debugger can see it, why cant dynamic? // cf http://stackoverflow.com/questions/2630370/c-sharp-dynamic-cannot-access-properties-from-anonymous-types-declared-in-anot Assert.IsTrue(((dynamic)result.Data).success); Assert.AreEqual(1, postRepo.GetAll().Count()); Assert.AreEqual(PostStatus.Unpublished, postRepo.GetAll().First().Status); Assert.AreEqual("Test Title", postRepo.GetAll().First().DraftTitle); Assert.AreEqual("Test Description", postRepo.GetAll().First().DraftDescription); Assert.AreEqual("Test Body", postRepo.GetAll().First().DraftBody); }
public CachedUserRepository(SimpleRepository <Data.User> baseRepo, ICachedUserRepositoryStorage cache) { _cache = cache; _baseRepo = baseRepo; }
public IList <Order> SearchOrder(string imsi, List <string> targetContentId, string productCode) { var res = SimpleRepository.Find <Order>(s => s.Imsi == imsi && s.Status == OrderStatus.Successed && s.ProductCode == productCode && targetContentId.ToArray().Contains(s.TargetContentID)); return(res); }
static void Main(string[] args) { var connectionString = ConfigurationManager.AppSettings["AzureStorageConnectionString"]; if (string.IsNullOrEmpty(connectionString)) throw new Exception("Config Section 'appSettings' missing AzureStorageConnectionString value!"); var storageAccount = CloudStorageAccount.Parse(connectionString); var blobClient = storageAccount.CreateCloudBlobClient(); var deleteTasks = new List<Task>(10000000); Action<Task> delete = t => { lock (deleteTasks) { deleteTasks.Add(t); } Console.Clear(); Console.WriteLine("Deleting " + deleteTasks.Count + " items"); }; var version = TwitterModel.VERSION; bool content = args.Any(a => a.ToLower() == "content"); bool cleanVersion = args.Any(a => a.ToLower() == "version"); bool shrink = args.Any(a => a.ToLower().StartsWith("shrink")); int newSize = args.Where(a => a.ToLower().StartsWith("shrink")).Select(x => x == "shrink" ? 500 : int.Parse(x.Replace("shrink", ""))).FirstOrDefault(); blobClient.ListContainers() //.Skip(1) //Short circuit for testing //.Take(1) //Short circuit for testing .ToList().AsParallel().ForAll(c => { #region Index Cleanup var index = c.GetDirectoryReference("Index"); foreach (var b in index.ListBlobs().Where(x => x is CloudBlockBlob).Cast<CloudBlockBlob>()) { if (cleanVersion && !b.Name.Contains(version)) { //Delete Index var i = c.GetBlockBlobReference(b.Name); delete(i.DeleteIfExistsAsync()); //Delete all Tweets var d = c.GetDirectoryReference(b.Name.Split('/').Last()); foreach (var t in d.ListBlobs().Where(x => x is CloudBlockBlob).Cast<CloudBlockBlob>()) { delete(t.DeleteIfExistsAsync()); } } if (shrink && newSize > 0 && b.Name.Contains(version)) { //Get Storage Index var i = c.GetBlockBlobReference(b.Name); var storageIndex = Newtonsoft.Json.JsonConvert.DeserializeObject<StorageEntityIndex>(DownloadBlob(i)); if (storageIndex.EntityKeys.Count > newSize) { //Delete extra Tweets var d = c.GetDirectoryReference(b.Name.Split('/').Last()); foreach (var t in d.ListBlobs().Where(x => x is CloudBlockBlob).Cast<CloudBlockBlob>().OrderByDescending(x => x.Properties.LastModified).Skip(newSize)) { storageIndex.EntityKeys.Remove(t.Name.Split('/').Last()); delete(t.DeleteIfExistsAsync()); } //Update Storage Index UploadBlob(i, storageIndex); } } } #endregion #region Content Cleanup if (content) { try { var repoIndex = new SimpleRepository<ArticleStubIndex>(c.Name); var repoPage = new SimpleRepository<ArticleStubPage>(c.Name); var stubIndex = repoIndex.Query(TwitterModel.Instance(c.Name).CONTENT_INDEX).FirstOrDefault(); if (stubIndex != null) { var remove = new List<KeyValuePair<long, string>>(); for (var i = stubIndex.ArticleStubPages.Count - 31; i > -1 && i < stubIndex.ArticleStubPages.Count; i++) // Only the last month(ish) { var si = stubIndex.ArticleStubPages[i]; var page = repoPage.Query(TwitterModel.Instance(c.Name).CONTENT + "_" + si.Value).FirstOrDefault(); if (page.ArticleStubs == null || page.ArticleStubs.Count == 0) { repoPage.Delete(TwitterModel.Instance(c.Name).CONTENT + "_" + si.Value); remove.Add(si); } } remove.ForEach(x => stubIndex.ArticleStubPages.Remove(x)); repoIndex.Save(TwitterModel.Instance(c.Name).CONTENT_INDEX, stubIndex); } } catch { } } #endregion }); Console.WriteLine("Waiting on all tasks to complete"); Task.WaitAll(deleteTasks.ToArray()); }
public CachedStyleRepository(SimpleRepository <Data.Style> baseRepo, ICachedStyleRepositoryStorage cache) { _cache = cache; _baseRepo = baseRepo; }
private static void SelectSimpleRepo(IDataProvider provider) { Console.WriteLine("Selecting 10000 records with SimpleRepo: " + DateTime.Now + " using " + provider.Client); var repo = new SimpleRepository(provider); DateTime start = DateTime.Now; for(int i = 1; i < 10000; i++) { SubSonic.Tests.TestClasses.Product p = repo.Single<SubSonic.Tests.TestClasses.Product>(1); Console.WriteLine(i); } DateTime end = DateTime.Now; TimeSpan ts = end.Subtract(start); Console.WriteLine("End: " + DateTime.Now + " (" + ts.Seconds + ":" + ts.Milliseconds + ")"); }
static void Main(string[] args) { EGT_OTA.Models.Repository.UpdateDB(); SimpleRepository db = Repository.GetRepo(); try { var MusicStartIndex = Tools.SafeInt(System.Web.Configuration.WebConfigurationManager.AppSettings["MusicStartIndex"]); var MusicEndIndex = Tools.SafeInt(System.Web.Configuration.WebConfigurationManager.AppSettings["MusicEndIndex"]); var LineCount = Tools.SafeInt(System.Web.Configuration.WebConfigurationManager.AppSettings["LineCount"]); for (var i = 0; i < LineCount; i++) { Thread thread = new Thread(delegate() { while (MusicStartIndex < MusicEndIndex) { lock (locker) { try { var json = HttpHelper.Get("http://music.163.com/api/song/detail?ids=%5B" + MusicStartIndex + "%5D"); JArray array = JArray.Parse(JObject.Parse(json)["songs"].ToString()); if (array.Count > 0) { JObject model = JObject.Parse(array[0].ToString()); var musicId = model["id"].ToString(); var musicName = model["name"].ToString(); if (!string.IsNullOrWhiteSpace(musicName)) { var musicUrl = model["mp3Url"].ToString(); var artistsArray = JArray.Parse(model["artists"].ToString()); var artists = JObject.Parse(artistsArray[0].ToString()); var artistsName = artists["name"].ToString(); var album = JObject.Parse(model["album"].ToString()); var albumName = album["name"].ToString(); var musicPicUrl = album["picUrl"].ToString(); if (!string.IsNullOrWhiteSpace(musicUrl)) { var result = true; try { HttpWebRequest wbRequest = (HttpWebRequest)WebRequest.Create(musicUrl); wbRequest.Method = "GET"; wbRequest.Timeout = 2000; HttpWebResponse wbResponse = (HttpWebResponse)wbRequest.GetResponse(); result = (wbResponse.StatusCode == System.Net.HttpStatusCode.OK); if (wbResponse != null) { wbResponse.Close(); } if (wbRequest != null) { wbRequest.Abort(); } Music music = new Music(); music.Author = artistsName; music.Cover = musicPicUrl; music.FileUrl = musicUrl; music.Name = musicName; music.Number = musicId; db.Add <Music>(music); Console.WriteLine(MusicStartIndex + ":成功"); } catch (Exception ex) { result = false; Console.WriteLine("失败:" + musicName + "," + ex.Message); } } } else { Console.WriteLine(MusicStartIndex + ":失败"); } } else { Console.WriteLine(MusicStartIndex); } } catch (Exception ex) { Console.WriteLine(MusicStartIndex + ":" + ex.Message); } MusicStartIndex += 1; } Thread.Sleep(1000); } }); thread.IsBackground = true; thread.Name = "同步音乐接口线程" + i; thread.Start(); } } catch (Exception ex) { Console.WriteLine(ex.Message); } Console.ReadLine(); }
private static void RunInsert(IDataProvider provider) { ResetDB(provider); var repo = new SimpleRepository(provider); Console.WriteLine("Inserting 1000 rows using Simple Repo: " + DateTime.Now + " using " + provider.Name); DateTime start = DateTime.Now; for (int i = 1; i < 1000; i++) { SubSonic.Tests.TestClasses.Product p = new SubSonic.Tests.TestClasses.Product(); p.CategoryID = 1; p.Discontinued = false; p.ProductName = "Product" + i; p.Sku = Guid.NewGuid(); p.UnitPrice = 1000; repo.Add(p); //Console.Write(i + ","); } WriteResult(start); }
public BotCommandController() { commandRepo = new SimpleRepository<BotCommand>(User.Identity.Name); }
private void LoadFromRepository() { var me = new Tweep(User, Tweep.TweepType.None); CachedRepository<TweetBotRuntimeSettings> settingsRepo = CachedRepository<TweetBotRuntimeSettings>.Instance(User.TwitterScreenName); SimpleRepository<BotCommand> commandRepo = new SimpleRepository<BotCommand>(User.TwitterScreenName); //var runtimeSettings = Newtonsoft.Json.JsonConvert.DeserializeObject<TweetBotRuntimeSettings>(System.IO.File.OpenText("c:\\temp\\runtimesettings.demo.json.txt").ReadToEnd()); var runtimeSettings = (settingsRepo.Query(RuntimeRepoKey) ?? new List<TweetBotRuntimeSettings> { new TweetBotRuntimeSettings() }).FirstOrDefault(); if (runtimeSettings != null) { IsSimulationMode = runtimeSettings.IsSimulationMode; BotStartupTime = runtimeSettings.BotFirstStart; LastTweetTime = runtimeSettings.LastTweetTime; TweetsSentSinceLastFriendRequest = runtimeSettings.TweetsSentSinceLastFriendRequest; TweetsPerHour = runtimeSettings.GetPastTweets().Count() > 1 ? runtimeSettings.GetPastTweets() .GroupBy(x => x.CreatedAt.ToShortDateString()) .SelectMany(y => y.GroupBy(z => z.CreatedAt.Hour)) .Select(x => x.Count()) .Average() : 0; TweetsPerHourMax = runtimeSettings.GetPastTweets().Count() > 2 ? runtimeSettings.GetPastTweets() .GroupBy(x => x.CreatedAt.ToShortDateString()) .SelectMany(y => y.GroupBy(z => z.CreatedAt.Hour)) .Select(x => x.Count()) .Max() : 0; MinimumRetweetLevel = (int)Math.Ceiling(runtimeSettings.MinimumRetweetLevel); CurrentClout = me.User.FollowersCount; FollowerCount = me.User.FollowersCount; FollowingCount = me.User.FriendsCount; TwitterStreamVolume = runtimeSettings.TotalTweetsProcessed / (1.0 * Runtime.TotalMinutes); TwitterFollowSuggestions = runtimeSettings.TwitterFollowSuggestions; PotentialTweets = runtimeSettings.GetPotentialTweets().OrderByDescending(t=>t.TweetRank).ToList(); PotentialReTweets = runtimeSettings.GetPotentialTweets(true).OrderByDescending(t => t.TweetRank).ToList(); Tweeted = runtimeSettings.GetPastTweets().ToList(); PotentialFriendRequests = runtimeSettings.PotentialFriendRequests .Select(x => new KeyValuePair<Tweep, int>(x.Key, x.Count)).ToList(); KeywordSuggestions = runtimeSettings.KeywordSuggestions .Select(x => new KeyValuePair<string, int>(x.Key, x.Count)).ToList(); runtimeSettings.GetPastTweets() .Where(t => t.CreatedAt.AddDays(30) >= DateTime.Now) .GroupBy(t => t.CreatedAt.Day) .Select(g => new { i = g.FirstOrDefault().CreatedAt.Day - 1, date = g.FirstOrDefault().CreatedAt, count = g.Count() }) .ToList() .ForEach(x => TweetsLastThirtyDays[x.i] = x.count); TopFriendTweetCounts = runtimeSettings.GetPastTweets() .Where(t => me.Followers().Select(f => f.ID).Contains(t.User.UserID)) .GroupBy(t => t.User.UserID) .Select(g => new KeyValuePair<Tweep, int>(new Tweep(g.FirstOrDefault().User, Tweep.TweepType.None), g.Count())) .ToList(); SeededKeywords = runtimeSettings.KeywordsToIgnore; KeywordsWithOccurrenceCount = runtimeSettings.Keywords //.Concat(runtimeSettings.KeywordSuggestions.Where(x => x.Count >= TweetBotProcessingStep.MINIMUM_KEYWORD_COUNT)) .OrderByDescending(x => x.Count) .ThenByDescending(x => x.Key) .Select(x => new KeyValuePair<string, int>(x.Key, x.Count)) .ToList(); PotentialKeywordsWithOccurrenceCount = runtimeSettings.KeywordSuggestions //.Where(x => x.Count < TweetBotProcessingStep.MINIMUM_KEYWORD_COUNT) .Select(x => new KeyValuePair<string, int>(x.Key, x.Count)).ToList(); } var commands = commandRepo.Query(CommandRepoKey, where: x => !x.HasBeenExecuted); if (commands != null) { PendingKeywordAdd = commands.Where(c => c.Command == BotCommand.CommandType.AddKeyword && !c.HasBeenExecuted).Select(c => c.Value).Distinct().ToList(); PendingKeywordIgnore = commands.Where(c => c.Command == BotCommand.CommandType.IgnoreKeyword && !c.HasBeenExecuted).Select(c => c.Value).Distinct().ToList(); PendingTweetRemoval = commands.Where(c => (c.Command == BotCommand.CommandType.RemovePotentialTweet || c.Command == BotCommand.CommandType.RemovePotentialRetweet) && !c.HasBeenExecuted).Select(c => c.Value).Distinct().ToList(); } }
public DataController(SimpleRepository simpleRepository, IMemoryCache cache) { _simpleRepository = simpleRepository; _cache = cache; }
public void Init(string screenName, TextWriter log) { this.log = log; PrimaryTweep = new Tweep(UsersCollection.Single(screenName), Tweep.TweepType.None); settingsRepo = CachedRepository<TweetBotRuntimeSettings>.Instance(screenName); commandRepo = new SimpleRepository<BotCommand>(screenName); RuntimeSettings = (settingsRepo.Query(RuntimeRepoKey) ?? new List<TweetBotRuntimeSettings> { new TweetBotRuntimeSettings() }).FirstOrDefault() ?? new TweetBotRuntimeSettings(); NoTweetList.Add(screenName.ToLower()); Messages = TweetBotSettings.Get.Messages.Count == 0 ? null : Enumerable.Range(0, TweetBotSettings.Get.Messages.Count - 1) .Select(i => TweetBotSettings.Get.Messages[i].Value).ToArray(); OnlyWithMentions = TweetBotSettings.Get.Filters["OnlyWithMentions"] != null ? TweetBotSettings.Get.Filters["OnlyWithMentions"].Value : false; ForceSimulationMode = TweetBotSettings.Get.Settings["IsSimulationMode"] != null ? TweetBotSettings.Get.Settings["IsSimulationMode"].Value : false; if (ForceSimulationMode) log.WriteLine("{0}: Running in forced simulation mode. No actions will be taken.", DateTime.Now); else if (SimulationMode) log.WriteLine("{0}: Running in automatic simulation mode to aquire a baseline. No actions will be taken for {1}hrs.", DateTime.Now, TweetBotRuntimeSettings.SIMULATION_MODE_HOURS); if (Messages == null) log.WriteLine("{0}: 'TweetBotSettings' configuration section is missing Messages. No responses will be sent.", DateTime.Now); else { log.WriteLine("{0}: TweetBot will respond with: {1}", DateTime.Now, Environment.NewLine + string.Join(Environment.NewLine, Messages)); } try { StopWords = File.OpenText("Resources/stopwords.txt") .ReadToEnd() .Split('\n').Select(x => x.Replace("\r", "").ToLower()); if (StopWords.Count() > 0) StopWordsRegex = new Regex("(" + string.Join("|", StopWords.Select(sw => "\\b" + sw + "\\b")) + ")", RegexOptions.Compiled | RegexOptions.IgnoreCase); log.WriteLine("{0}: Stop Words: {1}", DateTime.Now, string.Join(",", StopWords)); } catch { StopWords = new List<string>(); } }
/// <summary> /// Initializes the simple repository. /// </summary> /// <param name="databasePath">The database path.</param> /// <exception cref="Uncas.PodCastPlayer.Repository.RepositoryException"></exception> private void InitializeSimpleRepository( string databasePath) { string repositoryPath = databasePath; if (string.IsNullOrEmpty(repositoryPath)) { string currentDir = Directory.GetCurrentDirectory(); repositoryPath = Path.Combine( currentDir, "PodCastPlayer.db"); } try { FileInfo fi = new FileInfo(repositoryPath); if (!fi.Directory.Exists) { fi.Directory.Create(); } } catch (IOException ex) { throw GetRepositoryFolderException(ex); } catch (SecurityException ex) { throw GetRepositoryFolderException(ex); } catch (UnauthorizedAccessException ex) { throw GetRepositoryFolderException(ex); } catch (NotSupportedException ex) { throw GetRepositoryFolderException(ex); } string connectionString = string.Format( CultureInfo.InvariantCulture, "Data Source={0}", repositoryPath); try { var provider = ProviderFactory.GetProvider( connectionString, "System.Data.SQLite"); this.simpleRepository = new SimpleRepository( provider, SimpleRepositoryOptions.RunMigrations); } catch (Exception ex) { // TODO: EXCEPTION: Unknown exceptions from third-party SubSonic... throw new RepositoryException( "Error initializing SQLite repository", ex); } }
static void Main(string[] args) { var loss = 0; EGT_OTA.Models.Repository.UpdateDB(); SimpleRepository db = Repository.GetRepo(); try { var CurrDatabase = Tools.SafeString(System.Web.Configuration.WebConfigurationManager.AppSettings["CurrDatabase"]); Console.WriteLine("正在运行"); var music01 = new List <Music01>(); var music02 = new List <Music02>(); var music03 = new List <Music03>(); var music04 = new List <Music04>(); var music05 = new List <Music05>(); var music06 = new List <Music06>(); var music07 = new List <Music07>(); var music08 = new List <Music08>(); var music09 = new List <Music09>(); var music10 = new List <Music10>(); var music11 = new List <Music11>(); var music12 = new List <Music12>(); var music13 = new List <Music13>(); Console.WriteLine("读取Music01"); if (CurrDatabase.Contains(",1,")) { music01 = db.All <Music01>().ToList(); music01.ForEach(x => { x.DataBaseNumber = 1; }); } Console.WriteLine("读取Music02"); if (CurrDatabase.Contains(",2,")) { music02 = db.All <Music02>().ToList(); music02.ForEach(x => { x.DataBaseNumber = 2; }); } Console.WriteLine("读取Music03"); if (CurrDatabase.Contains(",3,")) { music03 = db.All <Music03>().ToList(); music03.ForEach(x => { x.DataBaseNumber = 3; }); } Console.WriteLine("读取Music04"); if (CurrDatabase.Contains(",4,")) { music04 = db.All <Music04>().ToList(); music04.ForEach(x => { x.DataBaseNumber = 4; }); } Console.WriteLine("读取Music05"); if (CurrDatabase.Contains(",5,")) { music05 = db.All <Music05>().ToList(); music05.ForEach(x => { x.DataBaseNumber = 5; }); } Console.WriteLine("读取Music06"); if (CurrDatabase.Contains(",6,")) { music06 = db.All <Music06>().ToList(); music06.ForEach(x => { x.DataBaseNumber = 6; }); } Console.WriteLine("读取Music07"); if (CurrDatabase.Contains(",7,")) { music07 = db.All <Music07>().ToList(); music07.ForEach(x => { x.DataBaseNumber = 7; }); } Console.WriteLine("读取Music08"); if (CurrDatabase.Contains(",8,")) { music08 = db.All <Music08>().ToList(); music08.ForEach(x => { x.DataBaseNumber = 8; }); } Console.WriteLine("读取Music09"); if (CurrDatabase.Contains(",9,")) { music09 = db.All <Music09>().ToList(); music09.ForEach(x => { x.DataBaseNumber = 9; }); } Console.WriteLine("读取Music10"); if (CurrDatabase.Contains(",10,")) { music10 = db.All <Music10>().ToList(); music10.ForEach(x => { x.DataBaseNumber = 10; }); } Console.WriteLine("读取Music11"); if (CurrDatabase.Contains(",11,")) { music11 = db.All <Music11>().ToList(); music11.ForEach(x => { x.DataBaseNumber = 11; }); } Console.WriteLine("读取Music12"); if (CurrDatabase.Contains(",12,")) { music12 = db.All <Music12>().ToList(); music12.ForEach(x => { x.DataBaseNumber = 12; }); } Console.WriteLine("读取Music13"); if (CurrDatabase.Contains(",13,")) { music13 = db.All <Music13>().ToList(); music13.ForEach(x => { x.DataBaseNumber = 13; }); } var list = new List <Music>(); list.AddRange(music01); list.AddRange(music02); list.AddRange(music03); list.AddRange(music04); list.AddRange(music05); list.AddRange(music06); list.AddRange(music07); list.AddRange(music08); list.AddRange(music09); list.AddRange(music10); list.AddRange(music11); list.AddRange(music12); list.AddRange(music13); var LineCount = Tools.SafeInt(System.Web.Configuration.WebConfigurationManager.AppSettings["LineCount"]); for (var i = 0; i < LineCount; i++) { Thread thread = new Thread(delegate() { while (list.Count > 0) { lock (locker) { var model = list[0]; var result = CheckFile(model); if (!result) { switch (model.DataBaseNumber) { case 1: db.Delete <Music01>(model.ID); break; case 2: db.Delete <Music02>(model.ID); break; case 3: db.Delete <Music03>(model.ID); break; case 4: db.Delete <Music04>(model.ID); break; case 5: db.Delete <Music05>(model.ID); break; case 6: db.Delete <Music06>(model.ID); break; case 7: db.Delete <Music07>(model.ID); break; case 8: db.Delete <Music08>(model.ID); break; case 9: db.Delete <Music09>(model.ID); break; case 10: db.Delete <Music10>(model.ID); break; case 11: db.Delete <Music11>(model.ID); break; case 12: db.Delete <Music12>(model.ID); break; case 13: db.Delete <Music13>(model.ID); break; default: break; } loss++; } list.RemoveAt(0); } Thread.Sleep(1000); } }); thread.IsBackground = true; thread.Name = "过滤音乐接口线程" + i; thread.Start(); } } catch (Exception ex) { Console.WriteLine(ex.Message); } Console.ReadLine(); }
public Dll Get(int id) { var repo = new SimpleRepository <Dll>(con); return(repo.Get(id)); }
public CachedRedirectRepository(SimpleRepository <Data.Redirect> baseRepo, ICachedRedirectRepositoryStorage cache) { _cache = cache; _baseRepo = baseRepo; }
public DataSet Get(int id) { var repo = new SimpleRepository <DataSet>(con); return(repo.Get(id)); }
public void Init() { _db = new PCRemoteDB(); _repo = new SimpleRepository(_db.Provider); }
public IEnumerable <DataSet> GetAll() { var repo = new SimpleRepository <DataSet>(con); return(repo.GetAll()); }
private void LoadFromRepository() { var me = new Tweep(User, Tweep.TweepType.None); CachedRepository <TweetBotRuntimeSettings> settingsRepo = CachedRepository <TweetBotRuntimeSettings> .Instance(User.TwitterScreenName); SimpleRepository <BotCommand> commandRepo = new SimpleRepository <BotCommand>(User.TwitterScreenName); //var runtimeSettings = Newtonsoft.Json.JsonConvert.DeserializeObject<TweetBotRuntimeSettings>(System.IO.File.OpenText("c:\\temp\\runtimesettings.demo.json.txt").ReadToEnd()); var runtimeSettings = (settingsRepo.Query(RuntimeRepoKey) ?? new List <TweetBotRuntimeSettings> { new TweetBotRuntimeSettings() }).FirstOrDefault(); if (runtimeSettings != null) { IsSimulationMode = runtimeSettings.IsSimulationMode; BotStartupTime = runtimeSettings.BotFirstStart; LastTweetTime = runtimeSettings.LastTweetTime; TweetsSentSinceLastFriendRequest = runtimeSettings.TweetsSentSinceLastFriendRequest; TweetsPerHour = runtimeSettings.GetPastTweets().Count() > 1 ? runtimeSettings.GetPastTweets() .GroupBy(x => x.CreatedAt.ToShortDateString()) .SelectMany(y => y.GroupBy(z => z.CreatedAt.Hour)) .Select(x => x.Count()) .Average() : 0; TweetsPerHourMax = runtimeSettings.GetPastTweets().Count() > 2 ? runtimeSettings.GetPastTweets() .GroupBy(x => x.CreatedAt.ToShortDateString()) .SelectMany(y => y.GroupBy(z => z.CreatedAt.Hour)) .Select(x => x.Count()) .Max() : 0; MinimumRetweetLevel = (int)Math.Ceiling(runtimeSettings.MinimumRetweetLevel); CurrentClout = me.User.FollowersCount; FollowerCount = me.User.FollowersCount; FollowingCount = me.User.FriendsCount; TwitterStreamVolume = runtimeSettings.TotalTweetsProcessed / (1.0 * Runtime.TotalMinutes); TwitterFollowSuggestions = runtimeSettings.TwitterFollowSuggestions; PotentialTweets = runtimeSettings.GetPotentialTweets().OrderByDescending(t => t.TweetRank).ToList(); PotentialReTweets = runtimeSettings.GetPotentialTweets(true).OrderByDescending(t => t.TweetRank).ToList(); Tweeted = runtimeSettings.GetPastTweets().ToList(); PotentialFriendRequests = runtimeSettings.PotentialFriendRequests .Select(x => new KeyValuePair <Tweep, int>(x.Key, x.Count)).ToList(); KeywordSuggestions = runtimeSettings.KeywordSuggestions .Select(x => new KeyValuePair <string, int>(x.Key, x.Count)).ToList(); runtimeSettings.GetPastTweets() .Where(t => t.CreatedAt.AddDays(30) >= DateTime.Now) .GroupBy(t => t.CreatedAt.Day) .Select(g => new { i = g.FirstOrDefault().CreatedAt.Day - 1, date = g.FirstOrDefault().CreatedAt, count = g.Count() }) .ToList() .ForEach(x => TweetsLastThirtyDays[x.i] = x.count); TopFriendTweetCounts = runtimeSettings.GetPastTweets() .Where(t => me.Followers().Select(f => f.ID).Contains(t.User.UserID)) .GroupBy(t => t.User.UserID) .Select(g => new KeyValuePair <Tweep, int>(new Tweep(g.FirstOrDefault().User, Tweep.TweepType.None), g.Count())) .ToList(); SeededKeywords = runtimeSettings.KeywordsToIgnore; KeywordsWithOccurrenceCount = runtimeSettings.Keywords //.Concat(runtimeSettings.KeywordSuggestions.Where(x => x.Count >= TweetBotProcessingStep.MINIMUM_KEYWORD_COUNT)) .OrderByDescending(x => x.Count) .ThenByDescending(x => x.Key) .Select(x => new KeyValuePair <string, int>(x.Key, x.Count)) .ToList(); PotentialKeywordsWithOccurrenceCount = runtimeSettings.KeywordSuggestions //.Where(x => x.Count < TweetBotProcessingStep.MINIMUM_KEYWORD_COUNT) .Select(x => new KeyValuePair <string, int>(x.Key, x.Count)).ToList(); } var commands = commandRepo.Query(CommandRepoKey, where : x => !x.HasBeenExecuted); if (commands != null) { PendingKeywordAdd = commands.Where(c => c.Command == BotCommand.CommandType.AddKeyword && !c.HasBeenExecuted).Select(c => c.Value).Distinct().ToList(); PendingKeywordIgnore = commands.Where(c => c.Command == BotCommand.CommandType.IgnoreKeyword && !c.HasBeenExecuted).Select(c => c.Value).Distinct().ToList(); PendingTweetRemoval = commands.Where(c => (c.Command == BotCommand.CommandType.RemovePotentialTweet || c.Command == BotCommand.CommandType.RemovePotentialRetweet) && !c.HasBeenExecuted).Select(c => c.Value).Distinct().ToList(); } }
public void DisplayPostNavigationTest() { IRepository <Post> postRepo = new SimpleRepository <Post>(new InMemoryRepositoryDataSource <Post>(new List <Post> { new Post { Status = PostStatus.Published, Title = "some-other-post", Path = "2013/04/9/some-other-post", Posted = new DateTime(2013, 4, 9), Author = new User { Email = "" }, BlogId = 1 }, new Post { Status = PostStatus.Published, Title = "some-other-post2", Path = "2013/04/10/some-other-post2", Posted = new DateTime(2013, 4, 10), Author = new User { Email = "" }, BlogId = 1 }, new Post { Canonical = "http://blog.con/2013/04/14/canonical", Status = PostStatus.Published, Title = "some-post", Path = "2013/04/14/some-post", Posted = new DateTime(2013, 4, 14), Author = new User { Email = "*****@*****.**" }, BlogId = 1 }, new Post { Status = PostStatus.Published, Title = "some-other-post3", Path = "2013/04/15/some-other-post3", Posted = new DateTime(2013, 4, 15), Author = new User { Email = "" }, BlogId = 1 }, })); var mockVisitLoggerService = new Mock <IVisitLoggerService>(); PostController sut = new PostController(postRepo, mockVisitLoggerService.Object, _blogRepo, _mockHttpContext.Object); var result = (ViewResult)sut.Display("2013/04/14/some-post"); Assert.IsNotNull(result); var model = result.Model as PostModel; Assert.IsNotNull(model); Assert.AreEqual("http://blog.con/2013/04/14/canonical", model.CanonicalUrl); Assert.AreEqual(new DateTime(2013, 4, 15), model.NextPost.Date); Assert.AreEqual("2013/04/15/some-other-post3", model.NextPost.Link); Assert.AreEqual("some-other-post3", model.NextPost.Title); Assert.AreEqual(new DateTime(2013, 4, 10), model.PreviousPost.Date); Assert.AreEqual("2013/04/10/some-other-post2", model.PreviousPost.Link); Assert.AreEqual("some-other-post2", model.PreviousPost.Title); Assert.AreEqual(4, model.OtherPosts.Count()); Assert.AreEqual("2013/04/15/some-other-post3", model.OtherPosts[0].Link); Assert.AreEqual("2013/04/14/some-post", model.OtherPosts[1].Link); Assert.AreEqual("2013/04/10/some-other-post2", model.OtherPosts[2].Link); Assert.AreEqual("2013/04/9/some-other-post", model.OtherPosts[3].Link); Assert.IsFalse(model.OtherPosts[0].IsCurrentPost); Assert.IsTrue(model.OtherPosts[1].IsCurrentPost); Assert.IsFalse(model.OtherPosts[2].IsCurrentPost); Assert.IsFalse(model.OtherPosts[3].IsCurrentPost); Assert.AreEqual("some-other-post3", model.OtherPosts[0].Title); Assert.AreEqual("some-post", model.OtherPosts[1].Title); Assert.AreEqual("some-other-post2", model.OtherPosts[2].Title); Assert.AreEqual("some-other-post", model.OtherPosts[3].Title); }
public AssetBundle Get(int id) { var repo = new SimpleRepository <AssetBundle>(con); return(repo.Get(id)); }
public void DisplayPostContentTest() { IRepository<Post> postRepo = new SimpleRepository<Post>(new InMemoryRepositoryDataSource<Post>(new List<Post> { new Post { Status = PostStatus.Published, Path ="2013/04/10/some-other-post", Posted = new DateTime(2013,4,10), Author = new User{ Email = "" }, BlogId = 1 }, new Post { Title = "Test Title", DraftTitle = "Draft Title", Body = "Test Body", DraftBody = "Draft Title", Description = "Test Description", DraftDescription = "Draft Description", Status = PostStatus.Published, Path ="2013/04/14/some-post", Posted = new DateTime(2013,4,14), Author = new User{ Email = "*****@*****.**" }, BlogId = 1 } })); var mockVisitLoggerService = new Mock<IVisitLoggerService>(); PostController sut = new PostController(postRepo, mockVisitLoggerService.Object, _blogRepo, _mockHttpContext.Object); var result = (ViewResult)sut.Display("2013/04/14/some-post"); Assert.IsNotNull(result); var model = result.Model as PostModel; Assert.IsNotNull(model); var md = new MarkdownDeep.Markdown(); Assert.AreEqual("Test Title", model.Title); Assert.AreEqual(md.Transform("Test Body"), model.Body); Assert.AreEqual("Test Description", model.Description); }
public CachedBlogRepository(SimpleRepository <Data.Blog> baseRepo, ICachedBlogRepositoryStorage cache) { _cache = cache; _baseRepo = baseRepo; }
public void DisplayPostNavigationTest() { IRepository<Post> postRepo = new SimpleRepository<Post>(new InMemoryRepositoryDataSource<Post>(new List<Post> { new Post { Status = PostStatus.Published, Title = "some-other-post", Path ="2013/04/9/some-other-post", Posted = new DateTime(2013,4,9), Author = new User{ Email = "" }, BlogId = 1 }, new Post { Status = PostStatus.Published, Title = "some-other-post2", Path ="2013/04/10/some-other-post2", Posted = new DateTime(2013,4,10), Author = new User{ Email = "" }, BlogId = 1 }, new Post { Canonical = "http://blog.con/2013/04/14/canonical", Status = PostStatus.Published, Title = "some-post", Path ="2013/04/14/some-post", Posted = new DateTime(2013,4,14), Author = new User{ Email = "*****@*****.**" } , BlogId = 1 }, new Post { Status = PostStatus.Published, Title = "some-other-post3", Path ="2013/04/15/some-other-post3", Posted = new DateTime(2013,4,15), Author = new User{ Email = "" }, BlogId = 1 }, })); var mockVisitLoggerService = new Mock<IVisitLoggerService>(); PostController sut = new PostController(postRepo, mockVisitLoggerService.Object, _blogRepo, _mockHttpContext.Object); var result = (ViewResult)sut.Display("2013/04/14/some-post"); Assert.IsNotNull(result); var model = result.Model as PostModel; Assert.IsNotNull(model); Assert.AreEqual("http://blog.con/2013/04/14/canonical", model.CanonicalUrl); Assert.AreEqual(new DateTime(2013, 4, 15), model.NextPost.Date); Assert.AreEqual("2013/04/15/some-other-post3", model.NextPost.Link); Assert.AreEqual("some-other-post3", model.NextPost.Title); Assert.AreEqual(new DateTime(2013, 4, 10), model.PreviousPost.Date); Assert.AreEqual("2013/04/10/some-other-post2", model.PreviousPost.Link); Assert.AreEqual("some-other-post2", model.PreviousPost.Title); Assert.AreEqual(4, model.OtherPosts.Count()); Assert.AreEqual("2013/04/15/some-other-post3", model.OtherPosts[0].Link); Assert.AreEqual("2013/04/14/some-post", model.OtherPosts[1].Link); Assert.AreEqual("2013/04/10/some-other-post2", model.OtherPosts[2].Link); Assert.AreEqual("2013/04/9/some-other-post", model.OtherPosts[3].Link); Assert.IsFalse(model.OtherPosts[0].IsCurrentPost); Assert.IsTrue(model.OtherPosts[1].IsCurrentPost); Assert.IsFalse(model.OtherPosts[2].IsCurrentPost); Assert.IsFalse(model.OtherPosts[3].IsCurrentPost); Assert.AreEqual("some-other-post3", model.OtherPosts[0].Title); Assert.AreEqual("some-post", model.OtherPosts[1].Title); Assert.AreEqual("some-other-post2", model.OtherPosts[2].Title); Assert.AreEqual("some-other-post", model.OtherPosts[3].Title); }
private static void RunInsert(IDataProvider provider) { ResetDB(provider); var repo = new SimpleRepository(provider); Console.WriteLine("Inserting 1000 rows using Simple Repo: " + DateTime.Now + " using " + provider.Client); DateTime start = DateTime.Now; for(int i = 1; i < 1000; i++) { SubSonic.Tests.TestClasses.Product p = new SubSonic.Tests.TestClasses.Product(); p.CategoryID = 1; p.Discontinued = false; p.ProductName = "Product" + i; p.Sku = Guid.NewGuid(); p.UnitPrice = 1000; repo.Add(p); //Console.WriteLine(i); } DateTime end = DateTime.Now; TimeSpan ts = end.Subtract(start); Console.WriteLine("End: " + DateTime.Now + " (" + ts.Seconds + ":" + ts.Milliseconds + ")"); }
public string LabelPrintProductAddWithDetail(string branchCode, string createdBy, string remark, string labelType, List <LabelPrintProductDetail> details) { string docno = string.Empty; using (DbManager db = new DbManager(branchCode)) { docno = db.SetCommand(GetSql(79)).ExecuteScalar <string>(); } var culture = new System.Globalization.CultureInfo("th-TH"); int index = 1; if (!string.IsNullOrEmpty(docno)) { index = Convert.ToInt32(docno) + 1; } docno = string.Format("PR{0}-{1:0000}", DateTime.Now.Date.ToString("yyMMdd", culture), index); var master = new LabelPrintProduct(); master.Branchcode = branchCode; master.Createuser = createdBy; master.Createdate = DateTime.Now; master.Computername = "PDA"; master.Docno = docno; master.Docdate = DateTime.Now.Date; master.Remark = remark; master.Printlabeltype = labelType; //var labelPrintProduct = repo.Single<LabelPrintProduct>(docno); var displayOrder = 0; ProductPrice productPrice = null; foreach (var item in details) { item.Docno = docno; item.Docdate = DateTime.Now.Date; item.Roworder = displayOrder.ToString(); //item.PrintLabelTypeCode = labelPrintProduct.Printlabeltype; productPrice = ProductPriceGetCurrentPrice(branchCode, item.Productcode, item.Unitcode); if (productPrice != null) { item.Sellprice = productPrice.Saleprice; item.Pricedate = productPrice.Begindate; //item.OthUnitprice = item.Sellprice; item.OthUnitprice = 0; item.OthUnitcode = ""; item.OthUnitname = ""; var UnitOther = ProductPriceGetUnitOther(branchCode, item.Productcode, item.Unitcode); if (UnitOther != null) { item.OthUnitcode = UnitOther.UnitCode; item.OthUnitname = UnitOther.UnitName; var OthPrice = ProductPriceGetCurrentPrice(branchCode, item.Productcode, item.OthUnitcode); if (OthPrice != null) { item.OthUnitprice = OthPrice.Saleprice; } else { item.OthUnitprice = 0; item.OthUnitcode = ""; item.OthUnitname = ""; } } } displayOrder++; } var provider = ProviderFactory.GetProvider(branchCode); var repo = new SimpleRepository(provider); using (System.Transactions.TransactionScope ts = new TransactionScope()) { using (SharedDbConnectionScope scs = new SharedDbConnectionScope(provider)) { repo.Add <LabelPrintProduct>(master); repo.AddMany <LabelPrintProductDetail>(details); ts.Complete(); } } return(docno); }
public void CreatePostAuthorTest() { var userRepo = new SimpleRepository<Data.User>(new InMemoryRepositoryDataSource<Data.User>(new List<Data.User> { new Data.User { Id = 1, ClaimedIdentifier = "zzz", Email = "*****@*****.**" }})); PostAuthoringController sut = new PostAuthoringController( _postRepo, _postModificationRepo, userRepo, _redirectRepo, _blogRepo, _mockSecurityHelper.Object, new MockDateTimeProvider(new DateTime(2013, 1, 2)), _mockHttpContext.Object); var result = sut.Create(new Areas.Manage.Models.PostEditModel { Title = "Test Title", Body = "Test Body", Description = "Test Description", Reposted = true, CanonicalUrl = "http://someotherblog.com/post" }) as RedirectToRouteResult; Assert.IsNotNull(result); Assert.AreEqual("Index", result.RouteValues["action"]); Assert.AreEqual("Dashboard", result.RouteValues["controller"]); Assert.AreEqual(2, _postRepo.GetAll().Count()); Assert.AreEqual(1, _postRepo.GetAll().Last().AuthorId); }
public void DisplayPostAuthorDetailsTest() { IRepository<Post> postRepo = new SimpleRepository<Post>(new InMemoryRepositoryDataSource<Post>(new List<Post> { new Post { Status = PostStatus.Published, Path ="2013/04/10/some-other-post", Posted = new DateTime(2013,4,10), Author = new User{ Email = "" }, BlogId = 1 }, new Post { Status = PostStatus.Published, Path ="2013/04/14/some-post", Posted = new DateTime(2013,4,14), Author = new User{ Id = 1, GooglePlusProfileUrl = "https://plus.google.com/u/0/1234567890", Email = "*****@*****.**", FirstName = "Joe", LastName = "Bloggs" }, BlogId = 1 } })); var mockVisitLoggerService = new Mock<IVisitLoggerService>(); PostController sut = new PostController(postRepo, mockVisitLoggerService.Object, _blogRepo, _mockHttpContext.Object); var result = (ViewResult)sut.Display("2013/04/14/some-post"); Assert.IsNotNull(result); var model = result.Model as PostModel; Assert.IsNotNull(model); Assert.AreEqual("Joe Bloggs", model.Author.Name); Assert.AreEqual("*****@*****.**".GravitarUrlFromEmail(), model.Author.GravatarUrl); Assert.AreEqual("https://plus.google.com/u/0/1234567890", model.Author.GooglePlusProfileUrl); }
public CachedUserRepositoryStorage(SimpleRepository <Data.User> baseRepo) { CachedUsers = baseRepo.GetAll().AsNoTracking().ToList(); }
private static void InitServices() { var eventStoreConnString = ConfigurationManager.ConnectionStrings["EventStore"].ConnectionString; var bus = new Bus.Bus(); var eventStore = new EventStore.SQL.EventStore(eventStoreConnString, bus); var readModelRepo = new SimpleRepository("ReadModel", SimpleRepositoryOptions.RunMigrations); var dtoManager = new SubSonicDtoManager(readModelRepo); var readModel = new SubSonicReadModelFacade(readModelRepo); var commandHandlersAssemblies = new [] { Assembly.Load(new AssemblyName("ECom.Domain")) }; MessageHandlersRegister.RegisterCommandHandlers(commandHandlersAssemblies, bus, eventStore); RegisterEventHandlers(bus, readModel, dtoManager); ServiceLocator.Bus = bus; ServiceLocator.ReadModel = readModel; ServiceLocator.IdentityGenerator = new SqlTableDomainIdentityGenerator(eventStoreConnString); ServiceLocator.EventStore = eventStore; }
public CachedRedirectRepositoryStorage(SimpleRepository <Data.Redirect> baseRepo) { CachedRedirects = baseRepo.GetAll().AsNoTracking().ToList(); }
public CommuStatusService(IAppStoreUIService appStoreUISvc) { Repository = new SimpleRepository(ConnectionStrings.Key_ORACLE_LOG, SimpleRepositoryOptions.None); AppStoreUIService = appStoreUISvc; }
public void LoadRepository(string connectionString) { ConnectionString = connectionString; dataRespository = new SimpleRepository(ConnectionString, SimpleRepositoryOptions.RunMigrations); }
public CommandRepository(PCRemoteDB db) { _db = db; _repo = new SimpleRepository(db.Provider); }
public IEnumerable <T> Get() { var repo = new SimpleRepository <T>(connectionFactory); return(repo.GetAll()); }
static void Main(string[] args) { if (!EnsureSingleLoad()) { Console.WriteLine("{0}: Another Instance Currently Running", DateTime.Now); return; } var start = DateTime.Now; Console.WriteLine("{0}: Started", start); var users = UsersCollection.PrimaryUsers() ?? new List <PostworthyUser>(); var tasks = new List <Task>(); users.AsParallel().ForAll(u => { var tweet = ""; var repoIndex = new SimpleRepository <ArticleStubIndex>(u.TwitterScreenName); var repoPage = new SimpleRepository <ArticleStubPage>(u.TwitterScreenName); ArticleStubIndex articleStubIndex = null; string dayTag = ""; DateTime day = DateTime.MinValue; if (args.Length > 0) { if (DateTime.TryParse(args[0], out day)) { day = day.StartOfDay(); dayTag = "_" + day.ToShortDateString(); articleStubIndex = repoIndex.Query(TwitterModel.Instance(u.TwitterScreenName).CONTENT_INDEX).FirstOrDefault() ?? new ArticleStubIndex(); if (articleStubIndex.ArticleStubPages.Where(x => x.Key == day.ToFileTimeUtc()).Count() == 0) { articleStubIndex.ArticleStubPages.Add(new KeyValuePair <long, string>(day.ToFileTimeUtc(), day.ToShortDateString())); } else { articleStubIndex = null; } } } else { articleStubIndex = repoIndex.Query(TwitterModel.Instance(u.TwitterScreenName).CONTENT_INDEX).FirstOrDefault() ?? new ArticleStubIndex(); day = DateTime.Now.AddDays(-1); day = day.StartOfDay(); if (articleStubIndex.ArticleStubPages.Where(x => x.Key == day.ToFileTimeUtc()).Count() == 0) { dayTag = "_" + day.ToShortDateString(); articleStubIndex.ArticleStubPages.Add(new KeyValuePair <long, string>(day.ToFileTimeUtc(), day.ToShortDateString())); var domain = u.PrimaryDomains.OrderBy(x => x.Length).FirstOrDefault(); if (!string.IsNullOrEmpty(domain) && !domain.StartsWith("beta")) { tweet = "Here are the top articles from " + day.ToShortDateString().Replace('/', '-') + " http://" + domain + "/" + day.ToShortDateString().Replace('/', '-'); } } else { articleStubIndex = null; day = DateTime.MinValue; dayTag = ""; } } var groupingResults = CreateGroups(u, day == DateTime.MinValue ? null : (DateTime?)day); var existing = repoPage.Query(TwitterModel.Instance(u.TwitterScreenName).CONTENT + dayTag).FirstOrDefault(); var contentTask = CreateContent(u, groupingResults, existing); Console.WriteLine("{0}: Waiting on content for {1}", DateTime.Now, u.TwitterScreenName); var continueTask = contentTask.ContinueWith(task => { Console.WriteLine("{0}: Content completed for {1}", DateTime.Now, u.TwitterScreenName); var stubs = task.Result.Take(MAX_CONTENT); if (stubs.Count() > 0 || !string.IsNullOrEmpty(dayTag)) { var articleStubPage = new ArticleStubPage(1, stubs); if (existing != null && existing.ExcludedArticleStubs.Count > 0) { articleStubPage.ExcludedArticleStubs = existing.ExcludedArticleStubs.Where(e => articleStubPage.ArticleStubs.Contains(e)).ToList(); } Console.WriteLine("{0}: Deleting old data from files from storage for {1}", DateTime.Now, u.TwitterScreenName); repoPage.Delete(TwitterModel.Instance(u.TwitterScreenName).CONTENT + dayTag); Console.WriteLine("{0}: Storing data in repository for {1}", DateTime.Now, u.TwitterScreenName); repoPage.Save(TwitterModel.Instance(u.TwitterScreenName).CONTENT + dayTag, articleStubPage); if (articleStubIndex != null) { repoIndex.Save(TwitterModel.Instance(u.TwitterScreenName).CONTENT_INDEX, articleStubIndex); } if (!string.IsNullOrEmpty(tweet)) { try { TwitterModel.Instance(u.TwitterScreenName).UpdateStatus(tweet, processStatus: false); } catch (Exception ex) { Console.WriteLine("{0}: Could not tweet message: {1}" + Environment.NewLine + "The following exception was thrown: {2}", DateTime.Now, tweet, ex.ToString()); } } } else { Console.WriteLine("{0}: No articles found for {1}", DateTime.Now, u.TwitterScreenName); } }); tasks.Add(contentTask); tasks.Add(continueTask); }); Task.WaitAll(tasks.ToArray()); var end = DateTime.Now; Console.WriteLine("{0}: Ending and it took {1} minutes to complete", end, (end - start).TotalMinutes); }
public SimpleDataTests() { _connectionFactory = new FakeConnectionFactory(); _repository = new SimpleRepository(_connectionFactory); }
public void EditPostNoChangeDoesNotTriggerDraftStatus() { var postRepo = new SimpleRepository<Post>(new InMemoryRepositoryDataSource<Post>(new List<Post> { new Post { Id=1, Status = PostStatus.Published, Title = "Test Title", Description = "Test Description", Body = "Test Body", Path ="2013/04/9/some-other-post", Posted = new DateTime(2013,4,9), Author = new User{ Email = "" }, BlogId = 1 }})); PostAuthoringController sut = new PostAuthoringController( postRepo, _postModificationRepo, _userRepo, _redirectRepo, _blogRepo, _mockSecurityHelper.Object, new DateTimeProvider(), _mockHttpContext.Object); var result = sut.Edit(1, new Areas.Manage.Models.PostEditModel { Title = "Test Title", Body = "Test Body", Description = "Test Description", Reposted = false, }) as RedirectToRouteResult; Assert.IsNotNull(result); Assert.AreEqual("Index", result.RouteValues["action"]); Assert.AreEqual("Dashboard", result.RouteValues["controller"]); Assert.AreEqual(1, postRepo.GetAll().Count()); Assert.IsFalse(postRepo.GetAll().Last().HasDraftContent()); }
private static void SelectSimpleRepo(IDataProvider provider) { Console.WriteLine("Selecting 10000 records with SimpleRepo: " + DateTime.Now + " using " + provider.Name); var repo = new SimpleRepository(provider); DateTime start = DateTime.Now; for (int i = 1; i < 10000; i++) { SubSonic.Tests.TestClasses.Product p = repo.Single<SubSonic.Tests.TestClasses.Product>(1); //Console.Write(i + ","); } WriteResult(start); }
public static void BindKernel() { lock (kernelLock) { Logger.Debug("Binding Ninject's Kernel"); _kernel = new StandardKernel(); //SQLite //string connectionString = String.Format("Data Source={0};Version=3;", Path.Combine(AppPath, "SharpNzb.db")); //var dbProvider = ProviderFactory.GetProvider(connectionString, "System.Data.SQLite"); //SQLExpress string connectionString = String.Format(@"server=.\SQLExpress; database=SharpNzb; Trusted_Connection=True;"); var dbProvider = ProviderFactory.GetProvider(connectionString, "System.Data.SqlClient"); //SQLite //string logConnectionString = String.Format("Data Source={0};Version=3;", Path.Combine(AppPath, "log.db")); //var logDbProvider = ProviderFactory.GetProvider(logConnectionString, "System.Data.SQLite"); //SQLExpress string logConnectionString = String.Format(@"server=.\SQLExpress; database=SharpNzbLogs; Trusted_Connection=True;"); var logDbProvider = ProviderFactory.GetProvider(logConnectionString, "System.Data.SqlClient"); var logRepository = new SimpleRepository(logDbProvider, SimpleRepositoryOptions.RunMigrations); //dbProvider.ExecuteQuery(new QueryCommand("VACUUM", dbProvider)); //What does this do? dbProvider.Log = new NlogWriter(); dbProvider.LogParams = true; _kernel.Bind<IDiskProvider>().To<DiskProvider>(); _kernel.Bind<IConfigProvider>().To<ConfigProvider>().InSingletonScope(); _kernel.Bind<INzbQueueProvider>().To<NzbQueueProvider>().InSingletonScope(); _kernel.Bind<INzbImportProvider>().To<NzbImportProvider>().InSingletonScope(); _kernel.Bind<IHistoryProvider>().To<HistoryProvider>().InSingletonScope(); _kernel.Bind<ICategoryProvider>().To<CategoryProvider>().InSingletonScope(); _kernel.Bind<IScriptProvider>().To<ScriptProvider>().InSingletonScope(); _kernel.Bind<IPreQueueProvider>().To<PreQueueProvider>().InSingletonScope(); _kernel.Bind<IServerProvider>().To<ServerProvider>().InSingletonScope(); _kernel.Bind<INntpProvider>().To<NntpProvider>().InSingletonScope(); _kernel.Bind<IYencProvider>().To<IYencProvider>().InSingletonScope(); _kernel.Bind<IHttpProvider>().To<HttpProvider>(); _kernel.Bind<IXmlProvider>().To<XmlProvider>(); _kernel.Bind<IDecompressProvider>().To<DecompressProvider>(); _kernel.Bind<INzbParseProvider>().To<NzbParseProvider>(); _kernel.Bind<INotificationProvider>().To<NotificationProvider>().InSingletonScope(); _kernel.Bind<ILogProvider>().To<LogProvider>().InSingletonScope(); _kernel.Bind<IRepository>().ToMethod(c => new SimpleRepository(dbProvider, SimpleRepositoryOptions.RunMigrations)).InSingletonScope(); _kernel.Bind<IRepository>().ToConstant(logRepository).WhenInjectedInto<SubsonicTarget>().InSingletonScope(); _kernel.Bind<IRepository>().ToConstant(logRepository).WhenInjectedInto<LogProvider>().InSingletonScope(); ForceMigration(_kernel.Get<IRepository>()); } }
public EntryRepository(SimpleRepository repo) { this.Repository = repo; }
public BotCommandController() { commandRepo = new SimpleRepository <BotCommand>(User.Identity.Name); }
public CachedPostRepositoryStorage(SimpleRepository <Data.Post> baseRepo, IRepository <Data.User> userRepo) { CachedPosts = baseRepo.GetAll().AsNoTracking().ToList(); CachedPosts.ForEach((p) => { p.Author = userRepo.GetBy(a => a.Id == p.AuthorId); }); }
public CachedStyleRepositoryStorage(SimpleRepository <Data.Style> baseRepo) { CachedStyles = baseRepo.GetAll().AsNoTracking().ToList(); }
public void CannotEditPostWhenNotInCurrentBlog() { var postRepo = new SimpleRepository<Post>(new InMemoryRepositoryDataSource<Post>(new List<Post> { new Post { Id=1, Status = PostStatus.Published, Title = "Test Title", Description = "Test Description", Body = "Test Body", Path ="2013/04/9/some-other-post", Posted = new DateTime(2013,4,9), Author = new User{ Email = "" }, BlogId = 2 }})); PostAuthoringController sut = new PostAuthoringController( postRepo, _postModificationRepo, _userRepo, _redirectRepo, _blogRepo, _mockSecurityHelper.Object, new DateTimeProvider(), _mockHttpContext.Object); try { sut.Edit(1, new Areas.Manage.Models.PostEditModel { Title = "New Title", Body = "New Body", Description = "New Description", Reposted = true, CanonicalUrl = "http://blog.con/new-post" }); Assert.Fail("Was expecting an exception when trying to edit"); } catch{} Assert.AreEqual(1, postRepo.GetAll().Count()); Assert.IsFalse(postRepo.GetAll().Last().HasDraftContent()); Assert.AreEqual("Test Title", postRepo.GetAll().Last().Title); Assert.AreEqual("Test Body", postRepo.GetAll().Last().Body); Assert.AreEqual("Test Description", postRepo.GetAll().Last().Description); Assert.IsNull(postRepo.GetAll().Last().DraftTitle); Assert.IsNull(postRepo.GetAll().Last().DraftBody); Assert.IsNull(postRepo.GetAll().Last().DraftDescription); Assert.IsNull(postRepo.GetAll().Last().Canonical); }
public CachedPostRepository(SimpleRepository <Data.Post> baseRepo, ICachedPostRepositoryStorage cache, IRepository <Data.User> userRepo) { _cache = cache; _baseRepo = baseRepo; _userRepo = userRepo; }
public void CantPublishPostWhenItIsntInTheCurrentBlog() { var postRepo = new SimpleRepository<Post>(new InMemoryRepositoryDataSource<Post>(new List<Post> { new Post { Id=1, Status = PostStatus.Draft, DraftTitle = "Test Title", DraftDescription = "Test Description", DraftBody = "Test Body", Path ="2013/04/9/some-other-post", Posted = new DateTime(2013,4,9), Author = new User{ Email = "" }, BlogId = 2 }})); PostAuthoringController sut = new PostAuthoringController( postRepo, _postModificationRepo, _userRepo, _redirectRepo, _blogRepo, _mockSecurityHelper.Object, new MockDateTimeProvider(new DateTime(2013, 4, 27, 1, 2, 3)), _mockHttpContext.Object); try { sut.ConfirmPublish(1, new ConfirmPublishModel()); Assert.Fail("Was expecting an exception when trying to edit"); } catch { } // This requires [assembly: InternalsVisibleTo("StaticVoid.Blog.Site.Tests")] in StaticVoid.Blog.Site so that we can read anon types, needing this is kinda lame // dynamic should just jams it in there by itself. I mean heck the debugger can see it, why cant dynamic? // cf http://stackoverflow.com/questions/2630370/c-sharp-dynamic-cannot-access-properties-from-anonymous-types-declared-in-anot Assert.AreEqual(1, postRepo.GetAll().Count()); Assert.AreEqual(0, _postModificationRepo.GetAll().Count()); Assert.AreEqual(PostStatus.Draft, postRepo.GetAll().First().Status); }
public void Init(string screenName, TextWriter log) { this.log = log; PrimaryTweep = new Tweep(UsersCollection.Single(screenName), Tweep.TweepType.None); settingsRepo = CachedRepository <TweetBotRuntimeSettings> .Instance(screenName); commandRepo = new SimpleRepository <BotCommand>(screenName); RuntimeSettings = (settingsRepo.Query(RuntimeRepoKey) ?? new List <TweetBotRuntimeSettings> { new TweetBotRuntimeSettings() }).FirstOrDefault() ?? new TweetBotRuntimeSettings(); NoTweetList.Add(screenName.ToLower()); Messages = TweetBotSettings.Get.Messages.Count == 0 ? null : Enumerable.Range(0, TweetBotSettings.Get.Messages.Count - 1) .Select(i => TweetBotSettings.Get.Messages[i].Value).ToArray(); OnlyWithMentions = TweetBotSettings.Get.Filters["OnlyWithMentions"] != null ? TweetBotSettings.Get.Filters["OnlyWithMentions"].Value : false; ForceSimulationMode = TweetBotSettings.Get.Settings["IsSimulationMode"] != null ? TweetBotSettings.Get.Settings["IsSimulationMode"].Value : false; if (ForceSimulationMode) { log.WriteLine("{0}: Running in forced simulation mode. No actions will be taken.", DateTime.Now); } else if (SimulationMode) { log.WriteLine("{0}: Running in automatic simulation mode to aquire a baseline. No actions will be taken for {1}hrs.", DateTime.Now, TweetBotRuntimeSettings.SIMULATION_MODE_HOURS); } if (Messages == null) { log.WriteLine("{0}: 'TweetBotSettings' configuration section is missing Messages. No responses will be sent.", DateTime.Now); } else { log.WriteLine("{0}: TweetBot will respond with: {1}", DateTime.Now, Environment.NewLine + string.Join(Environment.NewLine, Messages)); } try { StopWords = File.OpenText("Resources/stopwords.txt") .ReadToEnd() .Split('\n').Select(x => x.Replace("\r", "").ToLower()); if (StopWords.Count() > 0) { StopWordsRegex = new Regex("(" + string.Join("|", StopWords.Select(sw => "\\b" + sw + "\\b")) + ")", RegexOptions.Compiled | RegexOptions.IgnoreCase); } log.WriteLine("{0}: Stop Words: {1}", DateTime.Now, string.Join(",", StopWords)); } catch { StopWords = new List <string>(); } }
private static List <TweetGroup> CreateGroups(PostworthyUser user, DateTime?day) { var repoTweets = new SimpleRepository <Tweet>(user.TwitterScreenName); List <string> screenNames = null; screenNames = TwitterModel.Instance(user.TwitterScreenName).GetRelevantScreenNames(user.TwitterScreenName); int RetweetThreshold = user.RetweetThreshold; DateTime start = day == null?DateTime.Now.AddHours(-48) : day.Value.StartOfDay(); DateTime end = day == null ? DateTime.Now : day.Value.EndOfDay(); Func <Tweet, bool> where = t => t != null && //Should everything be displayed or do you only want content (user.OnlyTweetsWithLinks == false || (t.Links != null && t.Links.Count > 0)) && //Minumum threshold applied so we get results worth seeing (if it is your own tweet it gets a pass on this step) ((t.RetweetCount > RetweetThreshold || t.User.ScreenName.ToLower() == user.TwitterScreenName.ToLower()) && //Apply Date Range (t.CreatedAt >= start && t.CreatedAt <= end)); var startGrouping = DateTime.Now; Console.WriteLine("{0}: Starting grouping procedure for {1}", startGrouping, user.TwitterScreenName); Console.WriteLine("{0}: Fetching tweets for {1}", startGrouping, user.TwitterScreenName); var tweets = screenNames //For each screen name (i.e. - you and your friends if included) select the most recent tweets .SelectMany(x => repoTweets.Query(x + TwitterModel.Instance(user.TwitterScreenName).TWEETS, where : where) ?? new List <Tweet>()) //Order all tweets based on rank (TweetRank takes into acount many important factors, i.e. - time, mentions, hotness, ect.) .OrderByDescending(t => t.TweetRank) //Just to make sure we are not trying to group a very very large number of items .Take(5000) .ToList(); Console.WriteLine("{0}: Grouping tweets by similarity for {1}", DateTime.Now, user.TwitterScreenName); var groups = tweets //Group similar tweets .GroupSimilar2() //Convert groups into something we can display .Select(g => new TweetGroup(g) { RepositoryKey = TwitterModel.Instance(user.TwitterScreenName).CONTENT }) //Order by TweetRank .OrderByDescending(g => g.TweetRank) //Only the top 500 .Take(500); List <TweetGroup> results = null; if (groups != null && groups.Count() > 0) { //Get Standard Deviation double stdev = 0; var values = groups.Select(x => x.TweetRank); double avg = values.Average(); stdev = Math.Sqrt(values.Sum(d => (d - avg) * (d - avg)) / values.Count()); //Filter groups that are way high... groups = groups.Where(x => x.TweetRank < (avg + stdev)); results = groups.ToList(); } var endGrouping = DateTime.Now; Console.WriteLine("{0}: Grouping procedure for {1} completed and it took {2} minutes to complete", endGrouping, user.TwitterScreenName, (endGrouping - startGrouping).TotalMinutes); return(results ?? new List <TweetGroup>()); }
public CachedBlogRepositoryStorage(SimpleRepository <Data.Blog> baseRepo) { CachedBlogs = baseRepo.GetAll().AsNoTracking().ToList(); }