static void Main(string[] args) { var provider = new InMemoryCacheProvider(); var r = new CachedRepository(provider); r.Add(new Customer(1, "Joe", "Vella")); r.Add(new Customer(2, "George", "Vella")); r.Add(new Customer(3, "Tatiana", "Camenzuli")); var id = GetCustomerId(r, "Joe"); var id2 = GetCustomerId(r, "George"); var id3 = GetCustomerId(r, new List<string>() { "George" }); var id4 = GetCustomerId(r, new[] { "Joe" }); //var allSalesByJoe1 = query1.Where(x => x.Name == "Joe").ToList(); //var allSalesByJoe2 = query1.Where(x => x.Name == "George").ToList(); //var filter1 = query1.Where(x => x.Value.Contains("t")).Select(x => x.Value); //var filter2 = query1.Where(x => x.Value.Contains("t")).Select(x => x.Value); //var result1 = filter1.ToList(); //var result2 = filter2.ToList(); //var t = filter1.FirstOrDefault(); }
private bool TryInstallPackageFromCache(Project project, string packageId, string version) { string userAppData = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData); string cachePath = Path.Combine(userAppData, "NuGet\\Cache"); bool cacheExists = Directory.Exists(cachePath); bool useLatest = string.IsNullOrEmpty(version) || version == "latest"; var latestCachePackage = CachedRepository.FindPackagesById(packageId) .OrderByDescending(x => x.Version.ToString()) .FirstOrDefault(x => useLatest && x.IsLatestVersion || x.Version.ToString() == version); if (!useLatest && latestCachePackage != null) { InstallPackageFromLocalCache(project, packageId, cachePath, version); return(true); } List <IPackage> latestNugetPackages; try { latestNugetPackages = NuGetPackageRepository.FindPackagesById(packageId).ToList(); } catch (Exception) { //Nuget down or no connection //Try and revert to latest cached packages OutputWindowWriter.WriteLine("--- WARNING: Unable to contact NuGet servers. Attempting to use local cache ---"); if (latestCachePackage == null) { OutputWindowWriter.WriteLine("--- ERROR: Unable to install ServiceStack from NuGet or local cache ---"); throw new WizardBackoutException("Failed to installed package from cache:" + packageId); } OutputWindowWriter.WriteLine("--- Installing " + packageId + " - " + latestCachePackage.Version + " from local cache ---"); InstallPackageFromLocalCache(project, packageId, cachePath, latestCachePackage.Version.ToString()); return(true); } if (cacheExists) { var latestNugetPackage = latestNugetPackages.FirstOrDefault(x => useLatest && x.IsLatestVersion || x.Version.ToString() == version); bool useCache = latestCachePackage != null && latestNugetPackage != null && latestNugetPackage.Version == latestCachePackage.Version; if (useCache) { OutputWindowWriter.WriteLine("--- Installing " + packageId + " - " + latestNugetPackage.Version + " ---"); InstallPackageFromLocalCache(project, packageId, cachePath, latestNugetPackage.Version.ToString()); return(true); } if (latestNugetPackage == null) { throw new ArgumentException("Invalid or unavailable version provided"); } OutputWindowWriter.WriteLine("--- Installing " + packageId + " - " + latestNugetPackage.Version + " ---"); } return(false); }
public ActionResult FrontPage() { ViewBag.ArticleStubIndex = CachedRepository <ArticleStubIndex> .Instance(PrimaryUser.TwitterScreenName) .Query(TwitterModel.Instance(PrimaryUser.TwitterScreenName).CONTENT_INDEX) .FirstOrDefault(); var page = CachedRepository <ArticleStubPage> .Instance(PrimaryUser.TwitterScreenName) .Query(TwitterModel.Instance(PrimaryUser.TwitterScreenName).CONTENT) .FirstOrDefault() ?? new ArticleStubPage(); var index = CachedRepository <ArticleIndex> .Instance(PrimaryUser.TwitterScreenName) .Query(TwitterModel.Instance(PrimaryUser.TwitterScreenName).ARTICLE_INDEX).FirstOrDefault() ?? new ArticleIndex(); var items = index.Articles.OrderByDescending(i => i.Published).Take(25); var fullArticles = new List <Article>(); foreach (var item in items) { var articles = CachedRepository <Article> .Instance(PrimaryUser.TwitterScreenName) .Query(TwitterModel.Instance(PrimaryUser.TwitterScreenName).ARTICLE + item.DayTag).ToList(); var article = articles.Where(x => x.UniqueKey == item.Key).FirstOrDefault(); if (article != null) { fullArticles.Add(article); } } return(View("FrontPage", new FrontPageModel(fullArticles, page.ArticleStubs))); }
void Application_Start(object sender, EventArgs e) { SqlDependency.Start(ConfigurationManager.ConnectionStrings["OneSourceConnectionString"].ConnectionString); CachedRepository<CS_JobStatus> _jobStatusRepository = new CachedRepository<CS_JobStatus>(); _jobStatusRepository.LoadCacheItem(j => j.Active); CachedRepository<CS_PriceType> _priceTypeRepository = new CachedRepository<CS_PriceType>(); _priceTypeRepository.LoadCacheItem(j => j.Active); CachedRepository<CS_JobCategory> _jobCategoryRepository = new CachedRepository<CS_JobCategory>(); _jobCategoryRepository.LoadCacheItem(j => j.Active); CachedRepository<CS_JobType> _jobTypeRepository = new CachedRepository<CS_JobType>(); _jobTypeRepository.LoadCacheItem(j => j.Active); CachedRepository<CS_JobAction> _jobActionRepository = new CachedRepository<CS_JobAction>(); _jobActionRepository.LoadCacheItem(j => j.Active); CachedRepository<CS_LostJobReason> _lostJobReasonRepository = new CachedRepository<CS_LostJobReason>(); _lostJobReasonRepository.LoadCacheItem(j => j.Active); CachedRepository<CS_Frequency> _frequencyRepository = new CachedRepository<CS_Frequency>(); _frequencyRepository.LoadCacheItem(j => j.Active); CachedRepository<CS_LocalEquipmentType> _localEquipmentTypeRepository = new CachedRepository<CS_LocalEquipmentType>(); _localEquipmentTypeRepository.LoadCacheItem(j => j.Active); //CachedRepository<CS_CallType> _localCallTypeRepository = new CachedRepository<CS_CallType>(); //_localCallTypeRepository.LoadCacheItem(j => j.Active); }
public void UpdateStatus(string statusText, string screenname = null, bool processStatus = true) { if (string.IsNullOrEmpty(screenname)) { screenname = PrimaryUser.TwitterScreenName; } var tweetTask = GetAuthorizedTwitterContext(screenname).TweetAsync(statusText); tweetTask.Wait(); var status = tweetTask.Result; if (processStatus) { status = TwitterModel.Instance(PrimaryUser.TwitterScreenName).GetAuthorizedTwitterContext(screenname) .Status .Where(s => s.StatusID == status.StatusID && s.ScreenName == screenname && s.IncludeEntities == true && s.Type == StatusType.User && s.Count == 1) .ToList().FirstOrDefault(); if (status != null) { var tweet = new Tweet(status); tweet.PopulateExtendedData(); CachedRepository <Tweet> .Instance(PrimaryUser.TwitterScreenName).Save(screenname + TWEETS, tweet); } } }
public void UpdateFriendsForPrimaryUser() { string screenname = PrimaryUser.TwitterScreenName; var user = UsersCollection.Single(screenname); if (user != null && user.CanAuthorize) { //try //{ var friends = GetFollowers(screenname); if (friends != null && CachedRepository <Tweep> .Instance(PrimaryUser.TwitterScreenName).ContainsKey(screenname + FRIENDS)) { //var repoFriends = CachedRepository<Tweep>.Instance.Query(screenname + FRIENDS); //friends = friends.Except(repoFriends).ToList(); } if (friends != null) { CachedRepository <Tweep> .Instance(PrimaryUser.TwitterScreenName).Save(screenname + FRIENDS, friends); //CachedRepository<Tweep>.Instance.FlushChanges(); } //} //catch { } } }
public GraphicHelper(CachedRepository repository, Project project, Diagram tableDiagram, Display tableDisplay) { Project = project; Repository = repository; TableDiagram = tableDiagram; TableDisplay = tableDisplay; }
public ArticleStubPage GetArticleStubPage(DateTime date) { var dayTag = date.ToShortDateString() == DateTime.Now.ToShortDateString() ? "" : "_" + date.ToShortDateString(); return(CachedRepository <ArticleStubPage> .Instance(PrimaryUser.TwitterScreenName) .Query(TwitterModel.Instance(PrimaryUser.TwitterScreenName).CONTENT + dayTag).FirstOrDefault() ?? new ArticleStubPage()); }
private string GetLatestVersionOfPackage(string packageId) { try { var package = NuGetPackageRepository.FindPackagesById(packageId).First(x => x.IsLatestVersion); return(package.Version.ToString()); } catch (Exception) { var package = CachedRepository.FindPackagesById(packageId) .OrderByDescending(x => x.Version.ToString()) .FirstOrDefault(); if (package != null && package.Version != null) { return(package.Version.ToString()); } MessageBox.Show( "Unable to connect to NuGet and no cached packages found for " + packageId, "ServiceStackVS Error", MessageBoxButtons.OK, MessageBoxIcon.Error, MessageBoxDefaultButton.Button1, MessageBoxOptions.DefaultDesktopOnly ); throw new WizardBackoutException("Unable to connect to NuGet and no cached packages found for " + packageId); } }
protected override void StoreInRepository(IEnumerable <Tweet> tweets) { var tracker = TwitterModel.Instance(screenName).TRACKER; CachedRepository <Tweet> .Instance(screenName).Save(tracker, tweets.OrderBy(t => t.CreatedAt).Select(t => t).ToList()); log.WriteLine("{0}: {1} Tweets Saved for {2}", DateTime.Now, tweets.Count(), tracker); //CachedRepository<Tweet>.Instance.FlushChanges(); }
// Helpers private static void EmptyRepository() { IRepository <Todo> repo = new CachedRepository <Todo>(); var ids = repo.Items.Select(p => p.Id).ToList(); foreach (var id in ids) { repo.Delete(repo.ItemBy(p => p.Id == id)); } }
public void Init() { _memoryCacheService = new MemoryCacheService { ExpirationTimeSpan = TimeSpan.FromSeconds(1) }; _memoryCacheService.Clear(); _repositoryMock = new RepositoryMock(); _cachedRepository = new CachedRepository(_repositoryMock, _memoryCacheService); }
protected virtual void StoreInRepository(IEnumerable <Tweet> tweets) { tweets .GroupBy(t => t.User.ScreenName) .ToList() .ForEach(g => { CachedRepository <Tweet> .Instance(screenName).Save(g.Key + TwitterModel.Instance(screenName).TWEETS, g.OrderBy(t => t.CreatedAt).Select(t => t).ToList()); log.WriteLine("{0}: {1} Tweets Saved for {2}", DateTime.Now, g.Count(), g.Key); }); }
public void SetupClass() { iocContainer = new Container(); iocContainer.Register <IRepository <Todo> >(() => { var repo = new CachedRepository <Todo>(); foreach (var todo in Stubs.CreateTodos()) { repo.Create(todo); } return(repo); }); }
public List <Tweep> Friends(string screenname) { var friends = CachedRepository <Tweep> .Instance(PrimaryUser.TwitterScreenName).Query(screenname + FRIENDS, pageSize: 1000).ToList(); /* * if (friends == null) * { * LoadFriendCache(); * friends = CachedRepository<Tweep>.Instance.Find(screenname + FRIENDS); * } * */ return(friends ?? new List <Tweep>()); }
public void Init(string screenname, TextWriter log) { this.log = log; PrimaryTweep = new Tweep(UsersCollection.Single(screenname), Tweep.TweepType.None); settingsRepo = CachedRepository<LanguageAnalyticsResults>.Instance(screenname); LanguageAnalyticsResults = (settingsRepo.Query(RuntimeRepoKey) ?? new List<LanguageAnalyticsResults> { new LanguageAnalyticsResults() }).FirstOrDefault() ?? new LanguageAnalyticsResults(); NoTweetList.Add(screenname); }
public void SaveArticle(Article article) { string dayTag = "_" + article.PublishedDate.ToShortDateString(); var index = GetArticleIndex(); CachedRepository <Article> .Instance(PrimaryUser.TwitterScreenName) .Save(TwitterModel.Instance(PrimaryUser.TwitterScreenName).ARTICLE + dayTag, article); index.Articles.Add(new ArticleIndex.Index(article.PublishedDate.ToFileTimeUtc(), article.Title, article.UniqueKey, article.Tags)); CachedRepository <ArticleIndex> .Instance(PrimaryUser.TwitterScreenName) .Save(TwitterModel.Instance(PrimaryUser.TwitterScreenName).ARTICLE_INDEX, index); }
public Article GetArticle(uint id) { var articleIndex = GetArticleIndex().Articles.Where(x => x.ID() == id).FirstOrDefault(); if (articleIndex != null) { var articles = CachedRepository <Article> .Instance(PrimaryUser.TwitterScreenName) .Query(TwitterModel.Instance(PrimaryUser.TwitterScreenName).ARTICLE + articleIndex.DayTag).ToList(); return(articles.Where(x => x.UniqueKey == articleIndex.Key).FirstOrDefault()); } return(null); }
public void ExcludeArticleStub(DateTime date, string slug) { var dayTag = "_" + date.ToShortDateString(); var model = new PostworthyArticleModel(PrimaryUser); var page = model.GetArticleStubPage(date); var article = page.ArticleStubs.Where(s => s.GetSlug() == slug).FirstOrDefault(); page.ExcludedArticleStubs.Add(article); page.ExcludedArticleStubs = page.ExcludedArticleStubs.Distinct().ToList(); CachedRepository <ArticleStubPage> .Instance(PrimaryUser.TwitterScreenName).Save(TwitterModel.Instance(PrimaryUser.TwitterScreenName).CONTENT + dayTag, page); }
public static void SQLCreateDatabase(string databaseName, int version, IEnumerable <string> libraryNames) { using (SqlStore sqlStore = CreateSqlStore(databaseName)) { // Create database string connectionString = string.Format("server={0};Integrated Security=True", sqlStore.ServerName); using (SqlConnection conn = new SqlConnection(connectionString)) { conn.Open(); try { SqlCommand command = conn.CreateCommand(); command.CommandText = string.Format("CREATE DATABASE {0}", databaseName); command.ExecuteNonQuery(); } catch (SqlException exc) { // Ignore "Database already exists" error if (exc.ErrorCode != sqlErrDatabaseExists) { throw exc; } } } // Create Repository CachedRepository repository = new CachedRepository(); repository.Version = version; repository.Store = CreateSqlStore(databaseName); // Create project Project project = new Project(); project.AutoLoadLibraries = true; project.Name = "..."; project.Repository = repository; // Add and register libraries project.RemoveAllLibraries(); project.AddLibrary(typeof(ValueDevice).Assembly, true); foreach (string libName in libraryNames) { project.AddLibraryByName(libName, true); } project.RegisterEntityTypes(); // Create schema sqlStore.CreateDbCommands(repository); sqlStore.CreateDbSchema(repository); // Close project project.Close(); } }
public void Init(string screenname, TextWriter log) { this.log = log; PrimaryTweep = new Tweep(UsersCollection.Single(screenname), Tweep.TweepType.None); settingsRepo = CachedRepository <LanguageAnalyticsResults> .Instance(screenname); LanguageAnalyticsResults = (settingsRepo.Query(RuntimeRepoKey) ?? new List <LanguageAnalyticsResults> { new LanguageAnalyticsResults() }).FirstOrDefault() ?? new LanguageAnalyticsResults(); NoTweetList.Add(screenname); }
public void EditArticle(Article article) { string dayTag = "_" + article.PublishedDate.ToShortDateString(); CachedRepository <Article> .Instance(PrimaryUser.TwitterScreenName) .Save(TwitterModel.Instance(PrimaryUser.TwitterScreenName).ARTICLE + dayTag, article); var index = GetArticleIndex(); var articleIndex = index.Articles.Where(x => x.Key == article.UniqueKey).FirstOrDefault(); articleIndex.Title = article.Title; articleIndex.Tags = article.Tags; CachedRepository <ArticleIndex> .Instance(PrimaryUser.TwitterScreenName) .Save(TwitterModel.Instance(PrimaryUser.TwitterScreenName).ARTICLE_INDEX, index); }
private string GetLatestVersionOfPackage(string packageId) { string packageVersion; try { var package = NuGetPackageRepository.FindPackagesById(packageId).First(x => x.IsLatestVersion); packageVersion = package.Version.ToString(); } catch (Exception) { OutputWindowWriter.WriteLine("Unable to get latest version number of '{0}' from NuGet. Falling back to cache.".Fmt(packageId)); var cachedPackage = CachedRepository.FindPackagesById(packageId).OrderByDescending(x => x.Version).First(x => x.IsLatestVersion); packageVersion = cachedPackage.Version.ToString(); } return(packageVersion); }
private List <ITweet> GetTweets(string screenname, bool includeRelevantScreenNames, List <ulong> excludeStatusIDs = null) { List <string> screenNames = null; var user = UsersCollection.Single(screenname); if (includeRelevantScreenNames) { screenNames = GetRelevantScreenNames(screenname); } else { screenNames = new List <string> { screenname.ToLower() } }; int RetweetThreshold = PrimaryUser.RetweetThreshold; Func <Tweet, bool> where = t => //If there are any IDs we want to filter out (excludeStatusIDs == null || !excludeStatusIDs.Contains(t.StatusID)) && //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.CreatedAt > DateTime.Now.AddHours(-48)*/) || t.User.ScreenName.ToLower() == screenname.ToLower()); var tweets = screenNames //For each screen name (i.e. - you and your friends if included) select the most recent tweets .SelectMany(x => CachedRepository <Tweet> .Instance(PrimaryUser.TwitterScreenName).Query(x + TWEETS, where : where) ?? new List <Tweet>()) //Order all tweets based on rank .OrderByDescending(t => t.TweetRank) .Distinct(Tweet.GetTweetTextComparer()) .ToList(); if (!string.IsNullOrEmpty(PrimaryUser.Track)) { tweets.AddRange(CachedRepository <Tweet> .Instance(PrimaryUser.TwitterScreenName).Query(TRACKER, pageSize: 1000, where : where) ?? new List <Tweet>()); } return(tweets.Cast <ITweet>().ToList()); }
private static async Task <IRepository <TEntity> > BuildTypedResult <TEntity>(DataSourceRepositoryConfiguration configuration, IServiceProvider serviceContainer, INamedServiceProvider namedServiceProvider) where TEntity : IHavePartition <string, string> { var dataSource = namedServiceProvider.GetServiceAsync <IDataSource>(configuration.DataSourceName).GetAwaiter().GetResult(); IRepository <TEntity> result = new DataSourceRepository <TEntity>(dataSource, configuration.StoreName); if (configuration.CacheDataSourceName != null) { var cacheDataSource = namedServiceProvider.GetServiceAsync <IDataSource>(configuration.CacheDataSourceName).GetAwaiter().GetResult(); IRepository <TEntity> cache = new DataSourceRepository <TEntity>(cacheDataSource, configuration.StoreName); Func <Task> clear = () => Task.CompletedTask; if (cacheDataSource is IClearable clearableCache) { clear = () => clearableCache.ClearAsync(configuration.StoreName); } result = new CachedRepository <TEntity>(cache, result, clear); } return(result); }
public async ValueTask WorkWithCachedSpecification() { const string dbName = "FakeDatabase"; using (TrainingDb dbContext = this.testFixture.CreateInMemoryDbContext(dbName)) { dbContext.Database.EnsureCreated(); IOptions <MemoryCacheOptions> memCacheOptions = Options.Create <MemoryCacheOptions>(new MemoryCacheOptions()); var memoryCache = new MemoryCache(memCacheOptions); IReadonlyRepository <Login> repo = new CachedRepository <Login, TrainingDb>(dbContext, memoryCache); ISpecification <Login> spec = this.specificationFactories.For <Login>() .Where(l => l.Id == 1) .Include(l => l.Student) .Not() .AsCached(TimeSpan.FromHours(12), 1); System.Collections.Generic.IEnumerable <Login> logins = await repo.ListAsync(spec); logins.Should().HaveCount(2); logins.Select(l => l.Student).Should().NotBeNull(); // Let's create a new repository instance with the same cache // I would expect in this case that the repository returns the same instances // if they have been retrieved from the cache. repo = new CachedRepository <Login, TrainingDb>(dbContext, memoryCache); System.Collections.Generic.IEnumerable <Login> cachedLogins = await repo.ListAsync(spec); cachedLogins.Should().HaveCount(2); cachedLogins.Should().BeSameAs(logins); } }
public IEnumerable <Article> Articles(Func <Article, bool> where = null) { var articleIndexGroups = GetArticleIndex().Articles.GroupBy(x => x.DayTag).OrderByDescending(x => x.First().Published); foreach (var group in articleIndexGroups) { var articles = CachedRepository <Article> .Instance(PrimaryUser.TwitterScreenName) .Query(TwitterModel.Instance(PrimaryUser.TwitterScreenName).ARTICLE + group.Key).ToList(); var filtered = where != null?articles .Where(where) : articles; if (articles != null) { foreach (var article in filtered) { yield return(article); } } } yield return(null); }
public void DeleteArticle(uint id) { var index = GetArticleIndex(); var articleIndex = index.Articles.Where(x => x.ID() == id).FirstOrDefault(); if (articleIndex != null) { var article = CachedRepository <Article> .Instance(PrimaryUser.TwitterScreenName) .Query(TwitterModel.Instance(PrimaryUser.TwitterScreenName).ARTICLE + articleIndex.DayTag, where : x => x.UniqueKey == articleIndex.Key).FirstOrDefault(); if (article != null) { CachedRepository <Article> .Instance(PrimaryUser.TwitterScreenName) .Delete(TwitterModel.Instance(PrimaryUser.TwitterScreenName).ARTICLE + articleIndex.DayTag, article); index.Articles.Remove(articleIndex); CachedRepository <ArticleIndex> .Instance(PrimaryUser.TwitterScreenName) .Save(TwitterModel.Instance(PrimaryUser.TwitterScreenName).ARTICLE_INDEX, index); } } }
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(); } }
private static int GetCustomerId(CachedRepository cachedRepository, string name) { return cachedRepository.All<Customer>().Where(x => x.Name == name).Select(x => x.Id).FirstOrDefault(); }
public IntervalManager(FCCLDbContext context) { repo = new CachedRepository <Interval>(context); application = (short)context.Application; }
public IntervalManager(FCCLDbContext context) { repo = new CachedRepository<Interval>(context); application = (short)context.Application; }
public MachineManager(FCCLDbContext context) { repo = new CachedRepository <Machine>(context); application = (short)context.Application; }
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 int GetCustomerId(CachedRepository cachedRepository, IEnumerable<string> names) { return cachedRepository.All<Customer>().Where(x => names.Contains(x.Name)).Select(x => x.Id).FirstOrDefault(); }
public MachineManager(FCCLDbContext context) { repo = new CachedRepository<Machine>(context); application = (short)context.Application; }
public List <ITweet> Tweets(string screenname, bool includeRelevantScreenNames = true) { List <ITweet> returnTweets; //Since the grouping can be a somewhat expensive task we will cache the results to gain a speed up. var cachedResponse = HttpRuntime.Cache[screenname + "_" + _CACHED_TWEETS] as List <ITweet>; if (cachedResponse != null && cachedResponse.Count > 0) { returnTweets = cachedResponse; } else { var sharedResult = CachedRepository <TweetGroup> .Instance(PrimaryUser.TwitterScreenName).Query(GROUPING, pageSize: 1000); //Check to see if we have a recent grouping available (by recent it must be within the last 30 minutes) //This is what the Grouping task does for us in the background var useShared = sharedResult != null && sharedResult.Count() > 0 && sharedResult.First().CreatedOn.AddMinutes(30) > DateTime.Now; if (useShared) { lock (tweets_lock) { cachedResponse = HttpRuntime.Cache[screenname + "_" + _CACHED_TWEETS] as List <ITweet>; if (cachedResponse != null && cachedResponse.Count > 0) { returnTweets = cachedResponse; } else { var results = sharedResult.Cast <ITweet>().ToList(); results.AddRange(GetTweets(screenname, includeRelevantScreenNames, sharedResult.SelectMany(g => g.GroupStatusIDs).ToList())); HttpRuntime.Cache.Add(screenname + "_" + _CACHED_TWEETS, results, null, DateTime.Now.AddMinutes(15), Cache.NoSlidingExpiration, CacheItemPriority.Normal, null); returnTweets = results; } } } //If there is nothing local and nothing in shared cache then pull something from the repo //These results are raw and ungrouped since they are pulled on the fly and grouping can be time consuming else { lock (tweets_lock) { cachedResponse = HttpRuntime.Cache[screenname + "_" + _CACHED_TWEETS] as List <ITweet>; if (cachedResponse != null && cachedResponse.Count > 0) { returnTweets = cachedResponse; } else { var results = GetTweets(screenname, includeRelevantScreenNames); if (results != null && results.Count > 0) { HttpRuntime.Cache.Add(screenname + "_" + _CACHED_TWEETS, results, null, DateTime.Now.AddMinutes(5), Cache.NoSlidingExpiration, CacheItemPriority.Normal, null); } returnTweets = results; } } } } //Before we return the results we should order the results rank return(returnTweets.OrderByTweetRank().ToList()); }
private void DoOpen(bool create) { if (IsOpen) { throw new InvalidOperationException("Project is already open."); } if (string.IsNullOrEmpty(Name)) { throw new InvalidOperationException("No name defined for the project."); } // if (repository == null) { repository = new CachedRepository(); repository.ProjectName = Name; } else { Debug.Assert(!repository.IsOpen); repository.Close(); repository.RemoveAllEntityTypes(); libraries.Clear(); } modelObjectTypes.Clear(); shapeTypes.Clear(); if (create) { repository.Version = LastSupportedSaveVersion; RegisterEntityTypesCore(true); repository.Create(); if (autoCreateTemplates) { foreach (ShapeType st in shapeTypes) { CreateDefaultTemplate(st); } } // Create model model = new Model(); repository.InsertModel(model); } else { // We unload all shape and model object types here. Only the ones defined by the // project will be usable. repository.ReadVersion(); if (repository.Version <= 0) { throw new NShapeException("Invalid repository base version: {0}", repository.Version); } RegisterBaseLibraryTypes(false); repository.Open(); } try { settings = repository.GetProject(); // Load the project libraries foreach (string ln in settings.AssemblyNames) { Library lib = FindLibraryByAssemblyName(ln); if (lib == null) { Assembly a = null; try { a = Assembly.Load(ln); } catch (FileLoadException) { a = FindAssemblyInSearchPath(ln); if (a == null) { throw; } } catch (FileNotFoundException) { a = FindAssemblyInSearchPath(ln); if (a == null) { throw; } } Debug.Assert(a != null); lib = DoLoadLibrary(a); } Debug.Assert(lib != null); DoRegisterLibrary(lib, false); } } catch (Exception exc) { Debug.Print(exc.Message); repository.Close(); throw; } if (Opened != null) { Opened(this, EventArgs.Empty); } }
public SettingManager(FCCLDbContext context) { repo = new CachedRepository<Setting>(context); application = (short)context.Application; }
public SettingManager(FCCLDbContext context) { repo = new CachedRepository <Setting>(context); application = (short)context.Application; }